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


/*
 * 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('Cannot process update at this time.');
    spWindowClose();
  }
}


/*
 * delete the selected answer
 */
function deleteAnswer (answerId)
{
  if (confirm('Are you sure you want to delete this answer?'))
  {
    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('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\');">View/Print Preview</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>Please select print layout</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;">templates designed for A4 paper<br/> NB if you have a pop-up blocker please hold down CTRL when choosing template</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>Select a practice:</strong> (click on thumbnail to select)';
  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>Selected Attachment</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>Selected Attachment</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('Loading My Stuff sessions...<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>Select a 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>Selected Attachment</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'){
			
		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>Select sport:</strong> " + sportDrop;
	document.getElementById("categories").innerHTML = "<strong>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>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>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("You haven't entered a question!");
		return false;
	}
  
  if (titlebox.value.indexOf("Ask a question and have it answered") > -1)
  {
    alert("Please enter an alternative short summary title for the question at the top.");
    titlebox.focus();
    titlebox.select();
    return false;
  }
	
	if(messagebox.value == ""){
		alert("You haven't entered a question body!");
		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("please select a category");return false;}
  var selectedCategory = categorySelect.options[categorySelect.selectedIndex].text;
  
  if(confirm('Ask this question under the ' + selectedSport + ' category called \'' + 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("You haven't entered an answer!");
		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] = 'January';
calendarMonths[calendarMonths.length] = 'Feburary';
calendarMonths[calendarMonths.length] = 'March';
calendarMonths[calendarMonths.length] = 'April';
calendarMonths[calendarMonths.length] = 'May';
calendarMonths[calendarMonths.length] = 'June';
calendarMonths[calendarMonths.length] = 'July';
calendarMonths[calendarMonths.length] = 'August';
calendarMonths[calendarMonths.length] = 'September';
calendarMonths[calendarMonths.length] = 'October';
calendarMonths[calendarMonths.length] = 'November';
calendarMonths[calendarMonths.length] = '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+" seconds";
      }else{
        //get minutes
        time = Math.round(time / 60);
        if(time < 60){
          timeString = time+" minutes";
        }else{
          //get hours and minutes
          var timeHours = Math.round(time / 60);
          var timeMins = time % 60;
          if(timeHours < 24){
             timeString = timeHours + " hours " + timeMins + " minutes";
          }else{
            //get days
            var timeDays = Math.round(timeHours / 24);
            timeString = timeDays + " days";
          }
        }
      }
      
    
      //insert time string
      timeString = timeString + " 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+" seconds";
		}else{
			//get minutes
			time = Math.round(time / 60);
			if(time < 60){
				timeString = time+" minutes";
			}else{
				//get hours and minutes
				var timeHours = Math.round(time / 60);
				var timeMins = time % 60;
				if(timeHours < 24){
					 timeString = timeHours + " hours " + timeMins + " minutes";
				}else{
					//get days
					var timeDays = Math.round(timeHours / 24);
					timeString = timeDays + " days";
				}
			}
		}
		
		//insert time string
		timeString = "Posted " + timeString + " 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"});

}
