/*##############################################################################################
########################### GESTION DES STOCKS MULTI-MAGASINS ########################### 
/*############################################################################################## */

var storeList = new Array();
// Variables gerant les appels multiples au service de disponibilite (cas ou le nombre de magasins a traiter > nbMaxMagasins)
var nbMaxMagasins = 20;
var appelEnCours = 0;
var nbAppels = 0;
var listeTemp;


/*************** Recuperation de la liste des magasins du xml store-list-codePays-langue.xml ****************/
function loadStoreList(_storeNumber, _localFunc){
    _loadStoreList(_storeNumber,POST_LOAD_STORE_LIST_FUNCTION);
}

function _loadStoreList(_storeNumber, _localFunc){
     var func = function (xmlHttp, httpStatus) {
        oGlobalXml = xmlHttp.responseXML;
        if(oGlobalXml != null) {
            var stores = oGlobalXml.getElementsByTagName("store");
            var idStore;
            var nameStore;
            for(var i=0;i<stores.length;i++){
                idStore =getAttributeValue(stores[i],'number');
                nameStore =  getChildNodeValue(stores[i],'name');
                storeList[idStore] = nameStore;
            }
        }
        if (_localFunc != null) {
            try {
                _localFunc(httpStatus, _storeNumber);
            } catch (e) {
                return false;
            }
        }
        return true;
    };

    //Lancement du processus
    var oProcess = new IAjaxProcess(storeListUrl, func);
    oProcess.run();
    return true;
}

var POST_LOAD_STORE_LIST_FUNCTION = function(httpStatus, _storeNumber){
    if(httpStatus != null && httpStatus==200) {
        loadProximityStores(_siteNumber, _language, listeArticles.value, _storeNumber);
    }
    else{
        displayError();
    }
}

/*************** Partie gerant les appels aux services nettools et erep ***************/
function JoArea(libelle) {
	this.libelle = libelle;
	this.thirds = new Array();
}

JoArea.prototype.addThird = function (third) {
	if (third == null || third == '') {
		return false;
	}
	this.thirds.push(third);
	return true;
}

JoArea.prototype.getLibelle = function () { return this.libelle; }

JoArea.prototype.getThirds = function () { return this.thirds; }


function loadAreas(httpStatus, _joService) {
    _loadAreas(_joService,_language,POST_LOAD_AREAS_FUNCTION);
}

// Appel le service de decoupage geographique
function _loadAreas(_oThirdsService,_language,_localFunc){
    var func = function (xmlHttp, httpStatus) {
        var listSearchAreas =new Array();
        oGlobalXml = xmlHttp.responseXML;
        if(oGlobalXml != null) {
            var areas =  oGlobalXml.getElementsByTagName("area");
            var orderedAreas = new Array();
            var libelles = new Array();
            var orders = new Array();
            var order;
            var libelle;
            for(var i = 0;i<areas.length;i++){
                order = getAttributeValue(areas[i],'order');
                orderedAreas[order] = areas[i];
                libelle = getChildNodeValue(areas[i],'label');
                libelles.push(libelle);
                orders[libelle] = order;
            }
            if(profondeurDecoupage != 0) libelles.sort();

            var indice;
            var thirdNumber;
            for(var i=0;i<libelles.length;i++){
                indice = orders[libelles[i]];
                var oArea = new JoArea(libelles[i]);
                var listThirds =  orderedAreas[indice].getElementsByTagName('third');
                for(var j=0;j<listThirds.length;j++){
                    thirdNumber = getAttributeValue(listThirds[j],'number');
                    var sKey = _thirdGenerateKey(THIRD_KIND_STORE, thirdNumber, thirdNumber);
                    var oThird = oThirdsContent.getThird(sKey);
                    if (typeof oThird != "undefined") {  
                        if (oThird.isOnline()) {
                            oArea.addThird(thirdNumber);
                        }
                    }
                }
                listSearchAreas.push(oArea);
            }
        }
        if (_localFunc != null) {
            try {
                _localFunc(httpStatus,listSearchAreas);
            } catch (e) {
                return false;
            }
        }
        return true;
    };

    // Recuperation contenu reponse du service tiers et id site
    var oThirdsContent = _oThirdsService.getContent();
    if (oThirdsContent ==null) {return null;}
    var oContexte = _oThirdsService.getContext();
    if (oContexte ==null) {return null;}
    var _siteNumber = oContexte.getThirdNumber();

    var url = proximityStoresUrl + '?langId='+ _language +'&siteId='+_siteNumber;
    //Lancement du processus
    var oProcess = new IAjaxProcess(url, func);
    oProcess.run();
    return true;
}
// Charge la liste de selection des elements correspondant au decoupage geographique
var POST_LOAD_AREAS_FUNCTION = function(httpStatus,listSearchAreas){
    if(httpStatus != null && httpStatus==200 && listSearchAreas.length>0) {
        for(var i=0;i<listSearchAreas.length;i++)
            if(listSearchAreas[i].getThirds().length > 0) addOptionToList('psdRecherche','listeDecoupages',listSearchAreas[i].getLibelle(),listSearchAreas[i].getThirds());

        if(profondeurDecoupage == -1) loadProductStoresDisponibility( _siteNumber, _language, _centralNumber, listeArticles.value, listeDecoupages.value.split(','));
    }
    else{
        displayError();
    }
}

