var currentPage = 1 ; //La page courante
var libToutAfficher = "" ; //La variable qui contient le texte tout afficher avec le nombre de produit pour cette famille
var afficherPaginationBas = false;

/** #########################################
* Permet d'avoir le nombre reel total de page a partir du nombre de produit reel dans la famille
*/
function getTotalPages(_nbProduitFamille){
    var nbPage = 1 ;
    if(_nbProduitFamille/nbProduitParPage == Math.floor(_nbProduitFamille/nbProduitParPage)){
        nbPage = Math.floor(_nbProduitFamille/nbProduitParPage) ;
    }
    else{
        nbPage = Math.floor(_nbProduitFamille/nbProduitParPage) + 1 ;
    }
    return nbPage
}


/** #########################################
* Permet d'ecrire dans l'html le bloc pagination
* @params :
*    _isModeDegrade : Sommes nous dans le cas ou erep est ko
*/
function writePagination(_isModeDegrade){
    var isModeDegrade = false ;
    if(typeof _isModeDegrade != undefined){
        isModeDegrade = _isModeDegrade ;
    }
    
    if(!isModeDegrade){
        nbProduitFamille = enableModelList.length() ;
    }
    else{
        nbProduitFamille = modelList.length() ;
    }

    var nbPage = getTotalPages(nbProduitFamille) ;
    
    var paginationBloc = "" ;
    for(var i=1 ; i<=nbPage ; i++){
        //[TAG]Ajout du taggage Google analytics pour le texte
        var func = setLinkTag(tagFamille+"pagination", "showPage("+i+", "+nbPage+");") ;
        
        paginationBloc = paginationBloc + '<a class="darkgrey" href="#" onclick="'+func+'" id="numpage'+i+'">' ;
        paginationBloc = paginationBloc + i ;
        paginationBloc = paginationBloc + '</a>' ;
        if(i < nbPage){
            paginationBloc = paginationBloc + "<span class='separ'>-</span>" ;
        }        
    }
    
    var paginationObj = getElement("listepage", true, "") ;

    if(paginationObj){
        paginationObj.innerHTML = paginationBloc ;
    }
    
    if(getElement("pagination", true, "")){
        getElement("pagination", true, "").style.visibility = "visible" ;
    }
    
    if(typeof typePageFamille != "undefined" && typePageFamille == "2"){
        if(nbPage == 1){
            hideBlocId("zonepage") ;
        }
    }
    
    //on va verifier si il faut afficher ou non le lien "Tout afficher"
    displayLinkAllPages(nbProduitFamille, nbProduitParPage ) ; //nbProduitParPage declare dans l'html classic
    
    //############ GESTION DES FILTRES/TRIS ############    
    //on va afficher le bloc tri seulement si la centrale est different de -1
    
    //traitement erep
    //on va verifier si le client ne vient pas d'un autre pays
    var idCentral = _centralNumber ;
    var valueCookieCountry = getCookie("country") ;
    if(valueCookieCountry){
        var enseigneSiteObj = mapUrlParPays.get(valueCookieCountry) ;
        if(enseigneSiteObj){
            idCentral = enseigneSiteObj.getCentrale() ;
        }
    }
    
    if(idCentral != "-1"){
        if(typeof activerTri != "undefined" && activerTri){
            displayBlocId("blocTri") ;
            displayBlocId("totalTriFiltre") ;
        }
        
        //on va afficher le bloc filtre
        if(typeof activerFiltre != "undefined" && activerFiltre){
            displayBlocId("blocFiltre") ;
            displayBlocId("totalTriFiltre") ;
        }
    }
}

/** #########################################
* Permet d'afficher le lien "Tout afficher"
*/
function displayLinkAllPages(_nbProduitFamille, _nbProduitParPage){
    //on va mettre a jour le texte "tout afficher" avec le nombre de resultat au total
    var replacementArray = new Array() ;
    replacementArray[0] =  "__NB_PRODUITS__" ;
    replacementArray[1] = _nbProduitFamille ;
    
    libToutAfficher = replaceAll(toutAfficherLabel, replacementArray) ;

    var allPagesBloc = getElement("all_pages", true, "") ;
    if(allPagesBloc && libToutAfficher){
        allPagesBloc.innerHTML = libToutAfficher ;
    }
    
    if(_nbProduitFamille <= _nbProduitParPage){
        hideBlocId("all-pages") ;
    }
    else{
        displayBlocId("all-pages") ;
    }
}

