/******indexOf fo Ie**************/
if(!Array.indexOf){
    Array.prototype.indexOf = function(obj){
        for(var i=0; i<this.length; i++){
            if(this[i]==obj){
                return i;
            }
        }
        return -1;
    }
}


/******************cookie Manager*******************/
var localMode = false;

function getCookie(sName) {
    var oRegex = new RegExp("(?:; )?" + sName + "=([^;]*);?");

    if (oRegex.test(document.cookie)) {
        return unescape(RegExp["$1"]);
    } else {
        return null;
    }

}

function setCookie (sName, value, min) {
    var expires;
    if (min) {
        var date = new Date();
        date.setTime(date.getTime()+(min*60*1000));
        expires = "; expires="+date.toGMTString();
    }
    else expires = "";
    document.cookie = sName+"="+escape(value)+expires+"; path=/";
}

function eraseCookie(sName) {
    setCookie(sName,"",-1);
    return null;
}


/************************Recupération ID catégorie****************************/
function getCatId () {
    var currentCatId=getCookie('currentCatId');

    if (!OxCatID1 && !OxCatID2 && !OxCatID3) {
        eraseCookie('currentCatId');
        return null;
    }

    if (!currentCatId) {
        if (OxCatID1) {
            setCookie ('currentCatId', OxCatID1);
            return OxCatID1;
        }
        if (OxCatID2) {
            setCookie ('currentCatId', OxCatID2);
            return OxCatID2;
        }
        if (OxCatID3) {
            setCookie ('currentCatId', OxCatID3);
            return OxCatID3;
        }
    } else {
        switch (parseInt(currentCatId, 10)) {
            case parseInt(OxCatID1, 10):
                setCookie ('currentCatId', OxCatID1);
                return OxCatID1;
                break;
            case parseInt(OxCatID2, 10):
                setCookie ('currentCatId', OxCatID2);
                return OxCatID2;
                break;
            case parseInt(OxCatID3, 10):
                setCookie ('currentCatId', OxCatID3);
                return OxCatID3;
                break;
            default:
                if (OxCatID1) {
                    setCookie ('currentCatId', OxCatID1);
                    return OxCatID1;
                }
                if (OxCatID2) {
                    setCookie ('currentCatId', OxCatID2);
                    return OxCatID2;
                }
                if (OxCatID3) {
                    setCookie ('currentCatId', OxCatID3);
                    return OxCatID3;
                }
                break;
        }
    }
}

/************** paramétrage du diaporama****************/
function myCarrousel (targetZone, targetWb) {
    showPageInOtherOne ({
        wbId:targetWb,
        classIdentifier:'#maincontainer',
        target:targetZone,
        insertionMode:'replace',
        ajaxCache: true
    });
}
// importation d'un webBlock
function showPageInOtherOne (setting) {

    if (!setting.wbId || !setting.classIdentifier || !setting.target ) return;
    if (!setting.insertionMode) setting.insertionMode="append"; //append, prepend or replace
    if (!setting.ajaxCache)  setting.ajaxCache=true; // Cache des données en Ajax

    if ($(setting.classIdentifier).length<1) return;

    $.ajax({
        url:'ws/wsGetWebBlock.asp?WBID='+setting.wbId,
        cache: setting.ajaxCache,
        dataType:'json',
        success: function(Data) {
            importTemplate (Data);
        }
    });

    function importTemplate (data) {

        if (!data || data.error) return;
        var target=$(setting.target);
        if (setting.insertionMode=='replace') target.html(data.htmlContent);
        if (setting.insertionMode=='prepend') target.prepend(data.htmlContent);
        if (setting.insertionMode=='append') target.append(data.htmlContent);

        var myDiapo = new customCarrousel();
        myDiapo.order = ['zone', 'tab'];
        myDiapo.autoHeight = true;
        myDiapo.autoWidth = true;
        myDiapo.timeToSlide = 8000;
        myDiapo.carrousel();
    }

}


//Diaporama Jquery
function customCarrousel () { }

