﻿Object.extend = function(destination, source) {
    for (var property in source)
        destination[property] = source[property];
    return destination;
};
Object.extend(String.prototype, {

    startsWith: function(pattern) {
        return this.indexOf(pattern) === 0;
    },

    endsWith: function(pattern) {
        var d = this.length - pattern.length;
        return d >= 0 && this.lastIndexOf(pattern) === d;
    },
    format: function() {
        var args = arguments;
        return this.replace(/\{(\d+)\}/g,
        function(m, i) {
            return args[i];
        });
    },
    trim: function() {
        return this.replace(/^\s+/g, "").replace(/\s+$/g, "");
    }
});

String.format = function(str) {
    var args = arguments;

    return str.replace(/\{(\d+)\}/g,
        function(m, i) {
            return args[parseInt(i) + 1];
        });
};


var Site = new Object();
Site.getservers = function(game, cb) {
    $.getJSON(g_url.gold, { getservers: game }, cb);
};
Site.getgoldlist = function(game, server, type, cb) {
    $.get(g_url.gold, { game: game, server: server, type: type }, cb);
};
Site.lastcurrency = "";
Site.lastgame = "";
Site.lastalpha = "";
Site.lastserver = "";
Site.lastquantity = 0;
Site.iscustom = "";
Site.customamount = "";
Site.customprice = "";

var g_host = (("https:" == document.location.protocol) ? " https://" : " http://") + window.location.host

//
var user_login = function () {
    var usr_name = $("div.#login-panel #txtName").val();
    var usr_pwd = $("div.#login-panel #txtPwd").val();
    if (!usr_name.trim().length) {
        alert("please input your login name!");
    }
    else if (usr_pwd == "") {
        alert("please input your password!");
    }
    else {
        $.get(g_url.user, { usrname: usr_name, usrpwd: usr_pwd }, function (data) {
            if (typeof data == 'string') {
                switch (parseInt(data)) {
                    case -1:
                        alert("Sorry,your login name is not exists!");
                        break;
                    case -2:
                        alert("Sorry,your login password wrong!");
                        break;
                    case -3:
                        break;
                    default:
                        if (parseInt(data) > 0) {

                        }
                        break;
                }
            }
            else {
                $(data).find("Table").each(

                    function () {

                        $(".box:first", $("#login-panel")).hide();
                        $(".box:last", $("#login-panel")).show();

                        if ($("#customerid").length) {
                            $("#customerid").attr("innerHTML", $(this).find("CustomerID").text());
                            $("#point").attr("innerHTML", $(this).find("IntegralValue").text());
                        }
                    });
            }
        });
    }
};
var user_loginout = function() {
    $("div.#login-panel #txtName").val("");
    $("div.#login-panel #txtPwd").val("");
    $(".box:first", $("#login-panel")).show();
    $(".box:last", $("#login-panel")).hide();
    $.get(g_url.user, { action: "logout" }, function(data) {
        if (parseInt(data)) {

            window.location.href = window.location.href;
        }
        else {

            alert("Sorry,login out error!");
        }
    });
};

//
var setCookie = function(cname, val, h) {
    if (jaaulde.utils.cookies.test()) {
        jaaulde.utils.cookies.set(cname, val, { hoursToLive: h, secure: true });
    }
    else {
        alert("browser's cookie is disabled!");
    }
};
var getCookie = function(cname) {
    if (jaaulde.utils.cookies.test()) {
        return jaaulde.utils.cookies.get(cname);
    }
    else {
        alert("browser's cookie is disabled!");
    }
};
var delCookie = function(cname) {
    if (jaaulde.utils.cookies.test()) {
        return jaaulde.utils.cookies.del(cname);
    }
    else {
        alert("browser's cookie is disabled!");
    }
};

//
function fAddFavorite(sTitle, sURL) {
    if (document.all) {
        window.external.AddFavorite(sURL, sTitle);
    } else {
        window.sidebar.addPanel(sTitle, sURL, "");
    }
 }

//create a form and submit it
 var createForm = function (obj, url, target) {
     var submitForm = document.createElement("FORM");
     document.body.appendChild(submitForm);
     submitForm.method = "POST";
     submitForm.target = "_self";
     for (var el in obj) {
         var newElement = document.createElement("input");
         newElement.name = el;
         newElement.type = "hidden";
         newElement.value = obj[el];
         submitForm.appendChild(newElement);
     }
     if (target) {
         submitForm.target = target;
     }
     submitForm.action = url;
     submitForm.submit();
 };

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        var path = '; path=/'; //options.path ? '; path=' + options.path : '';
        var domain = '; domain=' + window.location.host; //options.domain ? '; domain=' + options.domain : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join(''); //
        alert([name, '=', encodeURIComponent(value), expires, path, domain, secure].join(''));
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

