// default text in the search input
var switchMDR = "DESACTIVATION_MDR" ;

function submitEventListener(){
   if (event.keyCode==13){
        button = document.getElementById('bouton_mdrech');
        button.focus();
   }
}

/**
* Permet de vider le champ de saisie du mdr
*/
function removeValue(control, defaultLibSearch){
    if(typeof defaultLibSearch != "undefined"){
        if (control.value == defaultLibSearch) {
            control.value = '';
        }
    }
    else {
        control.value = '';
    }
}

function resetValue(control, defaultLibSearch){
    // if the text is empty, we set it with the default label
    if (control.value == ''){
        control.value = defaultLibSearch;
    }
}

/*
* permet d'initialiser le champs de recherche
* notamment en renseignant le champs de saisie
* inputSearchedText : id du champ de saisie
* champUrl : nom du champ dans l url
*/
function initMDR(inputSearchedText, champUrl){
    var valeurs = '';
    if (window.location.href.indexOf('/nettools/allsearch.search')!=-1 || window.location.href.indexOf('/nettools/advsearch.search')!=-1) {
        try {
            valeurs = decodeURIComponent(window.location.search);
        }
        catch(e) {
            valeurs = unescape(window.location.search);
        }
        if (valeurs) {            
            // Ajout du texte recherche dans le champ texte du bandeau de recherche
            var text = valeurs.substr(valeurs.indexOf(champUrl + "=") + (champUrl.length+1));
            text = text.substring(0,text.indexOf("&")!=-1 ? text.indexOf("&") : text.length);
            if (text) {
                var input = document.getElementById(inputSearchedText);
                input.value = text.replace(/\+/g,' ');
            }
        }
    }
}

/* ############# FONCTION SUITE REFONTE MDR 5.8 ############### */
function hideAllNode(_obj){
    var tree = getElement(_obj, true, "") ;
    if(tree){
        var eltsUl = tree.getElementsByTagName("UL") ;
        if(eltsUl){
            for(var i=0 ; i<eltsUl.length ; i++){
                var elt = eltsUl[i] ;
                if(elt && elt.className && elt.className == "arbo_fam"){
                    hideBloc(elt) ;
                }
            }
        }
        
        var eltsSpan = tree.getElementsByTagName("SPAN") ;
        if(eltsSpan){
            for(var i=0 ; i<eltsSpan.length ; i++){
                var elt = eltsSpan[i] ;
                if(elt && elt.className && elt.className == "expanded"){
                    elt.className = "title"
                }
            }
        }
    }
}

/**
* Permet d'etendre un noeud de l'arbo gauche
*/
function expandNode(_obj, _childNodeId, _treeId){    
    //changement de l'etat pour le noeud courant
    if(_obj){    
        if(_obj.className == "title"){
            //on cache tous les anciens noeuds
            hideAllNode(_treeId) ;
    
            _obj.className = "expanded" ;
            displayBlocId(_childNodeId) ;
        }
        else{
            _obj.className = "title" ;
            hideBlocId(_childNodeId) ;
        }
    }
}

/* ############# FONCTION pour cacher la saisie predictive ############### */
var dansDiv=false;

function cacheRecherchePredi(e){
    if(!dansDiv){
        if(typeof hidePredictiveSearchList != "undefined"){
            hidePredictiveSearchList();
        }
    }
}

//On ne met le onclick que si le formulaire de recherche est present
window.document.onclick = cacheRecherchePredi ;


/* ############# FONCTION pour tester le texte saisie ############### */
/**
 * Permet de faire les verifications necessaires avant de lancer le mdr
*/
function checkSearch(_idCentral, _messageAlert, _idInputTexte, _defaultText, _tagAnalytics){
    var result = checkSaisie(_messageAlert, _idInputTexte, _defaultText) ;
    if(result){
        setMdrValue(_idCentral, _idInputTexte,  _tagAnalytics) ;
        doLinkTag(_tagAnalytics) ;
    }
    return result ;
}


/**
 * Permet de setter correctment la central pour realiser correctement la recherche
*/
function setMdrValue(_idCentral, _idInputTexte, _tagAnalytics){
    var zoneTexte= "";
    if(getElement(_idInputTexte, true, "")){
        zoneTexte = getElement(_idInputTexte, true, "").value ;
    }
    
    document.getElementsByName("text")[0].value = zoneTexte ;

    //verification de la central => l'internaute vient il d'un autre pays
    var idCentral = _idCentral ;
    
    //Cas 1 : Recuperation du cookie present sur toutes les pages pour la centrale
    var valueCookieCountry = getCookie("country") ;
    if(valueCookieCountry && mapUrlParPays){
        var enseigneSiteObj = mapUrlParPays.get(valueCookieCountry) ;
        if(enseigneSiteObj){
            idCentral = enseigneSiteObj.getCentrale() ;
        }
    }
    //Cas 2 : Recuperation de la centrale depuis l'URL pour la page mdr
    else if(mapUrlParPays){
        var params = getParameters() ;
        if(params){
            for(var i=0 ; i<params.length ; i++){
                var id = params[i][0] ;
                if(id.indexOf("central") > -1){
                    idCentral = params[i][1] ;
                }
            }
        }
    }
    
    document.getElementsByName("central")[0].value = idCentral ;
}
            
