// +--------------------------------------------------------------------------+
// | <G a n e s h a> - Free Web Based Training System                         |
// +--------------------------------------------------------------------------+
// | <G a n e s h a> - Plate-forme de téléformation gratuite et en open source|
// +--------------------------------------------------------------------------|
// | Copyright (C) 2000-2003  Anéma Formation  <http://www.anema.fr/>         |
// +--------------------------------------------------------------------------+
// |           Developer : Georges CALDEIRA <gcaldeira@anemalab.org>          |
// +--------------------------------------------------------------------------+
// |              Infos on project <http://anemalab.org/>                     |
// +--------------------------------------------------------------------------+
// | This program is free software; you can redistribute it and/or modify     |
// | it under the terms of the GNU General Public License as published by     |
// | the Free Software Foundation; either version 2 of the License, or        |
// | (at your option) any later version.                                      |
// |                                                                          |
// | This program is distributed in the hope that it will be useful,          |
// | but WITHOUT ANY WARRANTY; without even the implied warranty of           |
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            |
// | GNU General Public License for more details.                             |
// |                                                                          |
// | You should have received a copy of the GNU General Public License        |
// | along with this program; if not, write to the Free Software              |
// | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA |
// +--------------------------------------------------------------------------+

/* ============================================================================= 
/* Fonction de debug JS et plus particulièrement pour AJAX
*/

function debug(message) {
    if($("#debugJS").size() == 0) {
        $('<div id="debugJS"><h6 style="border-bottom:1px solid black;padding:0;text-align:center;margin-bottom:1em;">Drag</h6><h1>Debug Javascript</h1><br><h3>Clear</h3><hr><br><ul></ul></div>')
        .appendTo("body")
        .css({
            position : "fixed",
            top : "10px",
            right : "10px",
            borderWidth : "1px",
            borderStyle : "solid",
            borderColor : "black",
            padding : "15px",
            width : "20%",
            height : "90%",
            overflow : "auto",
            backgroundColor : "#CADBFF",
            opacity : 0.9,
            zIndex : 5000
        })
        .jqDrag("h6")
        .find("h1")
        .css("cursor","pointer")
        .click(function(){
            if($(this).parent().css("height") == "90%") {
                $(this).parent().css({
                    height :"15%",
                    overflow : "hidden"
                });
            } else {
                $(this).parent().css({
                    height :"90%",
                    overflow : "auto"
                });
            }
        })
        .end()
        .find("h3")
        .css("cursor","pointer")
        .click(function(){
            $(this).parent().find("ul").html("");
        })
        .end()
        .find("h6")
        .css("cursor","move");
        
        $("#debugJS").alwaysOnTop();
    }
    
    $("#debugJS ul").append("<li>" + message + "</li>");
}

/* ============================================================================= 
/* Fonction qui permet de vérifier le skin
*/

    function setFCT(fct) {
        var find = false;

        if(typeof fct == "string") {
            fct = [fct];
        }
        
        $.each(fct,function(){
            if(G_MODE_FCT == this) {
                find = true;
                return false; //Interrompt le each
            }
        });
        
        return find;
    }

/* ============================================================================= 
/* Fonction qui soumet les formulaires
*/

    function submitForm(form) {
        if(form.onsubmit) {
            form.onsubmit();
        } else {
            form.submit();        
        }
        return false;
    }

/* ============================================================================= 
/* Fonction inconnues
*/

	   NS4 = (document.layers) ? 1 : 0;
	   IE4 = (document.all) ? 1 : 0;
	   if (!IE4)
	      MOZ = (document.getElementById) ? 1 : 0;
	   else
	      MOZ=0;

	   currentX = currentY = 0;

	   function grabEl(e) {
	      if (IE4) {
	         currentX = event.x;
	         currentY = event.y;
	      } else {
	         currentX = e.pageX;
	         currentY = e.pageY;
	      }
	   }

	   if ( NS4 ) {
	      document.captureEvents(Event.MOUSEDOWN | Event.MOUSEMOVE);
	   }

	   document.onmousemove = grabEl;

function show (name) {
    alertCss(currentX + "  " + currentY);
    x = currentX;
    y = currentY + 20;
        
    if (NS4) {
     document.layers[name].xpos = parseInt(x);
     document.layers[name].left = parseInt(x);
     document.layers[name].ypos = parseInt(y);
     document.layers[name].top = parseInt(y);
     document.layers[name].visibility = "show";
        }
    if (IE4) {
     document.all[name].style.left = self.document.body.scrollLeft + parseInt(x);
     document.all[name].style.top = self.document.body.scrollTop + parseInt(y);
     document.all[name].style.visibility = "visible";
            }
    if (MOZ) {
     document.getElementById(name).style.left = parseInt(x);
     document.getElementById(name).style.top = parseInt(y);
     document.getElementById(name).style.visibility = "visible";
            }
        }
        
function hide (name) {
  if (NS4) {
     document.layers[name].visibility = "hide";
  }
  if (IE4) {
     document.all[name].style.visibility = "hidden";
  }
  if (MOZ) {
     document.getElementById(name).style.visibility = "hidden";
  }
            }

