﻿//动态生成小购物车的HTML
function BindShopCart(shopCartInfo) {
    if (shopCartInfo == "" || shopCartInfo == null) {
        $("#ulShopCart").html("");
        var sumMoney = "<p><strong>Item(s):&nbsp;0</strong></p><p><strong>Total Price:&nbsp;￥<b>0</b>&nbsp;</strong><span style='margin-left:70px'>(US$0)</span></p>";
        $("#divCartSum").html(sumMoney);
    }
    else {
        var CommodityInfo = "";
        var SumInfo = new Array();
        SumInfo = shopCartInfo.split(';');
        var dtRows = new Array();
        dtRows = SumInfo[0].split('>');
        if (dtRows.length > 0) {
            for (i = 0; i < dtRows.length; i++) {
                var dtColumns = dtRows[i].split(',');
                var commodityId = dtColumns[0].split('|')[0];
                var productType = dtColumns[0].split('|')[1].split('=')[0];

                CommodityInfo += "<li id=liDel" + i + "><h4><a href='../Common/ProductPage.aspx?";
                if (productType == "1") {
                    CommodityInfo += "CommodityId=";
                }
                else if (productType == "2") {
                    CommodityInfo += "PointExchangeId=";
                }
                CommodityInfo += commodityId + "'>" + dtColumns[1] + "</a></h4><span><a>";
                CommodityInfo += "<img id='aaaa" + i + "' src='../images/cha.gif' longdesc='" + dtColumns[0] + "'/></a></span><label><b>";
                CommodityInfo += "￥" + dtColumns[2] + "</b>Qty&nbsp;&nbsp;<input type='text' value='" + dtColumns[3] + "' />&nbsp;&nbsp;&nbsp;￥" + Math.round(dtColumns[4], 0) + "</label></li>";

            }
            $("#ulShopCart").html(CommodityInfo);
            $("#ulShopCart img").each(function(i, domEle) {
                var dtColumns1 = dtRows[i].split(',');
                $(domEle).click(function() { RemoveCookieByCommodity(dtColumns1[0]); });
                $(domEle).mouseover(function() { this.src = '../images/cha_cu.gif'; })
                $(domEle).mouseout(function() { this.src = '../images/cha.gif'; })
            });
        }
        if (SumInfo.length > 1) {
            var sumMoney = "<p><strong>Item(s):&nbsp;" + SumInfo[1] + "</strong></p><p><strong>Total Price:&nbsp;￥<b>" + SumInfo[2] + "</b>&nbsp;</strong><span style='margin-left:70px'>(" + SumInfo[3] + ")</span></p>";
            $("#divCartSum").html(sumMoney);
        }
        else {
            $("#ulShopCart").html("");
            var sumMoney = "<p><strong>Item(s):&nbsp;0</strong></p><p><strong>Total Price:&nbsp;￥<b> 0 </b>&nbsp; </strong><span style='margin-left:70px'>(US$0) </span></p>";
            $("#divCartSum").html(sumMoney);
        }
    }
}

///Cookie
//根据Cookie来操作小购物车
function RemoveCookieByCommodity(commodityId) {
    if ($.cookie('Products') != null) {
        var allcookies = $.cookie('Products');
        var product = new Array();
        product = allcookies.split("&");
        var newcookies = "";
        for (i = 0; i < product.length; i++) {
            var productInfo = new Array();
            productInfo = product[i].split("=");
            if (productInfo[0] != commodityId) {
                newcookies += product[i] + "&";
            }
        }
        newcookies = newcookies.substring(0, newcookies.length - 1);
        if (newcookies == "") {
            $.cookie('Products', '', { expires: -1, path: '/' });
        }
        else {
            $.cookie('Products', newcookies, { expires: 7, path: '/' });
        }
        if ($.cookie('Products') == null) {
            BindShopCart("");
        }
        else {
            var commoditySum = eFruit_EN_SH.Js.AjaxProOperate.GetCommodityInfoByCookie($.cookie('Products')).value;
            if (commoditySum != "no") {
                BindShopCart(commoditySum);
            }
        }
    }
    else { BindShopCart(""); }
}
//添加商品到小购物车
function AddToShopCart(commodityId, type) {
    var allcookies = $.cookie('Products');
    var newcookies = "";
    if ($.cookie('Products') == null) {
        newcookies += commodityId + "|" + type + "=1";
        $.cookie('Products', newcookies, { expires: 7, path: '/' });
    }
    else {
        var product = new Array();
        product = allcookies.split("&");
        var flag = -1;
        for (i = 0; i < product.length; i++) {
            var productInfo = new Array();
            productInfo = product[i].split("|");
            if (productInfo[0] == commodityId) {
                flag = i;
                var num = parseInt(productInfo[1].split('=')[1]) + 1;
                product[i] = productInfo[0] + "|" + productInfo[1].split('=')[0] + "=" + num;
                newcookies += product[i] + "&";
            }
            else {
                newcookies += product[i] + "&";
            }
        }
        if (flag == -1) {
            newcookies += commodityId + "|" + type + "=1&";
        }
        newcookies = newcookies.substring(0, newcookies.length - 1);
        $.cookie('Products', newcookies, { expires: 7, path: '/' });
    }
    var commoditySum = eFruit_EN_SH.Js.AjaxProOperate.GetCommodityInfoByCookie($.cookie('Products')).value;
    if (commoditySum != "no") {
        BindShopCart(commoditySum);
    }
}

