﻿//初始化
var specialServer = null;
var showStr = false;
var Site = new Object();
Site.lastquantity = 0;
$().ready(function () {
    _gold = new goldclass();
    $("#sel_alpha").find("option").each(function (i) {
        if (i == 0) {
            $(this).attr("selected", true);
        }
    });
    $("#sel_game").val($("#hdGameID").val());
	//隐藏code
	var gid = $("#sel_game").val();
	if (gid == 1 || gid == 17 || gid == 18) {
		$("#trDiscount").hide();
	} else {
		$("#trDiscount").show();
	}
});

//
var _gold = null;
var AlphaList = new Array();
var _ServerList = new Array();
function CheckHasAlphaList(alpha) {
    for(var i=0;i<AlphaList.length;i++) {
        if (AlphaList[i] == alpha) {
            return true;
        }       
    }
}
//
var goldclass = function () {
    return {
        changeGame: function () {
            //隐藏code
            var gid = $("#sel_game").val();
            if (gid == 1 || gid == 17 || gid == 18) {
                $("#trDiscount").hide();
            } else {
                $("#trDiscount").show();
            }
            //加载服务器索引
            AlphaList.length = 0;
            $.getJSON("ashx/server.ashx", { "action": "alpha", "zone": 0, "game": $("#sel_game").val(), "random": Math.random() }, function (data) {
                $("#sel_alpha").empty().append("<option value=\"\">*</option>");
                _ServerList = data;
                if (data.length) {
                    for (var index in data) {
                        var server = $.trim(data[index].ServerName);
                        var alpha = server.substring(0, 1);
                        if (!CheckHasAlphaList(alpha)) {
                            $("#sel_alpha").append(String.format("<option value=\"{0}\" {1}>{0}</option>", alpha, $("#hdnAlpha").val() == alpha ? "selected" : ""));
                            AlphaList.push(alpha);
                        }
                    }
                    //
                    $("#sel_alpha").change();
                    //
                    changeCUR("cur_" + $("#sel_game option:selected").attr("cid"));
                }
            });
        },
        changeAlpha: function () {
            //加载服务器
            $("#sel_server").empty();
            if ($("#sel_alpha").val() == "") {
                $("#sel_server").append("<option value=\"\">-Choose Server-</option>");
                if ($("#sel_quantity").length) {
                    $("#sel_quantity").empty().append("<option q=\"0\" p=\"0\" value=\"\">-Choose Product-</option>").change();
                }
                return;
            };
            if (_ServerList.length > 0) {
                if ($("#sel_alpha").val() != "") {
                    $("#sel_server").append("<option value=\"\">-Choose Server-</option>");
                    for (var index = 0; index < _ServerList.length; index++) {
                        if ($("#sel_alpha").val() == _ServerList[index].ServerName.substring(0, 1)) {
                            if (specialServer != null) {
                                if (specialServer == _ServerList[index].ServerName)
                                    $("#sel_server").append(String.format("<option value='{1}' {2}>{0}</option>", _ServerList[index].ServerName, _ServerList[index].ID, "selected"));
                                else
                                    $("#sel_server").append(String.format("<option value='{1}' >{0}</option>", _ServerList[index].ServerName, _ServerList[index].ID));
                            } else
                                $("#sel_server").append(String.format("<option value='{1}' {2}>{0}</option>", _ServerList[index].ServerName, _ServerList[index].ID, $("#hdnServerID").val() == _ServerList[index].ID ? "selected" : ""));

                        }
                    }
                    //清空
                    specialServer = null;
                    //
                    $("#sel_server").change();
                }
            }
        },
        changeServer: function () {
            //加载金币段
            if ($("#sel_server").val() == "") {
                if ($("#sel_quantity").length) {
                    $("#sel_quantity").empty().append("<option q=\"0\" p=\"0\" value=\"\">-Choose Product-</option>").change();
                }
                return;
            };
            // 
            $("#hdGameID").val($("#sel_game option:selected").val());
            $("#hdGameName").val($("#sel_game option:selected").text());
            $("#hdServerID").val($("#sel_server option:selected").val());
            $("#hdServerName").val($("#sel_server option:selected").text());
            $("#spanGameServer").html($("#sel_game option:selected").text() + " - <em>" + $("#sel_server option:selected").text() + "</em>");
            //
            var CurrencyID = "$";
            if ($(".sel_currency").length) {
                CurrencyID = $(".sel_currency").attr("d");
            }
            if ($("div.quick_order").length) {
                CurrencyID = $("#sel_game option:selected").attr("cid")
            }
            //设置价格
            $.getJSON("ashx/gold.ashx", { "action": "list", "gid": $("#sel_game").val(), "server": $("#sel_server option:selected").val(), "cid": CurrencyID, "random": Math.random() }, function (_datasource) {
                _datasource = eval(_datasource);
                if (_datasource.length) {
                    var Unit = $("#sel_game option:selected").attr("unit");
                    var currencyname = "$";
                    if ($(".sel_currency").length) {
                        currencyname = $(".sel_currency").attr("s");
                    }
                    if ($("div.quick_order").length) {
                        currencyname = $("#sel_game option:selected").attr("cur")
                    }
                    //    
                    if (Site.lastquantity <= 0)
                        Site.lastquantity = $("#sel_game option:selected").attr("dq");
                    if ($("#hdnLastQuantity").length) {
                        if ($("#hdnLastQuantity").val() > 0) {
                            Site.lastquantity = $("#hdnLastQuantity").val();
                        }
                    }
                    //快速下单金币段数据
                    var strlist = "";
                    if ($("#sel_quantity").length) {
                        var AppendCashRate = 0;
                        for (var index in _datasource) {
                            var row = _datasource[index];
                            if (row.GoldQuantity) {
                                //              
                                AppendCashRate = row.AppendCashRate;
                                var SalePrice = row.SalePrice * parseFloat($(".sel_currency").attr("r"));
                                SalePrice = SalePrice - (SalePrice * row.AppendCashRate);
                                var BasePrice = row.BasePrice - (row.BasePrice * row.AppendCashRate);
                                //
                                strlist += String.format("<option value='{1}' p={2} b={6} q={0} m={7} {5}>{0} {3} {4}</option>", Number(row.GoldQuantity), row.ID, row.Moreantissa > 0 ? getDecimal(parseInt(getInt(SalePrice)) + parseFloat(row.Moreantissa), 2) : getDecimal(SalePrice, 2), Unit, Number(row.AppendQuantity) > 0 ? " + " + Number(row.AppendQuantity) + " " + Unit : "", (Site.lastquantity == row.GoldQuantity ? 'selected' : ''), BasePrice, row.Moreantissa);
                            }
                        }
                        $("#sel_quantity").empty().append(strlist).change();
                    }
                    //列表金币段数据
                    if ($("#tbProductList").length) {
                        var tblBody = "";
                        for (var index in _datasource) {
                            var row = _datasource[index];
                            if (row.GoldQuantity) {
                                var SalePrice = row.SalePrice * parseFloat($(".sel_currency").attr("r"));
                                var Bonus = "";
                                if (row.AppendQuantity) {
                                    Bonus = " + " + Number(row.AppendQuantity) / Number(row.GoldQuantity) * 100 + "% Bonus = <em><b>" + (Number(row.AppendQuantity) + Number(row.GoldQuantity)) + " " + Unit + "</b></em>";
                                }
                                tblBody += String.format("<tr id=\"tr{7}\" p={5} b={8} q={2} m={9} oldprice_={8} class=\"changeprice {6}\"><td><img src=\"images/golds.gif\" /> <span id=\"objQuantity\"><b class=\"quantity\">{2} {10}</b> {3}</span> </td><td class=\"changeprice red\" oldprice=\"{8}\"  moreantissa=\"{9}\">{4} {5} </td><td align=\"center\"><label><input type=\"button\" value=\"\" onclick=\"buyNow({7});\" class=\"btnBuyNow\"></label></td></tr>", $("#sel_server option:selected").text(), $("#sel_game option:selected").text(), row.GoldQuantity, Bonus, $(".sel_currency").attr("s"), row.Moreantissa > 0 ? (getInt(SalePrice)) + row.Moreantissa : getDecimal(SalePrice, 2), index % 2 == 0 ? "strip" : "", row.ID, row.SalePrice, row.Moreantissa, Unit);
                            }
                        }
                        //
                        $('#tbProductList').html(tblBody).show(1000);
                    }
                    //
                }
                else {
                    if ($("#sel_quantity").length) {
                        $("#sel_quantity").empty().append("<option q=\"0\" p=\"0\" value=\"\">-Choose Product-</option>").change();
                    }
                }
            });
        },
        changeQutity: function () {
            rollBack(0);
        }
    };
};

