// setup the current user to follow the requested user
function followUser (userAccountId, usersFirstName)
{
  var displayHTML = '<div style="margin:0px 20px 40px 20px;">';
  displayHTML += '<h2 style="color:#0071B6;">Follow ' + usersFirstName + '</h2>';
  displayHTML += '<p>Please confirm that you would like to follow ' + usersFirstName + '\'s activity?</p>';
  displayHTML += '<p>By following ' + usersFirstName + ' you will see notifications of their posted questions and answers in the activity feed that is shown on your home page.</p>';
  displayHTML += spButton('yes, follow ' + usersFirstName, 'confirmFollowUser(' + userAccountId + ', \'' + usersFirstName + '\');', 'FollowBut', 'left');
  displayHTML += spButton('no, cancel', 'spWindowClose();', 'CloseBut', 'left');
  displayHTML += '</div>';
  
  spWindowOpen(displayHTML, 500);
}


// process the requested following for the current user
function confirmFollowUser (userAccountId, usersFirstName)
{
  var params = 'postingId=' + userAccountId;
  spAjaxRequestWithId(followUserResponse, '/drills/FollowUser.do', params, usersFirstName, '');
  
  var displayHTML = '<div style="margin:0px 20px 30px 20px; align:center;"><img src="/drills/img/loading.gif" alt="loading..." /></div>';
  spWindowOpen(displayHTML, 500);
}


// process the response from adding the current user as a follower of the requested posting user
function followUserResponse (req, usersFirstName)
{
  var displayHTML = '<div style="margin:0px 20px 40px 20px;">';
  
  if (req.getResponseHeader('followError') != null)
  {
    displayHTML += '<h2 style="color:red;">Error Following ' + usersFirstName + '</h2>';
    displayHTML += '<p>There was an error whilst trying to process your follow request. Please try again or contact us using the Feedback link on the right hand side.</p>';
  }
  else
  {  
    displayHTML += '<h2 style="color:green;">Success</h2>';
    displayHTML += '<p>You are now following ' + usersFirstName + '\'s activity!</p>';
  }
  
  displayHTML += spButton('close', 'spWindowClose();', 'CloseBut', 'left');
  displayHTML += '</div>';

  spWindowOpen(displayHTML, 500);
}


// explain what following is to the user
function explainFollowing (usersFirstName)
{
  var displayHTML = '<div style="margin:0px 20px 40px 20px;">';
  displayHTML += '<h2 style="color:#0071B6;">Following ' + usersFirstName + '</h2>';
  displayHTML += '<p>Sportplan has introduced <em>following</em> so that you can keep up to date with the people that you are interested in.</p>';
  displayHTML += '<p>By following ' + usersFirstName + ' you will see notifications of their posted questions and answers in the activity feed that is shown on your home page.</p>';
  displayHTML += '<p>You can do this for any Sportplan user, it\'s that simple!</p>';
  displayHTML += spButton('close', 'spWindowClose();', 'CloseBut', 'left');
  displayHTML += '</div>';
  
  spWindowOpen(displayHTML, 500);
}


var usersQuestions = null;
var usersAnswers = null;

// load the list of Questions and Answers by the given user
function seeUsersThreads (userAccountId, showQuestions)
{
  var params = 'uaId=' + userAccountId;
  if (showQuestions == null || showQuestions)
  {
    spAjaxRequestWithId(displayUsersQuestions, '/drills/UsersQuestions.do', params, userAccountId, '');
  }
  else
  {
    spAjaxRequestWithId(displayUsersAnswers, '/drills/UsersAnswers.do', params, userAccountId, '');
  }
  
  var displayHTML = '<div style="margin:0px 20px 40px 20px; align:center;"><img src="/drills/img/loading.gif" alt="loading..." /></div>';
  spWindowOpen(displayHTML, 700);
}


// process the found questions for the selected user
function displayUsersQuestions (req, userAccountId)
{
  var displayHTML = '<div style="margin:0px 20px 40px 20px;">';
  
  if (req.responseText == 'error')
  {
    displayHTML += '<h2 style="color:red;">Error</h2>';
    displayHTML += '<p>There was an error whilst trying to load the user\'s questions. Please try again or contact us using the Feedback link on the right hand side.</p>';
  }
  else
  {
    var threads = eval('(' + req.responseText + ')');
    
    displayHTML += '<div>';
    displayHTML += '<span style="font-size:18px; font-weight:bold; color:#0071B6;">Questions</span>';
    displayHTML += '<a href="javascript:seeUsersThreads(' + userAccountId + ', false);" style="font-size:12px; margin-left:10px;" class="false_cursor">Answers</a>';
    displayHTML += '</div>';
    displayHTML += '<div style="height:400px; overflow:scroll;">';
    
    var threadsHTML = displayThreads(threads);
    if (threadsHTML == '')
    {
      threadsHTML = '<div>This user has not posted any questions.</div>';
    }
    displayHTML += threadsHTML;
    
    
    displayHTML += '</div><br />';
  }
  
  displayHTML += spButton('close', 'spWindowClose();', 'CloseBut', 'left');
  displayHTML += '</div>';

  spWindowOpen(displayHTML, 700);
}


