
function d9jsCart() 
{
    this.Init = function() {
    
    }
    this.Name = ['D9JS_ProductIDCookie', 'D9JS_ProductNumCookie'];  //保存的Cookie名称 ProductID:对应的商品ID，ProductNum:购买的数量
    
    this.TimeCookie = function(T) {      //设置保存Cookie有效时间 T为小时，T为空时默认为10天
        var cookieDate = new Date();
        if (!isNaN(T))
            cookieDate.setTime(cookieDate.getTime() + T * 60 * 60 * 1000);
        else
            cookieDate.setTime(cookieDate.getTime() + 10 * 24 * 60 * 60 * 1000);
        return cookieDate.toGMTString();
    }
    this.Get = function(name) {      //取得cookie的值
        //        var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
        //        return arr ? unescape(arr[2]) : null;
        var arg = name + "=";
        var alen = arg.length;
        var clen = document.cookie.length;
        var i = 0;
        var j = 0;
        while (i < clen) {
            j = i + alen;
            if (document.cookie.substring(i, j) == arg)
                return this.getCookieVal(j);
            i = document.cookie.indexOf(" ", i) + 1;
            if (i == 0)
                break;
        }
        return null;

    }
    this.Set = function(name, val, t) {     //设置cookie
    //        document.cookie = name + '=' + val + ';expires=' + this.TimeCookie(t); //设置时间
    //        //document.cookie=name+'='+val+';expires='+this.TimeCookie(10); //设置有效期为10小时
        //        document.cookie = 'path=/;';        //保存的路径
        var argv = arguments;
        var argc = arguments.length;
        var expires = (argc > 2) ? argv[2] : this.TimeCookie();
        var path = (argc > 3) ? argv[3] : '/';
        var domain = (argc > 4) ? argv[4] : null;
        var secure = (argc > 5) ? argv[5] : false;
        document.cookie = name + "=" + escape(val) +
           ((expires == null) ? "" : ("; expires=" + expires)) +
           ((path == null) ? "" : ("; path=" + path)) +
           ((domain == null) ? "" : ("; domain=" + domain)) +
           ((secure == true) ? "; secure" : "");

    }
    this.getCookieVal = function(offset) {
        var endstr = document.cookie.indexOf(";", offset);
        if (endstr == -1) {
            endstr = document.cookie.length;
        }
        return unescape(document.cookie.substring(offset, endstr));
    }
    this.$ = function(id) {       //获取页面元素
        try {
            if (document.getElementById(id) == null) {
                //throw('对象‘'+id+'’不存在！');
                //alert('对象‘'+id+'’不存在！');
                return false;
            }
            return document.getElementById(id);
        } catch (e) {
            alert(e.description);
            return false;
        }
    }
    this.isNum = function(val) {     //判断是否数字
        if (isNaN(val)) return (1);
        if (val == '') return (1);
        return val;
    }
    this.Add = function(Id, Num) {      //添加商品
        var a;
        if (Id == '' || isNaN(Id)) {
            alert('ID错误！');
            return false;
        }
        //var Num = !this.$('num'+Id)?1:this.isNum(this.$('num'+Id).value);
        var ProductIds = this.Get(this.Name[0]);
        var ProductNums = this.Get(this.Name[1]);
        if (ProductIds == null || ProductIds == '') {
            ProductIds = Id;
            ProductNums = Num;
            a = 1;
        } else {

            var Ids = ProductIds.split(',');
            var Nums = ProductNums.split(',');
            var isFound = false;
            for (var i = 0; i < Ids.length; i++) {
                if (Ids[i] == Id) {
                    if (parseInt(Nums[i], 10) <= 0)
                        Nums[i] = Num;
                    else//如果存在，则对已有的产品进行累加
                    {
                        var mynum = "";
                        mynum = mynum + Num;
                        if (mynum.indexOf(".") >= 0 || Nums[i].indexOf(".") >= 0)
                            Nums[i] = parseFloat(Nums[i]) + parseFloat(Num);
                        else
                            Nums[i] = parseInt(Nums[i], 10) + parseInt(Num, 10);
                    }
                    isFound = true;
                }
            }
            a = 2;
            if (isFound) {
                ProductIds = Ids.join(',');
                ProductNums = Nums.join(',');
            } else {
                ProductIds = ProductIds + ',' + Id;
                ProductNums = ProductNums + ',' + Num;
            }
        }
        //alert(ProductIds+'\n'+ProductNums+'\n'+a);
        this.Set(this.Name[0], ProductIds);
        this.Set(this.Name[1], ProductNums);
        //alert('商品已经加入购物车！');
        return true;
    }
    this.Update = function(Id, Num) {      //更新商品，如果不存在则添加商品
        var a;
        if (Id == '' || isNaN(Id)) {
            alert('ID错误！');
            return false;
        }
        //var Num = !this.$('num'+Id)?1:this.isNum(this.$('num'+Id).value);
        var ProductIds = this.Get(this.Name[0]);
        var ProductNums = this.Get(this.Name[1]);
        if (ProductIds == null || ProductIds == '') {
            ProductIds = Id;
            ProductNums = Num;
            a = 1;
        } else {

            var Ids = ProductIds.split(',');
            var Nums = ProductNums.split(',');
            var isFound = false;
            for (var i = 0; i < Ids.length; i++) {
                if (Ids[i] == Id) {
                    Nums[i] = Num;
                    isFound = true;
                }
            }
            a = 2;
            if (isFound) {
                ProductIds = Ids.join(',');
                ProductNums = Nums.join(',');
            } else {
                ProductIds = ProductIds + ',' + Id;
                ProductNums = ProductNums + ',' + Num;
            }
        }

        this.Set(this.Name[0], ProductIds);
        this.Set(this.Name[1], ProductNums);

        return true;
    }
    this.Subtract = function(Id, Num) {      //减少商品数量
        if (Id == "" || isNaN(Id)) {
            alert("ID错误！");
            return false;
        }
        var ProductIds = this.Get(this.Name[0]);
        var ProductNums = this.Get(this.Name[1]);
        if (ProductIds == null || ProductIds == '') {
            alert("没有可以删除的记录");
            return false;
        }

        var Ids = ProductIds.split(',');
        var Nums = ProductNums.split(',');
        ProductIds = new Array;
        ProductNums = new Array;
        var isFound = false;
        for (var i = 0, a = 0; i < Ids.length; i++) {
            if (Id != Ids[i]) {
                ProductIds[a] = Ids[i];
                ProductNums[a] = Nums[i];
                a++;
            } else {
                var iRet = Nums[i] - Num;
                if (iRet > 0) {
                    ProductIds[a] = Ids[i];
                    ProductNums[a] = iRet;
                    a++;
                }
                isFound = true;
            }
        }
        if (isFound) {
            if (ProductIds[0] == undefined) {
                this.Clear();
            } else {
                this.Set(this.Name[0], ProductIds.join(','));
                this.Set(this.Name[1], ProductNums.join(','));
            }
        }
    }
    this.Del = function(Id) {      //删除商品
        if (Id == '' || isNaN(Id)) {
            alert("ID错误！");
            return false;
        }
        var ProductIds = this.Get(this.Name[0]);
        var ProductNums = this.Get(this.Name[1]);

        if (ProductIds == null || ProductIds == '') {
            alert("没有可删除的记录。");
            return false;
        }
        var Ids = ProductIds.split(',');
        var Nums = ProductNums.split(',');
        ProductIds = new Array; ProductNums = new Array;
        var isFound = false;
        for (var i = 0, a = 0; i < Ids.length; i++) {
            if (Id != Ids[i]) {
                ProductIds[a] = Ids[i];
                ProductNums[a] = Nums[i];
                a++;
            } else { isFound = true; }
        }
        if (isFound) {
            if (ProductIds[0] == undefined) {
                this.Clear();
            } else {
                this.Set(this.Name[0], ProductIds.join(','));
                this.Set(this.Name[1], ProductNums.join(','));
            }
        }
    }
    this.Count = function() {      //添加商品

        var ProductIds = this.Get(this.Name[0]);
        if (ProductIds == null)
            return 0;
        var Ids = ProductIds.split(',');
        return Ids.length;
    }
    this.Clear = function() {      //清除所有商品

        this.clearName(this.Name[0]);
        this.clearName(this.Name[1]);
        //    this.Set(this.Name[0], '', exp);
        //        this.Set(this.Name[1], '',exp);
    }
    this.clearName = function(name) {
        if (this.Get(name)) {
            var expdate = new Date();
            expdate.setTime(expdate.getTime() - (86400 * 1000 * 1));
            this.Set(name, "", expdate.toGMTString());
        }
    }

}

