
/**
* @namespace Namespace global des javascripts MAIF
* @name window.maif
 */
window.maif={};

/**
* @namespace Namespace de la gestion des variables temporaires MAIF
* @name window.maif.temps
 */
window.maif.temps={};

/**
* @namespace Namespace de la gestion des evenements MAIF
* @name window.maif.evenements
 */
window.maif.evenements={};

/**
* @namespace Namespace de la gestion des communications AJAX
* @name window.maif.ajax
 */
window.maif.ajax={};

/**
* @namespace Namespace de la gestion des erreurs MAIF
* @name window.maif.error
 */
window.maif.error={};




////////////////////// IMPLEMENTATION

///////// window.maif.ajax


/**
* Permet l'appel d'une action struts en passant un formulaire et en mettant a jour une div precise de la page
* @param {String} urlAction Url ( namespace + nom + parametres eventuels) 
* @param {String} formulaire
* @param {String} div permettant l'affichage de la reponse
* @param {Object} tableau contenant les parametres de l appel ({param1:value,param2:value,...}), permet de mettre a jour des attributs de la classe action
*/
window.maif.ajax.appelUrl = function (url, formulaire, divReponse, oContent)
{     
    var kw = {
            preventCache: true,
            //url appelee
            url:  url,              
            form: formulaire, 
            handle:  jQuery.NiceJForms.saveNiceSelects(),                                                
            handleAs: "text",
            content: oContent,                        
            load: function (data, ioArgs) {
            //evenement load declenche au retour de l appel ajax
            
            if(data.indexOf("<!DOCTYPE") > -1 || data.indexOf("<!-- erreur -->") > -1)
            {
                //Si le retour est une page erreur technique   
                dojo.body().innerHTML = data;
                
            }else{
                //Si le retour est une div on reconstruit la page  
                dojo.byId(divReponse).innerHTML = data;
                //on recupere les infos pour les stats
                window.maif.ajax.countStat();    
            }     
                   
            //Reconstruction des selects avec niceforms.js (cf gabarit publicis)                       
            jQuery.NiceJForms.replaceSelectsReload();
            //Reinitialisation du javascript pour la classe thickbox  
            tb_init('a.thickbox, area.thickbox, input.thickbox');
            document.body.style.cursor = window.maif.temps[ 'cursor-default' ];
          
            //Reinitialisation des panelShowHide
            jQueryShowPanel("a#showHidePanel_1", "#panel_1");
          
            //Reinitialisation des bubbleHelp
            if(jQuery(".bubbleHelp").size() > 0){
                bubbleHelp.init();
                //Les bubbles help s affichent normalement pendant 3 secondes apres le chargement de la page
                // lors d une reconstruction de page on empeche ce comportement                  
                bubbleHelp.hide(".bubbleHelp");          
                }
          
            //Gestion du focus (tout sauf ie)             
            if(dojo.isIE = 0)
            {
	            if (document.getElementById)
	                var returnVar = document.getElementById(window.maif.evenements.elementFocusedId.id);
	            else if (document.all)
                    var returnVar = document.all[window.maif.evenements.elementFocusedId.id];
                else if (document.layers)
                    var returnVar = document.layers[window.maif.evenements.elementFocusedId.id]; 		            
		            if(window.maif.evenements.elementFocusedId != null && window.maif.evenements.elementFocusedId != ''){
		                if(window.maif.evenements.elementFocusedId.type == 'text'){
		                  returnVar.focus();
		                }
		            }
                }                       
            },
            mimeType: "text/html",
            error : function (data, ioArgs) {
                //En cas d erreur de traitement dojo lors de l appel ajax                           
                console.error('Error: ', data.message);
                document.body.style.cursor = window.maif.temps[ 'cursor-default' ];
            }
    };        
      

    //Si le navigateur accepte les cookies et que l accessibilite n est pas activee
      if(navigator.cookieEnabled && window.maif.accessibilite != "on" && window.maif.ajax.getAccessibiliteSession != "on"){
            window.maif.temps[ 'cursor-default' ] = document.body.style.cursor; 
            document.body.style.cursor = 'wait';
            dojo.xhrPost(kw);
            //On empeche la soumission de la page
            return false;
      }
      //On permet la soumission de la page
      return true;      
};