//
var buyNow = function (refer) {
    if ($("#tr" + refer).length) {
        var GoldQuantity = $("#tr" + refer).attr("q");
        var Moreantissa = $("#tr" + refer).attr("m");
        var SalePrice = $("#tr" + refer).attr("p");
        var BasePrice = $("#tr" + refer).attr("b");
        if ($("#sel_quantity").length) {
            $("#sel_quantity").empty().append(String.format("<option value='{0}' p={1} b={2} q={3} m={4} {5}></option>", refer, SalePrice, BasePrice, GoldQuantity, Moreantissa)).change();
        }
        $("#fs_baseinfo").show();
        $("#fs_fillinfo").show();
        window.location.hash = "fs_baseinfo";
        $("#tdGame").html($("#hdGameName").val());
        $("#tdServer").html($("#hdServerName").val());
        $("#tdQuantity").html($("#tr" + refer).find("span#objQuantity").html());
    }
};

//
var getPointsPrice = function () {
    if ($("#sel_quantity").length) {
        if ($("#sel_quantity").val() != "") {
            var eurrate = parseFloat($("ul.btn_currency li#eur").find("a").attr("r"));
            var needpoints = getInt(parseFloat($("#sel_quantity option:selected").attr("p")) / parseFloat($(".sel_currency").attr("r")) * eurrate) * 50;
            $("#needpoints").html(getInt(needpoints));
        }
    }
}

