﻿/*
* Mini Cart
*/

//var Dtimeout;
//var Dspeed;
var Dtimer = null;
var Dtimer2 = null;
var Mdisplay = false;
var hideDiv;
var Container;
var button;
var jqShowObj;
var offset;
var height;
var width;
var btnHeight;
var btnWidth;

function initDMenu(obj, showobj, Dtimeout, Dspeed) {
    //	Dtimeout=Dtimeout?Dtimeout:300;
    //	Dspeed=Dspeed?Dspeed:100;
    hideDiv = $("<div style='z-index:10000;'></div>");
    Container = $("<div id=\"Container\"></div>");
    hideDiv.append(Container);
    button = $(obj);
    jqShowObj = $(showobj);
    offset = button.offset();
    height = jqShowObj.height(); 
    width = jqShowObj.width();
    btnHeight = button.height();
    btnWidth = button.width();
    $(document.body).prepend(hideDiv);
}
function showDMenu() {
    if (Mdisplay == true) {
        return false;
    } else {
    Mdisplay = true;
    Container.css({ margin: "0 auto", width: btnWidth + "px", height: btnHeight + "px" }).show();        
    hideDiv.css({ position: "absolute", top: offset.top + 16 + "px", left: button.offset().left - 125 + "px", height: height + "px", width: width + "px" }).show();
        Container.css({ border: "1px solid #666666" });
        Container.animate({ marginTop: 10, height: height + 4, width: width + 4, opacity: '100' }, 100, function() {
            jqShowObj.show();
            Container.append(jqShowObj);
            Container.css({ border: "0px" });
            jqShowObj.mouseover(function() {
                clearTimeout(Dtimer); clearTimeout(Dtimer2);
            }).mouseout(function() {
                hideDMenu();
            });
        });
    }
}
function hideDMenu() {
    clearTimeout(Dtimer);
    clearTimeout(Dtimer2);
    Dtimer = setTimeout(function() {
        Container.css({ border: "1px solid #666666" });
        $(document.body).prepend(jqShowObj);
        jqShowObj.hide();
        Container.empty();
        Container.animate({ width: btnWidth, height: btnHeight, marginTop: '0', opacity: '0' }, 100, function() {
            Container.hide();
            hideDiv.hide();
            Mdisplay = false;
        });
    }, 100);
}

$(function() {
    var miniCartServiceUrl = "Handler/ShopCartHandler.ashx?func=GetMiniCart";

    refreshMiniCart();

    function refreshMiniCart() { $.MiniCart({ dowhat: 'load' }); };

    $(function() {

        initDMenu("#CartSwitch_wrap", "#MyCart");

        $("#CartSwitch_wrap").mouseover(function() {
            clearTimeout(Dtimer);
            height = $("#MyCart").height() + 100;
            Dtimer = setTimeout("showDMenu()", 100);
        }).bind("mouseleave", function() {
            clearTimeout(Dtimer);
            if (Mdisplay == true) {
                Dtimer2 = setTimeout("hideDMenu()", 100);
            }
        });
    })

    $("#MyCart .MyCart_List a[id][name]").livequery(
			"click",
			function() {
			    var cartId = parseInt($(this).attr("id"));
			    var cartType = $(this).attr("name");
			    if (cartId > 0 && cartType != "") {
			        $.getJSON(
						miniCartServiceUrl,
						{
						    method: cartType,
						    cartId: cartId
						},
						function(result) {
						    if (result.Result) {
						        refreshMiniCart();
						    }
						});
			    }
			});

});




