// JavaScript Document
/*----------------------------- Timeout functions --------------------------------------*/
var timeoutId;
function setUpTimeOut()
{
  if(timeoutId != null)
  {
    clearTimeout(timeoutId);
  }
  timeoutId = setTimeout("handleTimeOut()", 600000);
}
function handleTimeOut()
{
  alert("Your session will shortly expire if you do not take any action!");
}
//setUpTimeOut();
/*----------------------------- End Timeout functions --------------------------------------*/
function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}
	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}
	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}
function spWindowClose()
	{
	objOverlay = document.getElementById('overlay');
	if(objOverlay){
	 objOverlay.style.display = 'none';
	var objWindow=document.getElementById('spWindow');
	if(objWindow) 
		{		
				objWindow.style.display='none';
				objWindow.style.left=-800+'px';
		}
		showFlash();
		}
	}
// create rollunder speechBubble - appears below cursor
// SPwDITH REMOVED FOR THE MOMENT
function spSpeechBubble(spHTML,spSide,spX,spY)
	{
		  var objWindow = document.getElementById('spSpBub_'+spSide);
		  
		if(objWindow){
			objWindow.style.display = 'block';		
		}
		else {
			var objBody = document.getElementsByTagName("body").item(0);
			var objWindow = document.createElement("div");
				objWindow.setAttribute('id','spSpBub_'+spSide); // change Name 
				objWindow.className='speechBub';
				// objWindow.style.zIndex = '105';
	 			//objWindow.style.width = (spWidth+14)+'px';
				objBody.insertBefore(objWindow, objBody.firstChild);
		  
			var objTable= document.createElement('table');
				objTable.className="table_window";
			var tr = objTable.insertRow(0);
			var td = tr.insertCell(-1);
				td.className='speechBub_nw';
			// if Left
			var td = tr.insertCell(-1);
				td.className='speechBub_lpL';
		var td1 = tr.insertCell(-1);
			td1.className='speechBub_n';
			td1.style.width= '224px';
		var td2 = tr.insertCell(-1);
			td2.className='speechBub_ne';
		objWindow.appendChild(objTable);
		 var objTable= document.createElement('table');
			objTable.className="table_window";
		var tr = objTable.insertRow(0);
		var td = tr.insertCell(-1);
			td.className='speechBub_w';
		
		var tdContent = tr.insertCell(-1);
			tdContent.className='speechBub_content';
			tdContent.style.width= '248px';
			tdContent.setAttribute('id','speechBub_content_'+spSide); // change Name 
		var td = tr.insertCell(-1);
			td.className='speechBub_e';
			objWindow.appendChild(objTable);
		var objTable= document.createElement('table');
			objTable.className="table_window";
		var tr = objTable.insertRow(0);
		var td = tr.insertCell(-1);
			td.className='speechBub_sw';
		var td = tr.insertCell(-1);
			td.className='speechBub_s';
			td.style.width= '248px';
		var td = tr.insertCell(-1);
			td.className='speechBub_se';
			objWindow.appendChild(objTable);
		}
		
		
		
		if(!tdContent) {
			var tdContent=document.getElementById('speechBub_content_'+spSide);
			}
		 //tdContent.innerHTML='hello John';
		tdContent.innerHTML='<div >'+ spHTML +'</div>';
		objWindow.style.left=spX; // +'px';
	    objWindow.style.top=spY;  ///+'px';
		objWindow.style.display='block';
		//alert(objWindow.style.display+"---"+objWindow.style.top+"----"+objWindow.style.left+"----"+objWindow.innerHTML);
		
     // now need to position it
}
function spHideSpeech(spSide)
	{
	var objWindow=document.getElementById('spSpBub_'+spSide);
	if(objWindow) 
		{		
				objWindow.style.display='none';
				objWindow.style.left=-800+'px';
		}
	}
	
// Logging
function spLog(spText)
	{
		var box = document.getElementById('spLogWindow');
		if(box) box.innerHTML+='<div class="spLogEntry">'+spText+'</div>';
	}
function spSetUpLog()
	{
		var objOverlay = document.getElementById('spLogWindow');
	if(objOverlay){
		objOverlay.style.display = 'block';		
		}
	else {
		var objBody = document.getElementsByTagName("body").item(0);
		var objOverlay = document.createElement("div");
		objOverlay.setAttribute('id','spLogWindow');
		objBody.insertBefore(objOverlay, objBody.firstChild);
	  }
	}