//
var buyGold = function (refer) {
    //金币下单开始
    if ($("#sel_quantity option:selected").val() == "") {
        alert("Please choose product!");
        return;
    }
    var saleprice = $("#lbl_price").attr("nowprice");
    if (saleprice <= 0) {
        alert("The current price is invalid!");
        return;
    }
    if (!validate("fs_fillinfo")) return false;
    if ($("#tb_country").val() == "" || $("#tb_phone").val() == "") {
        alert("please input your full telephone number!");
        return;
    }
    //收集下单信息
    var product = new Object();
    product["ID"] = $("#sel_quantity option:selected").val();
    product["ProductType"] = 1;
    product["Discount"] = "";
    product["GameID"] = $("#hdGameID").val();
    product["GameName"] = $("#hdGameName").val();
    product["ServerName"] = $("#hdServerName").val();
    product["ServerID"] = $("#hdServerID").val();
    product["Currency"] = $(".sel_currency").attr("s");
    product["CurrencyID"] = $(".sel_currency").attr("d");
    product["Rate"] = $(".sel_currency").attr("r");
    product["Quantity"] = 1;
    product["SalePrice"] = saleprice;
    if ($("#tb_discount").val() != "" && parseFloat($("#td_discount").attr("title")) > 0) {
        product["Moreantissa"] = 0;
    }
    else {
        product["Moreantissa"] = $("#sel_quantity option:selected").attr("m");
    }
    product["RelateID"] = 0;
    //
    product["Subscribe"] = $("#chkSubscribe").attr("checked") ? true : false;
    product["UserPoints"] = parseInt($("#txt_pointsqty").val());
    product["PointsPrice"] = getDecimal($("#em_exchangeprice").attr("nowprice") / $(".sel_currency").attr("r"), 3);
    $("input[name='radGiftCoupon']").each(function () {
        if ($(this).attr("checked")) {
            product["GiftCouponPrice"] = getDecimal($(this).attr("savedprice") / $(".sel_currency").attr("r"), 3);
            product["GiftCouponID"] = $(this).attr("giftgiveid");
        }
    });    
    //
    CartInfo.Confirm(product, refer);
};

