//-- ajaxStruts.js
//-- 10/01/07 Mathieu Cathary
/*
function setResultContener(id)
function checkRuningConnections()
function retrieveURLwithForm(url,mode,argument,nameOfFormToPost) 
function retrieveURL(url,mode,argument)
function makeCall(url,mode,argument) 
function processStateChange()
function getFormAsString(formName)
function splitTextIntoSpan(textToSplit)
function replaceExistingWithNewHtml(newTextElements)
progressBar.on: function(elementId)
progressBar.off: function()
*/


/* global variables */
/* l'objet XML HttpRequest */
var req;
/* */
var which;
/* id du conteneur du resultat */
var where;

/**
 * détermine le conteneur du résultat
 */
function setResultContener(id) 
{
	where=id;
} 

/**	"submission throttling" pour eviter les requetes
 *	trop nombreuses envoyées au serveur 
 */	
/* Temps à attendre avant d'envoyer la requete */
var WAIT_TIME = 300;
/* handler du setTimeOut */
var submitURLHandler = null;

/**
 * Check if a connection is running :
 *	- abort a query if req object is not null
 *	- abort setTimout for the url submission
 */
function checkRuningConnections() 
{
	/* Check for running connections */
	if (req != null && req.readyState != 0 && req.readyState != 4) {
		// req.abort();
	} 

	/* If a query is running, abort it */
	if (submitURLHandler != null) {
		clearTimeout(submitURLHandler);
		submitURLHandler = null;
	}
}


/**
* Get the contents of the URL via an Ajax call
* url - to get content from (e.g. /struts-ajax/sampleajax.do?ask=COMMAND_NAME_1) 
* nodeToOverWrite - when callback is made
* nameOfFormToPost - which form values will be posted up to the server as part 
*					of the request (can be null)
*/
function retrieveURLwithForm(url,mode,argument,nameOfFormToPost) 
{
	/* get the (form based) params to push up as part of the get request */
	argument = argument + getFormAsString(nameOfFormToPost)
	/* Check for running connections */
	checkRuningConnections();
	/* display de progressbar */
	progressBar.on("results");            
	/* submit the url in WAIT_TIME miliseconds */
	submitURLHandler = setTimeout("makeCall('" + url + "','" + mode + "','" + argument + "')",WAIT_TIME);
}

/**
* Get the contents of the URL via an Ajax call
* url - to get content from (e.g. /struts-ajax/sampleajax.do?ask=COMMAND_NAME_1) 
* nodeToOverWrite - when callback is made
* nameOfFormToPost - which form values will be posted up to the server as part 
*					of the request (can be null)
*/
function retrieveURL(url,mode,argument) 
{
	/* Check for running connections */
	checkRuningConnections();
	/* display de progressbar */
	progressBar.on("results");            
	/* submit the url in WAIT_TIME miliseconds */
	submitURLHandler = setTimeout("makeCall('" + url + "','" + mode + "','" + argument + "')",WAIT_TIME);
}

/**
 * Make ajax Call
 */
function makeCall(url,mode,argument) 
{
	//Do the Ajax call
	if (window.XMLHttpRequest) 
	{ // Non-IE browsers
	  req = new XMLHttpRequest();
	}
	else if (window.ActiveXObject) 
	{ // IE	      
	  req = new ActiveXObject("Microsoft.XMLHTTP");
	}
	else
	{
		alert('Ajax non supporte');
		return;
	}
	req.onreadystatechange = processStateChange;
	req.open(mode, url, true);
	req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	req.send(argument);
}

/*
 * Set as the callback method for when XmlHttpRequest State Changes 
 * used by retrieveUrl
 */
function processStateChange() 
{  
	if (req != null) 
	{
		if (req.readyState == 4) 
		{ // Complete
			if (req.status == 200) 
			{ // OK response
				progressBar.off();
				var js_d=req.responseText.indexOf('@@DEBUT_JS@@',0);
				if(js_d != -1)
				{
					var js_f=req.responseText.indexOf('@@FIN_JS@@',0);
				}
				if(js_d != -1)
				{
					if(where!='noContener') document.getElementById(where).innerHTML=req.responseText.substring(0,js_d);
					eval(req.responseText.substring(js_d+12,js_f));
				}
				else if(where!='noContener') document.getElementById(where).innerHTML=req.responseText;
				else eval(req.responseText);
			}
			else alert("Problem with server response:\n " + req.statusText);
			
			req = null;
		}
	}
}

/**
* 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
	//in the form /strutsaction.do&name=value
	
	for ( var i=formElements.length-1; i>=0; --i ){
		//we escape (encode) each value
		if (formElements[i].type == "checkbox") {
			if (formElements[i].checked == true) {
				returnString=returnString+"&"+escape(formElements[i].name)+"="+escape(formElements[i].value);
			}
		} else {
			returnString=returnString+"&"+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");
			}
	}
}
}


/**
* display an image in the target container while loading
*/
var progressBar = {
	
	isLoading: false,
	elementContainer: null,
	/**************************************************************************
		PUBLIC METHODS
	*************************************************************************/
	
	on: function(elementId) {
		// if we're not loading something yet...
		if (this.elementContainer == null)
		{
			this.elementContainer = document.getElementById(elementId);
			// if the elementContainer is not null
			if (this.elementContainer != null) {
				this.elementContainer.innerHTML = "<div align='center'><img src='/gladmin/images/gears.gif' alt='in progress' /></div>";
			}
		}
	},
	off: function() {
		// delete the content of the container
		if (this.elementContainer != null) {
			this.elementContainer.innerHtml = "";
			this.elementContainer = null;
		}
	}
}


/**
* wait x ms
*/
function mywait(millis)
{
	date = new Date();
	var curDate = null;
	
	do { var curDate = new Date(); }
	while(curDate-date < millis);
}