// process the found questions for the selected user
function displayUsersAnswers (req, userAccountId)
{
  var displayHTML = '<div style="margin:0px 20px 40px 20px;">';
  
  if (req.responseText == 'error')
  {
    displayHTML += '<h2 style="color:red;">Error</h2>';
    displayHTML += '<p>There was an error whilst trying to load the user\'s answers. Please try again or contact us using the Feedback link on the right hand side.</p>';
  }
  else
  {
    var threads = eval('(' + req.responseText + ')');
    
    displayHTML += '<div>';
    displayHTML += '<span style="font-size:18px; font-weight:bold; color:#0071B6;">Answers</span>';
    displayHTML += '<a href="javascript:seeUsersThreads(' + userAccountId + ', true);" style="font-size:12px; margin-left:10px;" class="false_cursor">Questions</a>';
    displayHTML += '</div>';
    displayHTML += '<div style="height:400px; overflow:scroll;">';
    
    var threadsHTML = displayThreads(threads);
    if (threadsHTML == '')
    {
      threadsHTML = '<div>This user has not answered any questions.</div>';
    }
    displayHTML += threadsHTML;
    
    displayHTML += '</div><br />';
  }
  
  displayHTML += spButton('close', 'spWindowClose();', 'CloseBut', 'left');
  displayHTML += '</div>';

  spWindowOpen(displayHTML, 700);
}


// load the given user's Threads for which they posted the original question
function loadUsersThreads (userAccountId, displayDivId, action)
{
  var params = 'uaId=' + userAccountId;
  spAjaxRequestWithId(loadThreadsResponse, action, params, displayDivId, '');
}


// process the response from finding user's Threads for questions/answers
function loadThreadsResponse (req, displayDivId)
{
  var displayDiv = document.getElementById(displayDivId);
  if (displayDiv != null)
  {
    if (req.responseText != 'error')
    {
      var threads = eval('(' + req.responseText + ')');
      displayDiv.innerHTML = displayThreads(threads);
    }
  }
}


function displayThreads (threads)
{
  var displayHTML = '';
  
  for (var i = 0; i < threads.length; i++)
  {
    displayHTML += '<div class="questionDiv">';
    displayHTML += '<a href="' + threads[i].pageName + '" class="questionTitleLink"><img src="/drills/img/qSquareB.gif" align="left" border="0"></a>';
    displayHTML += '<div class="questionDivContents">';
    displayHTML += '<a href="' + threads[i].pageName + '" class="questionTitleLink">' + threads[i].title + '</a>';
    displayHTML += '<br />';
    displayHTML += '(viewed ' + threads[i].viewed + ' times) ';
    displayHTML += '<a href="/drills/answers/' + threads[i].sportName + '/index.jsp"><strong>' + threads[i].sportName + '</strong></a>';
    displayHTML += ' - ';
    displayHTML += '<a href="/drills/answers/' + threads[i].sportName + '/' + threads[i].categoryName + '/index.jsp">' + threads[i].categoryName + '</a>';
    displayHTML += '<br />';
    displayHTML += '<div>';
    displayHTML += threads[i].answersCount + ' answer';
    
    if (threads[i].answersCount != 1)
    {
      displayHTML += 's';
    }
    
    if (!(threads[i].latestAnsweringUser == null || threads[i].latestAnsweringUser == ''))
    {
      displayHTML += ' : latest ' + threads[i].latestAnsweringUser
    }
    
    displayHTML += '</div>';
    displayHTML += '</div>';
    displayHTML += '</div>';
  }
  
  return displayHTML;
}


function editAnswer (answerId)
{
	hideFlash();
  var answerText = document.getElementById('editAnswer' + answerId);
  if (answerText != null)
  {
    var editStr = '';
    editStr += '<div style="padding:20">';
    editStr += '<strong>' + langres_answers_EditAnswer + ':</strong><br />'
    editStr += '<textarea id="editedAnswer' + answerId + '" name="editedAnswer' + answerId + '" cols="60" rows="12">';
    editStr += answerText.innerHTML;
    editStr += '</textarea>';
    editStr += '<br /><br />';
    editStr += spButton(langres_answers_update, 'updateAnswer(' + answerId + ');', 'updateAnswer' + answerId, 'left');
    editStr += '</div>';
    
    spWindowOpen(editStr, 500);
    
    tinyMCE.init({
      mode : "textareas",
      theme : "simple"
    });
  }
  else
  {
    alert(langres_answers_cannotEdit);
  }
}


