//
// by olivM
//
  if ( ! xhr ) {
    if (window.XMLHttpRequest) var xhr = new XMLHttpRequest();
    else if (window.ActiveXObject) var xhr = new ActiveXObject("Microsoft.XMLHTTP");
  }

  var xhrForms = new Array();
  /*  example config :
      xhrForms['monForm'] = new Object();
      xhrForms['monForm'].target = "/index.php?ACTION=CONTENT&SID=43";      
  */

	var xhrFormConfig = new Object();
	xhrFormConfig.strValidate = "Valider";
	xhrFormConfig.strBack = "Retour";
	xhrFormConfig.strProcessing = "...";
	xhrFormConfig.strSaved = "Enregistré";

	//préparation de la soumission
  function xhrFormInit(strFormName, strTarget) {
    
    var xhrForm = new Object();
    xhrForm.target = strTarget;      
	xhr.abort(); // on remet à 0 l'etat de l'obj xhr
    xhrForm.submits = new Array();       
   // alert(strFormName);
   
   for (idxSubmit=0;idxSubmit<document.forms[strFormName].elements.length;idxSubmit++) {
   // for(idxSubmit in document.forms[strFormName].elements) { 
    	//alert(idxSubmit);
    	//alert(document.forms[strFormName].elements[idxSubmit].id);
      strSubmitName = document.forms[strFormName].elements[idxSubmit].id;
      if (strSubmitName && strSubmitName.match(/_xhrSubmit_/))
        xhrForm.submits.push(strSubmitName);
     }


    xhrForm.inputs = new Array();       
    	for (idxInput=0;idxInput<document.forms[strFormName].elements.length;idxInput++) {
    //for(idxInput in document.forms[strFormName].elements) { 
      strInputName = document.forms[strFormName].elements[idxInput].id;
      if (strInputName && strInputName.match(/_xhrInput_/)) {
        xhrForm.inputs.push(strInputName);
        
        oInput = el(strInputName);
        switch (oInput.type) {
          default :
            oInput.onfocus = function() {
              for(idxSubmit in xhrForm.submits) { 
                el(xhrForm.submits[idxSubmit]).disabled = false;
                if (xhrForm.submits[idxSubmit].match(/_xhrSubmit_BACK/))
                  el(xhrForm.submits[idxSubmit]).value = xhrFormConfig.strBack;
                if (xhrForm.submits[idxSubmit].match(/_xhrSubmit_SUBMIT/))
                  el(xhrForm.submits[idxSubmit]).value = xhrFormConfig.strValidate;
              }
            }
          break;
        }
      }
    }
    xhrForms[strFormName] = xhrForm;
  }

	// l'argument option est utilisé pour la dernière etape du formulaire
	// si c'est la fin, on fait une redirection vers une autre page après avoir mis en session 
	// les infos de formulaires
  function xhrFormPost(strFormName) {
  	//var option = (option == null) ? "1" : option;
    //alert (strFormName);

    //----
    bouton = document.getElementById("continuer");    
    bouton.value = "Veuillez patienter...";
    bouton.disabled = true;
    //----

    if ( ! xhrForms[strFormName] ) {
      Log.write(strFormName + " is not configured");
      exit();
    }
    
    aSubmits = xhrForms[strFormName].submits;
    aInputs = xhrForms[strFormName].inputs;
    /*for (var i=0; i<aInputs.length ; i++){
    	Log.write(aInputs[i]);
    }*/
    

    if ( ! xhr ) {
      Log.write(' no xhr ! ');
      exit();
    }
      
    for(idxSubmit in aSubmits) { 
      el(aSubmits[idxSubmit]).disabled = true;
      el(aSubmits[idxSubmit]).value = xhrFormConfig.strProcessing;
    }
    
   
    xhr.onreadystatechange = function () 
  	{
    if (xhr.readyState == 4) {
      if (xhr.status == 200) {
        Log.write('------Nouvelle reponse-------');
        Log.write(xhr.responseText);
        
        // TODO execBefore & execAfter
        
        if (xhr.responseXML && xhr.responseXML.getElementsByTagName('execOnFinish')[0] ) {
          //Log.write(xhr.responseXML.getElementsByTagName('execOnFinish')[0].firstChild.nodeValue);
          eval(xhr.responseXML.getElementsByTagName('execOnFinish')[0].firstChild.nodeValue);
        }
				Log.write('ici');
				 //Log.write(xhr.responseXML.getElementsByTagName('displayOnFinish')[0].childNodes[0].firstChild.nodeValue);
        if (xhr.responseXML && xhr.responseXML.getElementsByTagName('displayOnFinish')[0] ) {
          //Log.write('ici');
          //Log.write(xhr.responseXML.getElementsByTagName('displayOnFinish')[0].childNodes.length);
          for (var idx=0; idx<xhr.responseXML.getElementsByTagName('displayOnFinish')[0].childNodes.length;idx++) {
          //for(idx in xhr.responseXML.getElementsByTagName('displayOnFinish')[0].childNodes) {
          		//Log.write('ici');
          	//Log.write(idx);
            if (xhr.responseXML.getElementsByTagName('displayOnFinish')[0].childNodes[idx].nodeName) {
            	Log.write(xhr.responseXML.getElementsByTagName('displayOnFinish')[0].childNodes[idx].nodeName);
              divId = xhr.responseXML.getElementsByTagName('displayOnFinish')[0].childNodes[idx].nodeName;
              //Log.write(divId);
               
              divValue = xhr.responseXML.getElementsByTagName(divId)[0].firstChild.nodeValue;
              //Log.write(divValue);
              el(divId).innerHTML = divValue;
            }
          }
        }
        
        
        
				//Log.write(xhr.responseXML.getElementsByTagName('execOnFinishAfter')[0].nodeName);
        if (xhr.responseXML && xhr.responseXML.getElementsByTagName('execOnFinishAfter')[0] ) {
         
          //Log.write(xhr.responseXML.getElementsByTagName('execOnFinishAfter')[0].firstChild.nodeValue);
          eval(xhr.responseXML.getElementsByTagName('execOnFinishAfter')[0].firstChild.nodeValue);
        }
				
        xhrForm = xhrForms[strFormName];

        for(idxSubmit in xhrForm.submits) {
          if (el(xhrForm.submits[idxSubmit]) ) {
            if (xhrForm.submits[idxSubmit].match(/_xhrSubmit_BACK/) )
              el(xhrForm.submits[idxSubmit]).value = xhrFormConfig.strBack;
            if (xhrForm.submits[idxSubmit].match(/_xhrSubmit_SUBMIT/) )
              el(xhrForm.submits[idxSubmit]).value = xhrFormConfig.Saved;
          }
        }

        self.setTimeout('xhrResetSubmits("'+strFormName+'")', 2000)  
      }
      else {
        Log.write('There was a problem with the request.');
        exit();
      }
    }
	}
    
    postContent = '';
    Log.write("sending : ");
    aValues = new Object();
    for(idxInput in aInputs) {
    	
      oInput = el(aInputs[idxInput]);
      if ( ! oInput) {
        oInput = el(aInputs[idxInput]);
        if ( ! oInput)
          Log.write(aInputs[idxInput] + ' not found ');     
      }
      
      
      strValue = null;
  
      if (typeof(FCKeditorAPI) != 'undefined' && (oEditor = FCKeditorAPI.GetInstance(aInputs[idxInput]) ) ) {
        // wysiwyg
        strValue = encodeURIComponent(oEditor.GetXHTML());
        strKey = aInputs[idxInput].substring(aInputs[idxInput].indexOf('_xhrInput_')+10);
      }
      else {
        
        Log.write('-- NAME : ' + oInput.name + ' | ID : ' + oInput.id + " | TYPE : " + oInput.type + '--')
        switch(oInput.type) {
          case 'radio':
          case 'checkbox':
            if (oInput.checked) {
              strValue = oInput.value;
            }
            strKey = oInput.name;
          break;
          case 'select-multiple':
            for(idx in oInput.options)
                if (oInput.options[idx].selected)
                  strValue = strValue + ',' + oInput.options[idx].value;
            strKey = oInput.name;
          break;          
          default :
            strValue = oInput.value;
            strKey = aInputs[idxInput].substring(aInputs[idxInput].indexOf('_xhrInput_')+10);
          break;
        }
      }
      
      //Log.write('strValue :' + strValue);
      //Log.write("send : "+strKey + " : " + strValue);
      if (strValue != null) {
        if ( ! aValues[strKey] )
          aValues[strKey] = strValue;
        else
          //aValues[strKey] = aValues[strKey]+','+strValue;
          //fix temp bug accumulation des activites cas ruche
          aValues[strKey] = strValue;
      }
        
    }
    
    for(idx in aValues) {
      postContent += '&' + idx + '=' + encodeURIComponent(aValues[idx]);
    }
    Log.write(postContent);

    xhr.open('POST', xhrForms[strFormName]['target'], true);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.setRequestHeader("Content-length", postContent.length);
    xhr.setRequestHeader("Connection", "close");
    xhr.send(postContent);
  }
  
  function xhrResetSubmits(strFormName) {
     aSubmits = xhrForms[strFormName].submits;
     for( idxSubmit in aSubmits ) { 
       if ( el(aSubmits[idxSubmit]) ) {
         if (aSubmits[idxSubmit].match(/_xhrSubmit_BACK/) )
           el(aSubmits[idxSubmit]).value = xhrFormConfig.strBack;
         if (aSubmits[idxSubmit].match(/_xhrSubmit_SUBMIT/) )
           el(aSubmits[idxSubmit]).value = xhrFormConfig.strValidate;
         el(aSubmits[idxSubmit]).disabled = false;
       }
     }
  
  }
  
	function retourXhrFormPostFinal() 
  {
  	window.location.href='inscription_recap.php';
  }
  


