/*##############################################################################################
############# JS DES FONCTIONS D APPEL DE CHARGEMENT AJAX DES XML ET DE POST CHARGEMENT ####### 
################################## POUR LA PARTIE TIERS MAGASINS ################################ 
/*############################################################################################## */
var thirdSoldDateBegin = null;
var thirdSoldDateEnd = null;
var thirdSoldAnticipated = false;

/*############################################################################################## */
/* - Parcourt le tableau des tiers publies itool 
    - Met a jour leur propriete autorise a s afficher ou non dans la popup (flag online)
    - Ajoute la region ou le departement a la liste si il contient au moins 1 magasin publie et autorise
    - Appel la fonction de preselection de la region (ou dept) et du magasin dans la liste si cookie magasin existant
*/
var POST_LOAD_CHILDREN_FUNCTION = function displayRegionOrDept(httpStatus, _joService) {
    var oThird = null;

    if(httpStatus != null && httpStatus==200) {
        var oContent = _joService.getContent();
        if (oContent ==null) {return null;}
    }

    if (oContent != null) {
        var tempRegionOrDept = '';
        // Parcourt des magasins publies itool
        for (var i = 0; i < lPublishedThird.length; i++) {
            var sKey = _thirdGenerateKey(THIRD_KIND_STORE, lPublishedThird[i].number, lPublishedThird[i].number)
            oThird = oContent.getThird(sKey);
            if (typeof oThird != "undefined") {  
                // Test si le mag est online, donc autorise a s afficher dans la popup
                if (oThird.isOnline()) {
                    // Met a jour la propriete online du mag itool
                    lPublishedThird[i].online = true;
                    
                    // Si la region ou le dept n a pas encore ete ajoute 
                    if(lPublishedThird[i].parentTitle !=tempRegionOrDept) {
                        addOptionToList('formConnexion', 'listeDeptRegion', lPublishedThird[i].parentTitle, lPublishedThird[i].parentIdCat);  
                        tempRegionOrDept = lPublishedThird[i].parentTitle;                                                    
                    }
                }
            }
        }

        // Emailing client : numero de magasin en parametre dans l url
        var paramUrl = window.parent.location.search;
        if (paramUrl.indexOf('emailing=')!=-1) {
            paramUrl = paramUrl.substr(paramUrl.indexOf('emailing=') + 9);
            var numMagParam = paramUrl.substring(0,paramUrl.indexOf('&') != -1 ? paramUrl.indexOf('&') : paramUrl.length);
            // Parcourt des magasins publies et autorises 
            for (var i = 0; i < lPublishedThird.length; i++) {                                
                if (lPublishedThird[i].online && lPublishedThird[i].number==numMagParam) {
                    // Ecriture direct du cookie - fermeture de la popup de connexion - rechargement de la page
                    var magOnline = lPublishedThird[i];
                    checkBasket(function(){validate('',magOnline);},true);
                }
            }
        }
        else {
            // Preselectionne la region ou le magasin si cookie existant
            showOldStoreIfCookie();
        }

    }

}
/*############################################################################################## */
/* Recupere les dates de soldes du magasin puis charge le ou les modeles magasin */
var POST_LOAD_STORE_SOLD_DATES_FUNCTION = function getStoreSoldDates(httpStatus, _joService) {
    var oThirds = null;
    var oThird = null;
	
    if(httpStatus != null && httpStatus==200) {
        var oContent = _joService.getContent();
        if (oContent ==null) {return null;}
        oThirds = oContent.getThirdsList();
        if (oThirds ==null) {return null;}
        if (oThirds.length < 1) {return null;}
        oThird = oContent.getThird(oThirds[0]);
    }

    if (oThird != null) {
        if (oThird.getSoldBegin() != null && oThird.getSoldEnd() != null) {
            thirdSoldDateBegin = oThird.getSoldBegin();
            thirdSoldDateEnd = oThird.getSoldEnd()
        }

        // On determine si periode de soldes anticipees en cours
        var thirdServDate = _joService.getHeader().getTime();
        if (getSwitchMagasin('FLAG_IS_SOLD_PERIOD') && thirdSoldDateBegin != null && thirdServDate != null) {
            // Ajout de l heure a la date du mag
            var oDt = thirdSoldDateBegin;
            oDt.setHour("00");
            oDt.setMinute("00");
            oDt.setSecond("00");
            // Test
            thirdSoldAnticipated = thirdServDate.before(oDt);
        }

        if (typePage=='modele') {
                loadModel(_client, _siteNumber, _centralNumber, oThird.getNumber(), _modelId, _language);
            }
        if (typePage=='famille' || typePage=='famille-gdbc') {
            loadFamily(_client, _siteNumber, _centralNumber, oThird.getNumber(), _familyId);
        }
        if (typePage=='homepage' || typePage=='rayon' || typePage=='HPMarque' || typePage=='famille-hero' || typePage=='modele-vc' || typePage=='psd') { 
            loadModels(_client, _siteNumber, _centralNumber, oThird.getNumber());
        }
        if (typePage=='miniBoutique') {
            loadModelsBoutique(_siteNumber, _centralNumber, oThird.getNumber(), _idDepartement, getErepLanguageCode(_language));
        }
        if (typePage=='dktTv') {
            loadModeltDktTv(_client,_siteNumber, _centralNumber, oThird.getNumber(),_modelId,_language);
        }
    }
    
}
/*############################################################################################## */
/* Permet d appeler la fonction showBlocIfCookieMagasin en sachant si le magasin est autorise dans la popup */
var POST_LOAD_STORE_ONLINE_FUNCTION = function isStoreOnline(httpStatus, _joService) {
    var oThird = null;
	
    if(httpStatus != null && httpStatus==200) {
        var oContent = _joService.getContent();
        if (oContent != null) {
            var oContexte = _joService.getContext();
            if (oContexte != null) {
                var sKey = _thirdGenerateKey(oContexte.getThirdKind(), oContexte.getThirdNumber(), oContexte.getThirdSubNumber());
                oThird = oContent.getThird(sKey);
            }
        }
    }
    
    if (oThird != null) showBlocIfCookieMagasin(cookieMagasin,oThird.isOnline(), oThird.isBookable());
    else showBlocIfCookieMagasin(cookieMagasin,false,false);

}
/*############################################################################################## */
/* Definition de l objet javascript tiers publie dans itool */
function PublishedThird (_number, _name, _idCat, _online, _parentTitle, _parentIdCat) {
               /* Numero du tiers */ 
	this.number = _number;
	/* Nom du tiers */
	this.name = _name;
	/* Url du tiers */
	this.idCat = _idCat;
	/* Etat du tiers dans eRepository (autorise dans la popup de connexion ou non) */
	this.online = _online;
	 /* Titre du parent du tiers (region ou departement) */
	this.parentTitle = _parentTitle;
	 /* Id category du parent du tiers (region ou departement) */
	this.parentIdCat = _parentIdCat;
}
/*############################################################################################## */
/* Charge tous les tiers du site */
function loadChildrenThirdParty(_client, _kind, _number, _subNumber,service) {
    if(typeof service != 'undefined' && service == 'psd') localFunc = loadAreas;
    else localFunc = POST_LOAD_CHILDREN_FUNCTION;

    _urlErep = getUrlErep(_SERVICE_THIRD, _client, _kind, _number, _subNumber, null, null, null, localFunc) ;                           
    if(_urlErep != ""){
        var oContext = new JoServiceContext(_urlErep,getErepLanguageCode( _language), _siteNumber, _centralNumber, null);
        oContext.setThirdChildren(_kind, _number, _subNumber);
        var oService = new JoService(oContext);
        oService.execute(localFunc);
    }

}
/*############################################################################################## */
/* Charge un tiers */
function loadThirdParty(_client, _kind, _number, _subNumber) {	
    var oContext = new JoServiceContext(_urlErep,getErepLanguageCode( _language), _siteNumber, _centralNumber, null);
    oContext.setThirdSingle(_kind, _number, _subNumber);
    var oService = new JoService(oContext);
    
    if (typePage=='magasin') oService.execute(POST_LOAD_STORE_ONLINE_FUNCTION);
    else oService.execute(POST_LOAD_STORE_SOLD_DATES_FUNCTION);
}