// create overlay if doesn't exist
// create window if doesn't exist
// centre
function spWindowOpen(spHTML,spWidth)
	{
		var objOverlay = document.getElementById('overlay');
	if(objOverlay){
		objOverlay.style.display = 'block';		
		}
	else {
		var objBody = document.getElementsByTagName("body").item(0);
		
		// create overlay div and hardcode some functional styles (aesthetic styles are in CSS file)
		var objOverlay = document.createElement("div");
		objOverlay.setAttribute('id','overlay');
		objOverlay.onclick = function () { /*hideLightbox();*/ return false;}
		objOverlay.style.display = 'block';
		objOverlay.style.position = 'absolute';
		objOverlay.style.top = '0';
		objOverlay.style.left = '0';
		objOverlay.style.zIndex = '90';
	 	objOverlay.style.width = '100%';
		objBody.insertBefore(objOverlay, objBody.firstChild);
		}
	var arrayPageSize = getPageSize();
		objOverlay.style.height = (arrayPageSize[1] + 'px');
		objOverlay.style.display = 'block';
		var myWidth = 0, myHeight = 0;
				if( typeof( window.innerWidth ) == 'number' ) {
					    myWidth = window.innerWidth;
					    myHeight = window.innerHeight;
				} 
				else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
				    //IE 6+ in 'standards compliant mode'
				    myWidth = document.documentElement.clientWidth;
				    myHeight = document.documentElement.clientHeight;
				  } 
				else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
				    //IE 4 compatible
				    myWidth = document.body.clientWidth;
				    myHeight = document.body.clientHeight;
				  }
	
	  var objWindow = document.getElementById('spWindow');
	if(objWindow){
		objWindow.style.display = 'block';		
		}
	else {
		var objWindow = document.createElement("div");
			objWindow.setAttribute('id','spWindow'); // change Name 
			objWindow.className='dialog'
			objWindow.style.zIndex = '110';
	 		objWindow.style.width = (spWidth+14)+'px';
			objBody.insertBefore(objWindow, objBody.firstChild);
		
		var objCloseButton = document.createElement("div");
		objCloseButton.onclick = function () { /*hideLightbox();*/ spWindowClose();return false;}
		objCloseButton.setAttribute('id','windowClose');
		objCloseButton.className='alphacube_close';
//			<%-- <div onclick="Windows.minimize("window_1200070628703", event)" id="window_1200070628703_minimize" class="alphacube_minimize"> </div> 
		//	<%-- <div onclick="Windows.maximize("window_1200070628703", event)" id="window_1200070628703_maximize" class="alphacube_maximize"> </div> --%>
		objWindow.appendChild(objCloseButton);
		
		
		var objTable= document.createElement('table');
		
		objTable.className="top table_window";
		var tr = objTable.insertRow(0);
		var td = tr.insertCell(-1);
			td.className='alphacube_nw';
		var td1 = tr.insertCell(-1);
			td1.className='alphacube_n';
			td1.style.width= spWidth+'px';
		var td2 = tr.insertCell(-1);
			td2.className='alphacube_ne';
			
		
		objWindow.appendChild(objTable);
		 var objTable= document.createElement('table');
			objTable.className="mid table_window";
		var tr = objTable.insertRow(0);
		var td = tr.insertCell(-1);
			td.className='alphacube_w';
		var tdContent = tr.insertCell(-1);
			tdContent.className='alphacube_content';
			tdContent.style.width= spWidth+'px';
			tdContent.setAttribute('id','table_content'); // change Name 
		var td = tr.insertCell(-1);
			td.className='alphacube_e';
			objWindow.appendChild(objTable);
		var objTable= document.createElement('table');
			objTable.className="bot table_window";
		var tr = objTable.insertRow(0);
		var td = tr.insertCell(-1);
			td.className='alphacube_sw';
		var td = tr.insertCell(-1);
			td.className='alphacube_s';
			td.style.width= spWidth+'px';
		var td = tr.insertCell(-1);
			td.className='alphacube_se';
			objWindow.appendChild(objTable);
		}
		
		
		
		if(!tdContent) {
			var tdContent=document.getElementById('table_content');
			}
		 //tdContent.innerHTML='hello John';
		tdContent.innerHTML='<div style="width:'+ spWidth + 'px;">'+ spHTML +'</div>';
			
		
		var IpopTop = (myHeight - objWindow.offsetHeight) / 2;
		var IpopLeft = (myWidth - objWindow.offsetWidth) / 2;
		
			  if(IpopTop<20) IpopTop=20;
  		        objWindow.style.left=(IpopLeft + document.body.scrollLeft+ document.documentElement.scrollLeft)+'px';
		        objWindow.style.top=(IpopTop + document.body.scrollTop + document.documentElement.scrollTop)+'px';
				
	}