//折扣码处理
var checkCode = function () {
    var baseprice = getDecimal($("#sel_quantity option:selected").attr("p"), 2);
    //
    var info = new Object();
    info.GameID = $("#hdGameID").val();
    info.ProductType = 1;
    info.Gold = getInt($("#sel_quantity option:selected").attr("q"));
    info.SalePrice = baseprice;
    if ($("#tb_discount").val() != "" && $("#sel_quantity option:selected").val() > 0) {
        applycode($("#tb_discount").val(), info, function (obj, info) {
            if (obj) {
                if (obj.Invalid == 0) {
                    //
                    var arr = [];
                    arr.push(String.format("<table class=\"tab_discount\"><tr><td class=\"tl2\">Bonus Gold:</td><td class=\"tr2\">{0}</td><td class=\"tl2\">Discount:</td><td id=\"td_discount\" class=\"tr2\" title=\"{1}\">{2} {1}</td></tr>", obj.Gold, obj.Price, $(".sel_currency").attr("s")));
                    arr.push(String.format("<tr><td class=\"tl2\">Bonus Gift:</td><td class=\"tr2\">{0}</td><td class=\"tl2\">Loyalty Points:</td><td class=\"tr2\">{1}</td></tr></table>", obj.Item || "none", obj.Point));
                    $("#trDiscountPanel").show();
                    $("#li_discount").empty().html(arr.join(''));
                    //
                    if (obj.Price == -1) {
                        var num = $("#txt_pointsqty").val() / 50;
                        $("#em_exchangeprice").empty().html($(".sel_currency").attr("s") + "0");
                        if (num != "" && num > 0) {
                            $.get("ashx/gold.ashx", { action: 'exchangePoints', quantity: num, 'random': Math.random() }, function (data) {
                                if (data) {
                                    if (data == -1) {
                                        $("#em_exchangeprice").empty().html($(".sel_currency").attr("s") + "0");
                                        $("#txt_pointsqty").val(0);
                                        alert("Input current points is invalidate!");
                                    }
                                    else if (data == -2) {
                                        $("#em_exchangeprice").empty().html($(".sel_currency").attr("s") + "0");
                                        $("#txt_pointsqty").val(0);
                                        alert("Please login first!");
                                    }
                                    else if (data == -3) {
                                        $("#em_exchangeprice").empty().html($(".sel_currency").attr("s") + "0");
                                        $("#txt_pointsqty").val(0);
                                        alert("Wait too long! Please refresh the page again!");
                                    }
                                    else {
                                        var exchangeprice = getDecimal(data, 2);
                                        var discountprice = parseFloat(exchangeprice) + parseFloat(obj.Price);
                                        $("#em_exchangeprice").empty().html($(".sel_currency").attr("s") + " " + exchangeprice).attr("nowprice", exchangeprice);
                                        //
                                        reducedPrice($(".sel_currency").attr("s"), info.SalePrice, discountprice);
                                    }
                                }
                            });
                        }
                        else {
                            //折扣价格处理
                            //
                            var discountprice = parseFloat(obj.Price);
                            reducedPrice($(".sel_currency").attr("s"), info.SalePrice, discountprice);
                        }
                    }
                }
                else {
                    rollBack(1);
                }
            }
        });
    }
    else {
        rollBack(1);
    }
};

