﻿//
$(document).ready(function () {
    if ($("#tb_starttime").length && $("#tb_endtime").length) {
        $("#tb_starttime").datepicker();
        $("#tb_endtime").datepicker();
    }
    if ($("#tb_birthday").length)
        $("#tb_birthday").datepicker({
            changeMonth: true,
            changeYear: true,
            yearRange: '1900:2011' 
        });

    if ($("#lb_username").length) {
        initMemberInfo();
    }
});

//初始化会员信息
var Member = null;
var initMemberInfo = function () {
    $.get("Ashx/Member.ashx", { action: "getInfo", 'random': Math.random() }, function (data) {
        if (data) {
            var info = eval("(" + data + ")");
            Member = info;
            if (info != null) {
                if (info.length <= 0) return;
                $("#lb_username").html("<em>" + info.UserName + "</em>");
                $("#tb_nickname").val(info.NickyName);
                var Birthday = eval("new " + info.Birthday.toString().replace("/", "").replace("/", ""));
                $("#tb_birthday").val(Birthday.toLocaleString());
                if (info.Gender == "1")
                    $("#rd_male").attr("checked", "checked");
                else
                    $("#rd_female").attr("checked", "checked");
                $("#tb_tel").val(info.Telephone);
                $("#tb_country").val(info.Country);
                $("#tb_state").val(info.State);
                $("#tb_city").val(info.City);
                $("#tb_address").val(info.Address);
                $("#sel_class").val(info.ClassID);
                $("#txtCharacter").val(info.Character);
                //
                if ($("#spanGame").length) {
                    $("#spanGame").html($("#sel_game option:selected").text());
                    //$("#spanServer").html($("#sel_server option:selected").text());
                    $("#spanCharacter").html(info.Character);
                    $("#spanContactMethod").html(info.UserName);
                    $("#spanPhoneNumber").html(info.Telephone);
                }
            }
        }
    });
};

//登出
var LoginOut = function () {
    $.getJSON("ashx/member.ashx", { "action": "loginout", random: Math.random() }, function (obj) {
        if (obj) {
            $("div.loginoff").show();
            $("div.loginon").hide();
            window.location.reload();
        }
    });
};

//登录（简洁）
var fastLogin = function () {
    var username = $("div.loginoff #tb_email").val();
    var password = $("div.loginoff #tb_password").val();
    //
    if (!/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/.test(username)) {
        alert("Email format is wrong!");
        return;
    }
    if (!/^[a-zA-Z0-9_]{6,15}$/.test(password)) {
        alert("Password needs 6-15 characters!");
        return;
    }
    //
    $.get("Ashx/member.ashx", { action: "checklogin", username: username, password: password, 'random': Math.random() }, function (data) {
        if (data) {
            if (data.length) {
                if (data == "0") {
                    alert("Sorry, Your account has not been enabled. \n\nIf a new registered user, Please check your registration email, Or contact our customer service.");
                }
                else if (data == "-1") {
                    alert("Sorry,Your email or password error,Please check it.");
                }
                else {
                    window.location.reload();
                }
            }
        } else {
            alert("Sorry,Your email or password error,Please check it.");
        }
    });
};

//登录（普通）
var normalLogin = function () {
    if (validate("dv_login")) {
        $.get("Ashx/member.ashx", { action: "checklogin", username: $("div#dv_login #tb_email").val(), password: $("div#dv_login #tb_password").val(), 'random': Math.random() }, function (data) {
            if (data) {
                if (data.length) {
                    if (data == "0") {
                        alert("Sorry, Your account has not been enabled. If a new registered user, Please check your registration email, Or contact our customer service.");
                    }
                    else if (data == "-1") {
                        alert("Sorry,Your email or password error,Please check it.");
                    }
                    else {
                        window.location.href = window.top.document.referrer;
                    }
                }
            } else {
                alert("Sorry,Your email or password error,Please check it.");
            }
        });
    }
};

//找回密码
var getPassword = function () {
    if (validate("dv_forgotpwd")) {
        $.get("Ashx/member.ashx", { action: "getpwd", username: $("div#dv_forgotpwd #tb_email").val(), 'random': Math.random() }, function (data) {
            if (data == "1") {
                $("div#dv_forgotpwd #tb_email").val("");
                alert("Information confirmed, please check your mailbox to retrieve your password.");
            } else if (data == "0") {
                alert("Sorry! Your Login ID is OpenID. Please check it from where it come from.");
            } else {
                alert("Sorry! Forgot your password failures.Please contact our customer service.");
            }
        });
    }
}