// définition des valeurs par défaut
customCarrousel.prototype.target = '#carrousel';
customCarrousel.prototype.urlParam = 'tab';
customCarrousel.prototype.autoSlide = true;
customCarrousel.prototype.crossTransition = true;
customCarrousel.prototype.autoHeight = false;
customCarrousel.prototype.autoWidth = false;
customCarrousel.prototype.timeToSlide = 3000;
customCarrousel.prototype.slideSpeed = 500;
customCarrousel.prototype.stopAfterFirstClick = false;
customCarrousel.prototype.htmlTemplate = '<tbody><tr><td class="leftColumn"><zone/></td><td class="rightColumn"><list/></td></tr></tbody>';
customCarrousel.prototype.order = ['tab', 'zone'];
customCarrousel.prototype.tabContainer = 'ul';
customCarrousel.prototype.tabLister = 'li';
customCarrousel.prototype.zIndex = 10;
customCarrousel.prototype.carrousel = function () {
        
    if (!$(this.target).length) return;
    var tags =[],
    zone=[],
    x=0,
    y=0,
    i=1,
    me=this;

    $(this.target).css({
        'position':'relative'
    });

    // récupération des élemetns du webBlock
    $(this.target+ ' > tbody > tr').each(function () {
        var thisElement = $(' > td', this);

        var thisTag = thisElement.eq(me.order.indexOf("tab")).html(),
            thisZone = thisElement.eq(me.order.indexOf("zone"));
        
        if (me.autoWidth) x = Math.max (thisZone.width(), x);
         if (me.autoHeight) y = Math.max (thisZone.height(), y);

        tags.push('<'+me.tabLister+' class="tagListElements" ><a class="tagLinks tagLink'+i+'">'+thisTag + '</a></'+me.tabLister+'>');

        var tempZone = thisZone.wrapInner('<div class="tagsZone tagZone'+i+'" />'),
            tempZoneChild = tempZone.children().detach();
        zone.push(tempZoneChild);
        i++;
    });

    // Position initiale diaporama
    var numberOfItems = tags.length,
    timeOut,
    uriCourant = document.location.href,
    reg= new RegExp ("[&\\?]"+this.urlParam+"=(\\d+)", "g"),
    infosInUrl = reg.exec(uriCourant);

    var current = null,
    next = (infosInUrl && infosInUrl.length>0 && parseInt(infosInUrl[1])>0 && parseInt(infosInUrl[1])<=numberOfItems )? parseInt(infosInUrl[1]) : 1;

    //création HTML
    $(this.target).html(this.htmlTemplate);
    
    $(this.target+' zone:first').replaceWith('<div class="tagsListZone" style="position:relative;"></div>');
    $(this.target+' list:first').replaceWith('<'+this.tabContainer+' class="tagsList">'+tags.join('')+'</'+this.tabContainer+'>');
    for (var j=0; j<numberOfItems; j++) {
        $(me.target+' .tagsListZone:first').append(zone[j]);
    }

        
    $(this.target+' .tagsListZone:first .tagsZone')
    .css({
        'opacity': 0,
        'left':0,
        'top':0,
        'position':'absolute'
    })
    .hide();

    if (this.autoHeight) $(this.target+' .tagsListZone:first .tagsZone').height(y);
    if (this.autoWidth) $(this.target+' .tagsListZone:first .tagsZone').width(x);


    shadeIt (1);
    // fonction de transition fondu/enchainé :
    function shadeIt (speed) {

        if (current==next) return;
        if(current) {
            var currentZone = $(me.target+' .tagsListZone:first > .tagZone'+current);
            
            if (me.crossTransition) {
                currentZone.css({
                    'position':'absolute'
                });
            }

            currentZone.animate({
                'opacity': 0,
                'z-index':0
            }, {
                queue: !me.crossTransition,
                duration : speed,
                complete : function () {
                    $(this)
                    .css({
                    'position':'absolute'
                    })
                    .hide();
                    if (!me.crossTransition) showNext ();
                }
            });
            
            $(me.target+' .tagsList:first > .tagListElements > .tagLink'+current).removeClass('taghighlighted');
        }

        $(me.target+' .tagsList:first > .tagListElements > .tagLink'+next).addClass('taghighlighted');
        
        if (me.crossTransition || !current) showNext ();

        function showNext () {
            $(me.target+' .tagsListZone:first > .tagZone'+next)
            .show()
            .css({
                'z-index':1,
                'position':'relative'
            })
            .animate({
                'opacity': 1,
                'z-index':me.zIndex
            }, speed);
        }

        current=next;
    }


    // affichage zone correspondante lors du clic sur un élement du carousel
    $(document).delegate(this.target+' .tagsList:first .tagLinks','click', function(){
        var meAgain = $(this).attr('class'),
        reg = new RegExp ('tagLink(\\d+)', 'g');
        next = parseInt(reg.exec(meAgain)[1], 10);

        if (me.autoSlide) {
            clearTimeout (timeOut);
        }
        if (me.autoSlide && !me.stopAfterFirstClick)  {
            autoscroll();
        }
        shadeIt (me.slideSpeed);
    });

    //auto défilement
    function autoscroll () {
        timeOut = setTimeout (function () {
            next = (next<numberOfItems) ? next+1 : 1;
            shadeIt (me.slideSpeed);
            autoscroll();
        }, me.timeToSlide);
    }

    if (this.autoSlide) autoscroll ();
}