function loadProximityStores(_siteNumber,_language, _articleId, _storeNumber) {
    _loadProximityStores(_siteNumber,_language, _articleId, _storeNumber,POST_LOAD_PROXIMITY_FUNCTION);
}
// Permet de recuperer les magasins situes a proximite du magasin ou le client est connecte
function _loadProximityStores(_siteNumber,_language, _articleId, _storeNumber,_localFunc) {
    var func = function (xmlHttp, httpStatus) {
        oGlobalXml = xmlHttp.responseXML;
        if(oGlobalXml!=null) {
            profondeurDecoupage = getChildNodeValue(oGlobalXml,'area-depth');
            var areas = oGlobalXml.getElementsByTagName("area");
            for(var i=0;i<areas.length;i++){
                var oArea = new JoArea(getChildNodeValue(areas[i],'label'));
                var listThirds =  areas[i].getElementsByTagName('third');
                for(var j=0;j<listThirds.length;j++){
                        listeMagProximity.push(getAttributeValue(listThirds[j],'number'));
                }
            }
        }
        if (_localFunc != null) {
            try {
                _localFunc(httpStatus,_articleId);
            } catch (e) {
                return false;
            }
        }
        return true;
    };

    var url = proximityStoresUrl + '?langId='+ _language +'&siteId='+_siteNumber+'&storeId='+_storeNumber;
    //Lancement du processus
    var oProcess = new IAjaxProcess(url, func);
    oProcess.run();

    return true;
}

// cette fonction recupere la liste des magasins a proximite et la formate en chaine de caractere pour la passer au service de disponibilite + prepare affichage bloc recherche
var POST_LOAD_PROXIMITY_FUNCTION = function postLoadProximityStores(httpStatus, _articleId) {
    if(httpStatus != null && httpStatus==200 && listeMagProximity.length>0) {
        // on affiche le lien pour le formulaire de recherche seulement si ce n'est pas un decoupage pays
        if(profondeurDecoupage != -1) showBloc('autresDispo');
        if(profondeurDecoupage == 0){
            showBloc('libelleRegionResult','inline');
            showBloc('libelleRegionIndispo','inline');
            showBloc('autreRegion','inline');
            showBloc('libelleNoVsRegion','inline');
            showBloc('libelleDecoupageRegion','inline');
        }
        else if(profondeurDecoupage == 1){
            showBloc('libelleDepartementResult','inline');
            showBloc('libelleDepartementIndispo','inline');
            showBloc('autreDepartement','inline'); 
            showBloc('libelleNoVsDepartement','inline');
            showBloc('libelleDecoupageDepartement','inline');
        }
        defineWidth('lienAutresDispo');
        articleIsDispo = false;
        loadProductStoresDisponibility( _siteNumber, _language,_centralNumber, _articleId, listeMagProximity);
    }
    else{
        displayError();
    }
}

