/**
 * Ajax.js
 *
 * Collection of Scripts to allow in page communication from browser to (struts) server
 * ie can reload part instead of full page
 *
 * How to use
 * ==========
 * 1) Call retrieveURL from the relevant event on the HTML page (e.g. onclick)
 * 2) Pass the url to contact (e.g. Struts Action) and the name of the HTML form to post
 * 3) When the server responds ...
 *		 - the script loops through the response , looking for <span id="name">newContent</span>
 * 		 - each <span> tag in the *existing* document will be replaced with newContent
 *
 * NOTE: <span id="name"> is case sensitive. Name *must* follow the first quote mark and end in a quote
 *		 Everything after the first '>' mark until </span> is considered content.
 *		 Empty Sections should be in the format <span id="name"></span>
 */

//global variables
  var req;
  var which;
  var spanAc;
  var postURLGet;
  var elementNameMod;


  /**
   * 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 retrieveURL2(url,nameOfFormToPost,spanAction) {
  
    //get the (form based) params to push up as part of the get request
    url=url+getFormAsString(nameOfFormToPost);
	spanAc = spanAction;
	document.getElementById(spanAction).innerHTML ="<img src='/imagen/ajax/indicator.gif'/>";
    //Do the Ajax call
    if (window.XMLHttpRequest) { // Non-IE browsers
      req = new XMLHttpRequest();
      req.onreadystatechange = processStateChange2;
      try {
      	req.open("GET", url, true); //was get
      } catch (e) {
        alert("Problem Communicating with Server\n"+e);
      }
      req.send(null);
    } else if (window.ActiveXObject) { // IE
      
      req = new ActiveXObject("Microsoft.XMLHTTP");
      if (req) {
        req.onreadystatechange = processStateChange2;
        req.open("GET", url, true);
        req.send();
      }
    }
  }
  
  function waitMM() {
    if (req.readyState == 4) {
    	if (req.status == 200) {
    	  setCookieTol(newLocale);
    	  location.reload()
      }
    }
  }
  
function setCookieTol (value) {
  var expires = 365 * 1000 * 60 * 60 * 24;
  var today = new Date();
  today.setTime( today.getTime() );

  var expires_date = new Date( today.getTime() + (expires) );


  document.cookie = "tolLocale=" + escape (value) + "; expires=" + expires_date.toGMTString() + ";path=/";

}
var newLocale;
  function changeLocale(url, locale) {
  
    newLocale = locale;
    //Do the Ajax call
    if (window.XMLHttpRequest) { // Non-IE browsers
      req = new XMLHttpRequest();
      
      req.onreadystatechange = waitMM;
      try {
      	req.open("GET", url, true); //was get
      } catch (e) {
        alert("Problem Communicating with Server\n"+e);
      }
      req.send(null);
    } else if (window.ActiveXObject) { // IE
      
      req = new ActiveXObject("Microsoft.XMLHTTP");      
      if (req) {
        req.onreadystatechange = waitMM;
        req.open("GET", url, true);
        req.send();
      }
    }
  }
  
  function remainSession(url) {
  
    //Do the Ajax call
    if (window.XMLHttpRequest) { // Non-IE browsers
      req = new XMLHttpRequest();
      try {
      	req.open("GET", url, true); //was get
      } catch (e) {
        alert("Problem Communicating with Server\n"+e);
      }
      req.send(null);
    } else if (window.ActiveXObject) { // IE
      
      req = new ActiveXObject("Microsoft.XMLHTTP");
      if (req) {
        req.open("GET", url, true);
        req.send();
      }
    }
  }
  
  /*
   * Set as the callback method for when XmlHttpRequest State Changes 
   * used by retrieveUrl
  */
  function processStateChange2() {
  	  if (req.readyState == 4) { // Complete
      if (req.status == 200) { // OK response
        
        //alert("Ajax response:"+req.responseText);
        //Split the text response into Span elements
        spanElements = splitTextIntoSpan(req.responseText);
        
        //Use these span elements to update the page
        replaceExistingWithNewHtml2(spanElements);
        
      } else {
        alert("Problem with server response:\n " + req.statusText);
      }
    }
  }
  
  function retrieveURL3(url,nameOfFormToPost, spanAction, postGet) {
    //get the (form based) params to push up as part of the get request
    var passData=getFormAsString(nameOfFormToPost);
	postURLGet = postGet;
	spanAc = spanAction;
    //Do the Ajax call
    if (window.XMLHttpRequest) { // Non-IE browsers
      req = new XMLHttpRequest();
      req.onreadystatechange = processStateChange;
      try {
      	req.open("POST", url, true); //was get
      	req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      	req.setRequestHeader("Content-length",passData.length);
      } catch (e) {
        alert("Problem Communicating with Server\n"+e);
      }
      document.getElementById(spanAction).innerHTML ="<img src='/imagen/ajax/indicator.gif'/>";
      req.send(passData);
    } else if (window.ActiveXObject) { // IE
      
      req = new ActiveXObject("Microsoft.XMLHTTP");
      if (req) {
        req.onreadystatechange = processStateChange;
        req.open("POST", url, true); //was get
      	req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      	req.setRequestHeader("Content-length",passData.length);
      	document.getElementById(spanAction).innerHTML ="<img src='/imagen/ajax/indicator.gif'/>";
        document.getElementById(spanAc).style.backgroundColor='#FFFFFF';
        req.send(passData);
      }
    }
  }
  
  function retrieveURL4(url,nameOfFormToPost, spanAction, elementName2) {
  
    elementNameMod = elementName2;
    //get the (form based) params to push up as part of the get request
    var passData=getFormAsString(nameOfFormToPost);
	spanAc = spanAction;
    //Do the Ajax call
    if (window.XMLHttpRequest) { // Non-IE browsers
      req = new XMLHttpRequest();
      req.onreadystatechange = processStateChange;
      try {
      	req.open("POST", url, true); //was get
      	req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      	req.setRequestHeader("Content-length",passData.length);
      } catch (e) {
        alert("Problem Communicating with Server\n"+e);
      }
      document.getElementById(spanAction).innerHTML ="<img src='/imagen/ajax/indicator.gif'/>";
      req.send(passData);
    } else if (window.ActiveXObject) { // IE
      
      req = new ActiveXObject("Microsoft.XMLHTTP");
      if (req) {
        req.onreadystatechange = processStateChange;
        req.open("POST", url, true); //was get
      	req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      	req.setRequestHeader("Content-length",passData.length);
      	document.getElementById(spanAction).innerHTML ="<img src='/imagen/ajax/indicator.gif'/>";
        document.getElementById(spanAc).style.backgroundColor='#FFFFFF';
        req.send(passData);
      }
    }
  }
  function retrieveURL(url) {
    
    //Do the Ajax call
    if (window.XMLHttpRequest) { // Non-IE browsers
      req = new XMLHttpRequest();
      req.onreadystatechange = processStateChange;
      try {
      
      	req.open("GET", url, true); //was get
      } catch (e) {
        alert("Problem Communicating with Server\n"+e);
      }
      req.send(null);
    } else if (window.ActiveXObject) { // IE
      
      req = new ActiveXObject("Microsoft.XMLHTTP");
      if (req) {
        req.onreadystatechange = processStateChange;
        req.open("GET", url, true);
        req.send();
      }
    }
  }  