/** #########################################
* Permet de positionner le bloc concu pour en fonction de la position de la fenêtre
*/
function hideAll(){
    var pagesDIV = getElement('produits', true, "")
    var page = pagesDIV.getElementsByTagName('li');
    for(i=0;i  < page.length; i++){
        if(page[i].id.indexOf("vignetteproduit-") > -1){
            page[i].style.display = 'none';
        }
    }
}


/** #########################################
* Permet de positionner le bloc concu pour en fonction de la position de la fenêtre
*/
function clearLienPage(){
    var lienpagesDIV = window.document.getElementById('pagination')
    var lienpage = lienpagesDIV.getElementsByTagName('a');
    
    if (afficherPaginationBas == true) {
        var lienpagesDIV = window.document.getElementById('pagination-bas')
        var lienpageBas = lienpagesDIV.getElementsByTagName('a');
        
        for(i=0;i  < lienpageBas.length; i++){
            if(lienpageBas[i].id.indexOf("numpage") > -1){
                lienpageBas[i].className = 'hover';
            }
         }
    }
            
    for(i=0;i  < lienpage.length; i++){
        if(lienpage[i].id.indexOf("numpage") > -1){
            lienpage[i].className = 'hover';
        }
     }
     
     
}


function getCurrentPage(){
    var currentPageSaved = getCookie("pagination") ;
    var numPage = 1 ;
    
    if(currentPageSaved && currentPageSaved != "" && currentPageSaved != "null"){
        if(currentPageSaved.indexOf("allproducts_") > -1){
             numPage = 1 ;
        }
        else{
            var lastPageUrl = currentPageSaved.split("_")[2] ;
            if(lastPageUrl == document.location.href){
                numPage = currentPageSaved.split("_")[0] ;
            }
        }
    }
    return numPage ;
}

/** #########################################
* Permet de gérer le bloc pagination : visibilite des fleches et mis à jour du numero de page
*/
function setPagination(numPage, totalPages){
    clearLienPage() ;
    
    var next = getElement('next-page', true, "");
    var previous = getElement('previous-page', true, "");
    currentPage=numPage;
    var lienPageCourante = getElement("numpage"+numPage, true, "") ;
    
    if (afficherPaginationBas == true) {
        setTimeout('var lienPageCouranteBas = getElement("paginationBas-numpage'+numPage+'", true, "")',3000) ;
    }

    //update the page number                    
    if(lienPageCourante){
        lienPageCourante.className = "" ;
    }
    if (afficherPaginationBas == true) {
/*        lienPageCouranteBas.className = "" ;*/
        setTimeout('getElement("paginationBas-numpage'+numPage+'", true, "").className = "" ',3000)
    }

    //Dans le cas d'une seule page, on cache les liens precedent et suivant
    if(totalPages == 1){
        if(previous){
            previous.style.visibility = 'hidden';
        }
        if(next){
            next.style.visibility = 'hidden';
        }
    }
    else{
        //update the previous and next page links
        if(numPage == 1){
            if(previous){
                previous.style.visibility = 'hidden';
            }
        }
        else{
               if(previous){
                previous.style.visibility = 'visible';
            } 
        }
            
        if(numPage == totalPages){
            if(next){
                next.style.visibility = 'hidden';
            }
        }
        else{
            if(next){
                next.style.visibility = 'visible';
            }
        }
    }
}


/** #########################################
* Permet d'afficher tous les produits
*/
var isAllPages = false ;

function showAll(){
    var next = getElement('next-page', true, "");
    var previous = getElement('previous-page', true, "");
    
    if(!isAllPages){
        var pagesDIV = getElement('produits', true, "");
        var page = pagesDIV.getElementsByTagName('ul');
        showall = getElement('all-pages', true, "");
        
        //On affiche tous les produits
        displayAllProducts(false, true) ;
        
        //On affiche le bouton "Comparer" du bas        
        if(isDisplayCompareButton){
            displayBlocId("lienGdbcBottom") ;
        }
    
        //On va modifier le texte
        var allPages = getElement("all_pages", true, "") ;
        if(allPages){
            allPages.innerHTML = libRetourPagination ;
            isAllPages = true ;
            
            //on va cacher le bloc liste pages
            var listePages = getElement("listepages", true, "") ;
            if(listePages){
                listePages.style.visibility = "hidden" ;
                if(next){
                    next.style.visibility = "hidden" ;
                }
                if(previous){
                    previous.style.visibility = "hidden" ;
                }
            }
        }
        var currentLocationHref = (document.location.href).split("#")[0] ;
        setCookie(_language, "pagination", "allproducts_"+currentLocationHref) ;
    }
    else{
        //On va modifier le texte
        var allPages = getElement("all_pages", true, "") ;
        if(allPages){
            allPages.innerHTML = libToutAfficher ;
            isAllPages = false ;
        }        
    
        showPage(1, 99) ;
        
        //on va cacher le bloc liste pages
        var listePages = getElement("listepages", true, "") ;
        if (afficherPaginationBas == true) {
            var listePageBasObj = getElement("listepageBas", true, "") ;
        }
        if(listePages){
            listePages.style.visibility = "visible" ;
            if(afficherPaginationBas == true) {
                listePageBasObj.style.visibility = "visible" ;
            }
        }
        
        //On cache le bouton "Comparer" du bas        
        if(isDisplayCompareButton){
            hideBlocId("lienGdbcBottom") ;
        }
    }
}