function AddToShopCartWithoutUpdate(commodityId, type, addnum) {
    var allcookies = $.cookie('Products');
    var newcookies = "";
    if ($.cookie('Products') == null) {
        newcookies += commodityId + "|" + type + "=1";
        $.cookie('Products', newcookies, { expires: 7, path: '/' });
    }
    else {
        var product = new Array();
        product = allcookies.split("&");
        var flag = -1;
        for (i = 0; i < product.length; i++) {
            var productInfo = new Array();
            productInfo = product[i].split("|");
            if (productInfo[0] == commodityId) {
                flag = i;
                var num = parseInt(productInfo[1].split('=')[1]) + parseInt(addnum);
                product[i] = productInfo[0] + "|" + productInfo[1].split('=')[0] + "=" + num;
                newcookies += product[i] + "&";
            }
            else {
                newcookies += product[i] + "&";
            }
        }
        if (flag == -1) {
            newcookies += commodityId + "|" + type + "=" + addnum + "&";
        }
        newcookies = newcookies.substring(0, newcookies.length - 1);
        $.cookie('Products', newcookies, { expires: 7, path: '/' });
        return true;
    }
    return false;
}

//清空小购物车
function ClearShopCart() {
    //    $.cookie('Products', null);
    $.cookie('Products', '', { expires: -1, path: '/' });
    BindShopCart("");
}

//更新小购物车
function UpdateShopCart() {
    var productNum = $("#ulShopCart li").length;
    var newcookies = "";
    for (i = 0; i < productNum; i++) {
        newcookies += $("#ulShopCart li:eq(" + i + ") img").attr("longdesc");
        var productCount = $("#ulShopCart li:eq(" + i + ") input").val();

        var patrn = /^[1-9]+[0-9]*]*$/;
        if (!patrn.test(productCount)) {
            alert("Please input a positive number in Qty.");
            return false;
        }
        newcookies += "=" + $("#ulShopCart li:eq(" + i + ") input").val() + "&";
    }
    newcookies = newcookies.substring(0, newcookies.length - 1);
    $.cookie('Products', newcookies, { expires: 7, path: '/' });
    var commoditySum = eFruit_EN_SH.Js.AjaxProOperate.GetCommodityInfoByCookie($.cookie('Products')).value;
    if (commoditySum != "no") {
        BindShopCart(commoditySum);
    }
}



