/**
 * 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 <ins id="name">newContent</ins>
 * 		 - each <ins> tag in the *existing* document will be replaced with newContent
 *
 * NOTE: <ins id="name"> is case sensitive. Name *must* follow the first quote mark and end in a quote
 *		 Everything after the first '>' mark until </ins> is considered content.
 *		 Empty Sections should be in the format <ins id="name"></ins>
 */

//global variables
  var idReq;
  var idFlag=true;
  var _id;


  /**
   * 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)
   * id - which 
   */
  function retrieveURLById(url,nameOfFormToPost,id) {
    //get the (form based) params to push up as part of the get request
    
    _id = id;
    
    //alert(url+" flag "+flag);
    if (nameOfFormToPost != null) {
	    url=url+getFormAsString(nameOfFormToPost);
	}
	
    //Do the Ajax call
    if(idFlag){
	    idFlag=false;
	    if (window.XMLHttpRequest) { // Non-IE browsers
	      idReq = new XMLHttpRequest();
	      idReq.onreadystatechange = id_processStateChange;
	      try {
	      	idReq.open("GET", url, true); //was get
	      } catch (e) {
	        alert("Problem Communicating with Server\n"+e);
	      }
	      idReq.send(null);
	    } else if (window.ActiveXObject) { // IE
	      idReq = new ActiveXObject("Microsoft.XMLHTTP");      
	      if (idReq) {
	        idReq.onreadystatechange = id_processStateChange;
	        idReq.open("GET", url, true);        
	        idReq.send();
	      }
	    }	    
	    idFlag=true;
    }    
  }

/*
   * Set as the callback method for when XmlHttpRequest State Changes 
   * used by retrieveUrl
  */
  function id_processStateChange() {
  	  if (idReq.readyState == 4) { // Complete
	      if (idReq.status == 200) { // OK response      
	        
	        //alert("Ajax response:"+req.responseText);
	        
	        //Split the text response into Span elements
	        idElement = getIdElement(idReq.responseText, _id);
	        
	        //Use these span elements to update the page
	        id_replaceExistingWithNewHtml(idElement, _id);
	        
	      } else {
	        alert("Problem with server response:\n " + idReq.statusText);
	      }
	}
  }
 
 /**
 * Splits the text into <span> elements
 * @param the text to be parsed
 * @return array of <span> elements - this array can contain nulls
 */
 function getIdElement(textToSplit, id){
	possibleElements=textToSplit.split("</ins>");
	for (var i=possibleElements.length-1; i>=0; --i){
		if (possibleElements[i].indexOf(id) == -1) {
			continue;
		}
		// remove everything before the 1st elements;
		spanPos = possibleElements[i].indexOf("<ins");
		
		if(spanPos>0){
 			return possibleElements[i].substring(spanPos);
		}
	}
 }
 
 /*
  * 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 span_splitTextIntoSpan)
  *					in the format <span id=name>texttoupdate
  */
 function id_replaceExistingWithNewHtml(newTextElement, id){

	// TODO: ajax
	// FEI: suppression de toutes les node <script> attach?es au head
	// par un appel pr?c?dent de retrieveURL.
	var head = document.getElementsByTagName("head")[0];
	// iteration sur les fils du head.
	var noeud = head.firstChild;
	while (noeud!=null) {
		if (noeud.nodeName=="SCRIPT") {
			//alert(noeud.nodeName + " " + noeud.getAttributeNode("ajax"));
			if (noeud.getAttributeNode("ajax") != null) {
				var nodeToRemove = noeud;
				noeud = noeud.nextSibling;
				head.removeChild(nodeToRemove);
				continue;
			}
		}
		noeud = noeud.nextSibling;
	}
	

	//check that this begins with <span
	if(newTextElement.indexOf("<ins")>-1){
 			
		//get the content - everything after the first > mark
		startContentPos=newTextElement.indexOf('>')+1;
 			
		contenu = newTextElement.substring(startContentPos);
 			
		//Now update the existing Document with this element
 			
		//check that this element exists in the document
		if(document.getElementById(id)){
			document.getElementById(id).innerHTML = contenu;
			// FEI
			// ex?cution du code html
			// cf: http://kratcode.wordpress.com/2006/03/07/javascript-script-execution-in-innerhtml-the-revenge/
			// TODO: ajax
			ins_execJS(document.getElementById(id));
	 	} else {
 			//alert("Element:"+name+"not found in existing document");
		}
 	}
 }

function ins_execJS(node){
  var bSaf = (navigator.userAgent.indexOf('Safari') != -1);
  var bOpera = (navigator.userAgent.indexOf('Opera') != -1);
  var bMoz = (navigator.appName == 'Netscape');

  if (!node) return;

  /* IE wants it uppercase */
  var st = node.getElementsByTagName('SCRIPT');
  var strExec;

  for(var i=0;i<st.length; i++){
    if (bSaf) {
      strExec = st[i].innerHTML;
      st[i].innerHTML = "";
    } else if (bOpera) {
      strExec = st[i].text;
      st[i].text = "";
    } else if (bMoz) {
      strExec = st[i].textContent;
      st[i].textContent;
    } else {
      strExec = st[i].text;
      st[i].text = "";
    }

    try {
      var x = document.createElement("script");
      x.type = "text/javascript";

	  // FEI: ajout d'un attribut sp?cifique permettant de savoir que le script 
	  // a ?t? cr?? par ajax.js.
	  var ajax = document.createAttribute("ajax");
      ajax.nodeValue = "true";
      x.setAttributeNode(ajax);
       
      /* In IE we must use .text! */
      if ((bSaf) || (bOpera) || (bMoz))
        x.innerHTML = strExec;
      else x.text = strExec;

	  if (!strExec.match(/^\s*$/)) {
	      document.getElementsByTagName("head")[0].appendChild(x);
	  }
    } catch(e) {
      alert(e);
    }
  }
}



