﻿var serverlist = null;
var goldlist = null;
var selgoldnum = 0;

$().ready(function () {

    $("#sel_game").change(function () {

        mask($("#sel_alpha"));
        $.get(g_url.gold, { getservers: $("#sel_game").val() }, function (data) {

            mask($("#sel_alpha"));
            var list = $.xml2json(data).Table;

            serverlist = list;

            if (list) {
                //
                var arralpha = [];
                if (list.length) {

                    for (var index = 0, len = list.length; index < len; index++) {

                        var obj = list[index];
                        var alpha = obj.server.substr(0, 1);

                        //
                        var flag = 0;
                        for (var i = 0; i < arralpha.length; i++) {

                            if (arralpha[i].substr(15, 1) == alpha) {
                                flag += 1;

                            }
                        }

                        //
                        if (flag == 0) {

                            arralpha.push(String.format("<option value=\"{0}\" {1}>{0}</option>", alpha, Site.lastalpha != "" ? (Site.lastalpha == alpha ? 'selected' : '') : ''));
                        }
                    }
                }
                else {
                    var alpha = list.server.substr(0, 1);
                    arralpha.push(String.format("<option value=\"{0}\" {1}>{0}</option>", alpha, list.lastalpha != "" ? (list.lastalpha == alpha ? 'selected' : '') : ''));
                }
                $("#sel_alpha").empty().append(arralpha.join(''));

                //
                if ($("#sel_game").attr("value") != "") {
                    $("#sel_alpha").change();
                }
            }
        });
    });
    $("#sel_alpha").change(function () {

        if (getPageName().toLowerCase() != "default") {
            $('#div_goldTable').html("");
            $('#div_goldTable').hide();
            $('#goldSell').html(0);
            $('#storage').html(0);
        }
        //
        var arr = [];
        arr.push(String.format("<option value=\"{0}\">{1}</option>", "", "-Bitte Server wählen-"));

        if (serverlist.length) {
            for (var i = 0; i < serverlist.length; i++) {

                if ($("#sel_alpha").val() == serverlist[i].server.substr(0, 1)) {

                    var obj = serverlist[i];
                    arr.push(String.format("<option value=\"{0}\" style=\"{2}\" {3}>{1}</option>", obj.twgoldsellid, obj.server, parseInt(obj.lowpriceflag) ? "color:#f00;" : "", Site.lastserver > 0 ? (Site.lastserver == obj.twgoldsellid ? 'selected' : '') : ''));
                }
            }
        }
        else {
            arr.push(String.format("<option value=\"{0}\" style=\"{2}\" {3}>{1}</option>", serverlist.twgoldsellid, serverlist.server, parseInt(serverlist.lowpriceflag) ? "color:#f00;" : "", Site.lastserver > 0 ? (Site.lastserver == serverlist.twgoldsellid ? 'selected' : '') : ''));
        }

        $("#sel_server").empty().append(arr.join(''));

        //
        if ($("#sel_alpha").attr("value") != "") {
            $("#sel_server").change();
        }
    })
    $("#sel_server").change(function () {

        if ($("#sel_server").attr("value") == "") {

            $("#sel_quantity").empty().append(String.format("<option value=\"{0}\">{1}</option>", "", "-Bitte Produkt wählen-"));
            $("#lbl_total").html("");
            $("#customprice").html("");
            return;
        }

        //
        $(".redtip", $("#sel_server").parent()).remove();
        $(".redtip", $("#sel_quantity").parent()).remove();

        mask($("#sel_quantity"));
        Site.getgoldlist($("#sel_game").val(), $("#sel_server>option:selected").text(), $("#hdn_currency").val(), function (data) {
            mask($("#sel_quantity"));
            var list = $.xml2json(data).Table;
            if (list) {
                goldlist = list;

                $('#div_goldTable').html("");
                $('#div_goldTable').hide();

                bindgold(list);
            }

            //
            $("#sel_quantity").change();
        });
    });
    $("#sel_quantity").change(function () {
        $("#lbl_total").text(Number($("#sel_quantity>option:selected").attr("title")).toFixed(2));
        $("#lbl_currency").text(getCurrency($("#hdn_currency").val()));
        if ($("#tb_code").length && $("#tb_code").val().trim().length) {
            checkGoldCode();
        }
    });

    if ($("#hdn_currency").length && $("#hdn_currency").val().length) {
        $("#a_EUR").css("color", "");
        $("#a_USD").css("color", "");
        $("#a_GBP").css("color", "");

        $("#a_" + $("#hdn_currency").val()).css("color", "red");
        $("#lbl_currency").text(getCurrency($("#hdn_currency").val()));
    }

    if ($("#hdn_game").length && $("#sel_game").length && $("#hdn_game").val().length) {
        $(String.format("#sel_game>option[value='{0}']", $("#hdn_game").val().toLowerCase())).attr("selected", true);
    }

    //
    init();

    //
    $("#sel_game").change();
});