/*
 * update the text of the selected answer
 */
function updateAnswer (answerId)
{
  var updatedText = document.getElementById('editedAnswer' + answerId);
  if (updatedText != null)
  {
    toggleEditor('editedAnswer' + answerId);
  
    var updateForm = document.getElementById('UpdateForm' + answerId);
    updateForm.fmMessage.value = updatedText.value;
    updateForm.submit();
    spWindowClose();
  }
  else
  {
    alert(langres_answers_cannotUpdate);
    spWindowClose();
  }
}


/*
 * delete the selected answer
 */
function deleteAnswer (answerId)
{
  if (confirm(langres_answers_confirmDeleteAnswer))
  {
    var deleteForm = document.getElementById('DeleteForm' + answerId);
    deleteForm.submit();
  }
}


var attachedFS = null;

/*
 * open an attached SessionEntity that is link to a ForumMessage
 */
function openAttachedForumSession (sessionEntityId, forumSessionId)
{
  hideFlash();
  spWindowOpen(langres_answers_Opening_attached_session + '...<img src="/sisvp/img/loading.gif" alt="" align="absmiddle" />', 500);
  spAjaxRequestWithId(displayAttachedForumSession, '/drills/EditSession.do', 'OpenedSession=true&jsonOpen=true&seId=' + sessionEntityId, forumSessionId,'');
}


function displayAttachedForumSession (req, forumSessionId)
{
  var fsDiv = document.getElementById('openSession' + forumSessionId);
  fsDiv.innerHTML = req.responseText;
  fsDiv.innerHTML = "<strong>Contents of div with id: openSession" + forumSessionId + "</strong><br /><br />" + fsDiv.innerHTML;
  
  // replace these lines with new display of opened SessionEntity
  attachedFS = eval("(" + findStart(req.responseText) + ")");
  var result='';
  if(attachedFS.session.sportCodeId==3332) result+='<a href="javascript:printFromForum(\'Workout\');">Print Session</a><br/>';
   else result+='<a href="javascript:printFromForum(\'Open\');">' + langres_answers_ViewPrintPreview + '</a><br/>';
   result+='<div style="height:50px;">';
  result+='<div style="margin:4px;width:80px;height:40px;float:left;overflow:hidden;">';
		result+='<img src="/drills/img/headerIcon.gif" width="78" height="43">';
		result+='</div>';		
		for(var i=0;i<attachedFS.practices.length;i++){
			result+=' <div style="margin:4px;width:80px;float:left;overflow:hidden;">';
			//result+=' <table border="0" cellpadding="0" cellspacing="0" width="74" ><tr>';
			//result+=' <td width="52" rowspan="2" valign="top" bgcolor="'+editSession.practices[i].colour+'">';
			result+=drawPractice(attachedFS.practices[i],56,34);
			//result+='</td>';
			//result+='<td><a href="javascript:changeClipOrder('+i+');"><img src="/userapp/app/images/clipup_f2.gif" name="up'+i+'" width="20" height="18" border="0" alt="Up clipboard"></a></td></tr>';
			//result+='<tr><td><a href="javascript:removeFromClip('+i+');" ><img src="/userapp/app/images/clipdel_f2.gif" name="del'+i+'" width="20" height="18" border="0" alt="Delete from Clipboard"></a></td></tr></td></tr> </table>';
		 	result+='</div>';
			
		}
	 result+='</div >';
//result+='<div style="margin:4px;width:10px;height:40px;overflow:hidden;">&nbsp;</div>';
  fsDiv.innerHTML=result;
  fsDiv.className='forumSessionHolder';
  fsDiv.style.display="block";
  fsDiv.style.height=parseInt(fsDiv.offsetHeight)+'px';
  if(fsDiv.height) fsDiv.height=parseInt(fsDiv.offsetHeight)+'px';
  spWindowClose();
}