// Permet de recuperer les infos stock de l'article dans les magasins retournes par loadProximityStores
function loadProductStoresDisponibility(_siteNumber, _language, _centralNumber, _articleId, _listeMagasins) {
    // gestion du multi-appels du service de disponibilite
    if(nbAppels == 0){
        dispoTrouvee = false;
        var nbMags = _listeMagasins.length; // Nombre de magasins a traites
        nbAppels = nbMags / nbMaxMagasins;
        if(parseInt(nbAppels) != parseFloat(nbAppels)) nbAppels = parseInt(nbAppels) + 1;
        appelEnCours = 0;
        listeTemp = new Array(); // contiendra nbMaxMagasins magasins par case
        for(var i=0;i<nbAppels;i++){
            listeTemp[i] = new Array();
            for(var j=nbMaxMagasins*i;j<nbMaxMagasins*(i+1) && j<_listeMagasins.length;j++){
                listeTemp[i].push(_listeMagasins[j]);
            }
        }
    }
    
     // Creation du contexte
     var oContext = new JoServiceContext(_urlErep, getErepLanguageCode( _language), _siteNumber, _centralNumber, listeTemp[appelEnCours].join(','));
     appelEnCours++;
     oContext.setDisponibility(_articleId);
     oContext.activateDataFilter();
     // Filtres prix, assortiement, disponibilite et hot data
     oContext.enableDataFilter(SERVICE_CONSTANTS.DATA_FILTER_MIX);
     oContext.enableDataFilter(SERVICE_CONSTANTS.DATA_FILTER_AVAILABLE);
     oContext.enableDataFilter(SERVICE_CONSTANTS.DATA_FILTER_HOT_DATA);
     
     var oService = new JoService(oContext);
     oService.execute(POST_LOAD_PSD_FUNCTION);
}

// si des magasins ont de la disponibilite pour l article on affiche la liste de magasins sinon on affiche les VS ou rien
var POST_LOAD_PSD_FUNCTION = function postLoadProductStoresDisponibility(httpStatus, _joService) {
    if(httpStatus != null && httpStatus==200) {
        try{
           var oContent = _joService.getContent();
           var oDisponibilities = oContent.getDisponibilities();
           var oContext = _joService.getContext();
           var serverDate = _joService.getHeader().getTime();
           setBlocByHtml('psd_hot_infoDate',serverDate.getLiteralDate(getFormatDateHeure()));

          if(oDisponibilities != null){
               var disponibilities = oDisponibilities.getDisponibilitiesByState(true,true);
               if(disponibilities.length > 0){
                   var disponibilitiesEnable = new Array();
                   for(var i = 0;i < disponibilities.length;i++) if(disponibilities[i].getItem().isEnable()) disponibilitiesEnable.push(disponibilities[i]);
                   if(disponibilitiesEnable.length > 0){
                       getAffichagePsdListeMag(disponibilitiesEnable);
                       dispoTrouvee = true;
                   }
               }
           }

           if(appelEnCours < nbAppels){
                loadProductStoresDisponibility(_siteNumber, _language, _centralNumber,oContext.getArticleId(),'');
           }
           else{
               if(dispoTrouvee){
                   var blocs = document.getElementById("psdListeMagasins").childNodes;
                   var derBloc = blocs[blocs.length-1];
                   changeBlocClass(derBloc.id, AddClassName(derBloc.className,"blocMagDer"));
                   hideBloc('psdWaitMags');
                   defineIframeHeight("popup-product-stores-disponibility",true);
               }
               else getAffichagePsdVs();
           }
       }
       catch(e){
        displayError();
       }
    }
    else{
        displayError();
    }
}


/*************** Partie gerant l affichage des blocs selon les resultats des services ***************/

