function GetCartId() {
    var host = window.location.host;
    if (host.indexOf(":") > 0) {
        host = host.substring(0, host.indexOf(":"));
    }
    var virtualPath = "/";
    if (virtualPath.length > 1) {
        virtualPath = virtualPath.substring(0, virtualPath.lastIndexOf("/"));
    }
    var ckn = "Cart" + host + virtualPath;
    return ShowCookiesByName(ckn, "CartID");
}

function ShowCookiesByName(strTk, strTn) {
    var strCookie = document.cookie;
    var strTT = strTk + "=";
    var strTvalue = "";
    if (strCookie.indexOf(strTT) >= 0) {
        var strTemp = strCookie.substring(strCookie.indexOf(strTT) + strTT.length);
        strTvalue = strTemp;
        if (strTemp.indexOf(";") >= 0) {
            strTvalue = strTemp.substring(0, strTemp.indexOf(";"));
        }
        if (strTvalue.length > 1) {
            strTT = strTn + "=";
            if (strTvalue.indexOf(strTT) >= 0) {
                strTemp = strTvalue.substring(strTvalue.indexOf(strTT) + strTT.length);
                if (strTemp.indexOf("&") >= 0) {
                    strTvalue = strTemp.substring(0, strTemp.indexOf("&"));
                }
                else {
                    strTvalue = strTemp;
                }
            }
            else {
                strTvalue = "";
            }
        }
        if (strTvalue.length > 0) {
            strTvalue = decodeURIComponent(strTvalue);
        }
    }
    return strTvalue;
}

//购物车Ajax请求
function ShoppingCartAjax(action, paramsValue, callBackFn) {
    var $LoadingTips = jQuery("#DivLoadingTips").overlay({
        top: "50%",
        left: "50%",
        mask: {
            color: '#fff',
            loadSpeed: 200,
            opacity: 0.5
        },
        closeOnClick: false,
        closeOnEsc: false,
        load: true,
        api: true
    });

    jQuery.pe.ajax(action, { params: paramsValue,
        success: function (response) {
            $LoadingTips.close();
            callBackFn(response);
        }
    });
}

function GetShoppingCart() {
    ShoppingCartAjax('getshoppingcartfulllist', { cartId: GetCartId() }, function (response) {
        switch (jQuery(response).find('status').text()) {
            case "ok":
                RenderShoppingCart(jQuery(response).find('json').text());
                break;
            default:
                alert("获取数据失败");
                break;
        }
    });
}

//购物车数据
var jsonResult = null;
var selectedPresentId = jQuery.pe.cookie("presentId");
function RenderShoppingCart(jsonText) {
    //更新随身购物车
    GetShoppingCart();
    jQuery("#TbShoppingCart").html(""); //清空列表
    jQuery("#TbShoppingCartPresentProject").html(""); //清空促销方案选中礼品
    jsonResult = eval('(' + jsonText + ')');

    if (jsonResult.ProductList.length > 0) {
        jQuery("#TrNoData").hide();
    }
    else {
        jQuery("#TrNoData").show();
    }
    //处理列表
    jQuery('#myTemplate').tmpl(jsonResult.ProductList).appendTo('#TbShoppingCart');

    //设置购买数量输入框失去焦点的响应事件
    jQuery(".fn-text-amount").blur(function () {
        var $this = jQuery(this);
        var oldQuantity = parseInt($this.attr("OldQuantity"));
        var quantity = parseInt($this.val());

        //文本框值发生变化
        if (quantity != oldQuantity) {
            if (isNaN(quantity) || quantity <= 0) {
                quantity = 1;
            }
            UpdateQuantity(parseInt($this.attr("CartItemId")), quantity);
        }
    });

    //处理总价
    SetTotalPrice(jsonResult.TotalInfo.TotalMoney);


    //处理促销方案可选商品列表
    if (jsonResult.PresentProjectInfo != null && jsonResult.PresentProjectInfo.PresentList.length > 0) {
        jQuery(".presentProject").show();
        jQuery("#ULPresentProjectList").html("");
        var PresentProjectInfo = jsonResult.PresentProjectInfo;
        jQuery('#presentProjectTemplate').tmpl(PresentProjectInfo.PresentList).appendTo('#ULPresentProjectList');
        jQuery("#PresentProjectInfoIntro").text("【" + PresentProjectInfo.Name + "】，以￥" + PresentProjectInfo.Price + "可换购以下任一礼品");

        //处理已选中的礼品
        ShoppingCartAddPresentProject(selectedPresentId);
    }
    else {
        jQuery(".presentProject").hide();
    }
}