function spTableRow(label,formHTML)
	{
		var result='';
		result+='<tr><td nowrap>'+label+'</td>';
		result+='<td nowrap>'+formHTML+'</td></tr>';
		return result;
	}
function spRadioBut(id,label,spName,spValue,spChecked)
	{
		var result='';
		result+='<label for="'+id+'" class="false_cursor">'+label+' <input id="'+id+'" name="'+spName+'" type="radio" value="'+spValue+'" '+spChecked+'></label> ';
		return result;
	}
function spOption(spValue,spLabel,spChecked)
	{
		var result='';
		result+='<option value="'+spValue+'" '+spChecked+'>'+spLabel+'</option>';
		return result;
	}
/*
	Create a sportplan button
	
	spButLabel - The text to be displayed in the button
	spButOnClick - The function to be called when button pressed
	spButId - The Id to be given to the button div
	spButAlign - The class to be given to the button div
*/
function spButton(spButLabel,spButOnClick,spButId,spAlign)
{
  var spHTML='';
  spHTML+='<div id="'+spButId+'" onclick="'+spButOnClick+'" class="spButtonDiv_'+spAlign+'" >'; // align="left"
  spHTML+='<table width="10" border="0" cellspacing="0" cellpadding="0"><tr>';
  spHTML+='<td><img src="/ltad/app/images/sGreyButleft.gif" align="absmiddle" ></td>';
  spHTML+='<td nowrap class="spButton_c">&nbsp;'+spButLabel+'&nbsp;</td>';
  spHTML+='<td><img src="/ltad/app/images/sGreyButRight.gif" align="top" ></td>';
  spHTML+='</tr></table></div>';
  return spHTML;
}

/*
	The request variable has been
	made golbal so a request can
	be aborted if the user navigates
	to a different page.
*/
var req = null;
/*
	Function aborts any current
	ajax request
*/
function spAbortAjaxRequest(){
	if(req != null){
		try{
			/*
				Have to reassign onreadystatechange call back
				function otherwise when the request is aborted
				it calls the previously assigned callback
				function with the previously retrieved data.
		  	*/
			req.onreadystatechange = function(){};
			req.abort();
		}catch(e){
		}
	}
}
/*
*/
function spAjaxRequest(spHandler,spAction,spParams,box){
	//reset session timeout timer
	//setUpTimeOut();
	req = newXMLHttpRequest();
	var handlerFunction = getReadyStateHandlerResponse(req, spHandler);
	req.onreadystatechange = handlerFunction;
	req.open("POST", spAction+";"/*jsessionid="+jSession*/, true);
	spLog(spAction+" - "+spParams);
	req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	req.send(spParams);
	
	if(box) box.innerHTML='<div id="loadingImage"></div>';
}
/// Sportplan Ajac Request with Token
// spHandler = handler function
// spAction = .do on server
// sp Params = paremeters for .do action
// Id = token to pass back with response
// box = div to fill with loading Icon
function spAjaxRequestWithId(spHandler,spAction,spParams,Id,boxId){
	req = newXMLHttpRequest();
	var handlerFunction = getSportplanReadyStateHandlerResponse (req, Id, spHandler)
	req.onreadystatechange = handlerFunction;
	req.open("POST", spAction+";jsessionid="+jSession, true);
	spLog(spAction+" - "+spParams);
	req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	req.send(spParams);
  var box = document.getElementById(boxId);
	if(box) box.innerHTML='<span class="loadingImage"></span>';
	//else alert("notFound "+spLoadingId);
		
}
function removeAmpersands (note)
{
  if (note != null)
  {
    var i = note.indexOf("&");
    while(i >= 0)
    {
      note = note.substring(0,i) + "%26" + note.substring(i+1,note.length);
      i = note.indexOf("&");
    }
  }
  return note;
}
function collectVariables(thisForm)
	{
		var theString='';
		 var element;
		for(var i = 0; i < thisForm.elements.length; i++)
			  {
		    element = thisForm.elements[i];
		    if(element != null)
			    {
		        if(element.type == 'radio')
		        {
        		  if(element.checked)
			          {
            			theString += element.name + '=' + removeAmpersands(element.value) + '&';
			          }
		        }
        		else
		        {
        		  theString += element.name + '=' + removeAmpersands(element.value) + '&';
		        }
		    }
		  }
		 theString = theString.split("?").join("");
   	    theString = theString.split("'").join("");
		 return theString;
	}
	
/*
 * Returns a new XMLHttpRequest object, or false if this browser
 * doesn't support it
 */