var rollBack = function (refer) {
    //
    Site.lastquantity = $("#sel_quantity option:selected").attr("q");
    //货币类型处理
    var currencyname = "$";
    if ($(".sel_currency").length) {
        currencyname = $(".sel_currency").attr("s");
    }
    if ($("div.quick_order").length) {
        currencyname = $("#sel_game option:selected").attr("cur")
    }

    //折扣码处理
    if ($("#tb_discount").length) {
        if ($("#tb_discount").val() != "" && $("#sel_quantity option:selected").val() > 0 && refer == 0) {
            checkCode();
            return;
        }
        else {
            if ($("#lbl_price").attr("title")) {
                var price = $("#lbl_price").attr("title");
                $("#lbl_price").html(currencyname + " " + price).attr("nowprice", price);
            }
            $("#trDiscountPanel").hide();
            $("#li_discount").empty().html("");
            $("#tb_discount").val("");
        }
    }
    else {
        $("#trDiscountPanel").hide();
        $("#li_discount").empty().html("");
        $("#tb_discount").val("");
    }

    //
    if ($("#sel_quantity option:selected").val() > 0) {
        var price = getDecimal($("#sel_quantity option:selected").attr("p"), 2);
        //市场价格处理
        if ($("#lbl_oldprice").length) {
            $("#lbl_oldprice").html(currencyname + " " + getDecimal(price * (130 / 100), 2));
        }
        //积分兑换处理
        var discountprice = 0;
        var num = $("#txt_pointsqty").val() / 50;
        $("#em_exchangeprice").empty().html($(".sel_currency").attr("s") + "0");
        if (num != "" && num > 0 && price == -1) {
            $.get("ashx/gold.ashx", { action: 'exchangePoints', quantity: num, 'random': Math.random() }, function (data) {
                if (data) {
                    if (data == -1) {
                        $("#em_exchangeprice").empty().html($(".sel_currency").attr("s") + "0");
                        $("#txt_pointsqty").val(0);
                        alert("Input current points is invalidate!");
                    }
                    else if (data == -2) {
                        $("#em_exchangeprice").empty().html($(".sel_currency").attr("s") + "0");
                        $("#txt_pointsqty").val(0);
                        alert("Please login first!");
                    }
                    else if (data == -3) {
                        $("#em_exchangeprice").empty().html($(".sel_currency").attr("s") + "0");
                        $("#txt_pointsqty").val(0);
                        alert("Wait too long! Please refresh the page again!");
                    }
                    else {
                        var exchangeprice = getDecimal(data, 2);
                        discountprice += parseFloat(exchangeprice);
                        $("#em_exchangeprice").empty().html($(".sel_currency").attr("s") + " " + exchangeprice).attr("nowprice", exchangeprice);
                        //

                    }
                    reducedPrice(currencyname, price, discountprice);
                }
            });
        }
        else {
            reducedPrice(currencyname, price, discountprice);
        }
    }
    else {
        if ($("#lbl_oldprice").length) {
            $("#lbl_oldprice").html(currencyname + " 0");
        }
        $("#lbl_price").html(currencyname + " 0").attr("nowprice", 0);
    }
};