function ShoppingCartMinus(cartItemId) {
    var quantity = parseInt(jQuery("#TxtQuantity_" + cartItemId).val());
    quantity--;
    if (quantity == 0) {
        quantity = 1;
    }
    UpdateQuantity(cartItemId, quantity);
}

function ShoppingCartPlus(cartItemId) {
    var quantity = parseInt(jQuery("#TxtQuantity_" + cartItemId).val());
    quantity++;
    UpdateQuantity(cartItemId, quantity);
}

//更新购物车商品数量
function UpdateQuantity(cartItemId, quantity) {
    ShoppingCartAjax('updateshoppingcartquantity', { cartId: GetCartId(), cartItemId: cartItemId, quantity: quantity, isGetShoppingcart: "true" }, function (response) {
        if (jQuery(response).find('status').text() == "err") {
            alert(jQuery(response).find('result').text());
        }
        RenderShoppingCart(jQuery(response).find('json').text());
    }
            );
}

function ShoppingCartDelete(cartItemId) {
    ShoppingCartAjax('deleteshoppingcartitem', { cartId: GetCartId(), cartItemId: cartItemId, isGetShoppingcart: "true" },
                 function (response) {
                     jQuery("#TrShoppingCartLoading").hide();
                     switch (jQuery(response).find('status').text()) {
                         case "ok":
                             RenderShoppingCart(jQuery(response).find('json').text());
                             break;
                         default:
                             alert("删除数据失败");
                             break;
                     }
                 }
            );
}

function ShoppingCartSaveFavorite(productId) {
    jQuery.pe.ajax('savefavorite', { params: { ID: productId },
        success: function (response) {
            switch (jQuery(response).find('status').text()) {
                case "ok":
                    alert("收藏成功");
                    break;
                case "nologin":
                    alert("请先登录");
                    break;
                default:
                    alert("收藏失败");
                    break;
            }
        }
    });
}

function ShoppingCartSelectedPresent(parentCartItemId, productId, quantity, belongsToProductID, cartItemId) {
    var operateType = jQuery("#ChkPresentId_" + parentCartItemId).prop("checked") ? "addpresenttocart" : "deletepresentfromcart";
    ShoppingCartAjax(operateType, { cartId: GetCartId(), cartItemId: cartItemId, isGetShoppingcart: "true", productId: productId, belongstoproductid: belongsToProductID, quantity: quantity },
                 function (response) {
                     switch (jQuery(response).find('status').text()) {
                         case "ok":
                             RenderShoppingCart(jQuery(response).find('json').text());
                             break;
                         default:
                             alert("处理数据失败");
                             break;
                     }
                 }
            );
}

function ShoppingCartAddPresentProject(presentId) {
    jQuery("#TbShoppingCartPresentProject").html("");
    var presentList = jsonResult.PresentProjectInfo.PresentList;
    for (var i = 0; i < presentList.length; i++) {
        if (presentList[i].PresentId == presentId) {
            jQuery('#selectedPresentTemplate').tmpl(presentList[i]).appendTo('#TbShoppingCartPresentProject');

            //处理总价
            SetTotalPrice(jsonResult.TotalInfo.TotalMoney + jsonResult.PresentProjectInfo.Price);
            break;
        }
    }
    selectedPresentId = presentId;
    jQuery.pe.cookie("presentId", selectedPresentId);

}

function ShoppingCartDeletePresentProject(presentId) {
    jQuery("#TbShoppingCartPresentProject").html("");
    selectedPresentId = 0;
    jQuery.pe.cookie("presentId", "");
    //处理总价
    SetTotalPrice(jsonResult.TotalInfo.TotalMoney);
}

function SetTotalPrice(price) {
    jQuery(".total_price").html(price.toFixed(2));
}

function ShoppingCartAddProduct(generalId, property) {
    ShoppingCartAjax("AddToCart", { cartId: GetCartId(), isGetShoppingcart: "true", generalid: generalId, property: property, quantity: 1 },
                 function (response) {
                     switch (jQuery(response).find('status').text()) {
                         case "ok":
                             RenderShoppingCart(jQuery(response).find('json').text());
                             break;
                         default:
                             alert("处理数据失败");
                             break;
                     }
                 }
            );
}

jQuery(document).ready(function () {
    ShoppingCartAjax('getshoppingcartfulllist', { cartId: GetCartId() }, function (response) {
        switch (jQuery(response).find('status').text()) {
            case "ok":
                RenderShoppingCart(jQuery(response).find('json').text());
                break;
            default:
                alert("获取数据失败");
                break;
        }
    });
    //GetShoppingCart();
});