function printFromForum(type)
	{
		var content='';
		hideFlash();
		content+='<div style="padding:10px;"><span style="color:#888888;font-size:15px;padding-bottom:6px;"><strong>' + langres_answers_selectPrintLayout + '</strong></span>';
		content+='<br><table width="460" border="0" cellspacing="0" cellpadding="0">';
  content+='<tr>';
  var showWorkoutOptions=false;
  if(type=='Workout') var showWorkoutOptions=true;
  if(showWorkoutOptions){
	   content+='<td><a href="/drills/layout/print/print'+type+'.jsp?layout=workoutCard" onclick="spWindowClose();pageTracker._trackPageview(\'/printWorkoutCard\');" target="_blank"><img src="/drills/img/printLayoutWorkout.gif" width="102" height="131" border="0"></a></td>';
    content+='<td style="width:10px;">&nbsp;</td>';
    content+='<td><a href="/drills/layout/print/print'+type+'.jsp?layout=sideBySide" onclick="spWindowClose();pageTracker._trackPageview(\'/printSideBySide\');" target="_blank"><img src="/drills/img/printLayout2.gif" width="102" height="131" border="0"></a></td>';
    content+='<td style="width:10px;">&nbsp;</td>';
  }
  else{
    content+='<td><a href="/drills/layout/print/print'+type+'.jsp?layout=standard" onclick="spWindowClose();pageTracker._trackPageview(\'/printStandard\');" target="_blank"><img src="/drills/img/printLayout1.gif" width="102" height="131" border="0"></a></td>';
    content+='<td style="width:10px;">&nbsp;</td>';
    content+='<td><a href="/drills/layout/print/print'+type+'.jsp?layout=sideBySide" onclick="spWindowClose();pageTracker._trackPageview(\'/printSideBySide\');" target="_blank"><img src="/drills/img/printLayout2.gif" width="102" height="131" border="0"></a></td>';
    content+='<td style="width:10px;">&nbsp;</td>';
    content+='<td><a href="javascript:alert(\'coming Soon\');pageTracker._trackPageview(\'/print2Up\');"><img src="/drills/img/printLayout3.gif" width="102" height="131" border="0"></a></td>';
   content+='<td style="width:10px;">&nbsp;</td>';
  //  content+='<td><a href="javascript:alert(\'coming Soon\');pageTracker._trackPageview(\'/print1Up\');"><img src="/drills/img/prLayout4.gif" width="132" height="103" border="0"></a></td>';
  	  content+='<td><a href="/drills/layout/print/print'+type+'.jsp?layout=4Up" onclick="spWindowClose();pageTracker._trackPageview(\'/print4Up\');" target="_blank"><img src="/drills/img/prLayout4up.gif" width="132" height="103" border="0"></a></td>';
  }
   content+='</tr></table>';
  content+='<p><a href="/drills/layout/print/print'+type+'.jsp?layout=new08" onclick="spWindowClose();pageTracker._trackPageview(\'/printNew08\');" target="_blank"><img src="/drills/img/printLayout08.gif" width="238" height="114" border="0"></a></p>';
  content+='<P style="color:#888888;font-size:13px;">' + langres_answers_templatesForA4 + '<br/> NB ' + langres_answers_popupBlockerAdvice + '</P></div>';
	spWindowOpen(content,550);
	}


function showAttachmentOptions ()
{
  var attachmentDiv = document.getElementById('attachmentOptions');
  attachmentDiv.style.display = 'block';
  
  attachmentDiv = document.getElementById('openAttachmentOptions');
  attachmentDiv.style.display = 'none';
}


function openAttachmentOption (theForm)
{
  var attachmentType = theForm.attachmentType;
  hideFlash();
  if (attachmentType[0].checked)
  {
    customPracticeAttachment();
  }
  else if (attachmentType[1].checked)
  {
    practiceVariantAttachment();
  }
  else if (attachmentType[2].checked)
  {
    sessionEntityAttachment();
  }
}

/* ---------------------- CustomPractice Attachment Start ---------------------- */

/*
 * give options to user to create an image, describing their question
 */
function customPracticeAttachment (bgImage, sportName)
{
  // if answer a question
  if (bgImage != null && sportName != null)
  {
    spAjaxRequest(displayCPAttachment, '/drills/OpenCustomPracticeInFolder.do', 'template=simple&forward=attachment&pracSportName=' + sportName + '&bgImage=' + bgImage, '');
  }
  // if asking a question
  else
  {
    var sportSelect = document.getElementById('sportDrop');
    var selectedSport = '';
    
    if (sportSelect != null)
    {
      selectedSport = sportSelect.options[sportSelect.selectedIndex].text;
    }
    else
    {
      selectedSport = document.answerForm.sportName.value;
    }
  
    spAjaxRequest(displayCPAttachment, '/drills/ShowCPOpenOptions.do', 'isMemberSport=' + selectedSport + '&bgImage=' + bgImage, '');
  }
}

function displayCPAttachment (req)
{
  spWindowOpen(req.responseText, 700);
}

var IFrameObj;
var attachedcp = null;
/*
 * overriding function for custom practice creator when its loaded through ajax call
 */