/**
* Permet l'appel d'une action struts en passant un formulaire et en mettant a jour une div rpecise de la page
* @param {String} urlAction Url ( namespace + nom) de l'action visee (sans le suffixe Ajax.action ) 
* @param {String} formulaire
* @param {String} div permettant l'affichage de la reponse
*/
window.maif.ajax.appelAction = function (action, formulaire, divReponse)
{        
	var kw = {
	        preventCache: true,
	        //action ajax
	        url:  action + "Ajax.action",              
	        form: formulaire, 
	        handle:  jQuery.NiceJForms.saveNiceSelects(),                                                
	        handleAs: "text",
	        load: function (data, ioArgs) {
	        if(data.substr(0,11) == "forceReload")
	        {                
	            //action generique                   
	           window.maif.ajax.soumettreAction(formulaire,action + ".action");
	            }
	        else if(data.indexOf("<!DOCTYPE") > -1 || data.indexOf("<!-- erreur -->") > -1){
	         //au cas ou on aurait une page complete generee dans le div, on affiche le resultat dans toute la page
	         //pb si session inactive depuis trop longtps par exemple                   
	          //window.maif.ajax.soumettreAction(formulaire,action + ".action");
	          dojo.body().innerHTML = data; 
	        } else{
	 
	             dojo.byId(divReponse).innerHTML = data;
	             //on recupere les infos pour les stats
	         window.maif.ajax.countStat();    
	        }     
	         
	
	                         
	         jQuery.NiceJForms.replaceSelectsReload();  
	         tb_init('a.thickbox, area.thickbox, input.thickbox');
	         document.body.style.cursor = window.maif.temps[ 'cursor-default' ];

            //Reinitialisation des panelShowHide
            jQueryShowPanel("a#showHidePanel_1", "#panel_1");
	       
            //Reinitialisation des bubbleHelp             
            if(jQuery(".bubbleHelp").size() > 0){
                bubbleHelp.init();
                //Les bubbles help s affichent normalement pendant 3 secondes apres le chargement de la page
                // lors d une reconstruction de page on empeche ce comportement  
                bubbleHelp.hide(".bubbleHelp");   
	        }
            
            // Reinitialisation des tooltip et infosbulles
            try{
                jQuery("a.infobulles, a.tooltip").tooltip({
                     id : 'infobulle',
                     track: true, 
                     delay: 0, 
                     showURL: false,
                     showBody: "|",
                     top: 20,
                     left: 0
                 });
             }catch( oExpA ){
                 window.maif.error.log( oExpA, 'jQuery(document).ready.infobulle' );
             }
	       
	         //tout sauf ie 	        
	         if(dojo.isIE = 0)
	   		{
	         if (document.getElementById)
	             var returnVar = document.getElementById(window.maif.evenements.elementFocusedId.id);
	         else if (document.all)
	             var returnVar = document.all[window.maif.evenements.elementFocusedId.id];
	         else if (document.layers)
	             var returnVar = document.layers[window.maif.evenements.elementFocusedId.id]; 
	        
	         if(window.maif.evenements.elementFocusedId != null && window.maif.evenements.elementFocusedId != ''){
	         	if(window.maif.evenements.elementFocusedId.type == 'text'){
	                 			returnVar.focus();
	                     	}
	         		}
	       	}
	        
	        
	             
	        },
	        mimeType: "text/html",
	        error : function (data, ioArgs) {                           
	            //alert(data.message);   
	           	console.error('Error: ', data.message);
	           	document.body.style.cursor = window.maif.temps[ 'cursor-default' ];
	            //window.maif.ajax.soumettreAction(formulaire,action + ".action");
	            //dojo.body().innerHTML =  ioArgs.xhr.responseText; 
	                       
	        }
	};        
      

	//Si le navigateur accepte les cookies et que l accessibilite n est pas activee
      if(navigator.cookieEnabled && window.maif.accessibilite != "on" && window.maif.ajax.getAccessibiliteSession != "on"){
			window.maif.temps[ 'cursor-default' ] = document.body.style.cursor; 
			document.body.style.cursor = 'wait';
			dojo.xhrPost(kw);
			//On empeche la soumission de la page
			return false;
      }
      //On permet la soumission de la page
      return true;      
};
   
/**
* soumission d'un formulaire classique
* Cette methode est utilisee pour appeler une action depuis un evenement javascript
*  
* @param {String} formulaire
* @param {String} urlAction Url ( namespace + nom) de l'action visee (avec le suffixe .action )
*
**/

