/*================================================================
 * Ajax functions
 *================================================================*/
 
var ajax = new AjaxClient();
 
function AjaxClient()
{
	var request = getXMLHttpRequest();
	var calloutDestElement;
	var calloutOffsetTop;
	var calloutOffsetLeft;
	var calloutOverwriteElement;
	
	this.getSingleSpan = function( url )
	{
		this.get( url, replaceSingleSpan );
	}

	this.submitFormCallout = function( url, formName, offsetElement, destElement, offsetTop, offsetLeft )
	{
	    url=url+getFormAsString( formName );
		this.callout( url, offsetElement, destElement, offsetTop, offsetLeft );
	}

	this.submitFormGet = function( url, formName )
	{
	    url += '&' + getFormAsString( formName );
		this.get( url, updateSpans );
	}

	this.submitFormPost = function( url, formName )
	{
	    var params = getFormAsString( formName );
		this.post( url, params, updateSpans );
	}
	
	this.get = function( url, callback )
	{
		request.open( "GET", url, true );
      	request.onreadystatechange = callback;
      	request.send(null);
	}

	this.getSync = function( url, callback )
	{		
		request.open( "GET", url, false );
      	request.onreadystatechange = callback;
      	request.send(null);      	      	
	}

	this.post = function( url, params, callback )
	{
		request.open( "POST", url, true );
      	request.onreadystatechange = callback;
		request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
      	request.send(params);
	}
	
	this.callout = function( url, offsetElement, destElement, offsetTop, offsetLeft )
	{
		calloutDestElement = destElement;
		calloutOffsetTop = getOffset( offsetElement, "offsetTop" ) + offsetTop;
		calloutOffsetLeft = getOffset( offsetElement, "offsetLeft" ) + offsetElement.offsetWidth + offsetLeft;

		this.get( url, processCallout );
	}

	this.calloutReplace = function( url, overwriteElement, destElement )
	{		
		calloutDestElement = destElement;
		calloutOverwriteElement = overwriteElement;
		url = url + "&overwrite=" + overwriteElement.id;
		
		
		this.getSync( url, processCalloutReplace );
		//this.getSync( url, callBackTest );
	}
	
	
	
	function callBackTest(){alert('Buttlick');}
	
	this.calloutRestore = function( calloutDiv, restoreDiv )
	{
		calloutDivElm = document.getElementById( calloutDiv );
		restoreDivElm = document.getElementById( restoreDiv );
		calloutDivElm.style.display = "none";
		restoreDivElm.style.display = "block";
	}

	this.calloutClose = function( calloutDiv )
	{
		calloutDivElm = document.getElementById( calloutDiv );
		calloutDivElm.style.display = 'none';
	}
	
	function processCallout() 
	{		
  	  	if (request.readyState == 4) // Request complete
  	  	{ 
	      	if (request.status == 200) // OK response
	      	{
	      		calloutDestElement.style.display = 'none';
	      		calloutDestElement.innerHTML = request.responseText;
	      		calloutDestElement.style.top = calloutOffsetTop + "px";
	      		calloutDestElement.style.left = calloutOffsetLeft + "px";
	      		calloutDestElement.style.display = 'block';
      	  	} 
      	  	else 
          	{
            	//alert("Problem with server response:\n " + req.statusText + " status=" + req.status);
          	}
      	}
	}
		
	function processCalloutReplace() 
	{		
		//alert('got here');
  	  	if (request.readyState == 4) // Request complete
  	  	{ 
	      	if (request.status == 200) // OK response
	      	{
				calloutOverwriteElement.style.display = 'none';
	      		calloutDestElement.style.display = 'none';
	      		calloutDestElement.innerHTML = request.responseText;
	      		calloutDestElement.style.display = 'inline';
      	  	} 
      	  	else 
          	{
            	alert("Problem with server response:\n " + req.statusText + " status=" + req.status);
          	}
      	}
	}

	function replaceSingleSpan() 
	{
  	  	if (request.readyState == 4) // Request complete
  	  	{ 
	      	if (request.status == 200) // OK response
	      	{
				//debugResponse(request);         
       			// alert("Ajax response:"+request.responseText);
       			results = trim(request.responseText);

        		if ( results.substring(0, 12) == "AJAX_RESULTS" )
        		{
					var spanStart = results.indexOf("<span");
					var spanEnd = results.lastIndexOf("</span>");
					var spanContents = results.substring( spanStart, spanEnd );
					var spanBodyStart = spanContents.indexOf(">") + 1;
					var spanTag = spanContents.substring( 0, spanBodyStart );
					var spanBody = spanContents.substring( spanBodyStart );
					var spanID = spanTag.substring( spanTag.indexOf("id=") + 4 );
					spanID = spanID.substring( 0, spanID.indexOf("\""));
					var spanElm = document.getElementById( spanID );
					spanElm.innerHTML = spanBody;
        		}
				else	// Session timed out
				{
					window.location.href="/index.php";
				}
      	  	} 
      	  	else 
          	{
            	//alert("Problem with server response:\n " + req.statusText + " status=" + req.status);
          	}
      	}
	}

	function updateSpans() 
	{
  	  	if (request.readyState == 4) // Request complete
  	  	{ 
	      	if (request.status == 200) // OK response
	      	{
				//debugResponse(request);         
       			// alert("Ajax response:"+request.responseText);
       			results = trim(request.responseText);

        		if ( results.substring(0, 12) == "AJAX_RESULTS" )
        		{
	        		//Split the text response into Span elements
	        		spanElements = splitTextIntoSpan(results);
	        
	        		//Use these span elements to update the page
	        		replaceExistingWithNewHtml(spanElements);
        		}
				else	// Session timed out
				{
					window.location.href="/index.php";
				}
      	  	} 
      	  	else 
          	{
            	//alert("Problem with server response:\n " + req.statusText + " status=" + req.status);
          	}
      	}
	}
 
   /**
  	* gets the contents of the form as a URL encoded String
  	* suitable for appending to a url
  	* @param formName to encode
  	* @return string with encoded form values , beings with &
  	*/ 
 	function getFormAsString(formName)
 	{
	 	//Setup the return String
	 	returnString ="";
	 	
	  	//Get the form values
	 	formElements=document.forms[formName].elements;
	 	
	 	//loop through the array , building up the url
	 	
	 	for ( var i=formElements.length-1; i>=0; --i )
	 	{
	 		//we escape (encode) each value
			if ( formElements[i].type != 'checkbox' || formElements[i].checked )
			{
				var delimeter = i==(formElements.length-1) ? "" : "&";
				returnString=returnString+delimeter+escape(formElements[i].name)+"="+escape(formElements[i].value);
			}
	 	}
	 	//return the values
	 	return returnString; 
 	}
 
   /**
 	* Splits the text into <span> elements
 	* @param the text to be parsed
 	* @return array of <span> elements - this array can contain nulls
 	*/
 	function splitTextIntoSpan(textToSplit)
 	{
	  	//Split the document
	 	returnElements=textToSplit.split("</span>")
	 	
	 	//Process each of the elements 	
	 	for ( var i=returnElements.length-1; i>=0; --i ){
	 		//Remove everything before the 1st span
	 		spanPos = returnElements[i].indexOf("<span");		
	 		
	 		//if we find a match , take out everything before the span
	 		if(spanPos>0){
	 			subString=returnElements[i].substring(spanPos);
	 			returnElements[i]=subString;
	 		} 
	 	}
	 	return returnElements;
 	}
 
   /*
  	* Replace html elements in the existing (ie viewable document)
  	* with new elements (from the ajax requested document)
  	* WHERE they have the same name AND are <span> elements
  	* @param newTextElements (output of splitTextIntoSpan)
  	*					in the format <span id=name>texttoupdate
    */
 	function replaceExistingWithNewHtml(newTextElements)
 	{
 
	 	//loop through newTextElements
	 	for ( var i=newTextElements.length-1; i>=0; --i )
	 	{
	 		//check that this begins with <span
	 		if(newTextElements[i].indexOf("<span")>-1)
	 		{
	 			//get the name - between the 1st and 2nd quote mark
	 			startNamePos=newTextElements[i].indexOf('"')+1;
	 			endNamePos=newTextElements[i].indexOf('"',startNamePos);
	 			name=newTextElements[i].substring(startNamePos,endNamePos);
					
	 			//get the content - everything after the first > mark
	 			startContentPos=newTextElements[i].indexOf('>')+1;
	 			content=newTextElements[i].substring(startContentPos);
	 			//Now update the existing Document with this element
	 			
		 			//check that this element exists in the document
		 			if(document.getElementById(name))
		 			{
		 			
		 				//alert("Replacing Element:"+name);
		 				document.getElementById(name).innerHTML = content;
		 			} 
		 			else 
		 			{
		 				//alert("Element:"+name+"not found in existing document");
		 			}
	 		}
	 	}
 	}
 
 	function getXMLHttpRequest()
	{
	    if (window.XMLHttpRequest) 
	      return new XMLHttpRequest();  // Non-IE browsers
	    else if (window.ActiveXObject) 
	      return new ActiveXObject("Microsoft.XMLHTTP");   // IE
		else
			return null;
    }

	function getOffset( element, attribute )
	{
		var offset = 0;
		while( element )
		{
			offset += element[attribute];
			element = element.offsetParent;
		}
		return offset;
	}
	
	function trim( string )
	{
		var s = string;
	
		s = s.replace(/^\s+|\s+$/g, '');
		return s;
	}
	    
    function debugResponse( request )
    {
		// debugging code
		var newWindow = null;
		var windowWidth = 700;
		var windowHeight = ( screen.availHeight - 120 );
		var windowLeftPosition = ( screen.availWidth - windowWidth ) / 2;
		var windowTopPosition = ( screen.availHeight - windowHeight ) / 2 - 40;

		newWindow = window.open ("","HelpWindow","width=" + windowWidth + ",height=" + windowHeight + ',left=' + windowLeftPosition + ',top=' + windowTopPosition + ",toolbar=yes,resizable=yes,scrollbars=yes");	
		newWindow.document.write( request.responseText );
		if ( newWindow && newWindow.closed ){
			newWindow.focus();
		}
    }
    
    return this;
}