function imageToForm ()
{
  // copy the image data from the Canvas
  // to the hidden form field image (with scaling 1:1)
  document.EditCustomPracticeForm.image.value = document.applets["canvas"].GetImage(1,"png");

  var IFrameDoc;
  var URL = 'server.html';
  if (!IFrameObj)
  {
    // create the IFrame and assign a reference to the
    // object to our global variable IFrameObj.
    // this will only happen the first time 
    // callToServer() is called
    try
    {
      var tempIFrame=document.createElement('iframe');
      tempIFrame.setAttribute('id','cpFrame');
      tempIFrame.setAttribute('name','cpFrame');
      tempIFrame.style.border='0px';
      tempIFrame.style.width='0px';
      tempIFrame.style.height='0px';
      IFrameObj = document.body.appendChild(tempIFrame);
      
      if (document.frames)
      {
        // this is for IE5 Mac, because it will only
        // allow access to the document object
        // of the IFrame if we access it through
        // the document.frames array
        IFrameObj = document.frames['cpFrame'];
      }
    }
    catch(exception)
    {
      // This is for IE5 PC, which does not allow dynamic creation
      // and manipulation of an iframe object. Instead, we'll fake
      // it up by creating our own objects.
      iframeHTML='\<iframe id="cpFrame" name="cpFrame" style="';
      iframeHTML+='border:0px;';
      iframeHTML+='width:0px;';
      iframeHTML+='height:0px;';
      iframeHTML+='"><\/iframe>';
      document.body.innerHTML+=iframeHTML;
      IFrameObj = new Object();
      IFrameObj.document = new Object();
      IFrameObj.document.location = new Object();
      IFrameObj.document.location.iframe = document.getElementById('cpFrame');
      IFrameObj.document.location.replace = function(location)
      {
        this.iframe.src = location;
      }
    }
  }
  
  if (navigator.userAgent.indexOf('Gecko') !=-1 && !IFrameObj.contentDocument)
  {
    // we have to give NS6 a fraction of a second
    // to recognize the new IFrame
    setTimeout('imageToForm()',10);
    return;
  }

  document.EditCustomPracticeForm.target = 'cpFrame';
  document.EditCustomPracticeForm.forward.value = 'attachment';
  document.EditCustomPracticeForm.submit();
  
  //var templateDiv = document.getElementById('templateDiv');
  //templateDiv.innerHTML = '<div id="loadingImage"></div>';
}

function updateAttachedCPDetails (cpJSONOb)
{
  cpJSONOb = findStart(cpJSONOb);
  attachedcp = eval('(' + cpJSONOb + ')');
  spWindowClose();
  
  var attachmentDisplay = document.getElementById('attachmentDisplay');
  attachmentDisplay.innerHTML = attachedcp.title + "<br /><img src='" + attachedcp.imageSource + "' height='100px' alt='attached image' />";
  
  var theForm = document.askQuestionForm;
  if (theForm == null)
  {
    theForm = document.answerForm;
  }
  
  theForm.customPracticeId.value = attachedcp.customPracticeId;
  theForm.attachedcp.value = cpJSONOb;

  var pageDimensions = getPageSize();
  var iebody=(document.compatMode && document.compatMode != "BackCompat")? document.documentElement : document.body;
  iebody.scrollTop = pageDimensions[1]-200;
  
  theForm.answer.focus();
  
  // clear other attachment options
  theForm.practiceVariantId.value = '';
  theForm.sessionEntityId.value = '';
}

function showFCPImage (imageSource, width)
{
  var img = "<img src='" + imageSource + "' width='" + width + "' alt='attached image' />";
  spWindowOpen(img, width);
}

/* ---------------------- CustomPractice Attachment End ---------------------- */




/* ---------------------- PracticeVariant Attachment Start ---------------------- */

function practiceVariantAttachment ()
{
  if (lastSportName == null || lastSportName == '' || lastSportName == 'Sports')
  {
    var sportSelect = document.getElementById('sportDrop');
    lastSportName = sportSelect.options[sportSelect.selectedIndex].text;
  }
  
  var clipboardOptions = '';
  
  var jsonBox = document.getElementById('jsonClipboard');
  if(jsonBox)
  {
    jsonString = jsonBox.innerHTML;
    if(jsonString.length>5)
    {
      clipSession=eval("("+findStart(jsonString)+")");
    }
    else
    {
      alert("Clipboard is Empty");
      return;
    }
  }
  
  clipboardOptions += '<strong>' + langres_answers_Select_practice + ':</strong> (' +langres_answers_clickThumbnailToSelect + ')';
  clipboardOptions += '<table width="500" height="200" border="0" cellpadding="0" cellspacing="0"><tr><td valign="top">';
  for (var i = 0; i < clipSession.practices.length; i++)
  {
    clipboardOptions += '<div style="float:left; margin:4px;" class="false_cursor" onclick="selectPracticeVariant(\'';
    
    if (clipSession.practices[i].type == 0)
    {
      clipboardOptions += clipSession.practices[i].practiceVariantId;
    }
    else
    {
      clipboardOptions += clipSession.practices[i].customPracticeId;
    }
    
    clipboardOptions += '\',\'' + clipSession.practices[i].type + '\', ' + i + ');">' + drawPractice(clipSession.practices[i], 100, 66) +  '</div>';
  }
  clipboardOptions += '</td></tr></table>';
  
  spWindowOpen(clipboardOptions, 500);
}