/********************Selecteur carrousel/produits********************/
function chooseHeaderToDisplay (setting) {

    if (!setting.target || !setting.diaporamaId || !setting.productTmplId) return;
    var currentCatId = getCatId (),
        lastCatId= ($("diaporama, .scshopcart").length) ? eraseCookie('lastCatId') : getCookie('lastCatId');

    if (!currentCatId && !lastCatId) {
        myCarrousel (setting.target, setting.diaporamaId);
        return;
    }

    if (currentCatId) {
        setCookie ('lastCatId', currentCatId);
        showProduct (currentCatId, setting);
        return;
    }

    if (lastCatId) {
        showProduct (lastCatId, setting);
        return;
    }
}

/**************************afficher les produits**************************/
function showProduct(catId, setting) {

    if (!catId || !setting) return;
    $('#hmenu li.'+catId).addClass('currentMenu');

    var maxElements=4,
    arrowSize=30,
    CSSMargin=0;

    $.ajaxSetup({
        cache: true
    });

    /**********************************appel Json**********************************/
    var multiAjax = [];

    // recup prodtuis
    var getProducts = new webServiceQuery();
    //  getProducts.fonction = buildHTML;
    getProducts.url = 'ws/wsGetProducts.asp?CatID='+catId+'&shopcart=1&sort=position&sortdir=1';
    var firstQuery = new Json(getProducts);
    multiAjax.push(firstQuery);
        
    // recup tmpl
    var getTmpl = new webServiceQuery();
    //  getTmpl.fonction = getProductTmpl;
    // getTmpl.dataType = 'html';
    // getTmpl.url = '/PBCPPlayer.asp?ADContext=1&ID='+wbId+'&PW=1';
    getTmpl.url = 'ws/wsGetWebBlock.asp?WBID='+setting.productTmplId;
    var secondQuery = new Json(getTmpl);
    multiAjax.push(secondQuery);
        
    // exécution simultanée des 2 requetes
    var doQuery = new startQuery(multiAjax);
    doQuery.onDone(renderingCarrousel);
    doQuery.process();

    /**********************Construction du contenu carrousel*****************************/
    /*
        function buildHTML (data) {
            if (window.console) console.log ('buildHTML - Data', data);
        }
        function getProductTmpl (data) {
            if (window.console) console.log ('getProductTmpl - Data', data);
        }
     */
    function renderingCarrousel () {

        //initialisation
        if (!getTmpl.answer || !getProducts.answer || getTmpl.answer.error) {
            myCarrousel (setting.target, setting.diaporamaId);
            return;
        }
        var items = [];

        if (!getProducts.answer.products) { 
            myCarrousel (setting.target, setting.diaporamaId);
            return;
        }

        var numberOfItems = getProducts.answer.products.length;
        if (numberOfItems<1) {
            myCarrousel (setting.target, setting.diaporamaId);
            return;
        }
        //Création de l'HTML

        $.each(getProducts.answer.products, function(key, val) {
            var thisProductTmpl = getTmpl.answer.htmlContent,
            buyUrl = (val.buybtn) ? 'javascript: cart.ajaxCartSubmiter ( '+val.id+', \'ItemID='+val.id+'\');' : val.url,
            smallImg = (val.smallimg)? '<a href="'+val.url+'"><img src="'+val.smallimg+'" class="CarrouselImg"/></a>' : '',
            description = (val.description) ? val.description : "",
            price= (val.price && val.price!="")? val.price : 0,
            regDescription=new RegExp("<span class=\"PBMsg\">([^<>]+)</span>","g"),
            regDescriptionExec=regDescription.exec(description);
            description = (regDescriptionExec && regDescriptionExec.length>1)? regDescriptionExec[1] : description;
            description = description.replace(/<[^>]*>/g,"").substr(0, 100);

            thisProductTmpl = replaceFromTemplate (thisProductTmpl, '#PRICE#', convertToPrixe(price));
            thisProductTmpl = replaceFromTemplate (thisProductTmpl, '#IMAGE#',smallImg);
            thisProductTmpl = replaceFromTemplate (thisProductTmpl, '#DESCRIPTION#', description);
            thisProductTmpl = replaceFromTemplate (thisProductTmpl, '#TITLE#', val.name);
            thisProductTmpl = replaceFromTemplate (thisProductTmpl, 'http:\\/\\/#URL#', val.url);
            thisProductTmpl = replaceFromTemplate (thisProductTmpl, 'http:\\/\\/#BUY#', buyUrl);

            items.push('<li class="carrouselElement" id="itemCarrousel' + val.id + '">' + thisProductTmpl + '</li>');
        });

        var htmlContent = '<ul class="elementsContainer">'+items.join('')+'</ul>';
        $(setting.productTmplId).html("");
        var productZone = new carrouselZone (htmlContent, numberOfItems, setting.target);
        productZone.carrouselIt();

    }
}

/************************Générateur de carrousel*****************************/
function carrouselZone (htmlData, nbElements, target) {
    this.htmlData=htmlData;
    this.target=target;
    this.nbElements=nbElements;
}

//initialisation