var reducedPrice = function (currencyname, price, discountprice) {
    //
    $("input[name='radGiftCoupon']").each(function () {
        if ($(this).attr("checked")) {
            $("#hdnGiftCouponID").val($(this).attr("id"));
        }
    });
    //代金券处理
    var gameid = $("#hdGameID").val();
    var goldnum = $("#sel_quantity>option:selected").attr("q");
    var moneytype = $(".sel_currency").text();
    if (goldnum == -1 && ($("#hdnMemberID").val() > 0)) {
        $.ajax({ url: "ashx/gift.ashx", type: "POST", data: { action: "getDetail", gameid: gameid, goldnum: goldnum, moneytype: moneytype },
            success: function (data) {
                //未登录
                if (data) {
                    if (data.length) {
                        var res = eval('(' + data + ')');
                        var listCard = eval('(' + res.listCard + ')');
                        var listCoupon = eval('(' + res.listCoupon + ')');
                        var strGift = "";
                        var strCoupon = "";
                        $("#divGift, #divCoupon").empty();                     
                        //处理gift
                        if (listCard.length > 0) {
                            for (var i = 0; i < listCard.length; i++) {
                                if (listCard[i].GiftType == "card") {
                                    var temp = listCard[i];
                                    $("#liGift").show();
                                    strGift += "<input id=\"g" + temp.ID + "\" name=\"radGiftCoupon\" onclick=\"rollBack(0);\" type=\"radio\" savedprice=\"" + getDecimal(temp.CountPrice, 2) + "\" " + (("g" + temp.ID) == $("#hdnGiftCouponID").val() ? "checked" : "") + " giftgiveid=\"" + temp.GiftGiveID + "\"/><em> Saved " + currencyname + " " + getDecimal(temp.CountPrice, 2) + " " + " </em><br/>";
                                }
                            }
                            $("#divGift").html(strGift);
                        }
                        //处理coupon
                        if (listCoupon.length > 0) {
                            for (var i = 0; i < listCoupon.length; i++) {
                                if (listCoupon[i].GiftType == "coupon") {
                                    var temp = listCoupon[i];
                                    $("#liCoupon").show();
                                    strCoupon += "<input id=\"c" + temp.ID + "\" name=\"radGiftCoupon\" onclick=\"rollBack(0);\" type=\"radio\" nowprice=\"" + temp.CountPrice + "\" savedprice=\"" + getDecimal(temp.CountPrice, 2) + "\" " + (("c" + temp.ID) == $("#hdnGiftCouponID").val() ? "checked" : "") + " giftgiveid=\"" + temp.ID + "\"/><em> Saved " + currencyname + " " + getDecimal(temp.CountPrice, 2) + "</em><br/>";
                                }
                            }
                            $("#divCoupon").html(strCoupon);
                        }
                        //
                        $("input[name='radGiftCoupon']").each(function () {
                            if ($(this).attr("checked")) {
                                discountprice += parseFloat($(this).attr("savedprice"));
                            }
                        });
                        //价格处理
                        showPrice(currencyname, price, discountprice);
                    }
                }
                else {
                    showPrice(currencyname, price, discountprice);
                }
            }
        });
    }
    else {
        showPrice(currencyname, price, discountprice);
    }
};

var showPrice = function (currencyname, price, discountprice) {
    if (discountprice > 0) {
        //折扣价格处理
        if (discountprice >= price) {
            alert("The current price is invalid!");
        }
        var nowprice = price - parseFloat(discountprice);
        nowprice = getDecimal(nowprice, 2);

        $("#lbl_price").html(price + "-" + getDecimal(discountprice, 2) + " = " + currencyname + " " + nowprice);
        $("#lbl_price").attr("nowprice", nowprice);
    }
    else {
        //价格处理
        $("#lbl_price").html(currencyname + " " + price);
        $("#lbl_price").attr("nowprice", price);
    }
    //
    if ($("#dv_exchange").length) {
        getPointsPrice();
    }
};

//
var changeCUR = function (id) {
    var curid = 0;
    var currate = 0;
    var curname = "$";
    //
    if ($(".btn_currency").length) {
        $(".sel_currency").removeClass("sel_currency");
        $("#" + id).addClass("sel_currency");
    }
    if ($(".sel_currency").length) {
        currate = $(".sel_currency").attr("r");
        curid = $(".sel_currency").attr("d");
        curname = $(".sel_currency").attr("s");
    }
    //
    $.post("ashx/cart.ashx", { "action": "changecur", "cid": curid, cur: curname, 'random': Math.random() }, function (data) {
        if ($(".changeprice[oldprice]").length) {
            $(".changeprice[oldprice]").each(function (idx, obj) {
                var price = getDecimal($(obj).attr("oldprice") * currate, 2);
                var moreantissa = $(obj).attr("moreantissa");
                if (moreantissa > 0) {
                    price = getInt(price) + parseFloat(moreantissa);
                }
                $(obj).html(curname + " " + price);
                //                
                $("#fs_baseinfo").hide();
                $("#fs_fillinfo").hide();
            });
        }
        if ($(".changeprice[oldprice_]").length) {
            $(".changeprice[oldprice_]").each(function (idx, obj) {
                if ($(obj).attr("p")) {
                    var price_ = getDecimal($(obj).attr("oldprice_") * currate, 2);
                    var moreantissa_ = $(obj).attr("m");
                    if (moreantissa_ > 0) {
                        price_ = getInt(price_) + parseFloat(moreantissa_);
                    }
                    $(obj).attr("p", price_);
                }
            });
        }
    });
};