/* ============================================================================= 
/* Fonction de vérification des formulaires
*/

	function VerifSearch(form) {
		if (form.text1.value=="") {
			alertCss(searchInputIsEmpty,function() {
			form.text1.focus();
			});
			return false;
		}
		
		submitForm(form);
	}

	function VerifSearchBar(form) {
	/*
		if (form.text2.value=="") {
			alertCss(searchInputIsEmpty);
			form.text2.focus();
			return ;
		}
	*/
		submitForm(form);
	}

	function VerifPost(form) {
		if ( form.text1.value=="" ) {
			alertCss(subjectIsEmpty,function(){
			form.text1.focus();
            });
            
			return false;
		}
		if ( form.text2.value=="" ) {
			alertCss(messageIsEmpty,function(){
			form.text2.focus();
            });
			
            return false;
		}
		submitForm(form);
	}

	function ValiderFormFicheInfos(form){
		if(checkRequiredFormFields(form)) {
		submitForm(form);
	}

			return false;
		}
			
	function ValiderFormFicheLogin(form){
		if(checkRequiredFormFields(form)) {
            //Check confirm pwd
            if (form.pwd.value != form.pwd_confirm.value)   {
    			alertCss(passwordConfirmationIsDifferent,function(){form.pwd_confirm.focus();});
			return false;
		}
    
		// test si pwd different
            if ( form.old_password.value!=form.pwd.value) {
		  if (form.crypt.value == 'md5' ) {
                    form.pwd.value = MD5(form.pwd.value) ;
                    form.pwd_confirm.value = form.pwd.value ;
      }
    }
        
		submitForm(form);
	}

		return false;
	}

	function ValiderFormQuestion(form){
		if (form.prenom.value == "" )   {
			alertCss(firstNameIsEmpty,function(){
			form.prenom.focus();
			});
			
			return false;
		}
		if (form.nom.value == "" )   {
			alertCss(nameIsEmpty,function(){
			form.nom.focus();
			});
			
			return false;
		}
		if (form.subject.value == "" )   {
			alertCss(subjectIsEmpty,function(){
			form.subject.focus();
			});
			
			return false;
		}
		if (form.message.value == "" )   {
			alertCss(messageIsEmpty,function(){
			form.message.focus();
			});
			
			return false;
		}
		submitForm(form);
	}

	function ValiderFormMsg(form){
		if (form.text3.value == "" )   {
			alertCss(subjectIsEmpty,function(){
			form.text3.focus();
			});
			
			return false;
		}
		if (form.text4.value == "" )   {
			alertCss(messageIsEmpty,function(){
			form.text4.focus();
			});
			
			return false;
		}
		submitForm(form);
	}

	function ValiderFormPlanning(form)  {
		if (form.text1.value == "" )    {
			alertCss(fileIsEmpty,function(){
			form.text1.focus();
			});
			
			return false;
		}
		submitForm(form);
	}

    function ValiderFormActCollab(form) {
		if (form.text1.value == "" )    {
			alertCss(fileIsEmpty,function(){
			form.text1.focus();
			});

			return false;
        }
        submitForm(form);
    }
    
	function ValiderFormFile(form)  {
		if (form.text1.value == "" )    {
			alertCss(titleIsEmpty,function(){
			form.text1.focus();
			});
			
			return false;
		}
		if (form.text2.value == "" )    {
			alertCss(documentIsEmpty,function(){
			form.text2.focus();
			});
			
			return false;
		}
		submitForm(form);
	}

	function ValiderFormComment(form)  {
		if (form.text1.value == "" )    {
			alertCss(commentIsEmpty,function(){
			form.text1.focus();
			});
			
			return false;
		}
		submitForm(form);
	}

	function ValiderFormAjouterNote(form){
		if (form.text1.value == "" || isNaN(form.text1.value) ) {
			alertCss(noteInvalid,function(){
			form.text1.focus();
			});
			
			return false;
		}
		if (form.text1.value > 100) {
			alertCss(noteInvalid,function(){
			form.text1.value = "" ;
			form.text1.focus();
			});
			
			return false;
		}
		submitForm(form);
	}

	function DeleteFile(url)  {
		confirmCss(fileDeleteConfirm,function() {
			window.location.replace(url);
        });
	}

	function DeleteForumPost(url)  {
		confirmCss(postDeleteConfirm,function() {
			window.location.replace(url);
        });
		}
	
	function QuitterActCollab(url)  {
		confirmCss(confirmExit,function() {
			window.location.replace(url);
        });
	}

	function QuitterCorrectionActCollab(url)  {
		confirmCss(confirmExit,function() {
		alert(url);
			window.location.replace(url);
        });
	}

	function openWindow(theURL,winName,features) {
    	    var pload = G_URL + "ganesha/commun/p_chargement.php";
    	    pload += "?connexion=" + G_CNX;
    	    pload += "&page=" ;
    	    pload += escape(theURL) ;
		var hw = window.open(pload,winName,features);
	}

	function openWindow2(theURL) {
		window.open(theURL,'abc','width='+screen.width+',height='+screen.height+',top=0,left=0,scrollbars=yes,toolbar=no,resizable=yes');
	}

	function DeleteMessage(url){
		confirmCss(messageDeleteConfirm,function() {
			window.location.replace(url);
        });
	}

    function ValiderFormCodeInscr(form){
		if(checkRequiredFormFields()) {
            if(G_MODE_FCT == "dfpn") {
                if (form.ville.value.length != 7)   {
        			alertCss(cityIsEmpty,function(){form.ville.focus();});
			return false;
		}
            } else {
		if (form.email && !VerificationEmail(form.email) ) {
			return false;
		}
		
		if(form.email && $(form.email).is(".required") && form.email.value != form.confirme_email.value) {
            alertCss(emailConfirmFailed,function(){form.email.focus();});
            return false;
		}
		}
		
        submitForm(form);
	}

			return false;
		}

	function ValiderFormInscr(form){
		if(checkRequiredFormFields()) {
            if(G_MODE_FCT == "dfpn") {
		if ( ! VerificationEmail(form.email) ) {
			return false;
		}
        		
		if (form.confirme_email && form.email.value != form.confirme_email.value) {
            alertCss(emailConfirmFailed,function(){form.email.focus();});
            return false;
		}
		}
		
        submitForm(form);
        } 
        
        return false;
	}

	function verifcode(form) {
		if ( form.code.value == '' ) {
			alertCss(inscriptionCodeIsEmpty,function() {
			form.code.focus();
            });
            
			return(false);
		}
		submitForm(form);
	}

	function verifrepertoire(form) {
		if ( form.text1.value=='' && form.text2.value=='') {
            alertCss(requiredInputIsEmpty,function(){
			form.text1.focus();
            });
        
			return(false);
		}
        
		if ( form.text1.value=='' && form.text2.value!='') {
            confirmCss(selectFolderConfirm,function() {
  			submitForm(form);
            });
            
  		return(false);
		}
        
		submitForm(form);
	}

	function validerPAB(form) {
		//alertCss('valider PAB ?');
		submitForm(form);
	}

	function validerPB(form) {
		//alertCss('valider PB ?');
		submitForm(form);
	}

	function verifAddMembre(form) {
		if ( form.text1.value=='') {
			alertCss(firstNameIsEmpty,function(){
			form.text1.focus();
			});
			
			return(false);
		}
		if ( form.text2.value=='') {
			alertCss(nameIsEmpty,function(){
			form.text2.focus();
            });
            
			return(false);
		}
		submitForm(form);
	}

	function validAccueil(form) {
		if ( form.text1.value=='' ) {
			form.text2.value = yesText;
            submitForm(form);
		} else {
			var yesCallBack = function() {
                form.text2.value = yesText;
                submitForm(form);
            };
            
        var noCallBack = function() {
                form.text2.value = noText;
		submitForm(form);
            };
			
            confirmCss(form.text1.value,confirmationRequired,yesCallBack,noCallback);
		}
	}

