/**
 * 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 req;
  var flag=true;


  /**
   * 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,nameOfFormToPost) {
    //get the (form based) params to push up as part of the get request
    
   
    if ((nameOfFormToPost != null) && (nameOfFormToPost!="")){
     //alert(url+" "+nameOfFormToPost);
	    url=url+getFormAsString(nameOfFormToPost);
	}
	
    //Do the Ajax call
    if(flag){
	    flag=false;
	    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();
	      }
	    }	    
	    flag=true;
    }    
  }

  function retrieveURLasPost(url,nameOfFormToPost) {
    //get the (form based) params to push up as part of the get request
    var parameters = null;
   
    if ((nameOfFormToPost != null) && (nameOfFormToPost!="")){
     //alert(url+" "+nameOfFormToPost);
     	
	    parameters = getFormAsString(nameOfFormToPost);
	}
	
    //Do the Ajax call
    if(flag){
	    flag=false;
	    
	      try {
	      	
			makePOSTRequest(url,parameters);
	      } catch (e) {
	        alert("Problem Communicating with Server\n"+e);
	      }
	      
	    flag=true;
    }    
  }
  
  function makePOSTRequest(url, parameters) {
      req = false;
      if (window.XMLHttpRequest) { // Mozilla, Safari,...
         req = new XMLHttpRequest();
         if (req.overrideMimeType) {
         	// set type accordingly to anticipated content type
            //http_request.overrideMimeType('text/xml');
            req.overrideMimeType('text/html');
         }
      } else if (window.ActiveXObject) { // IE
         try {
            req = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               req = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
      }
      if (!req) {
         alert('Cannot create XMLHTTP instance');
         return false;
      }
      
      req.onreadystatechange = processStateChange;
      req.open('POST', url, true);
      
      req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      req.setRequestHeader("Content-length", parameters.length);
      req.setRequestHeader("Connection", "close");
      req.send(parameters);
   }
  
   function alertContents() {
      if (http_request.readyState == 4) {
         if (http_request.status == 200) {
            //alert(http_request.responseText);
            result = http_request.responseText;
            document.getElementById('results_span').innerHTML = result;            
         } else {
            alert('There was a problem with the request.');
         }
      }
   }
   

/*
   * Set as the callback method for when XmlHttpRequest State Changes 
   * used by retrieveUrl
  */
  function processStateChange() {
  	  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
        replaceExistingWithNewHtml(spanElements);

      } else {
      
        alert("Problem with server response:\n " + req.statusText);
      }
    }
  }
 
 /**
  * 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){
 	//alert("Form "+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
 		
		// FEI
 		// necessaire ? la bonne transmission des select multiples
		if(formElements[i].type == "select-multiple") {
			selectOptions = formElements[i].options;
			for (var j=selectOptions.length-1; j>=0; --j){
				if (selectOptions[j].selected == true) {
					returnString=returnString+"&"+escape(formElements[i].name)+"="+escape(selectOptions[j].value);
				}
			}
		} 
		// necessaire ? la transmission des radio buttons check?s.
 		else if((formElements[i].type == "radio" || formElements[i].type == "checkbox")) {
 			if (formElements[i].checked) {
				returnString=returnString+"&"+escape(formElements[i].name)+"="+escape(formElements[i].value);
			}
		} 
		else {
			// cas classique
			returnString=returnString+"&"+escape(formElements[i].name)+"="+escape(formElements[i].value);
		}
 	}

 	//return the values
 	return returnString; 
 }
 
 /**
 * Splits the text into <ins> elements
 * @param the text to be parsed
 * @return array of <ins> elements - this array can contain nulls
 */
 function splitTextIntoSpan(textToSplit){
  	//Split the document
 	returnElements=textToSplit.split("</ins>");
 	//alert(returnElements);
 	//Process each of the elements 	
 	for ( var i=returnElements.length-1; i>=0; --i ){
 		
 		//Remove everything before the 1st span
 		spanPos = returnElements[i].indexOf("<ins");		
 		
 		//if we find a match , take out everything before the ins
 		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 <ins> elements
  * @param newTextElements (output of splitTextIntoSpan)
  *					in the format <ins id=name>texttoupdate
  */
 function replaceExistingWithNewHtml(newTextElements){

	// 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;
	}
	

 	//loop through newTextElements
 	for ( var i=newTextElements.length-1; i>=0; --i ){
 		//check that this begins with <ins
 		if(newTextElements[i].indexOf("<ins")>-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;
 			
 			// RMG
 			//text = newTextElements[i];
 			contenu = newTextElements[i].substring(startContentPos);
 			//alert("Nouveau block pour ins = "+name+" :\n"+contenu);
 			//content=newTextElements[i].substring(startContentPos);
 			//alert("Contenu ? remplacer "+content );
 			
 			//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 = contenu;
	 				// FEI
	 				// ex?cution du code html
	 				// cf: http://kratcode.wordpress.com/2006/03/07/javascript-script-execution-in-innerhtml-the-revenge/
	 				// TODO: ajax	 				
	 				execJS(document.getElementById(name));

	 			} else {
	 				//alert("Element:"+name+"not found in existing document");
	 			}
 		}
 	}
 }

