/**
* FICHIER JS pour la gestion de la mise en avant des produits
* author : KIG
* version : 1.0
* date : 20070504
* historique :
*    => [KIG] 20070504 : Creation
*/

var contenuDecouvrirPlus = "" ; //Le contenu html qui contiendra les produit à decouvrir
var contenuScript = "" ;
var nbProduitAAfficher = 3 ;
var nbProduitVraimentAAfficher = 3 ;


/** #########################################
* Permet de recuperer le sous rayon passes à l'url
*/
function getSousRayon() {
    arrayUrl = new Array();
    arrayUrl = parent.document.location.href.split('/');
    //arrayUrl[7] correspond au sous rayon.
    if(arrayUrl[7]){
        return arrayUrl[7] ;
    }
}

/** #########################################
* Permet de recuperer la famille passes à l'url
*/
function getFamilleCourante() {
    arrayUrl = new Array();
    arrayUrl = parent.document.location.href.split('/');
    //arrayUrl[8] correspond à la famille
    if(arrayUrl[8]){
        return arrayUrl[8] ;
    }
}

/** #########################################
* Permet de recuperer la reference du produit
*/
function getIndexProduit() {
    arrayUrl = new Array();
    arrayUrl = parent.document.location.href.split('/');
    //arrayUrl[9] correspond au produit
    if(arrayUrl[9]){
        var productLabel = arrayUrl[9] ;
        productLabel = productLabel.split("_") ;
        if(productLabel[1]){
            return productLabel[1] ;
        }
        else{
            return "0" ;
        }
    }    
}

/** #########################################
* Permet de choisir au hasard une famille
*/
function randomizeFamille(nbTotalFamille){
   var randomNumber = Math.ceil(Math.random()*nbTotalFamille) ;
   return randomNumber ;
}

/** #########################################
* Permet de choisir au hasard un produit
*/           
function randomizeProduct(nbProduit){
   var randomProductId = Math.ceil(Math.random()*nbProduit) ;   
   
   return randomProductId ;               
} 
            
/** #########################################
* Permet de generer la zone "Decouvrir plus"
*/                      
function getDecouvrirPlus(langue, sousRayon, referenceProduit, labelDecouvrez, nbFamilleSousRayon, arrayParamFamille,urlFamille,urlRayon){
    //Recuperation des ventes complementaires associees aux differents niveaux
     var urlVcToCheck = new Array() ;
    urlVcToCheck[0] = document.location.href ;
    urlVcToCheck[1] = urlFamille ;
    urlVcToCheck[2] = urlRayon;
    
    _indexUrlToCheck = 0 ;
    getVc(urlVcToCheck, langue, sousRayon, referenceProduit, labelDecouvrez, nbFamilleSousRayon, arrayParamFamille) ; //la VC par itool est desactive
}

/** #########################################
* Permet de setter la VC ou de chercher la VC suivante
*/     
var POST_LOAD_VC_FUNCTION = function postGetVc(xmlHttp, httpStatus){
    //Si une VC repond, on va afficher l'iframe dans la bloc produit concerne 
    if(httpStatus == "200"){
        //Url de la VC qui a repondu
        var urlVc = _urlVcToCheck[_indexUrlToCheck];
        
       
       if(xmlHttp.responseText.indexOf('<body id="vc-body">')==-1){
             _indexUrlToCheck++ ;
            getVc(_urlVcToCheck, _langue, _sousRayon, _referenceProduit, _labelDecouvrez, _nbFamilleSousRayon, _arrayParamFamille) ;
        }else{
             var iframeVc = "<iframe id='iframe-vc' allowTransparency='true' src='"+urlVc+"VC.html?refProduit="+_referenceProduit+"' scrolling='no' frameborder='0'></iframe>" ;
            setHtml("bloc-vc", iframeVc) ;
        }
    }
    //Sinon on va chercher la VC au niveau superieur
    else{
        _indexUrlToCheck++ ;
        getVc(_urlVcToCheck, _langue, _sousRayon, _referenceProduit, _labelDecouvrez, _nbFamilleSousRayon, _arrayParamFamille) ;        
    }
}