/* ============================================================================= 
/* Fonction inconnues
*/
function setPointer(theRow, theAction, theDefaultColor, thePointerColor) {
    var theCells = null;

    if ( thePointerColor == '' || typeof(theRow.style) == 'undefined' ) {
        return false;
    }

    if (typeof(document.getElementsByTagName) != 'undefined') {
        theCells = theRow.getElementsByTagName('td');
    }
    else if (typeof(theRow.cells) != 'undefined') {
        theCells = theRow.cells;
    }
    else {
        return false;
    }

    // 3. Gets the current color...
    var rowCellsCnt  = theCells.length;
    var domDetect    = null;
    var currentColor = null;
    var newColor     = null;
    // 3.1 ... with DOM compatible browsers except Opera that does not return
    //         valid values with "getAttribute"
    if (typeof(window.opera) == 'undefined'
        && typeof(theCells[0].getAttribute) != 'undefined') {
        currentColor = theCells[0].getAttribute('bgcolor');
        domDetect    = true;
    }
    // 3.2 ... with other browsers
    else {
        currentColor = theCells[0].style.backgroundColor;
        domDetect    = false;
    } // end 3

    // 4. Defines the new color
    // 4.1 Current color is the default one
    if (currentColor == ''
        || currentColor.toLowerCase() == theDefaultColor.toLowerCase()) {
        if (theAction == 'over' && thePointerColor != '') {
            newColor = thePointerColor;
        }
    }
    // 4.1.2 Current color is the pointer one
    else if (currentColor.toLowerCase() == thePointerColor.toLowerCase()) {
        if (theAction == 'out') {
            newColor = theDefaultColor;
        }
    } // end 4

    // 5. Sets the new color...
    if (newColor) {
        var c = null;
        // 5.1 ... with DOM compatible browsers except Opera
        if (domDetect) {
            for (c = 0; c < rowCellsCnt; c++) {
                theCells[c].setAttribute('bgcolor', newColor, 0);
            } // end for
        }
        // 5.2 ... with other browsers
        else {
            for (c = 0; c < rowCellsCnt; c++) {
                theCells[c].style.backgroundColor = newColor;
            }
        }
    } // end 5

    return true;
};