function 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);
    }
  }
}

 //---------------------------DHTML--------------------------------------------------
 function toggleNode(node) {
 		
 		tr=document.getElementsByName("textnode");

 		for(j=0; j<tr.length; j++){
 			treeClass=tr[j].className;
 			if (treeClass.indexOf(' selected') > 0) {
  					 treeClass = childclass.replace(' selected', ' noselected');
				}
 			tr[j].className=treeClass;
 		}

        var nodeArray = node.childNodes;        
        for(i=0; i < nodeArray.length; i++) {          	
          node = nodeArray[i];
          
          if (node.tagName && node.tagName.toLowerCase() == 'a'){
       		   	childclass = node.className;
       		   	//alert(childclass);
				if (childclass.indexOf(' collapsed') > 0) {
  					 childclass = childclass.replace(' collapsed', ' expanded');
  					 
				} else {
  					 childclass = childclass.replace(' expanded', ' collapsed');
				}
				
				if (childclass.indexOf(' noselected') > 0) {
  					 childclass = childclass.replace(' noselected', ' selected');
				}
				node.className = childclass;
       	   }
                    
          if (node.tagName && node.tagName.toLowerCase() == 'div') {
          	if (node.style.display == 'block') {          		
          		node.style.display='none';
          		
          	} else {
          		node.style.display='block';
          	}
          }
        }
      } 


function sailNode(node) {

 		tr=document.getElementsByName("textnode");
		
 		for(j=0; j<tr.length; j++){
 			treeClass=tr[j].className;
 			if (treeClass.indexOf(' selected') > 0) {
  					 treeClass = childclass.replace(' selected', ' noselected');
				}
 			tr[j].className=treeClass;
 		}
        var nodeArray = node.childNodes; 
        //alert(node.id);      
        
      	childclass = node.className;
  	 	//alert("childclass="+childclass);			
		if (childclass.indexOf(' noselected') > 0) {
			 childclass = childclass.replace(' noselected', ' selected');
		}
		node.className = childclass;
		
}       

function updateBranch(node, url, form)
{	
	toggleNode(node);
	retrieveURL(url, form);
}

/*----------------------------------Actions---------------------------------*/

function popupModif(url, form, question){
	param = prompt(question,"");
	//alert(param);
	if(param!='' && param!=null){
		url+='&param='+param;
		retrieveURL(url, form);
	}else{
		alert("Le champ est obligatoire");
	}
}
function popupModifLoading(url, form, question, loading){
	if(''!=loading){
		Element.show(loading);
		param = prompt(question,"");
		var reg = new RegExp("&","g");
		param = param.replace(reg, "%26");
	
		if(param!='' && param!=null){
			url+='&param='+param;
			retrieveURL(url, form);
		}else{
			alert("Le champ est obligatoire");
		}
		Element.hide(loading);
	}else{
		popupModif(url, form, question);
	}
}

function popupConfirm(url, form, question){
	if(confirm(question)){
		retrieveURL(url, form);
	}
}
function popupConfirmLoading(url, form, question,loading){
	if(''!=loading){
		Element.show(loading);
		if(confirm(question)){
			retrieveURL(url, form);
		}
		Element.hide(loading);
	}else{
		popupConfirm(url, form, question);
	}
}
//--------------------------AJOUTS SDB


function treeLoading() {
	document.getElementById("makeTree").innerHTML='<div style=\"text-align:center\"><br/><img src=\"./images/habillage/generic/distribution/ajax_loader.gif\"></div>';
}
function questionLoading(){
	//alert('wesh');
	document.getElementById("questions").innerHTML='<div style=\"text-align:center\"><br/><img src=\"./images/habillage/generic/distribution/ajax_loader.gif\"></div>';
}

function findPos(obj) {
	
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	//return [curleft,curtop];
	position=new Array(curleft,curtop)
	return position
}


function ajax_wait_load(arg) {
	obj=document.getElementById(arg)
	obj.innerHTML='<img src=\"./images/habillage/generic/ajax_loader_mini.gif\">';
}

function ajax_wait_unload(arg) {
	obj=document.getElementById(arg);
	if(obj!=null){
		obj.innerHTML='';
	}
	
}

	function ajax_wait(target,position){
		
		var obj;
		var content
							
		obj=document.getElementById(target).innerHTML;
		content='';	
			
		if (position=='on'){
			
			content='<img src=\"./images/habillage/generic/ajax_loader_mini.gif\">';
			
			
		}
		
		objHTML=content;
		
	}



		