var modeleBlocMag = ''; // contient un modele (html) de bloc magasin
var typeBloc = 'proximite'; // permet de savoir si on affiche une liste de magasins venant du resultat d une recherche sur un decoupage ou venant de du service de proximite
var listeMagProximity = new Array(); // au cours d une meme session la liste des magasins a proximite ne change pas. donc pour eviter d appeler le service de proximite plus d une fois on garde la liste dans cette variable
var listeMagChanged = false; // permet de savoir si la liste des magasins situes a proximite a change (pour eviter de faire des appels au service qui ne sont pas utiles)
var articleIsDispo = false; //permet de savoir si l article est disponible dans au moins un magasin situe a proximite du magsin du cookie
var listeDecoupages; // liste de selection contenant les libelles du decoupage (region, departement, ou pays)
var profondeurDecoupage = ''; // profondeur du decoupage geographique (0,1, ou 2)
var dispoTrouvee = false; // Permet de savoir si dans un appel au service de disponibilite, une dispo a ete trouve afin de ne pas reinitialiser l affichage de la liste des magasins (cas ou nbMags > nbMaxMagasins) 
var listeArticles = '';
var srcDone = false; // lors d'un rechargement de la page sans avoir fermer la popup au prealable, la popup se recharge et s ouvre toute seule. Cette variable permet de detecter ce comportement

// Initialise le premier affichage de la popup stocks multi-magasins
function initDisplayPsd(){
        displayInfosModele();
        var libelleProximite = getBlocHtml('libelleMagProximite');
        libelleProximite = libelleProximite.replace("#store_name",getEltFromUrl(cookieMagasin, 'magasin').toUpperCase());
        setBlocByHtml('libelleMagProximite',libelleProximite);
        listeArticles = window.parent.s;
        displayInfosArticle();
        show_popup('popup-product-stores-disponibility');
        // Bloc magasin
        modeleBlocMag = document.getElementById('blocMag_').cloneNode(true);
}

// Initialisation de l affichage des blocs pour afficher la liste des magasins a proximite du magasin en cours
function initDisplayForProximity(){
    hideBloc('erreur');
    hideBloc('zoneRecherche');
    hideBloc('psdListeVs');
    hideBloc('psdListeMagasinsProximite');
    hideBloc('libelleResultRecherche');
    hideBloc('libelleArticleIndispo');
    showBloc('libelleMagProximite');
    showBloc('blocGlobalPsd');
    typeBloc = 'proximite';
    listeMagChanged = false;
    nbAppels = 0;
}

// Affiche le bouton permettant d afficher la popup product-stores-disponibility
function showPsdButton(){
    hideBloc('boutonPrixTpsreelOnclick');
    showBloc('boutonPsdOnclick');
    if(s.options.length > 2) showBloc('articleSelectionIndispo');
    else showBloc('articleIndispo');
    affichagePsd = true;
    document.getElementById("boutonPsdOnclick").onclick=function() {
        show_filter('filter');
        if(document.getElementById('popup-product-stores-disponibility').src == document.location.href || document.getElementById('popup-product-stores-disponibility').src == ''){
            srcDone = true;
            setSrc('popup-product-stores-disponibility',urlProductStoresDisponibility);
        }
        else{
            var iframe = document.getElementById('popup-product-stores-disponibility');
            iframe.height = "329px";
            iframe.contentWindow.location.reload();
        }
    }
}

// affiche les infos du modele: photo du produit, reference
function displayInfosModele(){
    if (window.parent.urlPhotoProduitLocalStock!='') {
        var oImg = new Image();
        oImg.onload = function(){createElement_img("","",oImg.src,"","","",document.getElementById('psdPhotoModele'));};
        oImg.src = window.parent.urlPhotoProduitLocalStock;
    }
    setBlocByHtml("psdLibelleModele",window.parent.libelleModele);
    setBlocByHtml("psdReferenceModele",window.parent._modelId);
}

// affiche les infos de l'article : reference, declinaison, prix
function displayInfosArticle(){
    setBlocByHtml("psdReferenceArticle",listeArticles.value);
    setBlocByHtml("psdDeclinaison",listeArticles[listeArticles.selectedIndex].text);
    if (etape==3 || etape==7 || etape==8) {
        showBloc('psdFinCollection');
    }
    if (affichePrixRouge) {
        changeBlocClass('psdPrix','psdPrixRouge');
    }
    if(afficheCartouchePrix == 'Y') setBlocByHtml('psdPrix',window.parent.displayPriceArticle());
    else hideBloc('psdPrice-bloc');
}