function selectPracticeVariant (id, type, practiceIndex)
{
  //alert(id + ' ' + type);
  var theForm = document.askQuestionForm;
  if (theForm == null)
  {
    theForm = document.answerForm;
  }
  
  if (type == 0)
  {
    theForm.practiceVariantId.value = id;
  
    // clear other attachment options
    theForm.customPracticeId.value = '';
    theForm.sessionEntityId.value = '';
  }
  else
  {
    theForm.customPracticeId.value = id;
    
    // clear other attachment options
    theForm.practiceVariantId.value = '';
    theForm.sessionEntityId.value = '';
  }
  
  var attachmentDisplayDiv = document.getElementById('attachmentDisplay');
  attachmentDisplayDiv.innerHTML = '<strong>' + langres_answers_SelectedAttachment + '</strong><br />' + drawPractice(clipSession.practices[practiceIndex], 100, 66);
  spWindowClose();
}

function addFromLinkPracticeVariant (id,thumbSrc)
{
  //alert(id + ' ' + type);
  var theForm = document.askQuestionForm;
  if (theForm == null)
  {
    theForm = document.answerForm;
  }
  
//  if (type == 0)
 // {
    theForm.practiceVariantId.value = id;
  
    // clear other attachment options
    theForm.customPracticeId.value = '';
    theForm.sessionEntityId.value = '';
/*  }
  else
  {
    theForm.customPracticeId.value = id;
    
    // clear other attachment options
    theForm.practiceVariantId.value = '';
    theForm.sessionEntityId.value = '';
  } */
  
  var attachmentDisplayDiv = document.getElementById('attachmentDisplay');
  attachmentDisplayDiv.innerHTML = '<strong>' + langres_answers_SelectedAttachment + '</strong><br /><img src="http://www.sportplan.net/viewer/movies/'+thumbSrc+'.gif" width="100" height="66"/>';
}

/* ---------------------- PracticeVariant Attachment End ---------------------- */




/* ---------------------- SessionEntity Attachment Start ---------------------- */

function sessionEntityAttachment ()
{
  spWindowOpen(langres_answers_LoadingMyStuff + '...<img src="/sisvp/img/loading.gif" alt="" align="absmiddle" />', 500);
  spAjaxRequest(displayMyStuffSessions, '/drills/FindMyStuffSessions.do', 'forward=list', '');
}


function displayMyStuffSessions (req)
{
  var sessions = eval('(' + findStart(req.responseText) + ')');
  var sessionOptions = '';
  sessionOptions += '<strong>' + langres_answers_Select_session + ':</strong>';
  sessionOptions += '<table width="500" height="200" border="0" cellpadding="0" cellspacing="0"><tr><td valign="top">';
  for (var i = 0; i < sessions.se.length; i++)
  {
    sessionOptions += '<div style="margin:4px; font-size:12px; font-family:Verdana,Arial,sans-serif;" class="false_cursor" onclick="selectSessionEntity(\'' + sessions.se[i].seId + '\', \'' + sessions.se[i].title + '\');"><img src="/userapp/app/images/sessFile.gif" alt="" align="absmiddle" /> ' + sessions.se[i].title +  '</div>';
  }
  sessionOptions += '</td></tr></table>';
  
  spWindowOpen(sessionOptions, 500);
}


function selectSessionEntity (sessionEntityId, title)
{
  var theForm = document.askQuestionForm;
  if (theForm == null)
  {
    theForm = document.answerForm;
  }
  
  theForm.sessionEntityId.value = sessionEntityId;
    
  // clear other attachment options
  theForm.practiceVariantId.value = '';
  theForm.customPracticeId.value = '';
  
  var attachmentDisplayDiv = document.getElementById('attachmentDisplay');
  attachmentDisplayDiv.innerHTML = '<strong>' + langres_answers_SelectedAttachment + '</strong><br /><img src="/userapp/app/images/sessFile.gif" alt="" align="absmiddle" /> ' + title;
  spWindowClose();
}

/* ---------------------- SessionEntity Attachment End ---------------------- */


