﻿
jQuery(document).ready(function() {

    //创建XML对象
    function getXMLDocument() {
        var xDoc = null;
        if (document.implementation && document.implementation.createDocument) {
            xDoc = document.implementation.createDocument("", "", null);
        } else {
            if ((typeof ActiveXObject) != "undefined") {
                var msXmlAx = null;
                try {
                    msXmlAx = new ActiveXObject("Msxml2.DOMDocument");
                }
                catch (e) {
                    msXmlAx = new ActiveXObject("Msxml.DOMDocument");
                }
                xDoc = msXmlAx;
            }
        }
        if (xDoc == null || typeof xDoc.load == "undefined") {
            xDoc = null;
        }
        return xDoc;
    };

    var currentPage = 0;
    var totalPages = 0;
    var pageSize = 10; //每页大小

    var userCredits = 0; //用户积分
    var oldTotalCredits = 0; //cookie中的积分总额

    var isLogin = false; //是否已登录
    if (jQuery.cookie("isLogin") != "" && jQuery.cookie("isLogin") != null) {
        isLogin = jQuery.cookie("isLogin");
    }

    var cookieExpires = null; //cookie的有效期:null表示有效期为浏览进程；可填入天数和具体的有效日期
    var cookieDomain = ""; //cookie的域,默认为网站的域名
    var cookiePath = '/'; //cookie的路径,如果发生cookie错误，一般是这里的路径没设置对
    if (document.URL.indexOf('WebApplication') > 0)
        cookiePath = '/WebApplication/';


    //构建购物车
    var shoppingCart = "";
    shoppingCart += '<div id="shoppingCart">';
    shoppingCart += '    <a href="#" id="closeShoppingCart"><img src="../Images/pageclose.gif" /></a>';
    shoppingCart += '    <div class="clearbox"></div>';
    shoppingCart += '    <table cellspacing="0">';
    shoppingCart += '        <thead>';
    shoppingCart += '            <tr>';
    shoppingCart += '              <th class="productName">商品名称</th>';
    shoppingCart += '              <th class="productCredit">积分</th>';
    shoppingCart += '              <th class="productQuantity">数量</th>';
    shoppingCart += '              <th class="productTotalCredit">总额</th>';
    shoppingCart += '              <th class="deleteProduct">&nbsp;</th>';
    shoppingCart += '            </tr>';
    shoppingCart += '        </thead>';
    shoppingCart += '        <tbody></tbody>';
    shoppingCart += '        <tfoot>';
    shoppingCart += '            <tr>';
    shoppingCart += '              <td class="productName">兑换总额</td>';
    shoppingCart += '              <td class="productCredit">&nbsp;</td>';
    shoppingCart += '              <td class="productQuantity">&nbsp;</td>';
    shoppingCart += '              <td class="productTotalCredit">' + oldTotalCredits + '</td>';
    shoppingCart += '              <td class="deleteProduct">&nbsp;</td>';
    shoppingCart += '            </tr>';
    shoppingCart += '        </tfoot>';
    shoppingCart += '    </table>';
    shoppingCart += '      <br />'
    shoppingCart += '    <a id="goToBuy" href="../Shop/CreditsProductCheckOut.aspx"><img src="../Images/Shop/ProductBuy.gif" alt="换购" /></a><br />'
    shoppingCart += '</div>';
    jQuery(shoppingCart).appendTo('#main_right').addClass("normalShoppingCart").hide();
    jQuery("#closeShoppingCart", "#shoppingCart").click(function() {
        jQuery("#shoppingCart").fadeOut("normal");
        return false;
    });
    jQuery("#shoppingCart").draggable({ cursor: 'move', opacity: 0.35 });

    if (isLogin) {
        CheckCookie();
    }

    //检查Cookie 
    function CheckCookie() {
        //总积分
        if (jQuery.cookie("totalCredits") != "" && jQuery.cookie("totalCredits") != null) {
            oldTotalCredits = parseInt(jQuery.cookie("totalCredits"));
        }
        //获取购物车商品cookie
        if (jQuery.cookie("creditProducts") != "" && jQuery.cookie("creditProducts") != null) {
            var creditProducts = jQuery.cookie("creditProducts");
            creditProducts = creditProducts.substring(0, creditProducts.length - 1).split(";");
            for (var i = 0; i < creditProducts.length; i++) {
                var creditProduct = eval('(' + creditProducts[i] + ')');
                if (IsExistProduct(creditProduct["ProductID"])) {
                    RemoveProductFromShoppingCart(creditProduct["ProductID"]);
                }
                AddProductToShoppingCart(creditProduct["ProductID"], creditProduct["ProductName"], parseInt(creditProduct["ProductCredit"]), parseInt(creditProduct["ProductQuantity"]));
            }
        };
    };

    //添加商品信息到cookie
    function AddProductToCookie(productID, productName, productCredit, productQuantity) {
        var creditProducts = "";
        if (jQuery.cookie("creditProducts") != "" && jQuery.cookie("creditProducts") != null) {
            creditProducts = jQuery.cookie("creditProducts");
        }
        var newCreditProduct = '{"ProductID":' + productID + ',"ProductCredit":"' + productCredit + '","ProductQuantity":"' + productQuantity + '","ProductName":"' + productName + '"};';
        creditProducts += newCreditProduct;
        jQuery.cookie("creditProducts", creditProducts, { path: cookiePath, expires: cookieExpires });
    };

    /*从cookie移除商品*/
    function RemoveProductFromCookie(productID, productName) {
        if (jQuery.cookie("creditProducts") != "" && jQuery.cookie("creditProducts") != null) {
            var creditProducts = jQuery.cookie("creditProducts");
            var regx = new RegExp('\{"ProductID":' + productID + ',[\\s\\S]*?,"ProductName":"' + productName + '"\};');
            creditProducts = creditProducts.replace(regx, "");
            jQuery.cookie("creditProducts", creditProducts, { path: cookiePath, expires: cookieExpires });
        }
    }

    //构建登录框
    var loginBox = "";
    loginBox += '<div id="loginBox" >';
    loginBox += '   <a id="closeLoginBox" href="#"><img src="../Images/pageclose.gif"/></a>';
    loginBox += '   <div class="clearbox"></div>';
    loginBox += '   <div class="loginBoxItem">';
    loginBox += '       <label for="userName">用户名：</label>';
    loginBox += '       <input type="text" name="userName" id="userName">';
    loginBox += '   </div>';
    loginBox += '   <br />';
    loginBox += '   <div class="loginBoxItem">';
    loginBox += '       <label for="userPassword">密&nbsp;码：</label>&nbsp;';
    loginBox += '       <input type="password" name="userPassword" id="userPassword">';
    loginBox += '   </div>';
    loginBox += '   <br />';
    loginBox += '   <div class="loginBoxItem">';
    loginBox += '       <a id="login" href="#"><img src="../Images/Shop/login_bt_icon.gif"/></a>';
    loginBox += '       <a id="register" href="../User/Register.aspx"><img src="../Images/Shop/reg_bt_icon.gif"/></a>';
    loginBox += '       <a id="getbackPassword" href="../User/GetPassword.aspx"><img src="../Images/Shop/forpwd.gif"/></a>';
    loginBox += '   </div>';
    loginBox += '</div>';
    jQuery(loginBox).appendTo("#center_all").hide();

    jQuery("#closeLoginBox", "#loginBox").click(function() {
        jQuery.unblockUI();
        return false;
    });

    //登录按钮
    jQuery("#login", "#loginBox").click(function() {
        var $loading = jQuery('<img src="../Images/indicator.gif" />');
        jQuery(this).ajaxStart(function() {
            $loading.insertBefore(jQuery('.loginBoxItem').eq(0));
        });
        jQuery(this).ajaxComplete(function() {
            $loading.remove();
        })
        Login();
        return false;
    });

    jQuery("#userPassword").keyup(function(event) {
        if (event.keyCode == 13) {
            Login();
        }
    });


    //显示信息
    function ShowMsg(msg, obj) {
        var position = jQuery(obj).position();
        var msgBox = '<div class="msgBox">' + msg + '</div>';
        jQuery(msgBox).insertBefore(obj).css({ top: position.top + "px", left: (position.left + jQuery(obj).outerWidth()) + "px" })
            .oneTime(1000, function() {
                jQuery(this).show("fast", function() {
                    jQuery(this).hide("fast", function() {
                        jQuery(this).remove();
                    });
                });
            });
    };

    var PrevPage = function() {
        MovePage("prev");
    };

    var NextPage = function() {
        MovePage("next");
    };

    jQuery("#firstPage", "#pager").click(function() {
        MovePage("first");
    });

    jQuery("#lastPage", "#pager").click(function() {
        MovePage("last");
    });

    //翻页
    function MovePage(action) {
        switch (action) {
            case "prev":
                currentPage--;
                break;
            case "next":
                currentPage++;
                break;
            case "first":
                currentPage = 0;
                break;
            case "last":
                currentPage = totalPages;
                break;
            default:
                currentPage = 0;
                break;
        }
        SetPager();
        LoadCreditProductList();
    };

    //设置翻页按钮
    function SetPager() {
        if (currentPage <= 0) {
            currentPage = 0;
            jQuery("#prevPage", "#pager").attr("disabled", "disabled").unbind('click', PrevPage);
            jQuery("#nextPage", "#pager").removeAttr("disabled").bind('click', NextPage);

        }
        else if (currentPage >= totalPages) {
            currentPage = totalPages;
            jQuery("#nextPage", "#pager").attr("disabled", "disabled").unbind('click', NextPage);
            jQuery("#prevPage", "#pager").removeAttr("disabled").bind('click', PrevPage);
        }
        else {
            jQuery("#nextPage", "#pager").removeAttr("disabled").bind('click', NextPage);
            jQuery("#prevPage", "#pager").removeAttr("disabled").bind('click', PrevPage);
        }
        jQuery("#currentPage", "#pager").text(currentPage + 1);
        jQuery("#totalPages", "#pager").text(totalPages + 1);
    }

    LoadCreditProductList();

    //加载积分商品列表
    function LoadCreditProductList() {
        jQuery("#creditsProductList").empty();
        var $productList = jQuery('<ul></ul>');
        jQuery("#creditsProductList").append($productList).append('<div class="clearbox"></div>');

        var $loading = jQuery('<div class="loading"><img src="../Images/indicator.gif"/></div>').css({ "top": "280px", "left": "50%" });
        jQuery("#creditsProductList").ajaxStart(function() {
            jQuery("#creditsProductList").append($loading);
        });
        jQuery("#creditsProductList").ajaxSuccess(function() {
            $loading.remove();
        });

        //ajax错误时的事件
        jQuery("#creditsProductList").ajaxError(function(event, XMLHttpRequest, ajaxOptions, thrownError) {
            $(this).append("<li>出错:" + XMLHttpRequest.status + "</li>");
        });
        jQuery.ajax({ url: "CreditsProductAjaxHandler.aspx", type: 'post', dataType: 'xml',
            data: { 'currentPage': currentPage, 'pageSize': pageSize, 'action': 'loadCreditProductList' },
            success: function(data) {
                totalPages = Math.ceil(parseInt(jQuery("CreditsProductCount", data).text()) / pageSize) - 1;
                SetPager();
                var productId, productName, productCredit, productThumb, productIntro;
                jQuery("CreditProduct", data).each(function() {
                    productId = jQuery("ProductID", this).text();
                    productName = jQuery("ProductName", this).text();
                    productCredit = jQuery("NeedCredits", this).text();
                    productThumb = jQuery("ProductThumb", this).text();
                    if (productThumb == '') {
                        productThumb = 'nopic.gif';
                    }
                    productIntro = jQuery("ProductIntro", this).text();
                    var productLink = "CreditsProductItem.aspx?id=" + productId;
                    var $productListItem = jQuery('<li id="' + productId + '" productName="' + productName + '" productCredit="' + productCredit + '"></li>');
                    var $productThumbDiv = jQuery('<div class="p_list_pic"></div>');
                    $productThumbDiv.append('<a href="' + productLink + '"' + '><img src="../UploadFiles/' + productThumb + '" /></a>');
                    $productListItem.append($productThumbDiv);

                    var $productNameDiv = jQuery('<div class="p_list_name"></div>');
                    $productNameDiv.append('<a href="' + productLink + '"' + '>' + productName + '</a>');
                    $productListItem.append($productNameDiv);

                    $productCreditDiv = jQuery('<div class="p_list_price"></div>');
                    $productCreditDiv.append('所需积分：<span class="p_list_price_number" id="productCredit">' + productCredit + '</span>');
                    $productListItem.append($productCreditDiv);

                    $productButtonDiv = jQuery('<div class="p_list_button"></div>');
                    $productButtonDiv.append('<a href="#" class="viewProduct"><img src="../Images/Shop/ProductView.gif" alt="查阅详情" /></a>&nbsp;&nbsp;');
                    $productButtonDiv.append('<a href="#" class="exchangeProduct"><img src="../Images/Shop/ProductBuy.gif" alt="换购" /></a>');
                    $productListItem.append($productButtonDiv);

                    $productListItem.append('<div class="clearbox"></div>');

                    $productList.append($productListItem);
                });

                //查阅详情按钮
                jQuery("a.viewProduct", "#creditsProductList li").each(function() {
                    jQuery(this).click(function() {
                        var productId = jQuery(this).parent().parent().attr("id");
                        window.open('CreditsProductItem.aspx?id=' + productId, '_blank');
                        return false;
                    });
                });

                //换购按钮
                jQuery("a.exchangeProduct", "#creditsProductList li").each(function() {
                    jQuery(this).click(function() {
                        if (isLogin) {
                            var addProductCredit = parseInt(jQuery(this).parent().parent().find("#productCredit").text());
                            var currentTotalCredits = parseInt(jQuery("#shoppingCart tfoot").find("td.productTotalCredit").eq(0).text());
                            if (userCredits < addProductCredit + currentTotalCredits) {
                                ShowMsg("您的积分不足！", this);
                                return false;
                            }

                            var $product = jQuery(this).parent().parent();
                            var productId = $product.attr("id");
                            var productName = $product.attr("productName");
                            var productCredit = parseInt($product.attr("productCredit"));
                            AddProductToShoppingCart(productId, productName, productCredit, 1);
                        }
                        else {
                            jQuery.blockUI({ message: jQuery("#loginBox"), css: { cursor: 'default' }, overlayCSS: { cursor: 'default'} });
                        }
                        return false;
                    });
                });
            }
        });
    };

    //判断商品是否已经存在购物车
    function IsExistProduct(productId) {
        var isExist = false;
        jQuery("tr", "#shoppingCart").each(function() {
            if (jQuery(this).attr("id") == productId) {
                isExist = true;
                return false;
            }
        });
        return isExist;
    };

    //添加商品到购物车
    function AddProductToShoppingCart(productId, productName, productCredit, productQuantity) {

        //如果购物车已存在该商品，则修改购买数量，否则添加到购物车
        if (IsExistProduct(productId)) {
            var $shoppingCartItem = jQuery("tr#" + productId, "#shoppingCart tbody");
            var pQuantity = parseInt($shoppingCartItem.find("td.productQuantity :input").eq(0).val());
            var pTotalCredit = parseInt($shoppingCartItem.find("td.productTotalCredit").eq(0).text());
            $shoppingCartItem.find("td.productTotalCredit").eq(0).text(pTotalCredit + productCredit);
            $shoppingCartItem.find("td.productQuantity :input").eq(0).val(pQuantity + productQuantity);
        }
        else {
            var shoppingCartItem = '<tr id="' + productId + '">';
            shoppingCartItem += '     <td class="productName">' + productName + '</td>';
            shoppingCartItem += '     <td class="productCredit">' + productCredit + '</td>';
            shoppingCartItem += '     <td class="productQuantity"><input type="text" value="' + productQuantity + '"></input></td>';
            shoppingCartItem += '     <td class="productTotalCredit">' + (productCredit * productQuantity) + '</td>';
            shoppingCartItem += '     <td class="deleteProduct"><img src="../Images/Shop/deleteProduct.gif"></td>';
            shoppingCartItem += '   </tr>';
            jQuery("#shoppingCart tbody").append(shoppingCartItem);
            jQuery("tr#" + productId, "#shoppingCart tbody").find("td.deleteProduct img").click(function(event) {
                if (event.target == this) {
                    var $shoppingCartItem = jQuery("tr#" + productId, "#shoppingCart tbody");
                    var productName = $shoppingCartItem.find('td.productName').eq(0).text();
                    var oldTotalProductCredit = parseInt($shoppingCartItem.find("td.productTotalCredit").eq(0).text());
                    var totalCredit = parseInt(jQuery("#shoppingCart tfoot").find("td.productTotalCredit").eq(0).text());
                    jQuery.cookie("totalCredits", totalCredit - oldTotalProductCredit, { path: cookiePath, expires: cookieExpires });
                    jQuery("#shoppingCart tfoot").find("td.productTotalCredit").eq(0).text(totalCredit - oldTotalProductCredit);
                    RemoveProductFromShoppingCart(productId);
                    RemoveProductFromCookie(productId, productName);
                }
            });

            //通过绑定键盘输入事件来验证商品数量的输入
            jQuery(".productQuantity :input", "#shoppingCart tbody").keypress(function(event) {
                if (event.charCode && (event.charCode < 48 || event.charCode > 57)) {
                    ShowMsg("请输入正确的数据！", this);
                    event.preventDefault();
                }
            }).keyup(function() {
                var newProductQuantity;
                if (isNaN(jQuery(this).val()) || jQuery(this).val() == "") {
                    newProductQuantity = 0;
                }
                else {
                    newProductQuantity = parseInt(jQuery(this).val());
                }
                var $shoppingCartItem = jQuery(this).parent().parent();
                var thisProductCredit = parseInt($shoppingCartItem.find(".productCredit").eq(0).text());
                var thisProductId = $shoppingCartItem.attr("id");
                var thisProductName = $shoppingCartItem.find("td.productName").eq(0).text();
                $shoppingCartItem.find("td.productTotalCredit").eq(0).text(newProductQuantity * thisProductCredit);
                var totalCredits = 0;
                jQuery("tr", "#shoppingCart tbody").find("td.productTotalCredit").each(function() {
                    totalCredits += parseInt(jQuery(this).text());
                });
                jQuery("#shoppingCart tfoot").find("td.productTotalCredit").eq(0).text(totalCredits);
                jQuery.cookie("totalCredits", totalCredits, { path: cookiePath, expires: cookieExpires });

                RemoveProductFromCookie(thisProductId, thisProductName);
                AddProductToCookie(thisProductId, thisProductName, thisProductCredit, newProductQuantity);
            });
        }
        var totalCredits = 0;
        jQuery("tr", "#shoppingCart tbody").find("td.productTotalCredit").each(function() {
            totalCredits += parseInt(jQuery(this).text());
        });
        jQuery("#shoppingCart tfoot").find("td.productTotalCredit").eq(0).text(totalCredits);
        jQuery.cookie("totalCredits", totalCredits, { path: cookiePath, expires: cookieExpires });

        var cProductQuantity = jQuery("tr#" + productId, "#shoppingCart tbody").find("td.productQuantity :input").eq(0).val();
        RemoveProductFromCookie(productId, productName);
        AddProductToCookie(productId, productName, productCredit, cProductQuantity);

        var $exchangeProductButton = jQuery("a.exchangeProduct", "#creditsProductList li#" + productId);
        if ($exchangeProductButton.length > 0) {
            ShowShoppingCart($exchangeProductButton.get());
        }

    };

    //显示购物车
    function ShowShoppingCart(callbutton) {
        var buttonPosition = jQuery(callbutton).position();
        jQuery("#shoppingCart").css({ top: (buttonPosition.top - jQuery("#shoppingCart").outerHeight() - 10) + 'px', left: (buttonPosition.left - jQuery("#shoppingCart").outerWidth() / 2) + 'px' });

        jQuery("#shoppingCart").fadeIn("slow");
    }

    //删除商品
    function RemoveProductFromShoppingCart(productId) {
        jQuery("tr#" + productId, "#shoppingCart tbody").fadeOut("normal", function() { jQuery(this).remove(); });
    };

    CheckLogin();

    //检验登录
    function CheckLogin() {
        jQuery.ajax({ url: "CreditsProductAjaxHandler.aspx", type: 'post', dataType: 'xml', data: { 'action': 'checkLogin' },
            success: function(data) {
                var status = jQuery("status", data).text();
                if (status == "false") {
                    isLogin = false;
                }
                else if (status == "true") {
                    isLogin = true;
                    var userName = jQuery("UserName", data).text();
                    userCredits = parseInt(jQuery("UserCredits", data).text());
                    jQuery('<div id="userIdentity"><span>用户名：' + userName + '</span>&nbsp;<span>当前积分：'
                    + userCredits + '</span>&nbsp;<a href="#" id="showShoppingCart" style="font-weight:bold;color:#000;">显示积分购物车</a></div>')
                    .insertBefore(jQuery("#creditsProductList"));

                    jQuery("#showShoppingCart").click(function() {
                        ShowShoppingCart(this);
                    });
                }
                jQuery.cookie("isLogin", isLogin, { path: cookiePath, expires: cookieExpires });
            }
        });
    };

    //用户登录
    function Login() {
        var xmlDoc = getXMLDocument();

        var root = xmlDoc.createElement("root");

        var typeElement = xmlDoc.createElement("type");
        var typeText = xmlDoc.createTextNode("userlogin");
        typeElement.appendChild(typeText);
        root.appendChild(typeElement);

        var userNameElement = xmlDoc.createElement("username");
        var userNameText = xmlDoc.createTextNode(jQuery("#userName").val());
        userNameElement.appendChild(userNameText);
        root.appendChild(userNameElement);

        var userPasswordElement = xmlDoc.createElement("password");
        var userPasswordText = xmlDoc.createTextNode(jQuery("#userPassword").val());
        userPasswordElement.appendChild(userPasswordText);
        root.appendChild(userPasswordElement);

        jQuery.ajax({ url: "../Ajax.aspx", type: 'post', dataType: 'xml', data: root.xml,
            success: function(data) {
                var status = jQuery("status", data).text();
                if (status == "err") {
                    isLogin = false;
                    ShowMsg(jQuery("body", data).text(), jQuery("#login", "#loginBox"));
                }
                else if (status == "ok") {
                    jQuery.unblockUI();
                    isLogin = true;
                    var userName = jQuery("username", data).text();
                    if (jQuery("usercredits", data).text() == "") {
                        userCredits = 0;
                    }
                    else {
                        userCredits = parseInt(jQuery("usercredits", data).text());
                    }

                    jQuery('<div id="userIdentity"><span>用户名：' + userName +
                    '</span>&nbsp;<span>当前积分：' + userCredits + '</span>&nbsp;<a href="#" id="showShoppingCart" style="font-weight:bold;color:#000;">显示积分购物车</a></div>')
                    .insertBefore(jQuery("#creditsProductList"));


                    jQuery("#showShoppingCart").click(function() {
                        ShowShoppingCart(this);
                    });

                    CheckCookie();
                }
                jQuery.cookie("isLogin", isLogin, { path: cookiePath, expires: cookieExpires });
            }
        });
    }
});


    
    