$.MiniCart = function(config) {
    config = $.extend(
			{
			    handler: "../Handler/ProductHandler.ashx",
			    catNo: null,
			    country: null,
			    dowhat: null,
			    incNum: 0,
			    from: null, //from which page
			    isFree: -1, //>0 is free sample
			    callback: null,
			    refresh: false
			},
			config || {});

    if (config.refresh) {
        $.cookie('ptg_mini_cart_list', null, SYSTEM_CONFIG.CookieOpt);
        //alert($.cookie('ptg_mini_cart_list'));
        return;
    }

    var priceAttr = { catNo: config.catNo, name: null, country: null, price: null, currency: null, shipfee: null, size: null, num: 0, t: -1 };

    //loading
    setLoading(true);
    switch (config.dowhat) {
        case "add":
            Add2Cart();
            break;
        case "del":
            Del4Cart();
            break;
        case "check":
            CheckOut();
            break;
        case "load":
            LoadCart();
            break;
        default: break;
    }

    //bind check out event
    $('#lnkCheckOut,#lnkCheckOut2,#lnkCheckOut3').click(CheckOut);

    setLoading(false);

    //Add to Cart
    function Add2Cart() {
        //free
        if (config.isFree == 0) { alert("Sorry,understock!"); return; }

        if (config.incNum == 0) config.incNum = 1;

        //read price
        $.getJSON("../Handler/ProductHandler.ashx?r=" + Math.random(),
        { func: 'GetProductPrice', param: 'catNo=' + config.catNo + '|cName=' + config.country },
        function(res) {
            priceAttr.name = res.table[1].rows[0].ProductName;
            priceAttr.country = config.country;
            priceAttr.price = config.isFree >= 0 ? 0 : Math.ceil(res.table[2].rows.length > 0 ? res.table[2].rows[0].Price : 0);
            priceAttr.currency = res.table[0].rows[0].Currency;
            priceAttr.shipfee = res.table[0].rows[0].ShippingFee;
            priceAttr.size = res.table[1].rows[0].Size;
            priceAttr.t = res.table[1].rows[0].t;

            //exist
            if (hasInCookie(config.catNo)) {

                if (config.isFree >= 0) {
                    alert("Only one allowed!");
                    return;
                }

                //update cookie
                updateCookie(config.catNo, config.incNum);
                //update list
                UpdateCart(config.catNo);
            }
            //No exist
            else {
                priceAttr.num = 1;
                //insert a pro
                insertOne(priceAttr);
                //insert cookie
                insertCookie(priceAttr);
            }

            //discount
            priceAttr.discount = 0;

            //total
            setTotal();

            //goto
            if (config.from == 'pro')
                window.location = "ShoppingCart.aspx";

            setLoading(false);
        });
    }
    function insertOne(proObj, list) {
        if (!proObj || !proObj.catNo) return;
        if (!list) {
            list = $('#MyCart .MyCart_List');

            if (list.find('li').length <= 0) {
                list.find('.empty').replaceWith("<ul/>");
            }

            list = list.find('ul');
        }

        var str = new Array();
        str.push('<LI name="' + proObj.catNo + '"><DL>');
        str.push('<DD class="p_Name"><A href="#">' + proObj.catNo + '&nbsp;&nbsp; ' + proObj.name + '</A></DD>');
        str.push('<DD class="p_Price"><STRONG class="cur">' + ((!proObj.currency) ? '' : proObj.currency) + '</STRONG>');
        str.push('<STRONG class="prc">' + ((!proObj.price) ? '--' : parseFloat(proObj.price).format('#.00')) + '</STRONG>');
        str.push('<font size=3> × </font><STRONG class="num">' + proObj.num + '</STRONG>');
        str.push('<BR /><A name="' + proObj.catNo + '" href="javascript:void(0)" class="del">Delete</A></DD>');
        str.push('</DL></LI>');

        list.append(str.join(''));

        bindDelEvent(list, proObj.catNo);
    }
    function Del4Cart() {
        if (config.incNum == 0) config.incNum = -1;
        updateCookie(config.catNo, config.incNum);
        //update list
        UpdateCart(config.catNo);
        //total
        setTotal();
        //var li = $('#MyCart .MyCart_List').find('li[name="' + catNo + '"]').remove();

        setLoading(false);
    }
    function UpdateCart(catNo, num) {
        var findit = false;
        var li = $('#MyCart .MyCart_List').find('li[name="' + catNo + '"]');
        var cArr = $.cookie('ptg_mini_cart_list');
        if (cArr != null) {
            var itms = eval('[' + cArr + ']');
            $.each(itms, function(i, t) {
                if (t.catNo == catNo) {
                    if (t.num > 0)
                        li.find('.num').html(t.num);
                    else
                        li.remove();

                    findit = true;
                    return;
                }
            });
        }

        if (!findit)
            li.remove();
    }
    function LoadCart() {
        var list = $('#MyCart .MyCart_List');
        try {
            var cArr = $.cookie('ptg_mini_cart_list');
            if (cArr && cArr != 'null') {
                var itms = eval('[' + cArr + ']');

                if (itms.length > 0) {
                    if (list.find('li').length <= 0) {
                        list.find('.empty').replaceWith("<ul/>");
                    }
                    list = list.find('ul');
                }

                $.each(itms, function(i, t) {
                    if (t.num > 0)
                        insertOne(t, list);
                });

                //total
                setTotal();
            }
            else {
                $.cookie('ptg_mini_cart_list', null, SYSTEM_CONFIG.CookieOpt);
                list.find('ul').remove().prepend('<span class="empty">No items in cart!</span>');
            }
        }
        catch (ex) {
            $.cookie('ptg_mini_cart_list', null, SYSTEM_CONFIG.CookieOpt);
            alert("Data's format is wrong!\r\nYour shop cart will be empty");
            window.location = window.location;
        }
    }

    function CheckOut() {
        //del quotation id
        var cArr = $.cookie('ptg_mini_cart_list');
        if (cArr && cArr != 'null')
            $.cookie('ptg_order_quotation_id', null, SYSTEM_CONFIG.CookieOpt);

    }

    function setTotal() {
        var cArr = $.cookie('ptg_mini_cart_list');
        var tNum = 0;
        var tPrice = 0;
        if (cArr != null && cArr != 'null') {
            var itms = eval('[' + cArr + ']');
            $.each(itms, function(i, t) {
                tNum = tNum + parseInt(t.num);
                tPrice = tPrice + t.price * parseInt(t.num);
            });
        }
        else {
            $.cookie('ptg_mini_cart_list', null, SYSTEM_CONFIG.CookieOpt);
        }
        var cur = $.cookie('ptg_user_currency_selected');
        if (!cur) cur = "";

        var list = $('#MyCart .MyCart_List');
        if (tNum > 0) {
            $('#CartBarProductNum').text(tNum);
            list.find('.Account').replaceWith('<DIV class="Account"><STRONG>' + tNum + '</STRONG> Items,&nbsp;&nbsp;&nbsp;Total: <STRONG>' + cur + ((!tPrice) ? '0.00' : tPrice.format('#.00')) + '</STRONG></DIV>');
            list.find('.Account,.CartLog').show();
        }
        else {
            $('#CartBarProductNum').text(0);
            list.find('.Account,.CartLog').hide();
            list.find('ul').remove();
            if (!list.find('.empty'))
                list.prepend('<span class="empty">No items in cart!</span>');
        }

        if (config.callback)
            config.callback();
    }
    //About Cookie
    function hasInCookie(catNo) {
        var rtn = false;
        var cArr = $.cookie('ptg_mini_cart_list');
        if (cArr != 'null' && cArr != null) {
            var itms = eval('[' + cArr + ']');
            $.each(itms, function(i, t) {
                if (t.catNo == catNo) {
                    rtn = true;
                    return;
                }
            });
        }
        return rtn;
    }
    function insertCookie(proObj) {
        var cArr = $.cookie('ptg_mini_cart_list');
        if (cArr == null)
            cArr = new Array();
        else
            cArr = cArr.split(',');

        cArr[cArr.length] = $.toJSON(proObj);
        $.cookie('ptg_mini_cart_list', cArr.join(','), SYSTEM_CONFIG.CookieOpt);
    }
    function updateCookie(catNo, addNum) {
        var cArr = $.cookie('ptg_mini_cart_list');
        var jsStr = null;
        if (cArr != null) {
            var itms = eval('[' + cArr + ']');
            $.each(itms, function(i, t) {
                if (t.catNo == catNo) {
                    t.num = parseInt(t.num) + addNum;
                    if (t.num <= 0) {
                        t.num = 0;
                        jsStr = 'itms.splice(' + i + ', 1)';
                    }
                    return true;
                }

            });
            //Delete it
            eval(jsStr);
            //alert($.toJSON(itms).replace('[', "").replace(']', ""));
            $.cookie('ptg_mini_cart_list', $.toJSON(itms).replace('[', "").replace(']', ""), SYSTEM_CONFIG.CookieOpt);
        }
    }
    function deleteCookie(catNo) {
        var cArr = $.cookie('ptg_mini_cart_list');
        if (cArr != null) {
            var itms = eval('[' + cArr + ']');
            $.each(itms, function(i, t) {
                if (t.catNo == catNo) {
                    itms.splice(i, 1);
                    return true;
                }
            });
            //alert($.toJSON(itms).replace('[', "").replace(']', ""));
            $.cookie('ptg_mini_cart_list', $.toJSON(itms).replace('[', "").replace(']', ""), SYSTEM_CONFIG.CookieOpt);
        }
    }

    //Event
    function bindDelEvent(obj, catNo) {
        obj.find('A[name="' + catNo + '"]').click(function() {
            //update cookie
            updateCookie($(this).attr('name'), -1);
            //update list
            UpdateCart($(this).attr('name'), -1);
            //total
            setTotal();
        });
    }

};