//动态生成大购物车的HTML
function BindMyCart(myCartInfo) {
    if (myCartInfo == "" || myCartInfo == null) {
        $("#ulMyCart").html("");
        $("#myCartItemNum").html("0");
        $("#myCartRMBSum").html("0");
        $("#myCartUSSum").html("0");
    }
    else {
        var CommodityInfo = "";
        var SumInfo = new Array();
        SumInfo = myCartInfo.split(';');
        var dtRows = new Array();
        dtRows = SumInfo[0].split('>');
        if (dtRows.length > 0) {
            for (i = 0; i < dtRows.length; i++) {
                var dtColumns = dtRows[i].split(',');
                var commodityId = dtColumns[0].split('|')[0];
                var bigproductType = dtColumns[0].split('|')[1].split('=')[0];
                CommodityInfo += "<li><span class='wid_140' style='text-align: left;'><a href='../Common/ProductPage.aspx?";
                if (bigproductType == "1") {
                    CommodityInfo += "CommodityId=";
                }
                else if (bigproductType == "2") {
                    CommodityInfo += "PointExchangeId=";
                }
                CommodityInfo += commodityId + "'>";
                CommodityInfo += "<img id='imgPricture' longdesc='" + dtColumns[0] + "' src='../img/" + dtColumns[5] + "' width='98' height='74' /></a></span> <span class='wid_140'><br /><br />";
                CommodityInfo += "<strong>" + dtColumns[1] + "</strong></span> <span class='wid_140'><br /><br />￥" + dtColumns[2] + "<br />" + dtColumns[7] + "</span> <span class='wid_80'><br /><br />";
                CommodityInfo += "<input type='text' value='" + dtColumns[3] + "' /></span> <span class='wid_140'><br /><br />￥" + Math.round(dtColumns[4], 0) + "<br />";
                CommodityInfo += dtColumns[8] + "</span> <span class='wid_80'><br /><br /><a><img id='imgMyCart' src='../images/cha.gif'/></a></span>";
                if (dtColumns[6] != "none") {
                    CommodityInfo += "<div id='divReserve' class='cart_sorry' style='display:" + dtColumns[6] + "'>Sorry, this product is currently unavailable. <a href='../Common/ProductPage.aspx?CommodityId=" + commodityId + "'>Click here</a> to reserve  this product.</div> </li>";
                }
            }
            $("#ulMyCart").html(CommodityInfo);

            $("#ulMyCart").find("#imgMyCart").each(function(i, domEle) {
                var dtColumns1 = dtRows[i].split(',');
                $(domEle).click(function() { RemoveMyCartByCommodity(dtColumns1[0]); });
                $(domEle).mouseover(function() { this.src = '../images/cha_cu.gif'; })
                $(domEle).mouseout(function() { this.src = '../images/cha.gif'; })
            });
        }
        if (SumInfo.length > 1) {
            $("#myCartItemNum").html(SumInfo[1]);
            $("#myCartRMBSum").html("￥" + Math.round(SumInfo[2], 2));
            $("#myCartUSSum").html(SumInfo[3]);
        }
        else {
            $("#ulMyCart").html("");
            $("#myCartItemNum").html("0");
            $("#myCartRMBSum").html("0");
            $("#myCartUSSum").html("0");
        }
    }
}

//清空大购物车
function ClearMyCart() {
    //    $.cookie('Products', null);
    $.cookie('Products', '', { expires: -1, path: '/' });
    BindMyCart("");
}

//根据commodityId来移除相应商品
function RemoveMyCartByCommodity(commodityId) {
    if ($.cookie('Products') != null) {
        var allcookies = $.cookie('Products');
        var product = new Array();
        product = allcookies.split("&");
        var newcookies = "";
        for (i = 0; i < product.length; i++) {
            var productInfo = new Array();
            productInfo = product[i].split("=");
            if (productInfo[0] != commodityId) {
                newcookies += product[i] + "&";
            }
        }
        newcookies = newcookies.substring(0, newcookies.length - 1);
        if (newcookies == "") {
            $.cookie('Products', '', { expires: -1, path: '/' });
        }
        else {
            $.cookie('Products', newcookies, { expires: 7, path: '/' });
        }
        if ($.cookie('Products') == null) {
            BindMyCart("");
        }
        else {
            var commoditySum = eFruit_EN_SH.Js.AjaxProOperate.GetCommodityInfoByCookie($.cookie('Products')).value;
            if (commoditySum != "no") {
                BindMyCart(commoditySum);
            }
        }
    }
    else { BindMyCart(""); }
}

//更新大购物车
function UpdateMyCart() {
    var productNum = $("#ulMyCart li").length;
    var newcookies = "";
    for (i = 0; i < productNum; i++) {
        newcookies += $("#ulMyCart li:eq(" + i + ") #imgPricture").attr("longdesc");

        var productCount = $("#ulMyCart li:eq(" + i + ") input").val();
        var patrn = /^[1-9]+[0-9]*]*$/;
        if (!patrn.test(productCount)) {
            alert("Please input a positive number in Qty.");
            return false;
        }

        newcookies += "=" + $("#ulMyCart li:eq(" + i + ") input").val() + "&";
    }
    newcookies = newcookies.substring(0, newcookies.length - 1);
    $.cookie('Products', newcookies, { expires: 7, path: '/' });
    var commoditySum = eFruit_EN_SH.Js.AjaxProOperate.GetCommodityInfoByCookie($.cookie('Products')).value;
    if (commoditySum != "no") {
        BindMyCart(commoditySum);
    }
}

//根据用户加入预定商品
function AddBookByUserid(commodityId) {
    var result = eFruit_EN_SH.Js.AjaxProOperate.AddBookByUserid(commodityId).value;
    if (result) {
        alert('You have sucessfully reserved this item. Please see My Account to review My Reserved Items.');
    }
    else {
        alert('Sorry,Please try again!');
    }
}