/*
	Function sets up the drops for the as question page
*/
var catDrop = new Array();
var sportObs;
function setupAskQuestion(question, sportName)
{
	sportObs = eval("("+answersSports+")");

	var sportDrop = "<select id='sportDrop' onchange='changeCats(this)'>";
	
	var count = 0;
	for(prop in sportObs.sports)
	{
		if (prop != 'toJSONString' && prop != 'parseJSON')
    {
  		sportDrop += "<option value='" + prop + "'>"+prop+"</option>";
  		
  		catDrop[count] = "<select id='catDrop' name='fscIndex'>";
  		var max = sportObs.sports[prop].length;
  		catDrop[count] += "<option value='-1'>&lt;select&gt;</option>";
  		
      for (var i = 0; i < max; ++i)
      {
  			catDrop[count] += "<option value='"+sportObs.sports[prop][i][1]+"'>"+sportObs.sports[prop][i][0]+"</option>";
		  }
  
  		catDrop[count] += "</select>";
  		++count;
  	}
  }
	
  sportDrop += "</select>";
	
  document.getElementById("sports").innerHTML = "<strong>" + langres_answers_Select_sport + ":</strong> " + sportDrop;
	document.getElementById("categories").innerHTML = "<strong>" + langres_answers_Select_category + ":</strong> " + catDrop[0];
  
  // check to see if a sport should be automatically selected
  sportDrop = document.getElementById('sportDrop');
  for (var i = 0; i < sportDrop.length; i++)
  {
    if (sportDrop[i].text == sportName)
    {
      sportDrop[i].selected = true;
	  document.getElementById("sports").style.display='none';
	  document.getElementById("sportsAlt").innerHTML = "<strong>" + langres_answers_Sport + ":</strong> <span style='color:#0000cc;'>" + sportName+"</span>";
	  document.getElementById("sportsAlt").style.display='block';
      break;
    }
  }

  // update the categories to match the sport
  changeCats(sportDrop);
 
  if (question != null && question != '')
  {
 	question = question.replace(/&lt;br \/&gt;/g,"\n");
	// alert(question);
	 var quoteMark = question.indexOf('&#039;');
    var formattedQ = '';
    while (quoteMark > -1)
    {
      formattedQ = question.substring(0, quoteMark) + "\'";
      if (question.length > (parseInt(quoteMark) + 6))
      {
        formattedQ += question.substring(quoteMark + 6);
      }
      question = formattedQ;
      quoteMark = question.indexOf('&#039;');
    }
    
    var remainder = '';
    var spaceIndex = -1;
    
    if (question.length > 50)
    {
      remainder = question.substring(50);
      spaceIndex = remainder.indexOf(' ');
    }
    
    if (spaceIndex > -1)
    {
      spaceIndex = 50 + spaceIndex;
      document.askQuestionForm.title.value = question.substring(0, spaceIndex) + "?";
      document.askQuestionForm.message.value = question;
    }
    else
    {
      document.askQuestionForm.title.value = question;
      document.askQuestionForm.message.value = question;
    }
  }
  updateQPreview();
}

function changeCats(drop){
	document.getElementById("categories").innerHTML = "<strong>" + langres_answers_Select_category + ":</strong> " + catDrop[drop.selectedIndex];
	if(sportObs.sports[drop.options[drop.selectedIndex].text].length==0)
	   	{
			document.getElementById("categories").style.display='none';
		}
	else document.getElementById("categories").style.display='block';
}

/*
	Function checks Ask question form
*/
function checkQuestion(form){
	var titlebox = form.title;
	var messagebox = form.message;
	
	if(titlebox.value == ""){
		alert(langres_answers_noQuestionEntered);
		return false;
	}
  
  if (titlebox.value.indexOf(langres_answers_askQuestionHaveAnswered) > -1)
  {
    alert(langres_answers_enterAlternativeSummary);
    titlebox.focus();
    titlebox.select();
    return false;
  }
	
	if(messagebox.value == ""){
		alert(langres_answers_noQuestionBody);
		return false;
	}
	
  var sportSelect = document.getElementById('sportDrop');
  var categorySelect = document.getElementById('catDrop');
  
  var selectedSport = sportSelect.options[sportSelect.selectedIndex].text;
  if(categorySelect.options[categorySelect.selectedIndex].value==-1) {alert(langres_answers_please_select_category);return false;}
  var selectedCategory = categorySelect.options[categorySelect.selectedIndex].text;
  
  if(confirm(langres_answers_askUnderCategory + ' \'' + selectedCategory + '\'?')) {
    form.message.value=removeNL(form.message.value);
    return true;
  }
  else return false;
}

/*
	Function checks answer question form
*/
function checkAnswer(form){
	var textbox = form.answer;
	tinyMCE.triggerSave();
	if(textbox.value == ""){
		alert(langres_answers_noAnswerEntered);
		return false;
	}
	
	return true;
}

//------------------------ Thread page functions ----------------------------------//

/*
	Setup the thread page.
*/
function setupThreadPage(threadId){
  
  // set question date
  setTimes('questionDate');
  
	//set the current times
	setTimes('timeSpanA');
	
	//update the thread read count
	updateReadCount(threadId);
}

var calendarMonths = new Array();
calendarMonths[calendarMonths.length] = langres_answers_january;
calendarMonths[calendarMonths.length] = langres_answers_february;
calendarMonths[calendarMonths.length] = langres_answers_march;
calendarMonths[calendarMonths.length] = langres_answers_april;
calendarMonths[calendarMonths.length] = langres_answers_may;
calendarMonths[calendarMonths.length] = langres_answers_june;
calendarMonths[calendarMonths.length] = langres_answers_july;
calendarMonths[calendarMonths.length] = langres_answers_august;
calendarMonths[calendarMonths.length] = langres_answers_september;
calendarMonths[calendarMonths.length] = langres_answers_october;
calendarMonths[calendarMonths.length] = langres_answers_november;
calendarMonths[calendarMonths.length] = langres_answers_december;