window.maif.ajax.soumettreAction = function (pIdFormulaire,pNomAction) {
	//Si le navigateur accepte les cookies et que l accessibilite n est pas activee
	if(navigator.cookieEnabled && window.maif.accessibilite != "on" && window.maif.ajax.getAccessibiliteSession != "on"){
		//si l accessibilite n est pas activee on soumet la page
	    document.forms[pIdFormulaire].action = pNomAction;
	    document.forms[pIdFormulaire].submit();
	}
};


/**
* setaccessibilite 
*
**/

window.maif.ajax.setAccessibilite = function (valeur) {
window.maif.ajax.callJsonAccessibilite();
if(valeur == "on"){
    dojo.cookie('accessibilite', valeur, {expires :365,path: '/'});
    }else{
    dojo.cookie('accessibilite', null, {expires :-1,path: '/'});
    }
    
      window.maif.servicesAccessibilite["Accessibilite.setAccessibilite"](valeur);
             
 
};

/**
* activerScriptsAccessibles 
*
**/
window.maif.ajax.activerScriptsAccessibles = function () {
window.maif.ajax.setAccessibilite("on");
};

/**
* desactiverScriptsAccessibles 
*
**/
window.maif.ajax.desactiverScriptsAccessibles = function () {
window.maif.ajax.setAccessibilite("off");
};


/**
* get accessiblite
*
**/
window.maif.ajax.getAccessibilite = function (){
window.maif.ajax.callJsonAccessibilite();
window.maif.servicesAccessibilite["Accessibilite.getAccessibilite"]().addCallback(function(result) {
window.maif.ajax.getAccessibiliteSession = result;

});

};
/**
* get stat
*
**/
window.maif.ajax.countStat = function (){
window.maif.ajax.callJsonStat();
window.maif.servicesStat["Stat.getStatComplete"]().addCallback(function(result) {
	window.maif.ajax.callJsonStat();
	window.maif.ajax.getStatAjax = result;
		window.maif.servicesStat["Stat.getNiveau2"]().addCallback(function(result) {
		window.maif.ajax.getNiveau2Ajax = result.value;
		/*pour affichage stat dans le bandeau*/
		if(dojo.byId("statXiti")!=null){
		dojo.byId("statXiti").innerHTML = "<b>Stats Xiti rechargement dynamique</b>: Niveau 2 :" + result.value + " // page : "+ window.maif.ajax.getStatAjax;
		}
		
		try{
		xt_med('F', window.maif.ajax.getNiveau2Ajax, window.maif.ajax.getStatAjax);
		}catch( oExpA ){
			window.maif.error.log( oExpA, 'callbakc.xt_med' );
		}
		});
});

};



/**
 * Methode de stats Xiti PDF.
 */
window.maif.xitiPDF = function (o,niveau2Xiti,chapitreXiti,sousChapitreXiti,sousSousChapitreXiti,pageXiti){
    window.maif.ajax.getStatAjax = xtpage;
    window.maif.ajax.getNiveau2Ajax = xtn2;

    var statsXitiPage = '';

    // Niveau par defaut, celui de la page
    if((niveau2Xiti == null) || (niveau2Xiti == ''))
    {
        niveau2Xiti = window.maif.ajax.getNiveau2Ajax;
    }

    if(((chapitreXiti != null) && (chapitreXiti != ''))
            || ((sousChapitreXiti != null) && (sousChapitreXiti != ''))
            || ((sousSousChapitreXiti != null) && (sousSousChapitreXiti != ''))
            || ((pageXiti != null) && (pageXiti != '')))
    {
        statsXitiPage = '';
        var append = '0';
        if((chapitreXiti != null) && (chapitreXiti != ''))
        {
            statsXitiPage = chapitreXiti;
            append='1';
        }
        if((sousChapitreXiti != null) && (sousChapitreXiti != ''))
        {
            statsXitiPage = statsXitiPage + ((append == '0')?'':'::') + sousChapitreXiti;
            append='1';
        }
        if((sousSousChapitreXiti != null) && (sousSousChapitreXiti != ''))
        {
            statsXitiPage = statsXitiPage + ((append == '0')?'':'::') + sousSousChapitreXiti;
            append='1';
        }
        if((pageXiti != null) && (pageXiti != ''))
        {
            statsXitiPage = statsXitiPage + ((append == '0')?'':'::') + pageXiti;
            append='1';
        }
    }
    else
    {
        // On retire le dernier element qui correspond a la page.
        statsXitiPage = window.maif.ajax.getStatAjax;
        var statSplit = statsXitiPage.split('::');                
        statsXitiPage = '';
        for(var i=0; i< (statSplit.length - 1); i++)
        {
            if(i>0)
            {
                statsXitiPage = statsXitiPage + '::';
            }
            statsXitiPage = statsXitiPage + statSplit[i];
        }

        // Ajout du pdf en page
        if(o != null)
        {
            pageXiti = o.href.replace('\\','/');
            var pageSplit = pageXiti.split('/');
            pageXiti = pageSplit[pageSplit.length - 1];
            statsXitiPage = statsXitiPage + '::' + pageXiti;
        }
    }

    try{
        xt_med('C', niveau2Xiti, statsXitiPage, 'T');
    }catch( oExpA ){
        window.maif.error.log( oExpA, 'callbakc.xt_med' );
    }

};