var init = function() {
    //初始化

    if ($("#hdn_currency").length && $("#hdn_currency").val().trim().length) {
        Site.lastcurrency = $("#hdn_currency").val().trim();

    }
    if ($("#hdn_game").length && $("#hdn_game").val().trim().length && $("#sel_game").length) {
        Site.lastgame = $("#hdn_game").val().trim();

    }
    if ($("#hdn_alpha").length && $("#hdn_alpha").val().trim().length && $("#sel_alpha").length) {
        Site.lastalpha = $("#hdn_alpha").val().trim();

    }
    if ($("#hdn_server").length && $("#hdn_server").val().trim().length && $("#sel_server").length) {
        Site.lastserver = $("#hdn_server").val().trim();
    }
    if ($("#hdn_quantity").length && $("#hdn_quantity").val().trim().length && $("#sel_quantity").length) {
        Site.lastquantity = $("#hdn_quantity").val().trim();

    }
    if ($("#hdn_iscustom").length && $("#hdn_iscustom").val() == 1) {

        $("#customchk").attr("checked", true);
        $("#custombox").show();
        $("#txtAmount").attr("value", $("#hdn_customamount").val());
        $("#customprice").attr("innerHTML", $("#hdn_customprice").val());
    }
};

//
var getMoneyType = function(refer) {

    var a_moneyTypeId = 'a_' + refer;

    $("#a_EUR").css("color", "");
    $("#a_USD").css("color", "");
    $("#a_GBP").css("color", "");

    $("#" + a_moneyTypeId).css("color", "red");

    $("#hdn_currency").attr("value", refer);
    $("#lbl_currency").text(getCurrency(refer));

    Site.lastquantity = $("#sel_quantity").val();

    if ($("#sel_server").attr("value") != "") {
        $("#sel_server").change();
    }
}

//
var GetServerStorage = function(gameServerCode) {

    if ($("#sel_server").attr("value") == "") {
        return;
    }

    for (var i = 1; i <= 10; i++) {
        var id = 'colorTd' + i;
        var nocolor = $('#' + id).attr('nocolor');
        $('#' + id).attr('style', 'BACKGROUND:' + nocolor);
    }

    $.get(g_url.gold, { gamename: $("#sel_game").val(), servername: $("#sel_server>option:selected").text() }, function(data) {

        var fullStorage = 1200000;
        $('#goldSell').html(480000 + Number(data));
        $('#storage').html(fullStorage);

        var count = parseInt(parseFloat(1200000 * 10) / fullStorage);
        var i = 1;
        var interValId = window.setInterval(function() {
            if (count >= 10) {
                count = 10;
            }
            if (i <= count) {
                var id = 'colorTd' + i;
                var old = $('#' + id).attr('old');
                $('#' + id).attr('style', 'BACKGROUND:' + old);
                i++;
            } else {
                window.clearInterval(interValId);
            }
        }, 100);
    });
}

var GetServerOrderRecord = function(gameServerCode) {

    if ($("#sel_server").attr("value") == "") {
        return;
    }

    $.getJSON(g_url.gold, { counts: "10", game: $("#sel_game").val(), server: $("#sel_server>option:selected").text() }, function(data) {

        var listResult = "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\"><tbody><tr><th>Order Code</th><th>Amount</th><th>User Name</th><th>Date</th><th>&nbsp;</th></tr>";
        for (var i = 0; i < data.length; i++) {

            listResult += "<tr><td class=\"id_2\">" + data[i]["CNO"] + "</td><td>" + data[i]["Unit"] + " Gold</td><td class=\"mail\">" + data[i]["User"] + "</td><td class=\"mail\">" + data[i]["Date"] + "</td><td class=\"mail\">&nbsp;</td></tr>";
        }
        listResult += "</tbody></table>";

        $('#font_server').html($("#sel_server>option:selected").text());

        $('#orderrecords').html(listResult);

        $('.goumaijilu').show(1000);
    });
}