carrouselZone.prototype.maxElements = 4;
carrouselZone.prototype.totalWidth = 770;
carrouselZone.prototype.arrowSize = 35;
carrouselZone.prototype.defaultPosition = 0;
carrouselZone.prototype.globalContainerClassname = "subDiaporamaZone";
carrouselZone.prototype.mainContainerClassname = "carrouselContainer";
carrouselZone.prototype.subContainerClassname = "carrouselSubContainer";
carrouselZone.prototype.contentMainTag = "ul";
carrouselZone.prototype.contentSubTag = "li";
carrouselZone.prototype.marginUl='0';
carrouselZone.prototype.floatUl='right';
carrouselZone.prototype.autoEnlargeZone = true;
carrouselZone.prototype.carrouselIt = function () {


    if (!this.htmlData || !this.target || !this.nbElements) return;

    if (this.autoEnlargeZone) {
        this.arrowSize = (this.nbElements > this.maxElements)? this.arrowSize : 0;
    }
    var items = [],
    slideWidth=Math.round((this.totalWidth -(this.arrowSize*2))/this.maxElements),
    ulWidth = this.nbElements * slideWidth,
    zoneWidth = slideWidth * this.maxElements,
    animateFirst=false,
    catIndex=0,
    marginUl = (this.nbElements<this.maxElements)?  this.marginUl : '0',
    floatUl = (this.nbElements<this.maxElements)?  this.floatUl : 'none';

    //Création de l'HTML
    var carrouselHTML='<div class="'+this.mainContainerClassname+'">';
    if (this.arrowSize>0) carrouselHTML += '<div class="control leftControl"></div>';
    carrouselHTML += '<div class="'+this.subContainerClassname+'">'+this.htmlData+'</div>';
    if (this.arrowSize>0) carrouselHTML += '<div class="control rightControl"></div>';
    carrouselHTML += '</div>';

    $('<div/>', {
        'class': this.globalContainerClassname,
        html:carrouselHTML
    }).prependTo(this.target);

    //Mise en forme CSS
    $('.'+this.subContainerClassname+' > '+this.contentMainTag)
    .css({
        'width':ulWidth,
        'margin' : marginUl,
        'float' : floatUl
    });

    $('.'+this.subContainerClassname+' > '+this.contentMainTag +' > ' +this.contentSubTag)
    .css({
        'width':slideWidth
    });

    $('.'+this.mainContainerClassname).css({
        'width':this.totalWidth
    });

    $('.'+this.subContainerClassname).css({
        'width':zoneWidth,
        'left':this.arrowSize,
        'position':'relative'
    });
        
    var me=this;
    //Cursors droite/Gauche et scrolling
    $('.'+this.mainContainerClassname+' .control')
    .bind('click', function(){

        var maxOffset=me.nbElements-me.maxElements-me.defaultPosition,
        rightOffset = (me.maxElements<maxOffset) ? me.maxElements : maxOffset,
        leftOffset = (me.maxElements<me.defaultPosition) ? me.maxElements : me.defaultPosition;

        me.defaultPosition = ($(this).attr('class')=='control rightControl') ? me.defaultPosition+rightOffset : me.defaultPosition-leftOffset;

        animateControl(me.defaultPosition);
        positionControl(me.defaultPosition);
    })
    .bind('mouseover', function(){

        $(this).css('opacity',0.5);
    })
    .bind('mouseout', function(){

        $(this).css('opacity',1);
    });

    // déplacement des éléments
    function animateControl (pos) {

        $('.'+me.subContainerClassname+' > '+me.contentMainTag).animate({
            'marginLeft' : slideWidth*(-pos)
        });
    }

    //affichage des curseurs droite et/ou gauche
    function positionControl (pos) {

        (pos==0)? $('.'+me.mainContainerClassname+' .leftControl').hide() : $('.'+me.mainContainerClassname+' .leftControl').show();
        (pos>=(me.nbElements-me.maxElements))? $('.'+me.mainContainerClassname+' .rightControl').hide() : $('.'+me.mainContainerClassname+' .rightControl').show();
    }

    // offset initial
    function firstAnim () {
        if (animateFirst)  {
            animateControl (me.defaultPosition);
            positionControl(me.defaultPosition);
        } else {
            positionControl(0);
        }
    }

    firstAnim();

}

/************************Ajax scheduler*****************/

//classe webServiceQuery
function webServiceQuery(){
}
webServiceQuery.prototype.url = 'ws/wsGetCategories.asp?Mode=3&shopcart=1';
webServiceQuery.prototype.dataType = 'json';
webServiceQuery.prototype.answer = null;
webServiceQuery.prototype.addParams = null
webServiceQuery.prototype.handleResponse = function(data) {
    if (this.fonction) this.fonction(data, this.addParams);
}
webServiceQuery.prototype.handleError = function() {
    if (this.fonctionError) this.fonctionError();
}