//注册
var rigister = function () {
    if (validate("dv_register")) {
        var email = $("div#dv_register #tb_email").val();
        var pwd = $("div#dv_register #tb_pass2").val();
        var isSubscribe = $("#chkSubscribe").attr("checked") ? "1" : "0";
        $.get("Ashx/member.ashx", { action: "register", email: email, pwd: pwd, isSubscribe: isSubscribe, 'random': Math.random() }, function (data) {
            var data = data.split('|');
            if (data.length == 2) {
                if (data[0] == "1") {
                    alert("You have registered successfully! You get a $ 5 GiftCard: " + data[1] + ", Please login in your mailbox to check our confirmation message!");
                    $("#giftcode").html(data[1]);
                    $("#giftcodeDiv").show();
                }
            }
            else if (data == "1") {
                alert("You have registered successfully! Please login in your mailbox to check our confirmation message!");
            }
            else if (data == "0") {
                alert("Already exists with this email!");
            }
            else if (data == "-1") {
                alert("Sorry, rigister fail, please contact us customer supporter.");
            }
        });
    }
};

//
var orderList = function (page) {
    var pz = $("#hdPageSize").val();
    var name = $("#tb_orderid").val();
    var stime = $("#tb_starttime").val();
    var etime = $("#tb_endtime").val();
    $.getJSON("Ashx/Member.ashx", { action: "orderList", pz: pz, pi: page, name: name, stime: stime, etime: etime, 'random': Math.random() }, function (data) {
        if (data) {
            //
            if (data.page.length) {
                $("div.pagelist").empty().append(data.page);
            }
            //
            $("#div-orderlist table.tabList tbody").empty().hide();
            //
            var strlist = "";
            data.list = eval(data.list);
            if (data.list.length) {
                for (var index in data.list) {
                    var obj = data.list[index];
                    var CreateTime = eval("new " + obj.CreateTime.toString().replace("/", "").replace("/", ""));
                    strlist += String.format("<tr class=\"{0}\">", index % 2 == 0 ? "d" : "s");
                    strlist += String.format("<td><cite>{0}</cite></td>", obj.Status == "1" ? "<em>" + obj.PNO + "</em>" : obj.PNO);
                    strlist += String.format("<td>{0}</td>", obj.Quantity);
                    strlist += String.format("<td><em>{1} {0}</em></td>", getDecimal(obj.SumPrice, 2), getCurCode(obj.CurrencyName), obj.SumPrice);
                    strlist += String.format("<td>{0}</td>", CreateTime.toLocaleString());
                    strlist += String.format("<td><a class=\"blue pointer\" onclick=\"viewItems('{0}','{1}','{2}','{3}')\">Order Details<a></td>", obj.PNO, obj.CurrencyName, obj.TransactionID, obj.Status);
                    strlist += "</tr>";
                    strlist += String.format("<tr class=\"{0}\"><td colspan=\"2\"><b>Status:</b> {1}</td><td colspan=\"3\"><b>Pay Method:</b> {2}</td></tr>", index % 2 == 0 ? "d" : "s", obj.Status == "1" ? "<em>Already Payment</em>" : "No Payment", obj.PayName);
                }
                //
                $("#div-orderlist table.tabList tbody").html(strlist).show();
            }
            else {
                $("#div-orderlist table.tabList tbody").html("<tr><td colspan=\"5\" style='text-align:center;' ><em>No Result! Choose search criteria and press \"Search\"</em></td></tr>").show();
            }
        } else {
            $("#div-orderlist table.tabList tbody").html("<tr><td colspan=\"5\" style='text-align:center;' ><em>No Result! Choose search criteria and press \"Search\"</em></td></tr>").show();
        }
    });
};

//
function viewStock(id, td) {
    $.get("Ashx/Member.ashx", { action: "getStock", ServerID: id },
        function (r) {
            $("#" + td).html(r);
        }
    );
}