/** #########################################
* Permet d'afficher les produits d'une page
*/
function show(numPage){
    if(nbProduitFamille <= nbProduitParPage){ //variable declarees dans l'html
        var toutAfficherObj = getElement("all-pages", true, "") ;
        var listePageObj = getElement("listepages", true, "") ;
        if (afficherPaginationBas == true) {
            var listePageBasObj = getElement("listepageBas", true, "") ;
        }
        
        if(toutAfficherObj){
            hideBloc(toutAfficherObj) ;
        }        
        if(listePageObj){
            listePageObj.style.visibility = "hidden" ;
                if(afficherPaginationBas == true) {
                    listePageBasObj.style.visibility = "hidden" ;
                }
        }
    }
    
    var nbPage = getTotalPages(nbProduitFamille) ;
    var currentPageSaved = getCookie("pagination") ;
    var currentLocationHref = (document.location.href).split("#")[0] ;

    if(currentPageSaved && currentPageSaved != "" && currentPageSaved != "null"){
        if(currentPageSaved.indexOf("allproducts_") > -1){
             var lastPageUrl = currentPageSaved.split("_")[1] ;
             
             if(lastPageUrl == currentLocationHref){
                showAll() ;
                return false ;
            }
            else{
                setCookie(_language, "pagination", currentPage+"_"+nbPage+"_"+currentLocationHref) ;
            }
        }
        else{
            var lastPageUrl = currentPageSaved.split("_")[2] ;
            
            if(lastPageUrl == currentLocationHref){
                numPage = currentPageSaved.split("_")[0] ;
                nbPage = currentPageSaved.split("_")[1] ;
            }
            else{
                setCookie(_language, "pagination", currentPage+"_"+nbPage+"_"+currentLocationHref) ;
            }
        }
    }
    else{
        setCookie(_language, "pagination", currentPage+"_"+nbPage+"_"+currentLocationHref) ;
    }
    
    //on sette la page courante avec la variable numPage
    currentPage = numPage ;
    
    hideAll();    
    
    setPagination(numPage, nbPage) ;

    //display the selected page
    displayProductsPage(numPage, nbPage, nbProduitFamille, nbProduitParPage) ;
    
    //update the show all link
    showall = window.document.getElementById('all-pages');
    if(showall){
        showall.style.visibility = 'visible';
    }
    
    //affichage ou non du bouton comparer
    var lienGdbcH = getElement("liengdbch") ;
    var lienGdbcB = getElement("liengdbc") ;
    
    if(nbProduitFamille == 1){
        if(lienGdbcH){
            hideBloc(lienGdbcH) ;
        }
        if(lienGdbcB){
            hideBloc(lienGdbcB) ;
        }
    }
}


/** #########################################
* Permet d'afficher les produits de la page selectionnee
*/
function displayProductsPage(_numPage, _totalPages, _nbProduitFamille, _nbProduitParPage){
    var listeProduitAAfficher = new ArrayList() ;

    //On va determine si on est en mode degrade ou non, cad est ce que erep est ok ou ko
    var isModeDegrade = false ;
    if(typeof enableModelList != "undefined" && enableModelList.length() > 0){
        isModeDegrade = false ;
    }
    else{
        isModeDegrade = true ;
    }
    
    //On va definir quelle liste d'origine prendre en compte
    var tempList = new ArrayList() ;    
    if(typeof sortedList != "undefined" && sortedList.length() > 0){
        tempList = sortedList ;
    }
    else if(isModeDegrade){
        tempList = modelList ;
    }
    else{
        tempList = enableModelList ;
    }
    
    //Si le nombre de produit de la famille est inferieur ou egal au nombre de produit a afficher par page, on copie la liste modelList dans listeProduitAAfficher
    if(_nbProduitFamille <= _nbProduitParPage){
        listeProduitAAfficher = tempList ;
    }
    else{
        var indexProduitInit = (parseInt(_numPage)*_nbProduitParPage) - _nbProduitParPage ;

        //On va parcourir la liste des modeles pour aficher les bons blocs produit
        for(var i=indexProduitInit ; i<indexProduitInit+_nbProduitParPage ; i++){
            var idModel = tempList.get(i) ;
            
            listeProduitAAfficher.add(idModel) ;
        }
    }
    
    //On va afficher les produits
    for(var i=0 ; i<listeProduitAAfficher.length() ; i++){
        var currentModel = listeProduitAAfficher.get(i) ;
        var blocModel = "vignetteproduit-"+currentModel ;
                
        displayBloc(getElement(blocModel, true, "")) ;
    }
}