//更新预定商品的数量
function UpdateBookQty(reservedId, controlName) {
    if (reservedId != "" && controlName != "") {
        var BookQty = $("#" + controlName).val();
        var patrn = /^[1-9]+[0-9]*]*$/;
        if (!patrn.test(BookQty)) {
            alert("Please input a positive number in Qty.");
            return false;
        }
        var result = eFruit_EN_SH.Js.AjaxProOperate.UpdateBookQty(reservedId, BookQty).value;
        if (result) {
            alert("save ok!");
            $("#" + controlName).val(BookQty);
        }
        else {
            alert("Sorry,Please try again!");
        }
    }
}

//MyReservedItems 多商品加入到购物车
function ReservedAddShopCart() {

    //判断是否有预定未上架商品
    var productNumR = $("#divReservedItem dl input[type=checkbox]").length;
    for (i = 0; i < productNumR; i++) {
        if ($("#divReservedItem dl input[type=checkbox]:eq(" + i + ")").attr('checked')) {
            alert("Sorry, this item is still on its way. We will notify you when it becomes available.");
            return false;
        }
    }

    var productNum = $("#divArrivedItem dl input[type=checkbox]").length;
    var commoditys = "";
    //更新购物车
    //    for (i = 0; i < productNum; i++) {
    //        if ($("#divArrivedItem dl input[type=checkbox]:eq(" + i + ")").attr('checked')) {
    //            var commodityId = $("#divArrivedItem dl input[type=checkbox]:eq(" + i + ")").val();
    //            commoditys += commodityId + ",";
    //            AddToShopCartWithoutUpdate(commodityId, "1", $("#lbAQty" + commodityId).html());
    //        }
    //    }//老的
    $("#divArrivedItem dl input[type=checkbox]").each(function(i, n) {
        if ($("#divArrivedItem dl input[type=checkbox]:eq(" + i + ")").attr('checked')) {
            var commodityId = $("#divArrivedItem dl input[type=checkbox]:eq(" + i + ")").val();
            commoditys += commodityId + ",";
            AddToShopCartWithoutUpdate(commodityId, "1", $("#lbAQty" + commodityId).html());
        }
    });

    if (commoditys != "") { commoditys = commoditys.substring(0, commoditys.length - 1); }
    //更新预定商品的状态
    if (commoditys != "") { eFruit_EN_SH.Js.AjaxProOperate.UpdateBookDisabledByCommodity(commoditys); }
    window.location.href = "../Shopping/MyCart.aspx";
}

//MyList_view.aspx
function MyListAddShopCart() {
    var productNum = $("#divListItem dl dd input[type=checkbox]").length;
    if (productNum == 0) {
        alert("Please add products to your list. ");
        return false;
    }
    var commoditys = "";
    var flag = 0;
    //更新购物车
    $("#divListItem dl input[type=checkbox]").each(function(i, n) {
        if ($("#divListItem dl input[type=checkbox]:eq(" + i + ")").attr('checked')) {
            var commodityId = $("#divListItem dl input[type=hidden]:eq(" + i + ")").val();
            AddToShopCartWithoutUpdate(commodityId, "1", "1");
            commoditys += commodityId + ",";
            flag++;
        }
    });
    if (flag == 0) {
        alert("Please choose a product.");
        return false;
    }
    if (commoditys != "") { commoditys = commoditys.substring(0, commoditys.length - 1); }
    window.location.href = "../Shopping/MyCart.aspx";
}

//MyReservedItems 多商品删除
function ReservedDelete() {
    var commoditys = "";

    //Arrived Item
    var productNum = $("#divArrivedItem dl input[type=checkbox]").length;
    for (i = 0; i < productNum; i++) {
        if ($("#divArrivedItem dl input[type=checkbox]:eq(" + i + ")").attr('checked')) {
            var commodityId = $("#divArrivedItem dl input[type=checkbox]:eq(" + i + ")").val();
            commoditys += commodityId + ",";
        }
    }
    //Reserved Item
    var productNumR = $("#divReservedItem dl input[type=checkbox]").length;
    for (i = 0; i < productNumR; i++) {
        if ($("#divReservedItem dl input[type=checkbox]:eq(" + i + ")").attr('checked')) {
            var commodityId2 = $("#divReservedItem dl input[type=checkbox]:eq(" + i + ")").val();
            commoditys += commodityId2 + ",";
        }
    }

    if (commoditys != "") { commoditys = commoditys.substring(0, commoditys.length - 1); }

    //删除预定商品
    if (commoditys != "") {
        eFruit_EN_SH.Js.AjaxProOperate.UpdateBookDisabledByCommodity(commoditys); alert("This item has been deleted from your reserved items.");
        window.location.href = "../MyAccounts/MyReservedItems.aspx";
    }
}

