﻿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 = 50000;
Site.iscustom = "";
Site.customamount = "";
Site.customprice = "";

var g_host = "http://" + window.location.host;

//
var user_login = function() {
    var usr_name = $("#user_login_name").val();
    var usr_pwd = $("#user_login_pwd").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, this user does not exist!");
                        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() {

                        $(".panel_3:first", $("#center")).hide();
                        $(".panel_3:last", $("#center")).show();

                        $(".right_3:first", $("#dv_user_panel")).hide();
                        $(".right_3:last", $("#dv_user_panel")).show();
                        
                        if ($("#customerid").length) {
                            $("#customerid").attr("innerHTML", $(this).find("CustomerID").text());  //.attr("title", usr.customerid)
                            $("#point").attr("innerHTML", $(this).find("IntegralValue").text());
                            $("#coupon").attr("innerHTML", $(this).find("CouponValue").text());
                        }
                        
                        if ($("#acc_customerid").length) {
                            $("#acc_customerid").attr("innerHTML", $(this).find("CustomerID").text());  //.attr("title", usr.customerid)
                            $("#acc_point").attr("innerHTML", $(this).find("IntegralValue").text());
                            $("#acc_coupon").attr("innerHTML", $(this).find("CouponValue").text());
                        }
                });
            }
        });
    }
};
var user_loginout = function() {
    $("#user_login_name").val("");
    $("#user_login_pwd").val("");

    $(".panel_3:first", $("#center")).show();
    $(".panel_3:last", $("#center")).hide();
    
    $(".right_3:first", $("#dv_user_panel")).show();
    $(".right_3:last", $("#dv_user_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) {
    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);
    }
    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 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(',') + '}';
};

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() {
    
    //
    //Main();
});