var validate = function(containerid) {
    var flag = true;
    $("input", $(containerid ? "#" + containerid : "$()")).each(function(index, el) {
        switch ($(el).attr("datatype")) {
            case "Require":
                $(".redtip", $(el).parent()).remove();
                if ($(el).val().trim().length < 1) {
                    $(el).after(" <span class=\"redtip\">" + $(el).attr("msg") + "</span>");
                    flag = false;
                }
                break;
            case "Email":
                $(".redtip", $(el).parent()).remove();
                if ($(el).val().trim().length < 1 || !/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/.test($(el).val())) {
                    $(el).after(" <span class=\"redtip\">" + $(el).attr("msg") + "</span>");
                    flag = false;
                }
                break;
            case "Repeat":
                $(".redtip", $(el).parent()).remove();
                if ($("#" + $(el).attr("to")).val() != $(el).val()) {
                    $(el).after(" <span class=\"redtip\">" + $(el).attr("msg") + "</span>");
                    flag = false;
                }
                break;
            case "Number":
                $(".redtip", $(el).parent()).remove();
                if ($(el).val().trim().length < 1 || !/^\d+$/.test($(el).val())) {
                    $(el).after(" <span class=\"redtip\">" + $(el).attr("msg") + "</span>");
                    flag = false;
                }
                break;
            case "Phone":
                $(".redtip", $(el).parent()).remove();
                if ($(el).val().trim().length < 1 || !/^[0-9()\-]+$/.test($(el).val())) {
                    $(el).after(" <span class=\"redtip\">" + $(el).attr("msg") + "</span>");
                    flag = false;
                }
                break ;
            case "CommonPassWord":
                $(".redtip", $(el).parent()).remove();
                if ($(el).val().trim().length < 6 || $(el).val().trim().length > 16) {
                    $(el).after(" <span class=\"redtip\">" + $(el).attr("msg") + "</span>");
                    flag = false;
                }
                break ;
            case "PassWord":
                $(".redtip", $(el).parent()).remove();
                if ($(el).val().trim().length > 0 && ($(el).val().trim().length < 6 || $(el).val().trim().length > 16)) {
                    $(el).after(" <span class=\"redtip\">" + $(el).attr("msg") + "</span>");
                    flag = false;
                }
                break ;
            case "PassWordRepeat":
                $(".redtip", $(el).parent()).remove();
                if ($(el).val().trim().length > 0 && $("#" + $(el).attr("to")).val() != $(el).val()) {
                    $(el).after(" <span class=\"redtip\">" + $(el).attr("msg") + "</span>");
                    flag = false;
                }
                break;
            case "BornDate":
                $(".redtip", $(el).parent()).remove();
                if ($(el).val().trim().length >0 &&!$(el).val().match(new RegExp("^(\\d{1,2})([-./])(\\d{1,2})\\2((\\d{4})|(\\d{2}))$"))) {
                    $(el).after(" <span class=\"redtip\">" + $(el).attr("msg") + "</span>");
                    flag = false;
                }
                break ;
            case "PaypalEmail":
                $(".redtip", $(el).parent()).remove();
                if ($(el).val().trim().length > 0 && !/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/.test($(el).val())) {
                    $(el).after(" <span class=\"redtip\">" + $(el).attr("msg") + "</span>");
                    flag = false;
                }
                break;
            case "AccountName":
                $(".redtip", $(el).parent()).remove();
                if ($(el).val().trim().length < 6 || $(el).val().trim().length > 16) {
                    $(el).after(" <span class=\"redtip\">" + $(el).attr("msg") + "</span>");
                    flag = false;
                }
                break;
        }
    });

    $("select", $(containerid ? "#" + containerid : "$()")).each(function(index, el) {
        switch ($(el).attr("datatype")) {

            case "drpClass":
                $(".redtip", $(el).parent()).remove();
                if ($(el).val().trim() == "") {
                    $(el).after(" <span class=\"redtip\">" + $(el).attr("msg") + "</span>");
                    flag = false;
                }
                break;
        }
    });
    
    return flag;
};

var switchContact = function () {
    if ($("#contact_method").get(0).selectedIndex > 1) {
        $("#usr_msn").attr("datatype", "Require").attr("msg", "Data format is incorrect");
    }
    else {
        $("#usr_msn").attr("datatype", "Email").attr("msg", "Mail format is incorrect!");
    }
};