// Gere l affichage de la liste des magasins ayant du stock dans la popup
function getAffichagePsdListeMag(disponibilities){
    if(!dispoTrouvee){ // premier appel
        hideBloc('psdWait');
        setBlocByHtml('psdListeMagasins',' ');
        showBloc('psdListeMagasinsProximite');
        if(appelEnCours < nbAppels) showBloc('psdWaitMags');
        
        if(typeBloc == 'proximite') articleIsDispo = true;
        if(typeBloc == 'recherche') listeMagChanged = true;
    }
    
    // Creation du tableau contenant les magasins et leur stock associe
    var listeDispoMag = new Array();
    var tabNomsMags = new Array();
    for(var i = 0;i < disponibilities.length;i++){
        var oItem = disponibilities[i].getItem();
        var oThird = disponibilities[i].getThird();
        var idMag = oThird.getNumber();
        var nomMag = storeList[idMag];
        if(nomMag){
            tabNomsMags.push(nomMag);
            var stock = oItem.getMix().getStock();
            // SUBSTITUTION NANTERRE DEBUT
            // Lorsque le magasin est CNIT et que la substitution est activee alors on ajoute la ligne de Nanterre
            if (substStoreNanterre && idMag == '539') {
                listeDispoMag[storeList[117]] = new Array();
                listeDispoMag[storeList[117]]['idMag'] = '117';
                listeDispoMag[storeList[117]]['stock'] = stock;
            }
            // SUBSTITUTION NANTERRE FIN
            listeDispoMag[nomMag] = new Array();
            listeDispoMag[nomMag]['idMag'] = idMag;
            listeDispoMag[nomMag]['stock'] = stock;
        }
    }
    
    tabNomsMags.sort();
    
    // definition de la hauteur de la div contenant la liste des magasins selon le nombre de magasins. On affiche au maximum 3 magasins sans barre de scroll
    var blocs = document.getElementById("psdListeMagasins").childNodes;
    var nbMagDispo = blocs.length + tabNomsMags.length;
    if(!dispoTrouvee && blocs.length == 1) nbMagDispo--; // Firefox considere un texte vide comme un node donc si c est le premier appel et que blocs.length vaut 1 on decrement nbMagDispo
    var hauteurListeMag;
    if(nbMagDispo < 3) hauteurListeMag = nbMagDispo * 115 - 15;
    else hauteurListeMag = 330;
    document.getElementById("psdListeMagasins").style.height = hauteurListeMag + 'px';
    
    // Ajout des blocs magasin dans la popup
    for(var i = 0;i < tabNomsMags.length;i++){
        var nomMag = tabNomsMags[i];
        addBlocMag(listeDispoMag[nomMag]['idMag'],nomMag,listeDispoMag[nomMag]['stock']);
    }
    
    defineIframeHeight("popup-product-stores-disponibility",true);
}