/* ============================================================================= 
/* Fonction fullscreen de la partie apprenant
*/

	function resizeScreen() {
		toggle('colonne_gauche');
		toggle('bandeau');
		toggle('logo');
		toggle('profil');
		toggle('menu_principal') ;
		toggle('nom') ;

		if (document.getElementById('colonne_gauche').style.display=='none'){
            document.getElementById('header').style.height = '30px' ;
            $("#content").css("backgroundImage","none");
		} else {
			document.getElementById('header').style.height = '100px';
			$("#content").css("backgroundImage","");
		}

		resizeIframe() ;
	}


	function resizeIframe() {
	    var width = document.body.offsetWidth ;
        frame = document.getElementById('idframe');
		if (document.getElementById('colonne_gauche').style.display=='none'){
			if(frame) frame.width = width - 110 ;
		} else {
			if(frame) frame.width = width - 260 ;
		}
	}

    function printIframe() {
        if(top.idframe) {
        try {
            top.idframe.mainFrame.focus() ;
            window.print();
        } catch(error) {
            top.idframe.focus() ;
            window.print();
        }
    }
        else {
            top.focus();
            window.print();
        }
    }

function toggle(id) {
    el = document.getElementById(id);
	var display = el.style.display ? '' : 'none';
	el.style.display = display;
}

/* ==============================================================================
/* Fonction de chargement des div avec un onglet au dessus 
/*      => liste des groupes par ex.
*/

function toggle_ajax(id,url) {
	var el = document.getElementById(id);
	
	if ( el.style.display ) {
        if(!$(el).is(".allready-loaded")) {
            var div = document.createElement("div");
    		div.className = "load";
    		el.innerHTML = '';
    		el.appendChild(div);
		
    	    $.get(url,function(data) {
                $(el).addClass("allready-loaded").html(data);
            });
        }
        
        el.style.display = "";
	    
	} else {
		el.style.display = "none";
		//el.innerHTML = '';
	}
}


   	
/* =============================================================================
/* Fonction utilisé dans les activités collaboratives
*/

    function appendFormAction(formId,content) {
        document.getElementById(formId).action += content;
    }

/* =============================================================================
/* Fonction d'export de la vCard
*/

	function ExportVCARD(url) {
		thewin = window.open(url,"vcard","width=10,height=10");
		return true ;
	}
	
/* =============================================================================
/* Fonctions du menu de formation en AJAX
*/
	