/* **************************************
* Fonction permettant d'afficher tous les produits
*/
function displayAllProducts(isDisplayPaginationBloc, isDisplayAllBloc){
    //on affiche ou on cache le bloc de pagination
    var listePages = getElement("listepages", true, "") ;
    if(listePages){
        if(isDisplayPaginationBloc){        
            listePages.style.visibility = "visible" ;
            if (afficherPaginationBas == true) {
                getElement("listepageBas").style.visibility = "visible" ;
            }
        }
        else{
            listePages.style.visibility = "hidden" ;
                if (afficherPaginationBas == true) {
                    getElement("listepageBas").style.visibility = "hidden" ;
                }
        }
    }
    
    //on affiche ou on cache le bloc de pagination
    if(isDisplayAllBloc){
        displayBloc(getElement("all-pages", true, "")) ;
    }
    else{
        hideBloc(getElement("all-pages", true, "")) ;
    }
    
    
    //on affiche tous les produits
    var produitsObj = getElement("produits", true, "") ;
    var produitsElts = produitsObj.getElementsByTagName("li") ;

    //Mode degrade ou non
    var isModeDegrade = false ;
    if(typeof enableModelList != "undefined" && enableModelList.length() > 0){
        isModeDegrade = false ;
    }
    else{
        isModeDegrade = true ;
    }
    
    for(var i=0 ; i<produitsElts.length ; i++){
        if(produitsElts[i] && produitsElts[i].id && produitsElts[i].id.indexOf("vignetteproduit-") > -1){
            var idModel = produitsElts[i].id.split("-")[1] ;
            
            if(isModeDegrade){
                displayBloc(produitsElts[i]) ;
            }
            else{
                if(enableModelList.contains(idModel) > -1){
                    displayBloc(produitsElts[i]) ;
                }
            }
        }
    }
}


/* **************************************
* Fonction permettant d'afficher tous les produits
*/
function hideAllProducts(){
    //on cache le bloc de pagination
    hideBloc(getElement("pagination", true, "")) ;    
    
    //on affiche tous les produits
    var produitsObj = getElement("produits", true, "") ;
    var produitsElts = produitsObj.getElementsByTagName("LI") ;
    
    for(var i=0 ; i<produitsElts.length ; i++){
        if(produitsElts[i] && produitsElts[i].id && produitsElts[i].id.indexOf("vignetteproduit-") > -1){
            hideBloc(produitsElts[i]) ;
        }
    }
}


/** #########################################
* Permet d'afficher les produits de la page d'apres
*/
function showAfter(){
    currentPage++ ;
    var currentLocationHref = (document.location.href).split("#")[0] ;
    setCookie(_language, "pagination", currentPage+"_"+totalPages+"_"+currentLocationHref) ;
    show(currentPage); 
}


/** #########################################
* Permet d'afficher les produits de la page precedente
*/
function showBefore(){
    currentPage-- ;
    var currentLocationHref = (document.location.href).split("#")[0] ;
    setCookie(_language, "pagination", currentPage+"_"+totalPages+"_"+currentLocationHref) ;
    show(currentPage);
}


/** #########################################
* Permet d'afficher les produit de la page selectionne
*/
function showPage(thePage, totalPages){
    var currentLocationHref = (document.location.href).split("#")[0] ;
    setCookie(_language, "pagination", thePage+"_"+totalPages+"_"+currentLocationHref) ;
    show(thePage);
}


function copyContent(idOfContent, idOfContainer) {
    afficherPaginationBas = true;
    setTimeout("copyContentWithTimeout('"+idOfContent+"', '"+idOfContainer+"' )",2000) ;
    /*copyContentWithTimeout(idOfContent, idOfContainer)*/
}

function copyContentWithTimeout(idOfContent, idOfContainer) {
    htmlToInput = document.getElementById(idOfContent);
    var reg=new RegExp('(numpage)', 'g');
    textToInput = htmlToInput.innerHTML;
    textToInput = textToInput.replace(reg,'id=\"paginationBas-numpage');
    document.getElementById(idOfContainer).innerHTML += textToInput;
}