/*############################################################################################## */
/* genere la cle d un Tiers en fonction de son type, numero et sous numero*/
function _thirdGenerateKey(_theKind, _theNumber, _theSubNumber) {
    if (_theKind == null || _theNumber == null || _theSubNumber == null) return null;
    
    return '#' + _theKind + '#' + _theNumber + '#' + _theSubNumber + '#';
}

/*############################################################################################## */
/* Genere le tableau lPublishedThird contenant les magasins et leur niveau superieur (region/dept) associe */
function loadStoreAreaMap (_siteNumber,profondeur,urlStoreAreaMap, _localFunc) {
        var func = function (xmlHttp, httpStatus) {
            oGlobalXml = xmlHttp.responseXML;
            if(oGlobalXml!=null) {
                var mags = oGlobalXml.getElementsByTagName("store");
                // Tableau associatif avec comme indice le nom du niveau parent et comme valeur l objet PublishedThird 
                var tabTemp = new Array();
                // Tableau contenant les noms des niveaux parents 
                var tabParent = new Array();
                
                for (var i = 0;i < mags.length;i++) {
                    if (getAttributeValue(mags[i], "open") == "true" && getAttributeValue(mags[i], "publish") == "true") {
                        var oParent = mags[i].parentNode;
                        if(profondeur == 1) oParent = oParent.parentNode;
                        var parentTitle = getNodeValue(getChildWithAttribute(oParent, "label", "language", _language));
                        var parentIdCat = getAttributeValue(oParent, "category");
                        
                        var numMag = getAttributeValue(mags[i],"number");
                        var nomMag = getNodeValue(getChildWithAttribute(mags[i], "label", "language", _language));
                        
                        if (nomMag) {
                            tabTemp[parentTitle.toUpperCase() + nomMag.toUpperCase()] = new PublishedThird(numMag, nomMag, getAttributeValue(mags[i],"category"), false, parentTitle, parentIdCat);
                            
                            tabParent.push(parentTitle.toUpperCase() + nomMag.toUpperCase());
                        }
                    }
                }
                // Tri des niveaux parents par ordre alphabetique 
                tabParent.sort();
                
                // construction du tableau lPublishedThird par ordre alphabetique sur le nom du niveau parent 
                for (var i = 0;i < tabParent.length;i++) lPublishedThird.push(tabTemp[tabParent[i]]);
            }
    
            if (_localFunc != null) {
                try {
                    _localFunc(httpStatus);
                } catch (e) {
                    return false;
                }
            }
        return true;
    };
    
    //Lancement du processus
    var oProcess = new IAjaxProcess(urlStoreAreaMap, func);
    oProcess.run();
    return true;
}


var POST_LOAD_STORE_MAP_FUNCTION = function postLoadStoreMap (httpStatus) {
    if(httpStatus != null && httpStatus==200) loadChildrenThirdParty(_client, THIRD_KIND_SITE, _siteNumber, _siteNumber); 
}