/*classe Json*/
function Json (webService) {
    this.webService=webService;
}
Json.prototype.onFinish = function (fn)
{
    this.onFinishCallBack=fn;
}
Json.prototype.ajaxSend = function () {
    var me=this;
    $.ajaxSetup({
        'beforeSend' : function(xhr) {
            xhr.overrideMimeType('text/html; charset=iso-8859-1');
        }
    });

    $.ajax({
        url: this.webService.url,
        cache: false,
        dataType: this.webService.dataType,
        success: function(Data) {
            me.webService.handleResponse (Data);
            me.webService.answer = Data;
            if (me.onFinishCallBack) me.onFinishCallBack();
        },
        error:function (xhr, ajaxOptions, thrownError){
            if (window.console) console.log ("error", xhr.status, thrownError);
            me.webService.handleError ();
        }
    });
}

/*classe startQuery*/
function startQuery(toSend){
    this.toSend = toSend;
    this.count=0;
}

startQuery.prototype.process = function(){
    var me = this;
    for (var i=0; i<this.toSend.length; i++) {
        this.toSend[i].onFinish(function(){
            me.returnProcess();
        });
        this.toSend[i].ajaxSend();
    }
}

startQuery.prototype.returnProcess = function(){
    this.count++;
    if ( this.toDo && (this.count == this.toSend.length) ) this.toDo();
}

startQuery.prototype.onDone = function(toDo){
    this.toDo = toDo;
}

/***************Mie en forme des prix**********************/
function convertToPrixe (price, coef) {
    if (!coef) coef=1;
    var amount = parseFloat(price)/coef;
    amount = amount.toString();
    amount = amount.replace('.', ',');

    var expregTest=new RegExp(',\\d\\d',"g"),
    expregTest2=new RegExp(',',"g"),
    test = amount.match(expregTest),
    test2 = amount.match(expregTest2);

    if  (!test && test2) amount += '0';

    return amount;
}


/***************************Panier dynamique*******************************/
function addHTMLStructure () {
    var testCartArea= $('#shopcartreturn');
 
    if (testCartArea.length<1) {
        $('body').eq(0).prepend('<div id="shopcartreturn"><div id="shopcartbody"></div><div id="shopcartcontainer"></div></div>');
    }
    $('#shopcartbody').css('height',$(document).height());

    var shopcartcontainer=$('#shopcartcontainer');
    $('#shopcartreturn').show();

    shopcartcontainer.append('<div id="shopcartpreload"></div>').css('top',$(window).scrollTop());

    return shopcartcontainer;
}


function dynamicCart () {}
dynamicCart.prototype.smallCartTmpl="";
dynamicCart.prototype.returnCartTmpl="";
dynamicCart.prototype.cookieSaving=true;
dynamicCart.prototype.cartTemplateCookie=null;
dynamicCart.prototype.ajaxCartSubmiter=  function (nProductID, strURLParams) {
   var me=this,
       shopcartcontainer = addHTMLStructure (),
       multiAjax = [];

    // Panier dynamqiue
    var getCart = new webServiceQuery();
    getCart.url = 'PBShoppingCart.asp?AjaxMode=1&'+strURLParams;
    var firstQuery = new Json(getCart);
    multiAjax.push(firstQuery);

    // recup tmpl
    var getTmpl = new webServiceQuery();
    getTmpl.url = 'ws/wsGetWebBlock.asp?WBID='+this.returnCartTmpl;
    var secondQuery = new Json(getTmpl);
    multiAjax.push(secondQuery);

    // exécution simultanée des 2 requetes
    var doQuery = new startQuery(multiAjax);
    doQuery.onDone(showCart);
    doQuery.process();

    function showCart () {

        if (!getCart.answer || !getTmpl.answer || getTmpl.error)  return;

        var htmlModel=getTmpl.answer.htmlContent,
        itemsCount=getCart.answer.result,
        totalItemsCount=getCart.answer.cartqtytotal,
        totalAmount=convertToPrixe(getCart.answer.cartsubtotalnet, 100);


        me.setDynamicCart ();
        htmlModel = replaceFromTemplate (htmlModel, '#ADDEDITEMS#', itemsCount, true );
        htmlModel = replaceFromTemplate (htmlModel, '#TOTALITEMS#', totalItemsCount, true );
        htmlModel = replaceFromTemplate (htmlModel, '#CARTAMOUNT#', totalAmount);
        htmlModel = replaceFromTemplate (htmlModel, 'http:\\/\\/#RETURN#', 'javascript:returnToSite();');
        shopcartcontainer.html(htmlModel);
    }

}