/**
 * Permet de verifier la validite du mot a rechercher
*/
function checkSaisie(_messageAlert, _idInputTexte, _defaultText){
    if(document.getElementById(_idInputTexte)){
        var zoneTexte = document.getElementById(_idInputTexte).value ;

        if(zoneTexte && zoneTexte != '' && zoneTexte != _defaultText){
            //Liste des caracteres interdits 
            var charList = new ArrayList()
            charList.add("~") ;
            charList.add("&") ;
            charList.add("+") ;
            charList.add("{") ;
            charList.add("}") ;
            charList.add("[") ;
            charList.add("]") ;
            charList.add("<") ;
            charList.add(">") ;
            charList.add("^") ;
            charList.add("%") ;
        
            for(var i=0 ; i<charList.length() ; i++){
                if(zoneTexte.indexOf(charList.get(i)) > -1){
                    alert(_messageAlert) ;
                    return false ;
                }
            }
            return true ;
        }
        else{
            alert(_messageAlert) ;
            return false ;
        }
    }
    alert(_messageAlert) ;
    return false ;    
}

// liste des affichages disponibles, doit correspondre aux liens dans l ordre
var viewClassNames = ['grid', 'list'];

/**
 * Permet d initialiser l affichage choisi par l utilisateur
 * lecture dans un cookie du choix
 * Param idParentNode : noeud qui contient les les choix possibles pour l utilisateur
 * Param idNodeStyle : noeud qui contient les les choix possibles pour l utilisateur
 * Param classSelected : class a utiliser pour mettre un choix en surbrillance
 * Param nameCookie : nom du cookie
*/
function initSwitchView(idParentNode, idNodeStyle, classSelected, nameCookie) {
    // recuperation du cookie
    var currentTypeAffichage = getCookie(nameCookie);
    // recuperation de l element contenant les liens de choix
    var parentNode = document.getElementById(idParentNode);
    if (parentNode) {
        // on recupere les liens de choix
        var allA = parentNode.getElementsByTagName('a');
        if (allA.length > 0) {
            // si le cookie contient une valeur, on initialise la classe
            if (currentTypeAffichage && currentTypeAffichage != "" && currentTypeAffichage != "null") {
                // on selectionne le type d affichage choisi par l utilisateur
                switchView(allA[currentTypeAffichage], idNodeStyle, classSelected, nameCookie);
            }
            else {
                // on selectionne le premier element
                switchView(allA[0], idNodeStyle, classSelected, nameCookie);
            }
        }
    }
}

/**
 * Permet de modifier l affichage des produits
 * modification de la classe du lien et enregistrement dans un cookie
 * Param lienSelected : lien correspondant au choix de l utilisateur
 * Param idNodeStyle : noeud qui contient les les choix possibles pour l utilisateur
 * Param classSelected : class a utiliser pour mettre un choix en surbrillance
 * Param nameCookie : nom du cookie
*/
function switchView(lienSelected, idNodeStyle, classSelected, nameCookie) {
    if (lienSelected) {
        var indexSelected = -1;

        // parcours de tous les liens, on efface la classe de chacun d eux
        // enregistrement de l index de l element selectionne pour retrouver le choix d affichage
        parentNode = lienSelected.parentNode;
        if (parentNode) {
            var allA = parentNode.getElementsByTagName('a');
            for (var i = 0; i < allA.length; i++) {
                allA[i].className = '';
                if (allA[i].id == lienSelected.id) {
                    indexSelected = i;
                }
            }
        }
        // on affecte au lien en cours la classe de surbrillance
        lienSelected.className = classSelected;

        // on modifie le style d'affichage des produits et on enregistre l'index de l'affichage choisi
        var nodeStyle = document.getElementById(idNodeStyle);
        if (viewClassNames.length > 0 && nodeStyle) {
            if (indexSelected > -1) {
                nodeStyle.className = viewClassNames[indexSelected];
                setCookie("", nameCookie, indexSelected);
            }
            else {
                // par defaut, on selectionne le premier element
                nodeStyle.className = viewClassNames[0];
            }
        }
    }
}

/**
* Permet de modifier l'url d'un lien
*/
function modifieUrlMdr(url, lien)
{
    // modification de l url du lien
    lien.href= url;
}
