
/***************************Panier dynamique V 2.2 *******************************/
// Need JQuery V 1.6.1 min.

/************************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;
    }
    
function dynamicCart () {}
dynamicCart.prototype.smallCartTmpl=null;
dynamicCart.prototype.popupCartTmpl=null;
dynamicCart.prototype.cookieSaving=true;
dynamicCart.prototype.countryType="FR" // "UK"
dynamicCart.prototype.cartTemplateCookie=null;
dynamicCart.prototype.returnCartMainId = 'shopcartreturn';
dynamicCart.prototype.returnCartBodyId = 'shopcartbody';
dynamicCart.prototype.returnCartContainerId = 'shopcartcontainer';
dynamicCart.prototype.returnCartPreloadId = 'shopcartpreload';
dynamicCart.prototype.showCartContainerId = 'showCartContainer';
dynamicCart.prototype.returnButton = '#returnShopping';
dynamicCart.prototype.oldCartButton = '#btnviewcart span';
dynamicCart.prototype.oldCartButtonExpRegModel = new RegExp('Votre\\s*?Panier(\\s*?:\\s*?\\<small\\>\\d*?\\s*?article\\(s\\)\\<\\/small\\>)',"gi");
dynamicCart.prototype.activate=  function (nProductID, strURLParams) {

    if (typeof jQuery == 'undefined') {
         if (window.console) console.log ('Error : Jquery must be activated');
        return;
    }
    
    if (!this.smallCartTmpl) {
        if (window.console) console.log ('Error : no smallCartTmpl ID');
        return;
    }

    if (!this.popupCartTmpl) {
        if (window.console) console.log ('Error : no popupCartTmpl ID');
        return;
    }

    var me=this,
        shopcartcontainer = this.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.popupCartTmpl;
    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) {
            if (window.console) console.log ('Error : Can\'t send Items in Cart');
            me.returnToSite();
            return;
        }
                
        if (!getTmpl.answer || getTmpl.answer.error) {
            if (window.console) console.log ('Error : Wrong popupCartTmpl ID');
            me.returnToSite();
            return;
        }

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

        me.showSmallCart ();
        htmlModel = me.replaceFromTemplate (htmlModel, '#ADDEDITEMS#', itemsCount, true );
        htmlModel = me.replaceFromTemplate (htmlModel, '#TOTALITEMS#', totalItemsCount, true );
        htmlModel = me.replaceFromTemplate (htmlModel, '#CARTAMOUNT#', totalAmount);
        shopcartcontainer.html(htmlModel);

        //clic sur bouton continuer
        $(me.returnButton).attr('href','#');
        $(me.returnButton).bind('click', function () {
            me.returnToSite();
        });
    } 
}

// Gestion des cookies
dynamicCart.prototype.getCookie = function(sName) {
    var oRegex = new RegExp("(?:; )?" + sName + "=([^;]*);?");

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

dynamicCart.prototype.setCookie = function (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=/";
}


// Conversion des prix
dynamicCart.prototype.convertToPrixe = function (price, coef) {
    if (!coef) coef=1;
    var decimal= (!this.countryType || this.countryType!="UK")? ',' : '\\.',
        amount = parseFloat(price)/coef;

    amount = amount.toString();
    amount =  (decimal==',')?  amount.replace('.', ',') : amount;

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

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


// Création structure HTML
dynamicCart.prototype.addHTMLStructure = function () {
    var testCartArea= $('#'+this.returnCartMainId);

    if (testCartArea.length<1) {
        $('body').eq(0).prepend('<div id="'+this.returnCartMainId+'"><div id="'+this.returnCartBodyId+'"></div><div id="'+this.returnCartContainerId+'"></div></div>');
    }
    $('#'+this.returnCartBodyId).css('height',$(document).height());

    var shopcartcontainer=$('#'+this.returnCartContainerId);
    $('#'+this.returnCartMainId).show();

    shopcartcontainer.append('<div id="'+this.returnCartPreloadId+'"></div>').css('top',$(window).scrollTop());
    return shopcartcontainer;
}

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

    if (typeof jQuery == 'undefined') {
         if (window.console) console.log ('Error : Jquery must be activated');
        return;
    }

    if (!this.smallCartTmpl)  {
        if (window.console) console.log ('Error : no smallCartTmpl ID');
        return;
    }

    if (this.cookieSaving) {
        this.cartTemplateCookie = this.getCookie('cartTemplateCookie');
    }

    var me=this;
    if (!this.cartTemplateCookie) {
        $.ajax({
            url: 'ws/wsGetWebBlock.asp?WBID='+this.smallCartTmpl,
            cache: true,
            dataType:'json',
            success: function(data) {
                if (!data.htmlContent || data.htmlContent.error) {
                    if (window.console) console.log ('Error : Wrong smallCartTmpl ID');
                    me.returnToSite();
                    return;
                }
                me.cartTemplateCookie = data.htmlContent ;
                me.setCartCookie ();
            }
        });
    } else {
        this.showCartInDocument ();
    }

}

dynamicCart.prototype.setCartCookie = function  () {
    if (!this.cartTemplateCookie) return;

    if (this.cookieSaving) {
        this.setCookie ('cartTemplateCookie', this.cartTemplateCookie);
    }
    this.showCartInDocument ();
}

dynamicCart.prototype.showCartInDocument = function () {

    //suppresions du nb d'articles dans l'ancien bouton
    var oldBuyButton = $(this.oldCartButton);
    if (oldBuyButton.length) {
        var htmlContent = oldBuyButton.html(),
            doResult=this.oldCartButtonExpRegModel.exec(htmlContent);
        if (doResult && doResult.length>0) {
            oldBuyButton.html(htmlContent.replace(doResult[1], ''));
        }
    }

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

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

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

}

/******************gestionnaire de template*************************/
dynamicCart.prototype.replaceFromTemplate = function (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,
            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;
}

// bouton continuer
dynamicCart.prototype.returnToSite = function () {
    $('#'+this.returnCartMainId).hide();
}