/**
* appelle du service pour accessiblite
*
**/

window.maif.ajax.callJsonAccessibilite = function (){

window.maif.servicesAccessibilite = new dojox.rpc.Service({
        target:"/JSON-RPC",
        transport:"POST",
        envelope:"JSON-RPC-1.0",
         //contentType:"application/json",  
       contentType:"text/json-comment-filtered",   
        services:{
                "Accessibilite.getAccessibilite":{ 
                returns:{"type":"string"}
                },
                "Accessibilite.setAccessibilite":{ 
                parameters:{"type":"string"}
                }
                }
                });
};


/**
* appelle du service pour statistique
*
**/

window.maif.ajax.callJsonStat = function (){

window.maif.servicesStat = new dojox.rpc.Service({
        target:"/JSON-RPC",
        transport:"POST",
        envelope:"JSON-RPC-1.0",
       contentType:"application/json",
       //contentType:"text/json-comment-filtered",   
        services:{
                "Stat.getStatComplete":{ 
                returns:{"type":"string"}
                },
                "Stat.getNiveau2":{ 
                returns:{"type":"string"}
                }
                }
                });
};


///////// window.maif.evenements

/**
 * pour recuperer le focus sous ff
 */
window.maif.evenements.onElementFocused=function(e)
{
	{
		var target; //initialisation		
		
		if(dojo.isIE > 5)
		  { 		
		   target = document.activeElement; //Si IE
		  } 
		else  { 
			
		   target = e ? e.explicitOriginalTarget : null;  // Si Firefox
		  }
		window.maif.evenements.elementFocusedId = target; 
		}
}

/**
* Permet d'ajouter un evenement sur un HTMLElement<br/>
* Tests ok sur : IE6, FF2, FF3
* @param {HTMLElement} elem Element dans la DOM
* @param {String} name Nom de l'evenement ex : si onscroll passer "scroll"
* @param {Function} func
*/
window.maif.evenements.addCustomEvent=function(elem,name,func){
    if(name=='load'){
        if (window.addEventListener)  window.addEventListener("load", func, false);
        else if (document.addEventListener)   document.addEventListener("load", func, false);
        else if (window.attachEvent)  window.attachEvent("onload", func);
    }else{
        if (elem.addEventListener)  elem.addEventListener(name, func, false);
        else    elem.attachEvent("on"+name, func);          
    }
};

/**
* Permet de definir la position de la page sur tous les formulaires de la page.
* Pour cela, on recherche les inputs nommes 'scrollPos'
* Tests ok sur : IE6, FF3
*/
window.maif.defineScrollPos=function(){
    try{
		ar=document.getElementsByName('scrollPos');
		siz=ar.length;   
		scr=document.documentElement.scrollTop ||document.body.scrollTop || window.pageYOffset || 0
		for(var i=0;i<siz;i++){
    		ar[i].value=scr;
		}
	}
	catch(ex) {
		// erreur
		ar=document.getElementsByName('scrollPos');
		siz=ar.length;
		for(var i=0;i<siz;i++){
		    ar[i].value=0;
		}
    }
};

