
addListenner(window, "load", loadAjaxForm, true);

/**
 * Place l'ouverture du popup de l'image sur le clic
 */
function loadAjaxForm()
{
    
    var linklist = document.getElementsByTagName('var');
    var linkNode = false, p1;
    for (var i = 0; i < linklist.length; i++) {
        if (linklist[i].className.indexOf('ajaxFormButton') >= 0) {
            linkNode = document.createElement('a');
            linkNode.href = linklist[i].innerHTML;
            linkNode.className = linklist[i].className;
            
            linklist[i].parentNode.replaceChild(linkNode, linklist[i]);
            //linklist[i].parentNode.insertBefore(linkNode, linklist[i]);
        }
    }
    
    
    loadAjaxFormActions(document);
} // end function "loadAjaxForm"



function loadAjaxFormActions(node)
{
    var linklist = node.getElementsByTagName('a');
    for (var i = 0; i < linklist.length; i++) {
        if (linklist[i].className.indexOf('ajaxFormButton') >= 0) {
            linklist[i].onclick = callAjaxForm;
            
            if (linklist[i].className.indexOf('onlyMethods') >= 0
                || linklist[i].className.indexOf('loadMethods') >= 0
                || linklist[i].className.indexOf('loadContent') >= 0) {
                
                linklist[i].onclick();
            }
        }
    }

} // end function "loadAjaxForm"




/**
 * Appel de l'url du lien en ajax pour afficher son contenu dans la lightbox
 * 
 * Il est possible de placer des paramètres dans la classe du lien ainsi :
 * <a href="url" class="ajax-content-lightbox  fn:loadMailActions,width:750,height:400">lien</a>
 * 
 * @returns {Boolean}
 */