// affichage du mini-panier
dynamicCart.prototype.setDynamicCart = function () {

    
    if (this.cookieSaving) {
        this.cartTemplateCookie = getCookie('cartTemplateCookie');
    }
    var me=this;
    if (!this.cartTemplateCookie) {
        $.ajax({
            url: 'ws/wsGetWebBlock.asp?WBID='+this.smallCartTmpl,
            cache: true,
            dataType:'json',
            success: function(data) {
                me.cartTemplateCookie = data.htmlContent ;
                me.setCartCookie ();
            }
        });
    } else {
        this.showCartInDocument ();
    }

}

dynamicCart.prototype.setCartCookie = function  () {
    if (!this.cartTemplateCookie) return;
    if (this.cookieSaving) {
        setCookie ('cartTemplateCookie', this.cartTemplateCookie);
    }
    this.showCartInDocument ();
}

dynamicCart.prototype.showCartInDocument = function () {

    var reg=new RegExp("QTYTotal=(\\d*)","g"),
    regAmount=new RegExp("SubTotalNet=(\\d*)","g"),
    chaine=getCookie('PCart'),
    nbItems=reg.exec(chaine),
    amount=regAmount.exec(chaine),
    totalCart = (amount && amount.length>1 && amount[1]!="")? convertToPrixe(amount[1], 100) : 0,
    items = (nbItems && nbItems.length>=1 && nbItems[1]!="")?  parseInt(nbItems[1]) : 0;

    var cartModel = this.cartTemplateCookie;
    cartModel = replaceFromTemplate (cartModel, '#NBITEMS#', items , true );
    cartModel = replaceFromTemplate (cartModel, '#CARTAMOUNT#', totalCart);

    var btncontainer = $('#showCartContainer');
    if (btncontainer.length<1) {
        $('<div/>', {
            'id': 'showCartContainer',
            html: cartModel
        }).prependTo('body');
    } else {
        btncontainer.html(cartModel);
    }

}

// bouton continuer
function returnToSite() {
    $("#shopcartreturn").hide();
}

/******************gestionnaire de template*************************/
function replaceFromTemplate (htmlModel, tag, value, recursive) {
    var reg = {};

    if (recursive) {

        reg = {
            expression:new RegExp(tag+"\\s*\\{\\s*\\[([^\\}|\\]]*)\\]\\s*\\[([^\\}|\\]]*)\\]\\s*\\[([^\\}|\\]]*)\\]\\}", "g"),
            tagValue:new RegExp("#value#", "g")
        }

        var doResult=reg.expression.exec(htmlModel);
        if (!doResult) return null;
        var idValue = (value>2)? 3 : value+1;
        var newHTML=doResult[idValue].replace(reg.tagValue, value);
        htmlModel=htmlModel.replace(reg.expression,newHTML);

    } else {

        reg = {
            tagValue:new RegExp(tag, "g")
        }
        htmlModel=htmlModel.replace(reg.tagValue,value);
    }

    return htmlModel;
}

// transformer des action de navigation vers la fiche détail en soumission au panier
function itemToBuy (tag) {
    $('a'+tag+':[href*="PBSCCatalog.asp?ItmID"]').each(function () {
        var targetUrl = $(this).attr('href'),
        reg = new RegExp("ItmID=(\\d+)", "g"),
        itemID=reg.exec(targetUrl);
        if (!itemID || itemID.length<1) return;
        var url = 'javascript: cart.ajaxCartSubmiter ( '+itemID[1]+', \'ItemID='+itemID[1]+'\');';
        $(this).attr('href', url);
    });
}


// WebBLock produits avec onglets
function customItems (setting) {
    imagePosition();
    productTabs ();

    function imagePosition () {
        if (!setting.targetPage) return;

        var checkZone =  $('.itemdetail '+setting.targetPage);
        if(!checkZone.length) return;

        checkZone
        .unwrap()
        .css({
            'float':'rigth'
        });

    }

    function productTabs () {

        if (!setting.targetTab) return;
        var checkZone =  $('.itemdetail '+setting.targetTab);
        if(!checkZone.length) return;

        var itemTabs = new customCarrousel ();
        itemTabs.target = '#itemTabs';
        itemTabs.crossTransition=false;
        itemTabs.autoSlide = false;
        itemTabs.htmlTemplate = '<tbody><tr><td class="tabsTD"><list/></td></tr><tr><td class="zonesTD"><zone/></td></tbody>';
        itemTabs.order = ['tab', 'zone'];
        itemTabs.carrousel();

    }

}

/****************Initialisation des tests de la page Panier*****************
 catId : identifiant catégorie Loofah
 wbId : WebBlock à afficher si uniquement loofah
 */