/** #########################################
* Permet de recuperer les VC
*/     
function getVc(urlVcToCheck, langue, sousRayon, referenceProduit, labelDecouvrez, nbFamilleSousRayon, arrayParamFamille){
    _urlVcToCheck = urlVcToCheck ;
    _langue = langue ;
    _sousRayon = sousRayon ; 
    _referenceProduit = referenceProduit ;
    _labelDecouvrez = labelDecouvrez ;
    _nbFamilleSousRayon = nbFamilleSousRayon ;
    _arrayParamFamille = arrayParamFamille ; 

    //Pour tous les niveaux (rayon, famille, produit) on va verifier si une VC y est associer
    if(_indexUrlToCheck < _urlVcToCheck.length){
        var urlVc = _urlVcToCheck[_indexUrlToCheck] ;
        
        if(urlVc && urlVc != ""){
             urlVc = urlVc + "VC.html"
            var oProcess = new IAjaxProcess(urlVc, POST_LOAD_VC_FUNCTION);
            oProcess.run();
        }
    }
    //sinon on va recuperer la VC propre au marque
    else{    
        var randomIdFamille = 0 ;
        var numPdtCurrent=0;
        //Pour chaque famille, on va recuperer le lien vers le depth.html de la famille
        //pour pouvoir recuperer un produit
        for(var i=0 ; i<arrayParamFamille.length() ; i++){
            var currentFamilleObj = arrayParamFamille.get(i)  ;
        
            if(currentFamilleObj != ""){
                var currentUrlFamille = currentFamilleObj.getUrl() ;
                numPdtCurrent++;
                //Recuperation d'un modèle de cette famille
                getAutreModele(langue, referenceProduit, currentUrlFamille, nbFamilleSousRayon, labelDecouvrez,numPdtCurrent) ;
            }
        }
   }
}