//
var viewItems = function (refer, CurrencyName, ppserial, status) {
    $("#div-orderlist").hide("slow");
    $.getJSON("Ashx/Member.ashx", { action: "getItems", cno: refer, 'random': Math.random() }, function (data) {
        if (data) {
            if (data.length) {
                var strlist = "";
                for (var index in data) {
                    var obj = data[index];
                    strlist += String.format("<tr class=\"{0}\">", index % 2 == 0 ? "d" : "s");
                    strlist += String.format("<td><cite>{0}</cite></td>", obj.Status == "1" ? "<em>" + obj.CNO + "</em>" : obj.CNO);
                    strlist += String.format("<td>{0}</td>", obj.Quantity);
                    strlist += String.format("<td><em>{1} {0}</em></td>", getDecimal(obj.LastPrice, 2), getCurCode(CurrencyName), obj.SalePrice);


                    var ProductType = "Currency";
                    var ProductName = obj.ProductName;
                    var cha = "none";
                    switch (obj.ProductType) {
                        case 1:
                            ProductType = "Currency";
                            var subLength = obj.ProductName.indexOf(".");
                            var Volume = parseFloat(obj.ProductName.substring(0, subLength) + obj.ProductName.substring(subLength, 3));
                            cha = Volume - obj.SentAmount;
                            if (cha > 0)
                                cha = "In process";
                            else if (cha == 0)
                                cha = "Delivered";
                            else
                                cha = "Undelivery";

                            break;
                        case 2:
                            ProductType = "PowerLeveling";
                            break;
                        case 4:
                            ProductType = "Items";
                            ProductName += " ×" + obj.Volume;
                            break;
                        case 8:
                            ProductType = "Accounts";
                            break;
                        case 16:
                            ProductType = "Game-Cards";
                            break;
                        case 32:
                            ProductType = "RaidDrops";
                            ProductName += " × " + obj.Volume;
                            break;
                        case 64:
                            ProductType = "TCG Loots";
                            //ProductName += " × " + obj.Volume;
                            break;
                    }
                    var str = String.format("<td><img src=\"images/I-am-in-Game.png\" style=\"cursor:pointer\" onclick=\"setOnline('{0}','{1}','{2}')\" /></td>", obj.CNO, ppserial, obj.SiteName);
                    if (status != "1") {
                        str = "<td></td>";
                    }

                    strlist += String.format("<td>{0}</td>", ProductType);
                    strlist += str; //客户打在线
                    strlist += "</tr>";
                    strlist += String.format("<tr class=\"{0}\"><td colspan=\"5\">", index % 2 == 0 ? "d" : "s");
                    strlist += String.format("<ul>");
                    strlist += String.format("<li><cite class=\"cite-left\"><b>Product Name:</b></cite> <cite class=\"cite-right\">{0}</cite> <cite class=\"cite-left\"><b>Product Code:</b></cite> <cite class=\"cite-right\">{1}</cite></li>", ProductName, obj.ProductCode != null ? obj.ProductCode : "*");
                    strlist += String.format("<li><cite class=\"cite-left\"><b>Game Name:</b></cite> <cite class=\"cite-right\">{0}</cite> <cite class=\"cite-left\"><b>Server Name:</b></cite> <cite class=\"cite-right\">{1}</cite></li>", obj.GameName, obj.ServerName);
                    strlist += String.format("<li><cite class=\"cite-left\"><b>Discount:</b></cite> <cite class=\"cite-right\">{0}</cite> <cite class=\"cite-left\"><b>Time:</b></cite> <cite class=\"cite-right\">{1}</cite></li>", "", FormatTime(obj.WebTime));
                    strlist += String.format("<li><cite class=\"cite-left\"><b>Character Name:</b></cite> <cite class=\"cite-right\">{0}</cite> <cite class=\"cite-left\"><b>Character Class:</b></cite> <cite class=\"cite-right\">{1}</cite></li>", obj.Character != null ? obj.Character : "*", obj.CharacterClass != null ? obj.CharacterClass : "*");
                    strlist += String.format("<li><cite class=\"cite-left\"><b>Contact Method:</b></cite> <cite class=\"cite-right\">{0}</cite> <cite class=\"cite-left\"><b>Phone Number:</b></cite> <cite class=\"cite-right\">{1}</cite></li>", obj.ContactMethod, obj.PhoneNumber);
                    strlist += String.format("<li><cite class=\"cite-left\"><b>Account:</b></cite> <cite class=\"cite-right\">{0}</cite> <cite class=\"cite-left\"><b>Password:</b></cite> <cite class=\"cite-right\">{1}</cite></li>", obj.Account != null ? obj.Account : "*", obj.Password != null ? obj.Password : "*");
                    strlist += String.format("<li><cite class=\"cite-left\"><b>Stock:</b></cite> <cite class=\"cite-right\" id=\"tdStatus{0}\" ></cite> <cite class=\"cite-left\"><b>Status:</b></cite> <cite class=\"cite-right\">{1}</cite></li>", index, cha);
                    //strlist += String.format("<li><cite>{0}</cite></li>", obj.Comment);
                    strlist += String.format("</ul");
                    strlist += String.format("</td></tr>")
                }
                $("#div_itemlist table tbody").empty().html(strlist);
                $("#div_itemlist").show("slow");

                viewStock(obj.ServerID, "tdStatus" + index);
            }
        }
    });
};