function cartConditions (infos) {
    var loofahTest=false;
    var presentTest=false;
    if (!infos.catId || !infos.wbId) return;
    if (!$('.scshopcart').length) return;
$(".cartlineqty .PB").each(function () {
    $(this).before ('<span  class="PBNumber">' + $(this).val() + '</span>&nbsp;').hide();
})
    $('.viewtbl').hide();
    var cartProducts = getCartProducts();
    checkLoofah (infos.catId, cartProducts, infos.wbId);
    if (!infos.presentsId || !infos.threshold) {
        presentTest=true;
        accessDenied();
        return;
    }
    checkGwp (infos.presentsId, cartProducts, infos.threshold);



    /*récupération contenu panier*/
    function getCartProducts () {
        var regItemCount=new RegExp("ItemCount=(\\d*)","g"),
        cookie=getCookie('PCart'),
        regItemCountExec=regItemCount.exec(cookie),
        cartProducts = {
            nbItems : (regItemCountExec && regItemCountExec.length>1)? parseInt(regItemCountExec[1]) : null,
            productsId : [],
            productsQtity : []
        }

        if (!cartProducts.nbItems) return null;

        for (var i=0; i<cartProducts.nbItems; i++) {
            var regProductsId=new RegExp("ProductID"+i+"=(\\d*)","g"),
            regProductsIdExec=regProductsId.exec(cookie),
            regProductsQtity=new RegExp("QTY"+i+"=(\\d*)","g"),
            regProductsQtityExec=regProductsQtity.exec(cookie);

            if (regProductsIdExec && regProductsIdExec.length) cartProducts.productsId.push (parseInt(regProductsIdExec[1]));
            if (regProductsQtityExec && regProductsQtityExec.length) cartProducts.productsQtity.push (parseInt(regProductsQtityExec[1]));
        }

        return cartProducts;
    }

    //récupération du contenu de la catégorie Loofah
    function checkLoofah (loofahCat, cartProducts, wbId) {

        if (!loofahCat || !cartProducts || !wbId) {
            loofahTest=true
            accessDenied();
            return;
        }

        $.ajax({
            url : 'ws/wsGetProducts.asp?CatID=' + loofahCat  + '&shopcart=1',
            cache: false,
            dataType:'json',
            success: function(Data) {
                processLoofahCheck (Data);
            },
            error:function (xhr, ajaxOptions, thrownError){
                if (window.console) console.log ("checkLoofah error", xhr.status, thrownError);
                loofahTest=true
                accessDenied();
            }
        });

        function processLoofahCheck(Data) {
            if (!Data || !Data.products) {
                loofahTest=true;
                accessDenied();
                return;
            }
            var loofahItems = 0;
            $.each(Data.products, function(key, val) {
                if (cartProducts.productsId.indexOf(val.id)>=0) loofahItems++;

            });
            if (cartProducts.nbItems == loofahItems) {
                $('a.btnmain[href*="ContinueCart"]').attr('href', 'javascript:notOnlyLoofah(' + wbId + ');');
            }
            loofahTest=true;
            accessDenied();
        }
    }

    
    /*******************Produit offert****************/

    function checkGwp (freeProductsCat, cartProducts, threshold) {

        if (!freeProductsCat || !cartProducts) {
                presentTest=true;
                accessDenied();
                return;
        }

        $.ajax({
            url : 'ws/wsGetProducts.asp?CatID=' + freeProductsCat,
            cache: false,
            dataType:'json',
            success: function(productData) {
                parseFreeProducts (productData);
            },
            error:function (xhr, ajaxOptions, thrownError){
                if (window.console) console.log ("checkGwp error", xhr.status, thrownError);
                errorFctn();
            }
        });

        //création des requetes
        function parseFreeProducts (productData) {
            if (!productData || !productData.products) {
                errorFctn();
                return;
            }

             var multiAjax = [];

            $.each(productData.products, function(key, val) {

             eval ('var getTmpl'+val.id+' = new webServiceQuery();');
             eval ('getTmpl'+val.id+'.fonctionError = errorFctn;');
             eval ("getTmpl"+val.id+".addParams = [val.id, val.description];");
             eval ("getTmpl"+val.id+".fonction = processGwpCheck ;");
             eval ("getTmpl"+val.id+".url = 'ws/wsGetRelatedProducts.asp?PdtID="+val.id+"&RelType=2';");
             eval("var query = new Json(getTmpl"+val.id+");");
             multiAjax.push(query);
            });


            //execution groupée des requetes
            var doQuery = new startQuery(multiAjax);
                doQuery.onDone(errorFctn);
                doQuery.process();

           //si erreur afficher tout de même le contenu du panier
           function errorFctn() {
                presentTest=true;
                accessDenied();
            }

            //masquer la en attendant que le recharmen de la page s'effectue
            function dontShow() {
                $('.view').hide();
            }

            function processGwpCheck(Data, more) {
                testproduct = more[0];
                description = more[1];
                var nbItems = 0,
                testItem,
                currentPresent = parseInt(cartProducts.productsId.indexOf(testproduct));

                if (!Data || !Data.upsell) return;

                $.each(Data.upsell, function(key, val) {
                    testItem = cartProducts.productsId.indexOf(val.id);
                    if (testItem>=0) nbItems=parseInt(cartProducts.productsQtity[testItem])+nbItems;

                });

                //Ajouter l'article cadeau
                if (nbItems >= threshold && currentPresent<1) {
                    var url = '/PBShoppingCart.asp?ItemID='+testproduct;
                    dontShow();
                    window.location.replace(url);
                    return;
                }

                //suprimer article cadeau
                if (nbItems < threshold && currentPresent>=0) {
                    dontShow();
                    DelCartItem(currentPresent);
                    return;
                }
             
                var presentQtity = cartProducts.productsQtity[currentPresent];

                //mettre à jour le stock de l'article cadeau
                if (presentQtity>1)  {
                    dontShow();
                    UpdateQty( currentPresent, 1-presentQtity );
                    return;
                }

                //Afficher message
                if (nbItems > 0 && nbItems < threshold) {                   
                    $('.sectiontbarea').eq(0).append('<div>'+description+'</div>');
                }
                
            }
        }
    }

    //Afficher le contenu de la page une fois les requetes ajax effectuées
    function accessDenied () {
        if (presentTest && loofahTest) $('.viewtbl').show();
    }

}
// Message si seulement Loofah
    function notOnlyLoofah (wbId) {
        if (!wbId) return;

        var shopcartcontainer = addHTMLStructure ();
        $.ajax({
            url: 'ws/wsGetWebBlock.asp?WBID='+wbId,
            cache: true,
            dataType:'json',
            success: function(Data) {
                showMessage (Data);
            }
        });

        function showMessage (Data) {
            if (!Data)   return;

            var htmlModel=Data.htmlContent;

            htmlModel = replaceFromTemplate (htmlModel, 'http:\\/\\/#RETURN#', 'javascript:returnToSite();');

            if (!htmlModel) {
                returnToSite();
            }
            shopcartcontainer.html(htmlModel);

        }
    }