// Ajoute un bloc magasin dans la liste des magasins
function addBlocMag(idMag,nomMag,stock){
    document.getElementById('psdListeMagasins').appendChild(modeleBlocMag.cloneNode(true));
    
    document.getElementById('blocMag_').id = 'blocMag_' + idMag;

    document.getElementById('nomMagPsdListe_').id = 'nomMagPsdListe_' + idMag;
    
    var nomMagPsdListe = getBlocHtml('nomMagPsdListe_'+idMag);
    nomMagPsdListe = nomMagPsdListe.replace("#store_name",nomMag);
    setBlocByHtml('nomMagPsdListe_'+idMag,nomMagPsdListe);

    document.getElementById('psdStock_').id = 'psdStock_' + idMag;
    setBlocByHtml('psdStock_' + idMag,stock);

    document.getElementById('libelleArticles_').id = 'libelleArticles_' + idMag;
    document.getElementById('libelleArticle_').id = 'libelleArticle_' + idMag;
    if(stock > 1){
        showBloc('libelleArticles_'+idMag,'inline');
    }
    else{
        showBloc('libelleArticle_'+idMag,'inline');
    }
    
    /* Parametrage des liens situer magasin et voir  l article dans ce magasin : ajout de l id magasin dans le lien */
    document.getElementById('situerMag_').id = 'situerMag_' + idMag;
    var onclickSituerMag = document.getElementById('situerMag_' + idMag).onclick.toString();
    onclickSituerMag = onclickSituerMag.substring(onclickSituerMag.indexOf('openNewWindow'),onclickSituerMag.indexOf('return false'));
    onclickSituerMag = onclickSituerMag.replace('emailing=','emailing='+idMag);
    document.getElementById('situerMag_' + idMag).onclick = function(){eval(onclickSituerMag);return false};
    
    urlCurrentPage = window.parent.document.location.href;
    if(urlCurrentPage.indexOf('?') != -1)
        urlCurrentPage = urlCurrentPage.substring(0,urlCurrentPage.indexOf('?'));
    if(urlCurrentPage.indexOf('#') != -1)
        urlCurrentPage = urlCurrentPage.substring(0,urlCurrentPage.indexOf('#'));
    document.getElementById('lienVoirArticle_').id = 'lienVoirArticle_' + idMag;
    setHref('lienVoirArticle_' + idMag,urlCurrentPage+'?emailing='+idMag+'&articleValue='+listeArticles.value);
}

// Affiche les produits en VS en copiant les bocs deja construits en bas de page
function getAffichagePsdVs(){
    hideBloc('psdWait');
    hideBloc('libelleMagProximite');
    hideBloc('libelleResultRecherche');
    showBloc('libelleArticleIndispo');
    
    if(typeBloc == 'proximite' && profondeurDecoupage != -1){
        hideBloc('libelleIndispoRecherche');
        showBloc('libelleIndispoProximite','inline');
    }
    else{
        hideBloc('libelleIndispoProximite');
         
        if(profondeurDecoupage != -1){
            if(profondeurDecoupage == 0){
                var libelleRegionIndispo = getBlocHtml('libelleRegionIndispo');
                libelleRegionIndispo = libelleRegionIndispo.replace(/<span>.*<\/span>/gi, '<span>' + listeDecoupages[listeDecoupages.selectedIndex].text + '</span>');
                setBlocByHtml('libelleRegionIndispo',libelleRegionIndispo);
            }
            else{
                var libelleDepartementIndispo = getBlocHtml('libelleDepartementIndispo');
                libelleDepartementIndispo = libelleDepartementIndispo.replace(/<span>.*<\/span>/gi, '<span>' + listeDecoupages[listeDecoupages.selectedIndex].text + '</span>');
                setBlocByHtml('libelleDepartementIndispo',libelleDepartementIndispo);
             }
            showBloc('libelleIndispoRecherche','inline');
        }
    }
    
    if(typeBloc!='recherche'){
     // On verifie si on a deja construit le bloc des VS
        if(document.getElementById('psdListeVs').childNodes.length > 0){
            hideBloc('libelleNoVs');
            showBloc('libelleVs','inline');
            showBloc('psdListeVs','inline');
        }
        else{
            if(typeBloc == 'proximite'){
                var libelleIndispoProximite = getBlocHtml('libelleIndispoProximite');
                libelleIndispoProximite = libelleIndispoProximite.replace("#store_name", getEltFromUrl(cookieMagasin, 'magasin').toUpperCase());
                setBlocByHtml('libelleIndispoProximite',libelleIndispoProximite);
             }

            if(window.parent.vsProduits.length > 0){
                showBloc('psdListeVs','inline');
                showBloc('libelleVs','inline');
                var blocVs;
                for(var i=0;i < window.parent.vsProduits.length;i++){
                    blocVs = parent.document.getElementById('vs_modele_product_' + i + '_visuel').innerHTML;
                    document.getElementById('psdListeVs').innerHTML += blocVs;
                }
            }
            else showBloc('libelleNoVs','inline');
        }
    }
    else {
        hideBloc('libelleVs');
        showBloc('libelleNoVs','inline');
    }
    // Utilisation d un timeout car Firefox n a pas le temps de remplir le bloc psdListeVs que la fonction defineiframeheight s est deja executee
    window.setTimeout(function(){defineIframeHeight("popup-product-stores-disponibility",true);},200);
}