//检查小购物车是否为空
function CheckSmallShopCart(flag) {
    var productNum = $("#ulShopCart li").length;
    if (productNum < 1) {
        alert("Your cart is empty, please choose some products. ");
    }
    else {
        //判断是否登录
        if (flag == 1) {
            if (!confirm('Please login or register to proceed. ')) {
                return false;
            }
            else {
                window.location.href = "https://secure.enjoyelife.com.cn/YiGuoEnSh/Login.aspx";
            }
        }

        //判断是否全部是兑换商品
        var flag = 0; //上架商品总数     
        if ($.cookie('Products') != null) {
            var allcookies = $.cookie('Products');
            var product = new Array();
            product = allcookies.split("&");
            for (i = 0; i < product.length; i++) {
                var productInfo = new Array();
                productInfo = product[i].split("|")[1].split("=");
                if (productInfo[0] == "1") {
                    flag++;
                }
            }
        }
        if (flag == 0) {
            alert("Sorry, points cannot be redeemed alone, they must be redeemed along with another purchase.");
            return false;
        }
        window.location.href = "../Shopping/MyCart.aspx";
    }
}

//检查大购物车是否为空
function CheckBigShopCart() {
    var productNum = $("#ulMyCart li").length;
    if (productNum < 1) {
        alert("Your cart is empty, please choose some products. ");
    }
    else {
        //判断是否全部是兑换商品
        var flag = 0; //上架商品总数
        var reserveflag = 0;
        var isRerserve = 0;
        var userPoints = eFruit_EN_SH.Js.AjaxProOperate.GetPointsByUserId().value;
        var commodityPoints = 0;
        if ($.cookie('Products') != null) {
            var allcookies = $.cookie('Products');
            var product = new Array();
            product = allcookies.split("&");
            for (i = 0; i < product.length; i++) {
                var productInfo = new Array();
                productInfo = product[i].split("|")[1].split("=");
                if (productInfo[0] == "1") {
                    flag++;
                }
                if (productInfo[0] == "2") {
                    reserveflag++;
                    commodityPoints += eFruit_EN_SH.Js.AjaxProOperate.GetPointsByExchangeId(product[i].split("|")[0]).value;
                }
                if (eFruit_EN_SH.Js.AjaxProOperate.CheckIsReserveByCommodityId(product[i].split("|")[0]).value) {
                    isRerserve++;
                }
            }
        }
        if (flag == 0) {
            alert("Sorry, points cannot be redeemed alone, they must be redeemed along with another purchase.");
            return false;
        }
        if (isRerserve > 0) {
            alert("Sorry, this item is presently out of stock, click here to reserve this item and then delete it to proceed to checkout.")
            return false;
        }
        if (reserveflag > 0 && userPoints < commodityPoints) {
            alert("Sorry, your points are insufficient for this purchase, please delete it to proceed or select another item that matches your point balance.")
            return false;
        }

        //判断是否有Fresh Herbs ,Vergetable
        var isExist = eFruit_EN_SH.Js.AjaxProOperate.CheckIsExistFreshAndVege().value;
        if (isExist.length > 0) {
            var result = new Array();
            result = isExist.split(",");
            if (result[0] == "false") {
                alert("Hi, we get our vegetables direct from the farm so we ask that they are ordered before 12pm for next day delivery. For orders after 12pm they are delivered the day after. The earliest delivery date for your order is " + (result.length > 1 ? result[1] : "") + ".");
            }
        }
        window.location.href = "../Shopping/MyDetails.aspx";
    }
}


function DeleteByOrderId(orderId, controlname, orderState) {
    var state = $("#" + orderState).html();
    if (state != "Successful") {
        alert("Once your order is confirmed or on its way, you can only cancel by speaking to customer service representative.");
        return false;
    }
    if (orderId != "") {
        var result = eFruit_EN_SH.Js.AjaxProOperate.DeleteOrderId(orderId).value;
        if (result) { $("#" + controlname + orderId).css({ display: "none" }); }
        else
        { alert("Please try again!"); }
    }
}

function CheckIsLogin(loginUrl) {
    if (!confirm('Please login or register to proceed. ')) { return false; } else { window.location.href = loginUrl; };
}