/*********Ajout de la classe scorderform à la page d'identification (Step2 sur toutes les pages du tunnel)************/
function addClassToUserLogin () {

if (!OxPageName) return;
if (OxPageName == "Identification") $('#maincontainer').addClass('scorderform');

}

/**********Pas de retour à la racine de catalogue***********/
function noRootCart (textCrumb) {
    if ( (OxCompName == "SCCatalog" && !OxCatID1 && !OxCatID2 && !OxCatID3) || ($('dontshow').length) ) {
        $('.sectiondata, .sectiontb').remove();
        window.location.replace("/");
    }

    $('.sccatalog #catbclevel0 a.PBBtnStd').html(textCrumb);
}

/*****facebook /Twitter***********/

function addSocialNetwork () {
    var zone = $('.itemdetail #btnaddtofav');
    if (!zone.length) return;

    var uriCourant = document.location.href,
        reg= new RegExp ("(http://[^/]*)/", "g"),
        url = reg.exec(uriCourant);

    var facebookHTML = '<div class="addthis_toolbox addthis_default_style">'
                     + '<a class="addthis_button_facebook" addthis:url="' + url[1] + OxPdtUrl + '" addthis:title="+'+OxPdtName+'" Title="Partager avec Facebook" ></a>'
                     + '<a class="addthis_button_twitter" addthis:url="' + url[1] + OxPdtUrl + '" addthis:title="'+OxPdtName+'" title="Partager avec Twitter"></a>'
                     + '<a class="addthis_button_google_plusone"  addthis:url="' + url[1] + OxPdtUrl + '" Title="Google+1" ></a>'
                     + '</div>';
    zone.replaceWith(facebookHTML);

    var po = document.createElement('script');
    po.type = 'text/javascript';
    po.src = 'http://s7.addthis.com/js/250/addthis_widget.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);


}


//Mise en forme article complémentaire

 function crossSalesManager () {
    //mise en forme vente suggestives
    var relatedPdts = $('.PBUpsellTable');
    if (!relatedPdts.length) return;

    $('td', relatedPdts).css('border', 'none');

    // récupération des élemetns du webBlock
    $(' .PBLayoutTable', relatedPdts).each(function () {
        var thisElement = $('td', this),
            htmlData = '<div class="upSaleTitle" >' + thisElement.eq(1).html() + '</div>' +
                       '<div class="upSaleImg" >' + thisElement.eq(0).html() + '</div>';

         $(this).replaceWith('<div class="PBLayoutTable">'+htmlData+'</div>');
    });

     $('.PBLayoutTable').css('textAlign', 'center');
 }

/* injection animation flash 1*/

function animFlash1(){
document.write("<object type=\"application\/x-shockwave-flash\" height=\"94\" width=\"200\" data=\"Files\/48298\/1123492584275.swf\">");
document.write("<param name=\"wmode\" value=\"opaque\" \/>");
document.write("<param name=\"movie\" value=\"Files\/48298\/1123492584275.swf\" \/>");
document.write("<\/object>");
}