function callAjaxForm()
{
	var that = this;
	//alert('lancement "callAjaxForm()" sur ' + that.nodeName + '."' + that.className + '"');
	
	/**
	 * Fermeture
	 * 
	 * @returns {Boolean}
	 */
     that.close = function() {
    	 var targetNode = getTargetNode();
		 removeClass(targetNode.parentNode, 'showAjaxForm');
		 removeClass(that, 'buttonToTitle');
    	 if (targetNode) {
    	     if (args['targetId']) {
    	         targetNode.innerHTML = '';
    	         
    	     } else {
    	         targetNode.parentNode.removeChild(targetNode);
    	     }
    	 }
    	 that.onclick = callAjaxForm;
    	 return false;
     }; // end function "close"
	
     
     
	/**
	 * Rafraîchissement du contenu
	 * 
	 * @returns {Boolean}
	 */
     that.reload = function() {
    	 var oData = {'no-gab':1, 'xhrAction': 'getFormContent'};
    	 XHR_get(that.href, oData, showAjaxFormContent, false, true);
    	 return false;
     }; // end function "closeLightBox"

     

    var args = {};
    var linkClass = 'ajaxFormButton';
    if (that.className && that.className.indexOf(linkClass) >= 0) {
        args = getArgsFromClass(that.className, linkClass);
    }

    if (that.parentNode.className && that.parentNode.className.indexOf('tabBar') >= 0) {
        var tabList = that.parentNode.getElementsByTagName('a');
        for (var j = 0; j < tabList.length; j++) {
            removeClass(tabList[j], 'activeTab');
        }
        addClass(that, 'activeTab');
    }
     
     
    if (that.className.indexOf('onlyMethods') >= 0 
        || that.className.indexOf('loadMethods') >= 0) {
        
        if (that.className.indexOf('onlyMethods') >= 0) {
            that.onclick = function() { return false; };
        }
        loadFormActions();
    }
    
    if (that.className.indexOf('onlyMethods') < 0) {
        //alert('lancement "that.reload()" sur ' + that.nodeName + '."' + that.className + '"');
        that.reload();
    }
        
    if (that.className && that.className.indexOf('noClose') < 0) {
        that.onclick = that.close;
    }
    
    return false;
    
    
    
    
    
    /* Fonction privées
    --------------------------------------------------------------------- */
    


    function getTargetNode()
    {
		var targetNode = false;
		if (args['targetId']) {
			targetNode = document.getElementById(args['targetId']);
		}
		if (!targetNode && !that.nextSibling) {
			return false;
		}
		if (!targetNode) {
			targetNode = that.nextSibling;
	    	while (targetNode.className.indexOf('ajaxFormBox') < 0
	    		   && targetNode.nextSibling) {
	    		targetNode = targetNode.nextSibling;
	    	}
	    	if (!targetNode) {
	    	    targetNode = that.nextSibling;
	    	}
		}
		return targetNode;
    } // end function "getTargetNode"
    
    
    
    
    
	function changeAjaxFormContent()
	{
	    var oData = {'no-gab':1, 'xhrAction': 'getFormContent'};
		XHR_get(this.href, oData, showAjaxFormContent, false, true);
		return false;
		
	} // end function "changeAjaxFormContent"
    
    
    
    
    
    
	/**
	 * Reçois le code html à afficher et le place dans la lightbox
	 * 
	 * @param htmlContent
	 * @returns {Boolean}
	 */
	function showAjaxFormContent(htmlContent)
	{
		var targetNode = getTargetNode();
	    //alert('affichage du contenu');
		
		// Le contenu peut être html (page à afficher)
		// ou "données" à transmettre à une fonction
		var header = htmlContent.substring(0, 5);
		that.saveSuccess = false;
		if (header == '#JSON') {
			var data = XHR_parseResponse(htmlContent.substring(5));
			if (args['callOnSuccess'] /*&& typeof args['callOnSuccess'] == 'function'*/) {
			    that.saveSuccess = true;
				eval(args['callOnSuccess'] + '(data, that)');
			}
			return false;
		}
		
		
		//alert('affichage du contenu');
		
		var boxContent = document.createElement('div');
		var boxClass = 'ajaxFormBox';
		if (targetNode && targetNode.className) {
		    //alert("targetNode.className = " + targetNode.className);
		    boxClass = ' ' + targetNode.className;
		}
	    boxContent.className = boxClass;
	    //addClass(boxContent.className, 'ajaxFormBox');
	    
	    
	    if (args['targetId']) {
	    	boxContent.id = args['targetId'];
	    	
	    } else if (targetNode && targetNode.id) {
            boxContent.id = targetNode.id;
            
        } else {
            var tryOuts = 30;
            var testId = 'zoneContenuAjax-' + Math.round((Math.random() * 1000));
            var testNode = document.getElementById(testId);
            while (testNode && tryOuts > 0) {
                testId = 'zoneContenuAjax-' + Math.round((Math.random() * 1000));
                testNode = document.getElementById(testId);
                tryOuts--;
            }
            boxContent.id = testId;            
        }
	    htmlContent = htmlContent.replace('<?xml version="1.0" encoding="iso-8859-1"?>', '');
	    htmlContent = htmlContent.replace('<!DOCTYPE div PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">', '');
	    boxContent.innerHTML = htmlContent;

	    // Si un contenu a déjà été placé, on le remplace
	    //alert('insertion du contenu');
	    if (targetNode) {
	    	//alert('noeud trouvé: ' + targetNode.nodeName + ' (' + targetNode.id + ')');
	    	targetNode.parentNode.replaceChild(boxContent, targetNode);
	    	
	    } else {
	    	//alert('ajout à la fin');
	    	that.parentNode.appendChild(boxContent);
	    }
	    if (!args['targetId']) {
	    	addClass(that.parentNode, 'showAjaxForm');
	    }
	    
	    if (that.className.indexOf('noButtonChange') < 0) {
	        addClass(that, 'buttonToTitle');
	    }
	    
	    
	    if (boxContent.id) {
    	    var contentNode = document.getElementById(boxContent.id);
    	    if (contentNode) {
    	        loadAjaxFormActions(contentNode);
    	    }
	    }
        loadFormActions();
		
	}; // end function "showAjaxFormContent"
	
	
	
	


	
	
	
	
	/**
	 * Place les actions "soumission de formulaire", "lien" et "fermeture lightbox"
	 * 
	 */
	function loadFormActions()
	{
		var targetNode = getTargetNode();
		if (!targetNode) {
			return false;
		}

	    var linklist = targetNode.getElementsByTagName('a');
	    for (var i = 0; i < linklist.length; i++) {
	    	if (linklist[i].className.indexOf('closeAjaxForm') >= 0) {
	            linklist[i].onclick = that.close;
	            
	        } else if (linklist[i].className.indexOf('ajaxFormButton') >= 0) {
	            linklist[i].onclick = callAjaxForm;
	            
	        // lien interne: même domaine
	        } else if (linklist[i].className.indexOf('nouvellePage') < 0
	                   && (linklist[i].href.indexOf('http://') < 0 
	        		   || linklist[i].href.indexOf('http://' + document.location.host) >= 0)) {
	            linklist[i].onclick = changeAjaxFormContent;
	        }
	    	if (/onlyMethods/.test(linklist[i].className)) {
	            linklist[i].onclick();
	        }
	    }

	    // Parcours les boutons de type "submit"
	    linklist = targetNode.getElementsByTagName('input');
	    var input2 = false;
	    for (i = 0; i < linklist.length; i++) {
	    	if (linklist[i].type && (linklist[i].type == 'submit' || linklist[i].type == 'image')) {
	    	    
	    	    // IE semble merder sur l'accès à type, même après test qu'il existe...
	    	    try {
    	    	    // indique que le bouton est traité et désactive le comportement par défaut
    	    	    if (linklist[i].type && linklist[i].type != 'image') {
    	    	        linklist[i].type = 'button';
    	    	    }
    	    	    
	    	    } catch (e) {
	    	        /*try {
	    	            linklist[i].setAttribute('type', 'button');
	    	        } catch (e) { 
	    	            alert('linklist[i].nodeName = "' + linklist[i].nodeName + '", linklist[i].id = "' + linklist[i].id + '"');
	    	        }*/
	    	        input2 = document.createElement('input');
	    	        if (linklist[i].id) {
                        input2.id = linklist[i].id;
	    	        }
	    	        if (linklist[i].name) {
	    	            input2.name = linklist[i].name;
	    	        }
	    	        if (linklist[i].className) {
                        input2.className = linklist[i].className;
	    	        }
	    	        if (linklist[i].value) {
                        input2.value = linklist[i].value;
	    	        }
	    	        input2.type = 'button';
	    	        
                    //input2 = linklist[i].cloneNode(false);
                    //input2.type = 'button';
                    linklist[i].parentNode.replaceChild(input2, linklist[i]);
	    	    }
	    	    
	    		linklist[i].onclick = function ()
	    		{ 
	    		    //alert('clic sur bouton');
	    		    if (this.className && this.className.indexOf('normalSubmit') >= 0) {
	    		        submitForm(this);
	    		    } else {
                        actionsBeforeSubmit(this);
	    		    }
	    			return false; 
    			};
	    	}
	    }
		//alert('load form actions: DONE');
	    
	    
        if (typeof loadCaisseActions == 'function') {
            loadCaisseActions();
        }
	    if (typeof installGeoPopup == 'function') {
	    	installGeoPopup();
	    }
	    if (typeof addCalendarEventListener == 'function') {
	    	addCalendarEventListener(targetNode);
	    }
        if (typeof loadSubFormActions == 'function') {
            loadSubFormActions(targetNode);
        }
        if (typeof loadAgendaDesCours == 'function') {
            loadAgendaDesCours(targetNode);
        }
        if (typeof spg_menuRollover == 'function') {
            spg_menuRollover(targetNode);
        }
        if (typeof addSearchListEventListener == 'function') {
            addSearchListEventListener(that.href);
        }
	    

	} // end function "loadFormActions"
	
	
	
	
	function actionsBeforeSubmit(button)
	{
		var targetNode = getTargetNode();
		if (!targetNode) {
			return false;
		}
		
		// s'il y a d'autres formulaires dans targetNode,
		// il faut les soumettres => parcours les boutons submit
		var tmpList = targetNode.getElementsByTagName('form');
		//alert('tmpList.length = ' + tmpList.length);
        var totalInterne = 0;
		if (tmpList.length > 1) {		
    	    tmpList = targetNode.getElementsByTagName('input');
            var buttonList = [];
    	    var readyList = {};
    	    for (var i = 0; i < tmpList.length; i++) {
    	    	if ((tmpList[i].type == 'submit' || tmpList[i].type == 'button' /*|| tmpList[i].type == 'image'*/)
    	    		&& tmpList[i].id != button.id
    	    	    && tmpList[i].onclick) {
    	    		
    	    		readyList[tmpList[i].id] = false;
                    buttonList[totalInterne] = tmpList[i];
    	    		totalInterne++;
    	    	}
    	    }
		}
	    
	    if (totalInterne == 0) {
	    	//alert('"' + button.id + '": pas de formulaires interne, soumission');
	    	submitForm(button);
	    	return false;
	    }
	    
	    
	    //alert('Formulaires internes trouvés');
	    
	    
	    var readyFn = function() 
				      {
    					  if (this.id) {
    						  readyList[this.id] = true;
    						  //alert('pret: this.id = "' + this.id + '"');
    					  } /*else {
    						  alert('pas d\'id de trouvé');
    					  }*/
    					  
    					  var test = true;
    					  for (var i in readyList) {
    						  test = test && readyList[i];
    					  }
    					  if (test) {
    						  //alert('"' + button.id + '": fin des soumissions interne');
    						  //if (button.onReady) {
    							  //button.onReady();
								  //button.onReady = null;
    							  submitForm(button);
    						  //}
    						  
    					  } /*else {
    						  alert('"' + button.id + '": reste encore un formulaire à soumettre');
    					  }*/
    					  
				          return false;
				      };
	    

	    for (i = 0; i < buttonList.length; i++) {
	    	if (buttonList[i] && buttonList[i].onclick) {
	    		
	    		//alert('installation de onReady');
	    		buttonList[i].onReady = readyFn;
	    		//alert('lancement de onclick');
	    		buttonList[i].onclick();
	    		buttonList[i].onclick = null;
	    		//alert('execution interne: linklist[i].id = "' + linklist[i].id + '"');
				//return false;
	    	}
	    }
		
		
	    
	} // end function "actionsBeforeSubmit"
	
	
	
	
	
	
	
     
	/**
	 * Simule la soumission d'un formulaire
	 * 
	 * Note: ne supporte pas les champs "file"
	 * 
	 * Note: lit l'attribut "action", les données sont envoyées cette page.
	 * 
	 * @returns {Boolean}
	 */
	function submitForm(button)
	{
		//alert('"' + button.id + '": soumission formulaire');
		var targetNode = getTargetNode();
		if (!targetNode) {
			return false;
		}
		
		var url = that.href;
		var form = button.parentNode;
		while (form.parentNode && form.nodeName != 'FORM') {
			form = form.parentNode;
		}
		if (form.nodeName != 'FORM') {
			form = that.nextSibling;
			
		} else if (form.action) {
			url = form.action;
		}
		
		var oData = readForm(form, button);
		
		oData['xhrData'] = 'on';
		//oData['no-gab'] = 1; // à mettre en get dans l'url
		if (url.indexOf('?') >= 0) {
			url += '&';
			
		} else {
			url += '?';
		}
		url += 'no-gab=1';
	
		
        var fnCount = 0;
        var fnOnSuccess = [];
        var fnOnSuccessLabels = [];
		fnOnSuccess[fnCount] = showAjaxFormContent;
		fnOnSuccessLabels[fnCount] = 'showAjaxFormContent';
		fnCount++;
		
		if (args['autoclose']) {
			fnOnSuccess[fnCount] = that.close;
			fnOnSuccessLabels[fnCount] = 'autoclose';
			fnCount++;
		}
		if (args['refreshId']) {
		    fnOnSuccess[fnCount] = function () { 
		        //alert('utilisation de refreshId: "' + args['refreshId'] + '"');
		        var link = document.getElementById(args['refreshId']);
		        if (!link || !link.reload) {
		            return false;
		        }
		        link.reload(true);
		        return true; 
	        };
            fnOnSuccessLabels[fnCount] = 'refreshId';
            fnCount++;
		}
		if (args['refreshMain']) {
			fnOnSuccess[fnCount] = function () { window.location.reload(true); return true; };
            fnOnSuccessLabels[fnCount] = 'refreshMain';
            fnCount++;
		}
		/*if (args['closeOnSuccess']) {
			fnOnSuccess = function () { window.location.reload(true); return true; };
		}*/	
		
		XHR_post(url, oData, function(htmlContent)
							{ 
								//alert('reception des données ajax');
                    		    if (fnOnSuccess.length) {
                    		        //alert('appel des fonctions...');
                    		        for (var fn = 0; fn < fnOnSuccess.length; fn++) {
                    		            //alert('appel fonction ' + fn + ' "' + fnOnSuccessLabels[fn] + '"');
                    		            if (fnOnSuccess[fn] && typeof fnOnSuccess[fn] == 'function') {
                    		                fnOnSuccess[fn](htmlContent);
                    		            }
                    		        }
                    		    }
								//fnOnSuccess(htmlContent);
								if (button.onReady && that.saveSuccess) {
								    //alert('"' + button.id + '": Lancement onReady()');
									button.onReady(that.saveSuccess);
									button.onReady = null;
								}
								
								/*if (that.saveSuccess) {
								    alert('"' + button.id + '": enregistrement sans erreur');
								} else {
								    alert('"' + button.id + '": un problème est survenu');
								}*/
							}, false, true);
		return false;
	} // end function "submitForm"


	


} // end function "callAjaxForm"