//
var getCurCode = function (CurrencyName) {
    var curcode = "€";
    if (CurrencyName == "EUR")
        curcode = "&euro;";
    if (CurrencyName == "USD")
        curcode = "$";
    if (CurrencyName == "GBP")
        curcode = "&pound;";
    return curcode;
}

// 
var closeItems = function () {
    $("#div_itemlist").hide("slow");
    $("#div_itemlist table tbody").empty();
    $("#div-orderlist").show("slow");
    scroll(0, 0);
};

//
var setOnline = function (serialno, ppserial, website) {
    $.ajax({ url: "Ashx/Member.ashx", data: { action: "setOnline", cno: serialno, pp: ppserial, website: website, 'random': Math.random() }, type: "POST",
        success: function (data) {
            alert("Yes! Updates Success.");
        },
        error: function (r) {
            //alert(r.responseText);
        }
    });
}

//
var modMemberInfo = function () {
    if (validate("memberinfo")) {
        var obj = new Object();
        obj["NickyName"] = escape($("#tb_nickname").val());
        obj["Birthday"] = $("#tb_birthday").val();
        obj["Telephone"] = $("#tb_tel").val();
        obj["State"] = escape($("#tb_state").val());
        obj["Country"] = escape($("#tb_country").val());
        obj["City"] = escape($("#tb_city").val());
        obj["Address"] = escape($("#tb_address").val());
        obj["GameID"] = $("#sel_game").val();
        obj["ServerID"] = $("#sel_server").val();
        obj["ClassID"] = $("#sel_class").val();
        obj["Character"] = $("#txtCharacter").val();
        obj["Gender"] = $("input[name=rd_sex]:checked").val() == 1 ? true : false;
        $.get("Ashx/Member.ashx", { action: "modInfo", info: json2str(obj), 'random': Math.random() }, function (data) {
            if (data) {
                if (data.length) {
                    if (data == "1") {
                        alert("Yes! Updates Success.");
                        //
                        if ($("#spanGame").length) {
                            $("#spanGame").html($("#sel_game option:selected").text());
                            $("#spanServer").html($("#sel_server option:selected").text());
                            $("#spanCharacter").html($("#txtCharacter").val());
                            //$("#spanContactMethod").html(info.UserName);
                            $("#spanPhoneNumber").html($("#tb_tel").val());
                        }
                        if ($("#labServer").length) {
                            $("#labServer").html($("#sel_server option:selected").text());
                            $("#labCharacter").html($("#txtCharacter").val());
                            $("#labEmail").html($("#username").text());
                            $("#labNumber").html($("#tb_tel").val());
                        }
                    }
                    else {
                        alert("Sorry! Updates failed. Please contact our customer service.");
                    }
                }
            } else {
                alert("Sorry! Updates failed. Please contact our customer service.");
            }
        });
    }
};

//
var modMemberPwd = function () {
    if (validate("changepwd")) {
        $.get("Ashx/Member.ashx", { action: "modPwd", oldpwd: $("#tb_pwd").val(), newpwd: $("#tb_newpwd").val(), 'random': Math.random() }, function (data) {
            if (data) {
                if (data.length) {
                    if (data == "1")
                        alert("Yes! Modify password successs!");
                    else if (data == "-2")
                        alert("Sorry! The old password your typed was wrong.");
                    else
                        alert("Sorry! Modify password failure. Please contact our customer service.");
                }
            }
            else {
                alert("Sorry! Modify password failure. Please contact our customer service.");
            }
        });
    }
};