function formattedDate (date)
{
  var formattedDate = '';
  formattedDate += date.getHours();
  formattedDate += ':';
  if (date.getMinutes() < 10)
  {
    formattedDate += '0';
  }
  formattedDate += date.getMinutes();
  formattedDate += ' ';
  formattedDate += date.getDate();
  formattedDate += 'th ';
  formattedDate += calendarMonths[parseInt(date.getMonth())];
  formattedDate += ' ';
  formattedDate += date.getFullYear();
  
  return formattedDate;
}

/*
	set the message times
*/
function setLastPostedTimes (spanId)
{
  var count = 1;
  //set all of the message times
  //alert(spanId + "-" + count);
  var currentTime = new Date().getTime();
  while(true){
    //get and check time element
    var timeElem = document.getElementById(spanId + "-" + count);
    //alert(spanId + "-" + count);
    ++count;
    if(!timeElem){
      //alert(spanId + "-" + count);
      break;
    }
    
    //get the message and current time
    var messageTime = parseInt(timeElem.innerHTML);
    if (messageTime != '0')
    {
      var time = currentTime - messageTime;
      //create time string
      time = Math.round(time / 1000);
      var timeString;
      if(time < 60){
        timeString = time+" " + langres_answers_seconds;
      }else{
        //get minutes
        time = Math.round(time / 60);
        if(time < 60){
          timeString = time+" " + langres_answers_minutes;
        }else{
          //get hours and minutes
          var timeHours = Math.round(time / 60);
          var timeMins = time % 60;
          if(timeHours < 24){
             timeString = timeHours + " " + langres_answers_hours + " " + timeMins + " " + langres_answers_minutes;
          }else{
            //get days
            var timeDays = Math.round(timeHours / 24);
            timeString = timeDays + " " + langres_answers_days;
          }
        }
      }
      
    
      //insert time string
      timeString = timeString + " " + langres_answers_ago + "."
      timeElem.innerHTML = timeString;
      
      //set the span visible
      timeElem.className = "timeSpan_vis";
    }
    else
    {
      // ensure zero time is hidden
      timeElem.style.display = 'none';
    }
  }
}

function setTimes(spanId){
	var count = 1;
	//set all of the message times
	//alert(spanId + "-" + count);
	var currentTime = new Date().getTime();
	while(true){
		//get and check time element
		var timeElem = document.getElementById(spanId + "-" + count);
		//alert(spanId + "-" + count);
		++count;
		if(!timeElem){
			//alert(spanId + "-" + count);
			break;
		}
		
		//get the message and current time
		var messageTime = parseInt(timeElem.innerHTML);
		var time = currentTime - messageTime;
		//create time string
		time = Math.round(time / 1000);
		var timeString;
		if(time < 60){
			timeString = time+" " + langres_answers_seconds;
		}else{
			//get minutes
			time = Math.round(time / 60);
			if(time < 60){
				timeString = time+" " + langres_answers_minutes;
			}else{
				//get hours and minutes
				var timeHours = Math.round(time / 60);
				var timeMins = time % 60;
				if(timeHours < 24){
					 timeString = timeHours + " " + langres_answers_hours + " " + timeMins + " " + langres_answers_minutes;
				}else{
					//get days
					var timeDays = Math.round(timeHours / 24);
					timeString = timeDays + " " + langres_answers_days;
				}
			}
		}
		
		//insert time string
		timeString = langres_answers_Posted + " " + timeString + " " + langres_answers_ago + "."
    var messageDate = new Date(messageTime);
    timeString += ' ' + formattedDate(messageDate);
    timeElem.innerHTML = timeString;
		
    //set the span visible
		timeElem.className = "timeSpan_vis";
	}
}

/*
	Function sends ajax request to update the thread
	read count
*/
function updateReadCount(threadId){
	spAjaxRequest(updateReadCountHandler,"/drills/IncrementReadCount.do","threadId="+threadId,"");
}

/*
	Update read count handler.
	Takes no action
*/
function updateReadCountHandler(req){
}


var updatePCount=2;
function updateQPreview()
	{
		//updatePCount++;
		//if(updatePCount%3==0){
		document.getElementById('questionPreviewTitle').innerHTML=document.askQuestionForm.title.value;
		var ed = tinyMCE.get('message');
		if(ed) { tinyMCE.triggerSave();}
		document.getElementById('questionPreviewMessage').innerHTML=removeNL(document.askQuestionForm.message.value);
		//}
	}

function setupTinyMCE() {
	tinyMCE.init({mode : "textareas",theme : "simple"});

}