var mask = function(jobj, img) {
    var offset = jobj.offset();
    var xleft = offset.left;
    var xtop = offset.top;
    var xwidth = jobj.width();
    var xheight = jobj.height();
    if (!img) {
        img = "images/loading.gif";
    }

    var x_mask = $(String.format("#dv_mask_{0}", jobj.attr("id")));
    if (x_mask.length) {
        x_mask.remove();
    }
    else {
        var strMask = String.format("<div id=\"dv_mask_{0}\">loading...<br/><img src=\"{1}\" /></div>", jobj.attr("id"), img);
        jobj.after(strMask);
        x_mask = $(String.format("#dv_mask_{0}", jobj.attr("id")));
        x_mask.css("left", xleft).css("top", xtop).css("width", xwidth).css("height".xheight).css("z-index", "500").css("position", "absolute").css("background-color", "#fff"); //.css("filter", "Alpha(opacity=70);").css("opacity", "0.7");
    }
};

var json2str = function(o) {
    var arr = [];
    var fmt = function(s) {
        if (typeof s == 'object' && s != null) return json2str(s);
        return /^string$/.test(typeof s) ? "'" + s + "'" : s;
    }
    for (var i in o) arr.push(i + ":" + fmt(o[i]));
    return '{' + arr.join(',') + '}';
};

/*
### jQuery XML to JSON Plugin v1.0 - 2008-07-01 ###
* http://www.fyneworks.com/ - diego@fyneworks.com
* Dual licensed under the MIT and GPL licenses:
*   http://www.opensource.org/licenses/mit-license.php
*   http://www.gnu.org/licenses/gpl.html
###
Website: http://www.fyneworks.com/jquery/xml-to-json/
*/
/*
# INSPIRED BY: http://www.terracoder.com/
AND: http://www.thomasfrank.se/xml_to_json.html
AND: http://www.kawa.net/works/js/xml/objtree-e.html
*/
/*
This simple script converts XML (document of code) into a JSON object. It is the combination of 2
'xml to json' great parsers (see below) which allows for both 'simple' and 'extended' parsing modes.
*/
// Avoid collisions
; if (window.jQuery) (function($) {

    // Add function to jQuery namespace
    $.extend({

        // converts xml documents and xml text to json object
        xml2json: function(xml, extended) {
            if (!xml) return {}; // quick fail

            //### PARSER LIBRARY
            // Core function
            function parseXML(node, simple) {
                if (!node) return null;
                var txt = '', obj = null, att = null;
                var nt = node.nodeType, nn = jsVar(node.localName || node.nodeName);
                var nv = node.text || node.nodeValue || '';
                /*DBG*/ //if(window.console) console.log(['x2j',nn,nt,nv.length+' bytes']);
                if (node.childNodes) {
                    if (node.childNodes.length > 0) {
                        /*DBG*/ //if(window.console) console.log(['x2j',nn,'CHILDREN',node.childNodes]);
                        $.each(node.childNodes, function(n, cn) {
                            var cnt = cn.nodeType, cnn = jsVar(cn.localName || cn.nodeName);
                            var cnv = cn.text || cn.nodeValue || '';
                            /*DBG*/ //if(window.console) console.log(['x2j',nn,'node>a',cnn,cnt,cnv]);
                            if (cnt == 8) {
                                /*DBG*/ //if(window.console) console.log(['x2j',nn,'node>b',cnn,'COMMENT (ignore)']);
                                return; // ignore comment node
                            }
                            else if (cnt == 3 || cnt == 4 || !cnn) {
                                // ignore white-space in between tags
                                if (cnv.match(/^\s+$/)) {
                                    /*DBG*/ //if(window.console) console.log(['x2j',nn,'node>c',cnn,'WHITE-SPACE (ignore)']);
                                    return;
                                };
                                /*DBG*/ //if(window.console) console.log(['x2j',nn,'node>d',cnn,'TEXT']);
                                txt += cnv.replace(/^\s+/, '').replace(/\s+$/, '');
                                // make sure we ditch trailing spaces from markup
                            }
                            else {
                                /*DBG*/ //if(window.console) console.log(['x2j',nn,'node>e',cnn,'OBJECT']);
                                obj = obj || {};
                                if (obj[cnn]) {
                                    /*DBG*/ //if(window.console) console.log(['x2j',nn,'node>f',cnn,'ARRAY']);
                                    if (!obj[cnn].length) obj[cnn] = myArr(obj[cnn]);
                                    obj[cnn][obj[cnn].length] = parseXML(cn, true/* simple */);
                                    obj[cnn].length = obj[cnn].length;
                                }
                                else {
                                    /*DBG*/ //if(window.console) console.log(['x2j',nn,'node>g',cnn,'dig deeper...']);
                                    obj[cnn] = parseXML(cn);
                                };
                            };
                        });
                    }; //node.childNodes.length>0
                }; //node.childNodes
                if (node.attributes) {
                    if (node.attributes.length > 0) {
                        /*DBG*/ //if(window.console) console.log(['x2j',nn,'ATTRIBUTES',node.attributes])
                        att = {}; obj = obj || {};
                        $.each(node.attributes, function(a, at) {
                            var atn = jsVar(at.name), atv = at.value;
                            att[atn] = atv;
                            if (obj[atn]) {
                                /*DBG*/ //if(window.console) console.log(['x2j',nn,'attr>',atn,'ARRAY']);
                                if (!obj[atn].length) obj[atn] = myArr(obj[atn]); //[ obj[ atn ] ];
                                obj[atn][obj[atn].length] = atv;
                                obj[atn].length = obj[atn].length;
                            }
                            else {
                                /*DBG*/ //if(window.console) console.log(['x2j',nn,'attr>',atn,'TEXT']);
                                obj[atn] = atv;
                            };
                        });
                        //obj['attributes'] = att;
                    }; //node.attributes.length>0
                }; //node.attributes
                if (obj) {
                    obj = $.extend((txt != '' ? new String(txt) : {}), /* {text:txt},*/obj || {}/*, att || {}*/);
                    txt = (obj.text) ? (typeof (obj.text) == 'object' ? obj.text : [obj.text || '']).concat([txt]) : txt;
                    if (txt) obj.text = txt;
                    txt = '';
                };
                var out = obj || txt;
                //console.log([extended, simple, out]);
                if (extended) {
                    if (txt) out = {}; //new String(out);
                    txt = out.text || txt || '';
                    if (txt) out.text = txt;
                    if (!simple) out = myArr(out);
                };
                return out;
            }; // parseXML
            // Core Function End
            // Utility functions
            var jsVar = function(s) { return String(s || '').replace(/-/g, "_"); };
            var isNum = function(s) { return (typeof s == "number") || String((s && typeof s == "string") ? s : '').test(/^((-)?([0-9]*)((\.{0,1})([0-9]+))?$)/); };
            var myArr = function(o) {
                if (!o.length) o = [o]; o.length = o.length;
                // here is where you can attach additional functionality, such as searching and sorting...
                return o;
            };
            // Utility functions End
            //### PARSER LIBRARY END

            // Convert plain text to xml
            if (typeof xml == 'string') xml = $.text2xml(xml);

            // Quick fail if not xml (or if this is a node)
            if (!xml.nodeType) return;
            if (xml.nodeType == 3 || xml.nodeType == 4) return xml.nodeValue;

            // Find xml root node
            var root = (xml.nodeType == 9) ? xml.documentElement : xml;

            // Convert xml to json
            var out = parseXML(root, true /* simple */);

            // Clean-up memory
            xml = null; root = null;

            // Send output
            return out;
        },

        // Convert text to XML DOM
        text2xml: function(str) {
            // NOTE: I'd like to use jQuery for this, but jQuery makes all tags uppercase
            //return $(xml)[0];
            var out;
            try {
                var xml = ($.browser.msie) ? new ActiveXObject("Microsoft.XMLDOM") : new DOMParser();
                xml.async = false;
            } catch (e) { throw new Error("XML Parser could not be instantiated") };
            try {
                if ($.browser.msie) out = (xml.loadXML(str)) ? xml : false;
                else out = xml.parseFromString(str, "text/xml");
            } catch (e) { throw new Error("Error parsing XML string") };
            return out;
        }

    }); // extend $

})(jQuery);