function newXMLHttpRequest()
{
  var xmlreq = false;
  if (window.XMLHttpRequest)
  {
    // Create XMLHttpRequest object in non-Microsoft browsers
    xmlreq = new XMLHttpRequest();
  }
  else if (window.ActiveXObject)
  {
    // Create XMLHttpRequest via MS ActiveX
    try
    {
      // Try to create XMLHttpRequest in later versions
      // of Internet Explorer
      xmlreq = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e1)
    {
      // Failed to create required ActiveXObject
      try
      {
        // Try version supported by older versions
        // of Internet Explorer
        xmlreq = new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch (e2)
      {
        // Unable to create an XMLHttpRequest with ActiveX
      }
    }
  }
  return xmlreq;
}
/*
 * Exactly the same as the default readyStateHandler above but with
 * an additional param accepted to pass through to the responseXmlHandle function
 * req - The XMLHttpRequest whose state is changing
 * param - additional paramater passed through to the repsonseXmlHandler
 * responseXmlHandler - Function to pass the XML response to
 */
function getSportplanReadyStateHandlerResponse (req, param, responseXmlHandler)
{
  // Return an anonymous function that listens to the 
  // XMLHttpRequest instance
  return function ()
  {
    // If the request's status is "complete"
    if (req.readyState == 4)
    {
      
      // Check that a successful server response was received
      if (req.status == 200)
      {
        // Pass the XML payload of the response to the 
        // handler function
        responseXmlHandler(req, param);
      }
      else
      {
        // An HTTP problem has occurred
        alert("HTTP error: "+req.status+"\n'"+req.statusText+"'");
        
      }
    }
  }
}
/*
 * Returns a function that waits for the specified XMLHttpRequest
 * to complete, then passes its XML response
 * to the given handler function.
 * req - The XMLHttpRequest whose state is changing
 * responseXmlHandler - Function to pass the XML response to
 */
function getReadyStateHandlerXML(req, responseXmlHandler)
{
  // Return an anonymous function that listens to the 
  // XMLHttpRequest instance
  return function ()
  {
    // If the request's status is "complete"
    if (req.readyState == 4)
    {
      
      // Check that a successful server response was received
      if (req.status == 200)
      {
        // Pass the XML payload of the response to the 
        // handler function
        responseXmlHandler(req.responseXML);
      }
      else
      {
        // An HTTP problem has occurred
        alert("HTTP error: "+req.status+"\n'"+req.statusText+"'");
      }
    }
  }
}
  
  
/*
 * Returns a function that waits for the specified XMLHttpRequest
 * to complete, then passes its response
 * to the given handler function.
 * req - The XMLHttpRequest whose state is changing
 * responseXmlHandler - Function to pass the XML response to
 */
function getReadyStateHandlerResponse(req, responseXmlHandler)
{
  // Return an anonymous function that listens to the 
  // XMLHttpRequest instance
  return function ()
  {
	try{
	    // If the request's status is "complete"
	    if (req.readyState == 4)
	    {
	      
	      // Check that a successful server response was received
	      if (req.status == 200)
	      {
	
	        //check if an error was returned
	        if(req.getResponseHeader('error')){
	        	window.location = errorPage;
	        	return;
	        }
	        
	        //check if the user session has timed out
	        if(req.getResponseHeader('timeout')){
	        	alert("Your server session has timed out!\n\nYou will be redirected to the login page.");
	        	window.location = timeoutPage;
	        	return;
	        }
	        
	        // Pass the XML payload of the response to the 
	        // handler function
	        responseXmlHandler(req);
	
	      }
	      else
	      {
	        // An HTTP problem has occurred
	        alert("HTTP error: "+req.status+"\n'"+req.statusText+"'\n\nThe application will now be reloaded.");
	        window.location = errorPage;
	        return;
	      }
      	}
      }catch(e){}
  }
}
/*
	On Error function displays
	msg and takes any action to
	restore program to consistant
	state.
*/
function hpError(msg){
	alert(msg);
	//should prob redirect to a safe page
}
/*
	Function finds elements by class name
*/
function getElementsByClassName(classname, node) {
	if(!node) node = document.getElementsByTagName("body")[0];
	var a = [];
	var re = new RegExp('\\b' + classname + '\\b');
	var els = node.getElementsByTagName("*");
	for(var i=0,j=els.length; i<j; i++)
	if(re.test(els[i].className))a.push(els[i]);
	return a;
}
// Toggle Divs
// basic funtion to show hide
// block1 show
// block 2 hide
function toggleDivs(block1,block2)
	{
	var box= document.getElementById(block1);
	if(box) box.style.display="block";
		var box= document.getElementById(block2);
	if(box) box.style.display="none";
	}