var Cart = new d9jsCart();


function show_cart_layer(obj, layerID) {
    var layer = document.getElementById(layerID);
    layer.style.display = "block";
}

function hide_cart_layer(obj, layerID) {
    var layer = document.getElementById(layerID);
    layer.style.display = "none";
}

function addtomycart(productid, obj) {

    Cart.Add(productid, 1);
    show_carthint(obj);

}

function addtomycart2(productid,quantity, obj) {

    Cart.Add(productid, quantity);
    show_carthint(obj);

}

function hide_carthint() {
    var div_addcart = document.getElementById("div_addcart");
    div_addcart.style.display = "none";
}

function clear_cart() {
    Cart.Clear();
}

function show_carthint(obj) {
    get_total_price();
    $("#span_productcount").text(Cart.Count());
    var div_addcart = $("#div_addcart");
    var p = getPosition(obj);
    div_addcart.css("left", p.x - 120);
    div_addcart.css("top", p.y - 50);
    div_addcart.css("display", "block");
}
var getPosition = function(el) {
    var ua = navigator.userAgent.toLowerCase();

    var isOpera = (ua.indexOf('opera') != -1);
    var isGecko = (ua.indexOf('gecko') != -1);
    var isIE = (ua.indexOf('msie') != -1 && !isOpera); // not opera spoof 

    if (el.parentNode == null || el.style.display == 'none') {
        return false;
    }

    var parent = null;
    var pos = [];
    var box;

    if (isIE && el.getBoundingClientRect)    //IE
    {
        box = el.getBoundingClientRect();
        var scrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
        var scrollLeft = Math.max(document.documentElement.scrollLeft, document.body.scrollLeft);

        return { x: box.left + scrollLeft, y: box.top + scrollTop };
    }
    else if (isGecko && document.getBoxObjectFor)    // gecko
    {
        box = document.getBoxObjectFor(el);

        var borderLeft = (el.style.borderLeftWidth) ? parseInt(el.style.borderLeftWidth) : 0;
        var borderTop = (el.style.borderTopWidth) ? parseInt(el.style.borderTopWidth) : 0;

        pos = [box.x - borderLeft, box.y - borderTop];
    }
    else    // safari & opera
    {
        pos = [el.offsetLeft, el.offsetTop];
        parent = el.offsetParent;
        if (parent != el) {
            while (parent) {
                pos[0] += parent.offsetLeft;
                pos[1] += parent.offsetTop;
                parent = parent.offsetParent;
            }
        }
        if (ua.indexOf('opera') != -1
            || (ua.indexOf('safari') != -1 && el.style.position == 'absolute')) {
            pos[0] -= document.body.offsetLeft;
            pos[1] -= document.body.offsetTop;
        }
    }

    if (el.parentNode) { parent = el.parentNode; }
    else { parent = null; }

    while (parent && parent.tagName != 'BODY' && parent.tagName != 'HTML') { // account for any scrolled ancestors 
        pos[0] -= parent.scrollLeft;
        pos[1] -= parent.scrollTop;

        if (parent.parentNode) { parent = parent.parentNode; }
        else { parent = null; }
    }
    return { x: pos[0], y: pos[1] };
}