/*
   * Set as the callback method for when XmlHttpRequest State Changes 
   * used by retrieveUrl
  */
  function processStateChange() {
  
  	try {
  	  	  	req.readyState;
	} catch (e){
  		// Firefox puede lanzar un error al leer el status
  	  	return;
	}

  	  if (req.readyState == 4) { // Complete
  	  	  document.getElementById(spanAc).innerHTML ="";	
  	  	  try {
  	  	  	req.status;
  	  	  } catch (e){
  	  	  	// Firefox puede lanzar un error al leer el status
  	  	  	showError();
  	  	  }
	      if (req.status == 200) { // OK response
	        document.getElementById(spanAc).innerHTML ="";
	        document.getElementById(spanAc).style.backgroundColor='#FFFFFF';
	        //alert("Ajax response:"+req.responseText);
	        if (elementNameMod != null && IsNumeric(req.responseText)) {
	        	if (elementNameMod.value == "")
		        	elementNameMod.value=req.responseText;
	        } else {
		        //Split the text response into Span elements
		        spanElements = splitTextIntoSpan(req.responseText);
		        //Use these span elements to update the page
		        replaceExistingWithNewHtml(spanElements);
		        
		        // Cambiamos el valor del for si es necesario
				if (postURLGet != null) {
		        	window.location=postURLGet;
		        }
			}	        
	      } else {
	      	//req.status("Error");
	        showError();
	        alert("Problem with server response:\n " + req.statusText);
	      }
    }
  }
 
 function IsNumeric(sText)

{
   var ValidChars = "0123456789";
   var IsNumber=true;
   var Char;

 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
   
   }
  function showError() {
  	document.getElementById(spanAc).innerHTML ="<b>Error...</b>";
	document.getElementById(spanAc).style.backgroundColor='#FF0000';
  }
 
 /**
  * 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
 		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("</div>");
 	//Process each of the elements 	
 	for ( var i=returnElements.length-1; i>=0; --i ){
 		//Remove everything before the 1st span
 		spanPos = returnElements[i].indexOf("<div");		
 		
 		//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){
 	var exp = '(?:<script.*?>)((\n|.)*?)(?:<\/script>)';
 	
 	//loop through newTextElements
 	for ( var i=newTextElements.length-1; i>=0; --i ){
 		//check that this begins with <span
		// Cambiamos span por div para compatibilidad con rico.js
 		if(newTextElements[i].indexOf("<div")>-1){
 			//get the name - between the 1st and 2nd quote mark
 			// Cambiamos " por ' para compatibilidad con rico.js
 			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)){
	 				var match    = new RegExp(exp, 'img');
				    var response = content.replace(match, '');
				    var scripts= "";
	 				scripts  = content.match(match);
	 				document.getElementById(name).innerHTML = response;
	 				
	 				if (scripts) {
	 					match2 = new RegExp(exp, 'im');
	 					setTimeout((function() {
							for (var i = 0; i < scripts.length; i++) {
					        	eval(scripts[i].match(match2)[1]);
					        }
					    }), 10);
				    }
	 			} else {
		 			document.getElementById(spanAc).innerHTML =req.responseText;
	 				//alert("Element: "+name+" not found in existing document");
	 				
	 			}
 		} else {
 			document.getElementById(spanAc).innerHTML =req.responseText;
 		}
 	}
 } 
 /*
  * 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 replaceExistingWithNewHtml2(newTextElements){
 	document.getElementById(spanAc).innerHTML =req.responseText;
 }