// Affiche le formulaire de recherche
function getAffichagePsdRecherche(){
    listeDecoupages = document.getElementById('listeDecoupages');
    if(profondeurDecoupage != -1){
        if(getBlocHtml('retourListeMag').indexOf('#store_name') != -1){
            var retourListeMag = getBlocHtml('retourListeMag');
            retourListeMag = retourListeMag.replace("#store_name", getEltFromUrl(cookieMagasin, 'magasin'));
            setBlocByHtml('retourListeMag',retourListeMag);
        }
        
        hideBloc('blocGlobalPsd');
        showBloc('zoneRecherche');
        defineIframeHeight("popup-product-stores-disponibility",true);
        // on remplit la liste de selection
        if(listeDecoupages.length == 0){
            loadChildrenThirdParty(_client, THIRD_KIND_SITE, _siteNumber, _siteNumber,'psd');
        }
    
        document.getElementById('retourListeMag').onclick = function(){
            typeBloc = 'proximite';
            // si article dispo on affiche la liste des magasins a proximite du magasin du coookie
            if(articleIsDispo) {
                // si la liste des magasins a change (il y a eu un resultat sur une recherche) -> il faut recreer la liste des magasins avec les magasins de proximite
                if(listeMagChanged) {
                    initDisplayForProximity();
                    showBloc('psdWait');
                    loadProductStoresDisponibility( _siteNumber, _language,_centralNumber, listeArticles.value, listeMagProximity);
                }
                else{
                    initDisplayForProximity();
                    showBloc('psdListeMagasinsProximite');
                    defineIframeHeight("popup-product-stores-disponibility",true);
                }
            }
            // sinon affichage liste des vs ou juste message indiquant que l article est indispo
            else{
                hideBloc('zoneRecherche');
                hideBloc('psdListeMagasinsProximite');
                showBloc('blocGlobalPsd');
                getAffichagePsdVs();
            }
        }
    }
    else{
        submitRecherche();
    }
}

// Au click sur le bouton valider on verifie la dispo des magasins du decoupage choisi
function submitRecherche(){
    typeBloc = 'recherche';
    hideBloc('libelleMagProximite');
    hideBloc('libelleArticleIndispo');
    hideBloc('psdListeVs');
    hideBloc('psdListeMagasinsProximite');
    if(profondeurDecoupage != -1){
        if(profondeurDecoupage == 0){
            var libelleRegionResult = getBlocHtml('libelleRegionResult');
            libelleRegionResult = libelleRegionResult.replace(/<span>.*<\/span>/gi, '<span>' + listeDecoupages[listeDecoupages.selectedIndex].text + '</span>');
            setBlocByHtml('libelleRegionResult',libelleRegionResult);
        }
        else{
            var libelleDepartementResult = getBlocHtml('libelleDepartementResult');
            libelleDepartementResult = libelleDepartementResult.replace(/<span>.*<\/span>/gi, '<span>' + listeDecoupages[listeDecoupages.selectedIndex].text + '</span>');
            setBlocByHtml('libelleDepartementResult',libelleDepartementResult);
        }
    }
    showBloc('libelleResultRecherche');
    showBloc('psdWait');
    hideBloc('zoneRecherche');
    showBloc('blocGlobalPsd');
    defineIframeHeight("popup-product-stores-disponibility",true);
    nbAppels = 0;
    if(profondeurDecoupage == -1 && listeDecoupages.length == 0) loadAreas(_siteNumber,_language);
    else loadProductStoresDisponibility( _siteNumber, _language, _centralNumber, listeArticles.value,listeDecoupages.value.split(','));
}

// Gere l affichage du message d erreur
function displayError(){
        showBloc('erreur');
        hideBloc('blocGlobalPsd');
        hideBloc('zoneRecherche');
        defineIframeHeight("popup-product-stores-disponibility",false);
}