function createXMLHttpRequest() {
    var xmlhttp;
    
    try {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    catch(e) {
        try {
            xmlhttp = new XMLHttpRequest();
        }
        catch(e) {
            xmlhttp = null;
        }
    }
    
    return xmlhttp;
}
	
	function ajaxToggleMenuSession(linkObject,addr,synch) {
        //Création des éléments
        var liElement = linkObject.parentNode;              //Source
        var ulElement = document.createElement("ul");       //Nouvelle liste pour le sous-menu
        var liImgElement = document.createElement("li");    //Liste avec style CSS pour l'image de preload
        var idAttribute = document.createAttribute("id");   //Id pour la liste de preload
        var xmlhttp = createXMLHttpRequest();
        
        if(xmlhttp == null) {
            alertCss("Unable to create XMLHttpRequest object for Ajax formation menu.");
            return;
        }
	    
        if (typeof synch == "undefined") {
            synch = true;
        }
        
        //Spécification de l'image de preloading
        idAttribute.nodeValue = "loading";
        liImgElement.setAttributeNode(idAttribute);
        
        //Ajout de la liste et de l'image de preloading
        liElement.appendChild(ulElement);
        ulElement.appendChild(liImgElement);
        
        //Switch de l'événement sur le lien
        linkObject.onclick = "";
        //linkObject.onClick = "";
        linkObject.removeAttribute("onclick");
        //linkObject.removeAttribute("onClick");
        addEvent(linkObject, 'click', simpleToggleMenuSession);
        
        //Préparation de la requête via XmlHttpRequest
        xmlhttp.open('get',addr, synch);
        
        //Bind d'une fonction pour gérer la réponse en asynchrone
        if(synch) {
        xmlhttp.onreadystatechange=function() {          
            //Si la requête est terminée
            if(xmlhttp.readyState == 4) {
                //Suppression del'image de preloading
                liImgElement.parentNode.removeChild(liImgElement);
                
                //Ajout du contenu récupéré dans la liste
                ulElement.innerHTML = xmlhttp.responseText ;
            }
        }
    }
        
        //Envoie des headers et de la requête
        xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=iso-8859-1');
        xmlhttp.send(null);
        
        //Gestion de la récéption en synchrone
        if(!synch) {
            if(xmlhttp.readyState == 4) {
                //Suppression del'image de preloading
                liImgElement.parentNode.removeChild(liImgElement);
                
                //Ajout du contenu récupéré dans la liste
                ulElement.innerHTML = xmlhttp.responseText ;
            }
        }
    }
    
    function addEvent(source, type, callback) {
        if (source.addEventListener) {
            source.addEventListener(type, callback, false);
            return true;
        } 
        else if(source.attachEvent) {
            var r = source.attachEvent("on"+type, callback);
            return r;
        } 
        else {
            eval('source.on' + type + '= callback') ;
            return true;
        }
    }
    
    function getStandardEvent(e) {
        if(e == null && window.event) {
            e = window.event ;
        }
        
        if(e.target == null && e.srcElement) {
            e.target = e.srcElement ;
        }
        
        if(! e.preventDefault ){
            e.preventDefault = function () { this.returnValue = false ; } ;
        }
        
        return e ;
    }
    
    function simpleToggleMenuSession(e) {
        e = getStandardEvent(e)  ;
        var linkObject = e.target  ;
        
        var display = linkObject.parentNode.lastChild.style.display;
        
        if(display == 'block') {
            linkObject.parentNode.lastChild.style.display = 'none';
        }
        else {
            linkObject.parentNode.lastChild.style.display = 'block';
        }
        
        e.preventDefault()  ;
        return false ;
    }
    
    function gotoPosition(parcours_id,parcours_loc,module_id,module_loc) {
        var ajaxUrlToMatch = "menu_session.php";
        //First level
        if(parcours_id == 0 && module_id == 0) {
            return;
        }
        
        if(parcours_id != 0) {
            //On déplie le parcours
            var link, list, i ;
            list = document.getElementsByTagName('a') ;
            
            for(i=0; i<list.length; i++) {
                var onclick, addr;
                link = list.item(i) ;
                
                if (link.getAttribute('onclick')) {
                    onclick = link.getAttribute('onclick');
                    if (onclick.indexOf(ajaxUrlToMatch) != -1 &&
                        onclick.indexOf('parcours_id='+parcours_id) != -1 && 
                        onclick.indexOf('parcours_loc='+parcours_loc) != -1 &&     
                        onclick.indexOf('action=getParcoursChilds') != -1) 
                    {
                        addr = onclick.substring(onclick.indexOf("'")+1,onclick.lastIndexOf("'"));
                        ajaxToggleMenuSession(link,addr,false);
                    }
                }
            }
            
            //On déplie le module
            if(module_id != 0) {
                var link, list, i ;
                list = document.getElementsByTagName('a') ;
                for(i=0; i<list.length; i++) {
                    var onclick, addr;
                    link = list.item(i) ;
                    
                    if (link.getAttribute('onclick')) {
                        onclick = link.getAttribute('onclick');
                        if (
                        onclick.indexOf(ajaxUrlToMatch) != -1 &&
                        onclick.indexOf('parcours_id='+parcours_id) != -1 && 
                        onclick.indexOf('parcours_loc='+parcours_loc) != -1 && 
                        onclick.indexOf('module_id='+module_id) != -1 && 
                        onclick.indexOf('module_loc='+module_loc) != -1 && 
                        onclick.indexOf('action=getModuleChilds') != -1) 
                        {
                            addr = onclick.substring(onclick.indexOf("'")+1,onclick.lastIndexOf("'"));
                            ajaxToggleMenuSession(link,addr,false);
                        }
                    }
                }
            }
        }
        else {
            var link, list, i ;
            list = document.getElementsByTagName('a') ;
            for(i=0; i<list.length; i++) {
                var onclick, addr;
                link = list.item(i) ;
                
                if (link.getAttribute('onclick')) {
                onclick = link.getAttribute('onclick');
                    if (onclick.indexOf(ajaxUrlToMatch) != -1 &&
                        onclick.indexOf('module_id='+module_id) != -1 && 
                        onclick.indexOf('module_loc='+module_loc) != -1 && 
                        onclick.indexOf('action=getModuleChilds') != -1) 
                    {
                        addr = onclick.substring(onclick.indexOf("'")+1,onclick.lastIndexOf("'"));
                        ajaxToggleMenuSession(link,addr,false);
                    }
                }
            }
        }
    }
    
/* =============================================================================
/* Fonction d'affichage des messages
*/

    function displayMessage(message,type) {
        var normalColor,highlightColor,timeBeforeHide,step,fadeInSpeed,fadeOutSpeed;

        //Définition des propriétés suivant le type de message
        if(type == "error") {
            normalColor = G_DM_ERREUR_normalColor       ;
            highlightColor = G_DM_ERREUR_highlightColor ;
            timeBeforeHide = G_DM_ERREUR_timeBeforeHide ;
            fadeInSpeed = G_DM_ERREUR_fadeInSpeed       ;
            fadeOutSpeed = G_DM_ERREUR_fadeOutSpeed     ;
            stepToHighlight = G_DM_ERREUR_stepToHighlight;
            stepToNormal = G_DM_ERREUR_stepToNormal;
            backgroundEffectPause = G_DM_ERREUR_backgroundEffectPause;
        }
        else {
            normalColor = G_DM_CONFIRM_normalColor       ;
            highlightColor = G_DM_CONFIRM_highlightColor ;
            timeBeforeHide = G_DM_CONFIRM_timeBeforeHide ;
            fadeInSpeed = G_DM_CONFIRM_fadeInSpeed       ;
            fadeOutSpeed = G_DM_CONFIRM_fadeOutSpeed     ;
            stepToHighlight = G_DM_CONFIRM_stepToHighlight;
            stepToNormal = G_DM_CONFIRM_stepToNormal;
            backgroundEffectPause = G_DM_CONFIRM_backgroundEffectPause;
        }

        //Affichage du message
        $(message).appendTo("body").width($("body").width())

        //Show message
        .fadeIn(fadeInSpeed,function(){
            //On show, fade the background
            $(this).backgroundFade({sColor:normalColor,eColor:highlightColor,steps:stepToHighlight},function() {
                var el = this;
                //Pause before unfade background
                setTimeout(function() {
                    //Unfade background
                    $(el).backgroundFade({sColor:highlightColor,eColor:normalColor,steps:stepToNormal},function(){
                        //Pause before hide message
                        setTimeout(function(){
                            $(el).fadeOut(fadeOutSpeed,function(){
                                $(el).stopAlwaysOnTop().remove();
                            });
                        },timeBeforeHide);
                    });
                },backgroundEffectPause);
            });
        })
        .alwaysOnTop();
    }
    
/* =============================================================================
/* Fonction de soumission d'un formulaire en AJAX
*/

   function ajaxSubmit(form) {
        var elements = form.elements;
        var data = "";
        var key,value;
        var xmlhttp = createXMLHttpRequest();
        
        if(xmlhttp == null) {
            alertCss("Unable to create XMLHttpRequest object for Ajax form submit.");
            return;
        }
        
        for(key=0;key<elements.length;key++) {      
            if(elements[key].name && elements[key].name.length > 0) {
                if(elements[key].type == "checkbox" || elements[key].type == "radio") {
                    if(elements[key].checked) {
                        value = elements[key].value;
                        data += elements[key].name + "=" + escape(value) + "&";
                    }
                } else if(elements[key].type == "select") {
                    value = $("option:selected",elements[key]).value;
                    data += elements[key].name + "=" + escape(value) + "&";
                } else {
                    value = (elements[key].name == "tiny_mce") ? tinyMCE.getContent() : elements[key].value;
                data += elements[key].name + "=" + escape(value) + "&";
            }
        }
        }
        
        if(data.length > 4) {
        data = data.substr(0,data.length-1);
        } else {
            data = null;
        }
        
        xmlhttp.open('POST',form.action,true);
        xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=iso-8859-1');
        xmlhttp.send(data);
        
        //Loading
        loadingLayout.show();
        
        //Gestion de la réponse
        xmlhttp.onreadystatechange = function() {          
            if(xmlhttp.readyState == 4) {
                loadingLayout.hide();
                processXmlHttpResponse(xmlhttp.responseXML);
            }
        }
    }
    
/* =============================================================================
/* Section qui initialise les éléments de formulaire doté de l'autompletition
*/

    function initializeAutocompleter() {
        $("input[@type=text][@rel]")
        .filter(".active_autocomplete")
        .each(function(){
            if($(this).parent("form[@action]").size() > 0) {
                var url = $(this).parent("form[@action]").attr("action") + "&action=" + $(this).attr("rel");
                
                $(this).Autocomplete({
                    source: url,
                    
                    minchars: 3,
                    autofill: false,
                    delay: 700,
                    
                    helperClass: 'autocompleter',
                    selectClass: 'selectAutocompleter',
                    
                    fx: {
                        type: 'fade',
                        duration: 400
                    },
                    
                    onSelect : function(xml) {
                        if(xml.url) {
                            window.location.href = xml.url;
                        }
                    }
                });
            }
        });
    }

    $(document).ready(function() {
        initializeAutocompleter();
    });

/* =============================================================================
/* Fonction de vérification et de login sur la plateforme
*/

    function LoginGanesha() {
    	var login = document.formulaire.txtuser.value ;
        document.formulaire.txtuser.value = '';
	
    	var pwd   = document.formulaire.txtpassword2.value ;
    	document.formulaire.txtpassword2.value = '' ;
    
    	if ( pwd == '' || login == '' ){
    		alertCss('L\'identifiant ou le mot de passe est vide !');
    		return(false);
    	}
    
        var data = {txtuser:login,md5password:MD5(pwd)};
    
        if(G_MODE_CNX == G_MODE_CNX_LDAP) {
            data.txtpassword = pwd;
        }
        
    	loadingLayout.show();
	
    	$.ajax({
            url : G_URL + "ganesha/index.php?action=ajax_login",
            type:"POST",
            dataType : "xml",
            data : data,
            complete : function(xmlhttp,typeOfSuccess){
                var xml = xmlhttp.responseXML;
                var text = xmlhttp.responseText;
                
                if($("action",xml).size() > 0) {
                    loadingLayout.hide();
                    
                    $("action",xml).each(function(){
                        type = $("type", this).text();
                        content = $("content", this).text();
                        
                        if(type == "confirm-message") {
                            displayMessage(content,"confirm");
                        } else if(type == "error-message") {
                            displayMessage(content,"error");
                        } else if(type == "redirection") {
                            window.location.replace(content);
                        } else if(type == "alert-css") {
                            setTimeout(function() {
                                alertCss(content);
                            },100);
                        } else {
                            alertCss(text);
                        }
                    });
                } else {
                    loadingLayout.hide();
                    alertCss("Une erreur est survenue : <br>" + text);
                }
            },
            error : function(xmlhttp,errorMessage){
                loadingLayout.hide();
                alert("Erreur AJAX::ajax_login");
            }
        });
    
    	return (false);
    }

/* =============================================================================
/* Function permettant de récupérer ses accès à Ganesha
*/

    function getLoginGanesha(form) {
    	var adresse = form.EmailSend.value	;
    
    	loadingLayout.show();
    	$.post(form.action,{email:adresse},function(data){
            loadingLayout.hide();
            processXmlHttpResponse(data);
        });
    	return (false);
    }
    
    function LoginInvite(user_id,confirmConnection) {
    	var login = function() {
    	loadingLayout.show();
    	$.get(G_URL + "ganesha/index.php?action=ajax_loginInvite&id=" + user_id,function(data){
            loadingLayout.hide();
            processXmlHttpResponse(data);
        });
        }
        
        if(confirmConnection) {
            confirmCss(guestAllreadyUsed,function(){
                setTimeout(login,500);
            });
        } else {
            login();
        }
        
    	return (false);
    }
    
    

/* =============================================================================
/* Fonction générique traitant la réponse d'une requête HTTP
*/
function processXmlHttpResponse(xml) {
    var type,content,expr,method;

    $("action",xml).each(function(){
        type = $("type", this).text();
        content = $("content", this).text();
        
        if(type == "confirm-message") {
            displayMessage(content,"confirm");
        }
        else if(type == "error-message") {
            displayMessage(content,"error");
        }
        else if(type == "redirection") {
            window.location.replace(content);
        }
        else if(type == "alert-css") {
            setTimeout(function() {
                alertCss(content);
            },100);
        }
        else if(type == "notification") {
            $(content).appendTo("body").Slide({maxElement:1});
        }
        else if(type == "html-replacement") {
            expr = $("expr", this).text();
            
            //Si on supprime un formulaire TinyMCE, on remove le control
            if($(expr).html().indexOf("tiny_mce") != -1) {
                tinyMCE.execCommand('mceRemoveControl', false, "tiny_mce");
            }

            //Html replacement
            $(expr).before(content).remove();
        
            //Si on ajoute un formulaire TinyMCE, on add le control
            if(content.indexOf("tiny_mce") != -1) {
                tinyMCE.execCommand('mceAddControl', false, "tiny_mce");
            } 
        } else if(type == "html-insertion") {
            expr = $("expr", this).text();
            method = $("method", this).text();
            eval("$(" + expr + ")." + method + "(" + content + ");");  
        } else {
            alertCss(modificationDone);
        }
    });
    }

/* =============================================================================
/* Gestion du système de notification
*/

function checkoutNotification() {
    if(G_CNX.length > 0 && G_GUSERID > 0) {
        var addr = G_URL + "ganesha/index.php?connexion=" + G_CNX + "&user_id=" + G_GUSERID + "&action=ajax_checkout_notification";

    $.ajax({
        type : "GET",
        url : addr,
        dataType : "xml",
        complete  : function(xmlhttp,typeOfSuccess){
                var contentType = xmlhttp.getResponseHeader("Content-type");
                var isXML = false;
                
                if(contentType && contentType.toLowerCase().indexOf("/xml") != -1) {
                    isXML = true;
                }
                
                //IE s'invente son propre status 1223 O_O'
                if(xmlhttp.status == 204 || xmlhttp.status == 1223) {
                    //Relance du checkout
                    setTimeout(checkoutNotification,G_NOTIF_refreshDelay);
                }
                else if(isXML) {
                    var isDeconnected = false;
                var content, type;
                var i = 0;
                
                    //Pour chaque action de la response XML
                $("action",xmlhttp.responseXML).each(function(){
                        //On récupère son type et son contenu
                    type = $("type", this).text();
                    content = $("content", this).text();
                    
                        //Si c'est un timeout de la connexion
                        if(type == "deconnected") {
                            isDeconnected = true;
                            
                            //Affiche message
                            confirmCss(deconnectedMessage,function() {
                                window.location.replace(content);
                            });
                        }
                        
                        //Si c'est un type "notification"
                    if(type == "notification") {
                            //Tant qu'on n'a pas dépasser le nombre maximum de notification par lot
                        if(i++ < G_NOTIF_maxElement) {
                            $("body").append(content);
                        }
                    }
    });
                
                    //Traitement du lot de notification
                $("div.notification").Slide({maxElement:G_NOTIF_maxElement});
    
                    //Relance du checkout si on n'est pas deconnecté
                    if(!isDeconnected) {
    setTimeout(checkoutNotification,G_NOTIF_refreshDelay);
}
            }
        }
    });
}
}

$(document).ready(function(){
    //Sauf IE6
    if(!(jQuery.browser.msie && navigator.appVersion.indexOf("MSIE 6.0") != -1)) {
        setTimeout(checkoutNotification,G_NOTIF_startDelay);
    }
});

/* =============================================================================
/* Confirme deconnexion
*/

function confirmDeconnexion(url) {
    confirmCss(confirmDeconnection,function() {
        window.location.href = url;
    });
}

/* =============================================================================
/* Liens ajax pour les ACL
*/

function changerACL(link) {
   var id = "#" + $(link).parents(".tab_content").attr("id");
   loadTabContent(id, $(link).attr("href")); // fonction du fichier tab.js
}

/* =============================================================================
/* Javascript pour masquer / afficher le menu de gauche
*/

function toggleLeftMenu(target) {
    //Reset des valeurs
    $("#contenu").css({
        width : "",
        margin : "",
        paddingLeft : ""
    });
    
    //Toggle
    $("#nom").toggle();
    if(setFCT(["anema2","anema","triangl","bcd","neutre","ch_perpignan","idap"])) {
        $("#profil").toggle();
    } else {
    $("#footer").toggle();
    }
    
    $("#colonne_gauche").slideToggle(function(){
        //Si le menu est masqué
        if($("#colonne_gauche:visible").size() == 0) {
            $("#contenu").css({
                width : "96%",
                margin : "0",
                paddingLeft : "2%",
                paddingRight : "2%"
            });
            
            if(setFCT(["anema2","anema","triangl","neutre"])) {
                $("#content").css("paddingBottom",0);
            }
            
            $.cookie("admin_menu_hide",true);
            $(target).attr("id","menu_admin_toggle_show");
        } else {
            if(setFCT(["anema2","anema","triangl","neutre"])) {
                $("#content").css("paddingBottom","");
            }
        
            $.cookie("admin_menu_hide",null);
            $(target).attr("id","menu_admin_toggle_hide");
        }
    });
}

$(document).ready(function(){
    if($.cookie("admin_menu_hide") && (setFCT(["anema2","anema","triangl","bcd","neutre","ch_perpignan","idap"]))) {
        $("#content").css("paddingBottom",0);
        $("#profil").hide();
        $("#footer").show();
    }
});

/* =============================================================================
/* Fonctions pour l'update de la base de données lors de la réplication
*/
var refreshLogTimer;

function getLog() {
    var el = $("#log").find("td").get(1);
    
    $.get("../install/log/install.html",function(data){
        data = data.replace(/(\r\n)|(\n\r)|\r|\n/g,"<br>");
        $(el).html("");
        $(el).html(data);
    });
    
    loadingLayout.hide(); //Pour reprendre la taille totale de l'ecran à chaque ajout
    loadingLayout.show();
    
    refreshLogTimer = setTimeout(function(){
        getLog(el);
    },2000);
}

function StartReplicUpdateBdd(form) {
    loadingLayout.show();
    
    $.get(form.action,function(xml){
        clearTimeout(refreshLogTimer);
        loadingLayout.hide();
        processXmlHttpResponse(xml);
    });
    
    $(form).find("input[@type=button]").hide();
    
    //On lance le chargement du log
    setTimeout(function(){
        getLog();
    },1500);
    
    return false;
}



/* =============================================================================
/* PAB
*/
var image_off 	= G_URL_THEMES + 'images/icones/checkbox_vide.gif' ;
var image_on 	= G_URL_THEMES + 'images/icones/checkbox.gif' ;
var image_over 	= G_URL_THEMES + 'images/icones/checkbox_rollover.gif' ;
var src = '' ;

function mouseOver(nom) {
	src = '' ;
	if ( document.images[nom].src != image_on ) {
		src = document.images[nom].src ;
		document.images[nom].src = image_over ;
	}
}

function mouseOut(nom) {
	if ( src != '' ) {
		document.images[nom].src = src ;
	}
}

function mouseClick(nom,value) {
    if ( document.formulaire[value].value == 0 ) {
		document.images[nom].src = image_on ;
		document.formulaire[value].value = 1 ;
	} else {
		document.images[nom].src = image_off ;
		document.formulaire[value].value = 0 ;
	}
	
	src = '' ;
}

    function ValidLoad(form) {
        //Loading
        loadingLayout.show();
        submitForm(form);
    }

    function ValidExportPDF(form) {
        //Loading
        if ( form.form_target.checked) {
            form.target = "_blank" ;
        } else {
            form.target = "_top" ;
        }
       submitForm(form);
    }
