/***************************Panier dynamique V3*******************************/


function dynamicCart () {}
dynamicCart.prototype.smallCartTmpl=null;
dynamicCart.prototype.cookieSaving=true;
dynamicCart.prototype.countryType="FR" // "UK"
dynamicCart.prototype.cartTemplateCookie=null;
dynamicCart.prototype.showCartContainerId = 'showCartContainer';
dynamicCart.prototype.mainTblSmallCart = '#dynamicCart';
dynamicCart.prototype.oldCartButton = '#btnviewcart span';
dynamicCart.prototype.oldCartButtonExpRegModel = new RegExp('Votre\\s*?Panier(\\s*?:\\s*?\\<small\\>\\d*?\\s*?article\\(s\\)\\<\\/small\\>)',"gi");
dynamicCart.prototype.defaultImg = "Files/15269/addToCart/no-product.png";
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.mainTblSmallCart).length) {
        if (window.console) console.log ('Error : container ' + this.mainTblSmallCart + ' is not in the page');
        return;
    }

    var shopCart=null,
        me= this;

    $.ajaxSetup({
        cache: false
    });

    $.getJSON('PBShoppingCart.asp?AjaxMode=1&'+strURLParams, function(data) {
        shopCart=data;
        showCart ();
    });

   function moveToCart (origin, url) {
        this.origin=origin;
        this.url=(!url)? null : url;
    }

    moveToCart.prototype.moveInCart= function () {

        var domOrigin = $(this.origin),
            domTarget = $(me.mainTblSmallCart),
            height = 100,
            width=100,
            isImage;

        // récupération image
        if (this.url) {
            isImage = this.url;
        } else {
            // récupr src
            isImage = domOrigin.attr('src');
            height = domOrigin.outerHeight();
            width = domOrigin.outerWidth();
        }

        // si pas de src, on pcherche une eventuelle bg-image
        if (!isImage) {
            var pattern = /url\(|\)|"|'/g,
            getUrl = domOrigin.css('backgroundImage');
            if (getUrl) {
                isImage= getUrl.replace(pattern,"");
                height = domOrigin.outerHeight();
                width = domOrigin.outerWidth();
            }
        }

        if (height<1) height = 1;
        var coef= width/height;
        
        if (!domOrigin.length || !domTarget.length || !isImage || isImage=="none")  return false;

        var offsetOrigin=domOrigin.offset(),
        offsetTarget=domTarget.offset();

        $('<img/>', {
            'src':isImage
        }).prependTo('body').css ({
            'z-index':3000,
            'position':'absolute',
            'top':offsetOrigin.top,
            'left':offsetOrigin.left,
            'height':height,
            'width': Math.ceil(height*coef)
        }).animate ({
            'height':domTarget.outerHeight(),
            'width': Math.ceil(domTarget.outerHeight()*coef),
            'top':offsetTarget.top,
            'left':offsetTarget.left+(Math.round(domTarget.outerWidth()/2))
        }, 1500).animate ({
            'opacity':0
        }, 500, function(){
            me.showSmallCart ();
            $(this).remove();
        });

        return true;
    }

    function showCart () {

           var isThereImages = false;

        function spotImage (referer, element, only, defaultZone) {
            /* referer : la zone du produit
               element : l'image du produit - null ou classe à trouver
               only : ne doit pas s'appliquer si une image a déjà été trouvée - true ou false
               defaultZone : point de référence si le produit n'a pas d'image
               defaultImage : Url image de rempalcement
            */
            if (isThereImages && only) return;

            var localObject = "$(this)";
            if (element) localObject += ".find('"+element+"')";
            localObject +=".eq(0)";

            referer.each(function () {
                var imgRelated = new moveToCart(eval(localObject));

            if (imgRelated.moveInCart()) {
                isThereImages=true ;
            } else {
                localObject = "$(this).find('"+defaultZone+"').eq(0)";
                var btnRelated = new moveToCart(eval(localObject), me.defaultImg);

                if (btnRelated.moveInCart()) {
                    isThereImages=true ;
                }

            }
            });

        }


        //image pincipale vue detail
        spotImage ($('.sectiondataarea').has('.itemdetail a.btnaddtocart[href*="AddToCart('+nProductID+'"]'), '.imgmain', true, '.btnmain');
        //images des articels cochés dans les ventes suggestives
        spotImage ($('.PBRelPdtTable table.PBLayoutTable').has('input[type=checkbox]:checked'), 'img', false, 'input[type=checkbox]');
        // image produit vue liste
        spotImage ($('.oxcell').has('a[href*="AddToCart('+nProductID+'"]'), 'img.imgthumbnail', true, '.btnaddtocart');
        // image produit vue liste
        spotImage ($('.PBOptImgTable td').has('a.btnoptaddtocart[href*="AddToCart('+nProductID+'"]'), '.PBOptImg img', true, '.PBOptBtn');

        // no image

        if (!isThereImages) {
                          me.showSmallCart ();
        }
    }

}

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.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();
}

// Gestion des cookies

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

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

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;
}