var getPageName = function() {
    var d = window.location.href.toString();
    if (d.lastIndexOf("/") > -1) {
        d = d.substring(d.lastIndexOf("/") + 1, d.length);
    }
    if (d.lastIndexOf(".") > -1) {
        d = d.substring(0, d.lastIndexOf("."));
    }
    return d;
};

$().ready(function () {

    $('.topnav li').hover(function () {
        $(this).children('ul').stop(true, true).show();
    }, function () {
        $(this).children('ul').stop(true, true).hide();
    });
    if ($("#alpha_list").length) {
        var arr = [];
        for (var i = 65; i < 91; i++) {
            arr.push(String.format("<li>{0}</li>", String.fromCharCode(i)));
        }
        $("#alpha_list").html(arr.join(''));
        $("#alpha_list>li").click(function () {
            document.getElementById("frm_game").contentWindow.filter($(this).html());
        });
    }
    if ($(".menu-middle dl").length) {
        $("dd", $("a[d=h]", $(".menu-middle")).parent().parent()).hide();
    }
    //
    Main();
});

var expand = function(obj) {
    if (!$(obj).attr("d") || $(obj).attr("d") == "s") {
        $("dd", $(obj).parent().parent()).hide(300);
        $(obj).attr("d", "h");
    }
    else {
        $("dd", $(obj).parent().parent()).show(300);
        $(obj).attr("d", "s");
    }
};