//
var bindgold = function (list, code) {

var tblHead = "<div class=\"VolumeDiscounttitle\">Diskont Tabelle</div><table class=\"VolumeDiscount\"><tbody>";
    //var tblBody = "";
    var tblFoot = "</tbody></table>";

    var unitname = "G";
    if ($("#gold_unitname").length) unitname = $("#gold_unitname").val();

    var arr = [];
    var tblBody = "<tr>";
    var len = list.length - 1;
    for (var index = len; index >= 1; index--) {
        var obj = list[index - 1];
        if (obj.unit > 0) {
            var givenum = Math.round(obj.givenum);
            var total = 0;
            var temp = obj.baseprice / obj.baseunit;
            temp = temp * obj.unit;
            temp = temp * obj.pricerate;
            temp = Math.round(temp);
            temp = Number(temp);
            total = Number(temp) + Number(obj.pricerest);

            var app = 0;
            if (code) {

                var flag = true;
                if (code.goldlimited > 0) {
                    if (code.goldlimited > obj.unit) flag = false;
                }
                if (code.moneylimited > 0) {
                    if (code.moneylimited > total) flag = false;
                }
                if (flag) {
                    if (code.rate > 0) {
                        app = Math.round(obj.unit * code.rate * 0.01);
                    }
                    var strTemp = total;
                    if (code.discount < 100) {
                        strTemp += " - " + (total * (1 - code.discount * 0.01)).toFixed(2);
                    }
                    if (code.money > 0) {
                        strTemp += " - " + code.money;
                    }
                    if (strTemp != total) {
                        total = eval(strTemp) + "(" + strTemp + ")";
                    }
                }
            }

            var symbol = "€";
            var type = $("#hdn_currency").val();
            if (type == "USD") {
                symbol = "$";
            }
            else if (type == "GBP") {
                symbol = "￡";
            }

            //
            arr.push(String.format("<option title=\"{1}\" value=\"{0}\" {5}>{0}{2}{3} {4}</option>", obj.unit, total, obj.givenum > 0 ? " + " + Math.round(obj.givenum) : "", app > 0 ? " + " + app : "", unitname, (Site.lastquantity > 0 ? (Site.lastquantity == obj.unit ? 'selected' : '') : '')));

            //
            if (getPageName().toLowerCase() != "default") {

                var oldPrice = formatFloat(parseFloat(total) * 1.12, 2);

                var trIndex = len - (index - 1);

                tblBody += "<th onclick=\"clickGoldTable('" + index + "')\"><span id=\"tdQuantity" + index + "\" title=\"" + obj.unit + "\">" + obj.unit + " " + unitname + "</span></th><td class=\"red\"><span id=\"tdPrice" + index + "\" title=\"" + total + "\">" + symbol + " " + total + "</span></td>";

                if ((trIndex % 3) == 0) {
                    tblBody = tblBody + "</tr>";
                }
            }
        }
    }

    if (len % 3 > 0) {
        for (var j = 0; j < (3 - (len % 3)); j++) {
            tblBody += "<th></th><td></td>";
        }
    }

    if (getPageName().toLowerCase() != "default") {

        $('#div_goldTable').html(tblHead + tblBody + tblFoot);
        $('#div_goldTable').show(1000);
    }
    $(".dv_tit").toggle(function () { $(".table_gold_list").hide(); }, function () { $(".table_gold_list").show(); $(".table_gold_list", "tbody").css("width", "100%"); })
    $("#sel_quantity").empty().append(arr.join(''));
    Site.lastquantity = 0;
};

//
var clickGoldTable = function(refer) {

    $(String.format("#sel_quantity>option[value='{0}']", $("#tdQuantity" + refer).attr("title"))).attr("selected", true);
    $("#lbl_total").text(Number($("#tdPrice" + refer).attr("title")).toFixed(2));
    $("#lbl_currency").text(getCurrency($("#hdn_currency").val()));
    
    if ($("#tb_code").length && $("#tb_code").val().trim().length) {
        checkGoldCode();
    }
}

function formatFloat(src, pos) { return Math.round(src * Math.pow(10, pos)) / Math.pow(10, pos); }

function getCurrency(moneyType) {

    switch(moneyType) {
        case "EUR": return "€";
    	break;
        case "USD": return "$";
            break;
        case "GBP": return "￡";
            break;
        default: return "€";
    }
}