/** #########################################
* Permet de recuperer un autre modèle à afficher dans "Decouvrez egalement"
* params :
*    => indexFamille : l'index de la famille à traiter
*    => urlFamille : l'url de la famille à traiter
*    => currentModele : le modèle courant de la page
*    => familleModele : le nom R3 de la famille à traiter
*    => maxFamille : le nombre de famille trouvee
*/
function getAutreModele(langue, referenceProduit, urlFamille, maxFamille, labelDecouvrez,numPdtCurrent) {
    var urlCeProduit = document.location.href ;
    urlFamille = langue+urlFamille + "depth.html" ; //Recuperation de l'url depth.html
    
    var POST_LOAD_CONTENT_DEC_FUNC = function postILoadContentDecouvrir(xhr, httpstatus){
        if(httpstatus == 200){
            var propertiesDivObjSr = document.getElementById("bloc-vc"); //le div qui va contenir les produits à mettre en avant
            
            var responseAjax = xhr.responseText ;
            var isPhotoNonDispo = "false" ;
            var aucunProduitAAffiche = "false" ;
            var funcVC = setLinkTag(tagProduit+"vc","");
                        
            //Le bloc html qui contient tous les produits de la famille actuellement analyse
            var contenuDepthProduit = responseAjax.split('<div class="produits" id="produits" style="display:none;">')[1] ;         
           
            if(contenuDepthProduit){
                var informationsProduit = contenuDepthProduit.split('<div class="bloc-product" id="vignetteproduit') ; //on va recuperer le flux html de chaque produit dans un tableau
                var produitPossibleFamille = new Array ; //va contenir les produits possibles de la famille à mettre en avant
                    
                //traitement sur la reponse ajax pour pouvoir recuperer l'url, le nom et l'image des produits possibles à mettre en avant
                if(informationsProduit.length > 1){
                    var indexProduitPossibleFamille = 0 ;
                    var maxDecouvrer=maxFamille;                   
                     if(maxDecouvrer == 1){
                         maxDecouvrer=informationsProduit.length-1;
                     }
                     if(maxDecouvrer>nbProduitAAfficher){
                        maxDecouvrer=nbProduitAAfficher;
                    }
                    
                    for(var p=1 ; p<informationsProduit.length ; p++){
                    
                        var infoProduit = informationsProduit[p].split('<div class="bloc-info" id="blocinfoplus')[0] ;
                        var refProduit = informationsProduit[p].split('-')[1].split('"')[0] ;
                        var libelleProduit = infoProduit.split('<div class="bloc-lien-produit"')[1].split('<a')[1].split('">')[1].split("</a>")[0] ; //lien du produit avec le libelle       
                        var urlProduit = infoProduit.split('<a')[1].split('>')[0].split('href="')[1].split('"')[0];

                        var imageProduit = infoProduit.split('<img class="label" id="picto-new')[1].split('</a>')[0] ; //lien du produit avec l'image
                        imageProduit=imageProduit.substring(imageProduit.indexOf("<"));

                        if(refProduit!=referenceProduit){
                           if(imageProduit != ''){
                               if(imageProduit.indexOf("mh-asset") > 0){      
                                   var reg=new RegExp("mh-", "g");
                                   imageProduit=imageProduit.replace(reg,"my-");
                                   isPhotoNonDispo = "false" ;
                               }
                               else if(imageProduit.indexOf("photo-non-dispo") > 0){
                                   isPhotoNonDispo = "true" ;
                               }
                               var display="style='display:none;'";
                                var reg2=new RegExp("src", "g");
                               imageProduit=imageProduit.replace(reg2,"onclick='document.location.href=\""+urlProduit+"\"' src");
                               if(isPhotoNonDispo == "false"){
                                  var blocProduit = refProduit + "__" +                                  
                                  '<div id="decouvrirplus'+refProduit+'" class="produits-vc">'+
                                       '<a href="'+urlProduit+'" onclick="'+funcVC+'">'+
                                           '<p class="img">'+ imageProduit+'</p>'+
                                           '<p class="label bold darkgrey s12">' + libelleProduit +'</p>' +                                     
                                       '</a>'+
                                   '</div>';
                                    
                                   produitPossibleFamille[indexProduitPossibleFamille] = blocProduit ;
                                   indexProduitPossibleFamille++;
                               }
                            }
                        }
                    }
                }
                //On recupère pour la famille selectionne, la liste des produits potentiellement affichable
                //Pour chacun de ces produits on en prend un au hasard et on le met dans la liste final à proposer à l'internaute                       
                if(produitPossibleFamille){
                    //************** 1- Cas particulier d'une seule famille
                    if(maxFamille == 1){
                        var produitDejaSelect = "" ;
                        var nbProduitSelect = 0 ;
                        var nbProduitToDisplay = nbProduitAAfficher ; //Par defaut, le nb de produit à afficher est de 4
                        if(produitPossibleFamille.length <= nbProduitAAfficher){ //On recalcule donc pour determiner si il ne faut pas en afficher moins car la famille peut contenir moins de 4 produits
                            nbProduitToDisplay = produitPossibleFamille.length ; 
                        }
                        
                        if(nbProduitToDisplay > 0){ //Si la famille possède au moins un produit, on va afficher au maxi 4 produits à mettre en avant
                            while(nbProduitSelect != nbProduitToDisplay){ //Tant que le nb de produit trouve est inferieur au nb de produit à afficher on continue de chercher des produits
                                var randomIdProduct = randomizeProduct(produitPossibleFamille.length) ; //on determine un produt au hasard dans cette famille mais dont l'index doit être different du produit courant
                                if(produitDejaSelect.indexOf(randomIdProduct) == -1){ //Si c ok et que le produit n'a pas encore ete choisi, on va former le contenu html et le fichier script pour le js price
                                    produitDejaSelect = produitDejaSelect + ";" + randomIdProduct ;
                                    
                                    var blocProduit = produitPossibleFamille[randomIdProduct-1] ;
                                    if(blocProduit){
                                        if(blocProduit.indexOf(urlCeProduit) == -1){ //Si le produit scanne est different du produit vue actuellement par l'internaute
                                            var nomModele = blocProduit.split("__")[0] ;
                                            var blocProduitHtml = blocProduit.split("__")[1] ;
                                            modelesADecouvrir = modelesADecouvrir + nomModele + ";" ;

                                            nbProduitSelect++;
                                            contenuDecouvrirPlus = contenuDecouvrirPlus + blocProduitHtml ;
                                       }
                                    }
                                }
                            }
                        }
                        else{ //Si la famille ne contient qu'un seul produit, ne pas afficher de mise en avant
                            contenuDecouvrirPlus = contenuDecouvrirPlus;
                            aucunProduitAAffiche = "true" ;                            
                        }
                    }
                    //************** 2- Cas particulier, si le nb de famille est inferieur ou egal à 4  
                    else if(maxFamille <= nbProduitVraimentAAfficher){                                                         
                        
                            var randomIdProduct = randomizeProduct(produitPossibleFamille.length) ;
                            var blocProduit = produitPossibleFamille[randomIdProduct-1] ;
                            if(blocProduit){
                                if(blocProduit.indexOf(urlCeProduit) == -1){ //Si le produit scanne est different du produit vue actuellement par l'internaute
                                    var nomModele = blocProduit.split("__")[0] ;
                                    var blocProduitHtml = blocProduit.split("__")[1] ;
                                    modelesADecouvrir = modelesADecouvrir + nomModele + ";" ;
                                    
                                    contenuDecouvrirPlus = contenuDecouvrirPlus + blocProduitHtml ;
                                }
                            }
                    }
                    //************** 3- Cas particulier, si le nb de famille est strictement superieur à 4  
                    else{
                        var randomIdProduct = randomizeProduct(produitPossibleFamille.length) ;
                        if(randomIdProduct){
                            var blocProduit = produitPossibleFamille[randomIdProduct-1] ;
                            if(blocProduit){
                                if(blocProduit.indexOf(urlCeProduit) == -1){ //Si le produit scanne est different du produit vue actuellement par l'internaute
                                    var nomModele = blocProduit.split("__")[0] ;
                                    var blocProduitHtml = blocProduit.split("__")[1] ;
                                    modelesADecouvrir = modelesADecouvrir + nomModele + ";" ;
                                    
                                    contenuDecouvrirPlus = contenuDecouvrirPlus +  blocProduitHtml 
                                        
                                }
                            }
                        }
                    }                                    
                }    
                
                //Traitement des id modèle pour supprimer les doublons
                
                var arrayModelesADecouvrirTmp = modelesADecouvrir.split(";") ;
                
                if(maxFamille < nbProduitVraimentAAfficher || (maxFamille >= nbProduitVraimentAAfficher && arrayModelesADecouvrirTmp.length == nbProduitAAfficher+1)){
                    if(contenuDecouvrirPlus && contenuDecouvrirPlus != ''){
                        if(aucunProduitAAffiche == "false"){
                            theInnerHTML = contenuDecouvrirPlus ;                        
                        }
                        else{
                            theInnerHTML = contenuDecouvrirPlus  ;
                            document.getElementById("bloc-vc").style.display = "none" ;
                        }
                        propertiesDivObjSr.innerHTML = "<div class='advice' id='produits-vc'><div class='titre'></div>"+theInnerHTML +"<div class='shadow'></div></div>";
                        displayProduct(referenceProduit, arrayModelesADecouvrirTmp) ;
                    }
                    else{
                        theInnerHTML = contenuDecouvrirPlus  ;
                        document.getElementById("bloc-vc").style.display = "none" ;
                    }
                }
            }
        }
    }

    var ajaxProc = new IAjaxProcess(urlFamille, POST_LOAD_CONTENT_DEC_FUNC) ;
    ajaxProc.run() ;
}


function displayProduct(referenceProduitCourant, arrayModelesADecouvrir){
    var nbProduitTrouve = 0 ;

    //on va verifier si il ne faut pas cacher le produit
    for(var q=0 ; q<arrayModelesADecouvrir.length ; q++){
        if(arrayModelesADecouvrir[q]){                 
            var modeleCourant = arrayModelesADecouvrir[q] ;

            if(modeleCourant != referenceProduitCourant){
                if(arrayModelesADecouvrir.length >= nbProduitVraimentAAfficher){                    
                    if(nbProduitTrouve < nbProduitVraimentAAfficher && document.getElementById(modeleCourant)){
                        document.getElementById(modeleCourant).style.display = "block" ;
                        nbProduitTrouve++ ;                        
                    }
                    else{
                        if(document.getElementById(modeleCourant)){
                            document.getElementById(modeleCourant).style.display = "none" ;
                        }
                    }
                }
                else{
                    if(document.getElementById(modeleCourant)){
                        document.getElementById(modeleCourant).style.display = "block" ;
                    }                        
                }                
            }
            else{
                if(document.getElementById(modeleCourant)){
                    document.getElementById(modeleCourant).style.display = "none" ;
                }
            }
        }
    }  
}