/**
* Permet de definir la position de la page sur tous les formulaires de la page.
* Pour cela, on recherche les inputs nommes 'scrollPos'
* Tests ok sur : IE6, FF3
*/
window.maif.manageFormSubmit=function(target) {
    target._submit = target.submit;
    target.addedFunction = function() {
	   try{
	       ar=document.getElementsByName('scrollPos');
	       siz=ar.length;   
	       scr=document.documentElement.scrollTop ||document.body.scrollTop || window.pageYOffset || 0;
	       for(var i=0;i<siz;i++){
	           ar[i].value=scr;
	       }
	   }
	   catch(ex) {
	       // erreur
	       ar=document.getElementsByName('scrollPos');
	       siz=ar.length;
	       for(var i=0;i<siz;i++){
	           ar[i].value=0;
	       }
	   }
    };
    target.submit = function (event) {
        var target = event ? event.target : this;
        if (target.addedFunction) {
            target.addedFunction();
        }
    
        target._submit();
    };

    window.maif.evenements.addCustomEvent(target, "submit", target.addedFunction); 
};

/**
* Permet de determiner si le navigateur est IE6
* Retoune un boolen indiquant si le nagigateur est IE6
*/
window.maif.isIE6=function(){
    try{
        return ( navigator.userAgent.toLowerCase().indexOf( 'msie 6' ) != -1 ) && ( navigator.userAgent.toLowerCase().indexOf( 'msie 7' ) == -1 );
    }catch( oExp ){
        window.maif.error.log( oExp, 'window.maif.isIE6' );
        return false;
    }
};


/**
* Permet de recuperer la valeur d'une variable de contenu dans l'url
* Retoune une chaine contenant la valeur de la variable
*/
window.maif.getUrlVar=function( sVar ){
    try{
        var sUrl = location.href.substring( location.href.indexOf( '?' ) + 1, location.href.length ) + '&';
        if( sUrl.indexOf( '#' ) != -1 )
            sUrl = sUrl.substring( 0, sUrl.indexOf( '#' ) ) + '&';
        var sResult = '';
        sVar = sVar + '=';
        var iSize = sVar.length;
        if( sUrl.indexOf( sVar ) !=-1 )
            sResult = sUrl.substring( sUrl.indexOf( sVar ) + iSize, sUrl.length ).substring( 0, sUrl.substring( sUrl.indexOf( sVar ) + iSize, sUrl.length ).indexOf( '&' ) );
        return sResult
    }catch( oExp ){
        window.maif.error.log( oExp, 'window.maif.getUrlVar' );
        return '';
    }
}

/**
* Permet la creation d'une popup de confirmation
* @param {sName} nom de la popup, en correspondance avec la variable "popconfirm" de l'url
* @param {sText} message de la popup
* @param {sYes} texte du bouton oui
* @param {eYes} evenement du bouton oui
* @param {sNo} texte du bouton non
* @param {eNo} evenement du bouton non
*/
window.maif.setPopupConfirm=function( sName, sText, eYes, eNo ){
    try{
       if( !window.maif.temps.oPopupConfirm )
           window.maif.temps.oPopupConfirm = new Array();
       window.maif.temps.oPopupConfirm[ sName ] = { sText:sText, eYes:eYes, eNo:eNo };
    }catch( oExp ){
        window.maif.error.log( oExp, 'window.maif.setPopupConfirm' );
        return '';
    }
}

/**
* Permet de recuperer les donnees d'une popup de confirmation
* Retoune un pseudo object contenant les donnees de la popup de confirmation
* @param {sName} nom de la popup, en correspondance avec la variable "popconfirm" de l'url
*/
window.maif.getPopupConfirm=function( sName ){
    try{
        if( !window.maif.temps.oPopupConfirm || !window.maif.temps.oPopupConfirm[ sName ] )
           return false;
       return window.maif.temps.oPopupConfirm[ sName ];
    }catch( oExp ){
        window.maif.error.log( oExp, 'window.maif.getPopupConfirm' );
        return false;
    }
} 

/**
* Permet la fermeture de la popup de dialog
*/
window.maif.closeDialog=function(){
    try{
        confDialog.hide();
    }catch( oExp ){
        window.maif.error.log( oExp, 'window.maif.closeDialog' );
        return false;
    }
} 


/**
* Permet la capture des erreurs javascript
* Recuperation du message d'erreur : mes = oExp.message
*/
window.maif.error.log=function( oExp, sPath ){

};

//ajout de la classe hasJs dans la balise HTML pour tout les css liees au javascript
document.documentElement.className = (document.documentElement.className + ' ' || '') + 'hasJS';