﻿//
$().ready(function () {
    //Tracker();
    initAjaxLogding();
    initOrderInfo();
});

//行为分析记录
var Tracker = function () {
    var refurl = window.top.document.referrer;
    var cururl = window.location.href;
    var temp_refurl = refurl.split("/");
    var temp_cururl = cururl.split("/");
    if (refurl == "") {
        refurl = $("#hdnRefUrl").val();
    }
    var info = ClientInfo.getScreenInfo();
    if ($("#hdnGEOIP").length && $("#hdnGEOIP").val() == 0) {
        $.getScript("http://j.maxmind.com/app/geoip.js", function (data, txt) {            
            $.post("ashx/track.ashx", { "action": "clientinfo", "refurl": refurl, "cururl": cururl, "city": geoip_city(), "country": geoip_country_name(), "region": geoip_region_name(), "width": info.width, "height": info.height, "color": info.colorDepth, 'random': Math.random() }, function (data) {
                if (data) { }
            });
        });
    }
    else {        
        $.post("ashx/track.ashx", { "action": "clientinfo", "refurl": refurl, "cururl": cururl, "city": '', "country": '', "region": '', "width": info.width, "height": info.height, "color": info.colorDepth, 'random': Math.random() }, function (data) {
            if (data) { }
        });
    }
};

//获取浏览器信息
var ClientInfo = {
    getScreenInfo: function () {
        return { width: window.screen.width, height: window.screen.height, colorDepth: window.screen.colorDepth };
    }
};

//Ajax加载提示
var initAjaxLogding = function (prompt) {
    if (!prompt) prompt = "processing";
    $(String.format("<div class=\"dv_loading\"><img src=\"images/{0}\" /><p>please wait for {1} ...</p></div>", "loading.gif", prompt)).appendTo("body").css("left", ($(document).width() - $("div.dv_loading").width()) / 2 + "px").css("top", (screen.availHeight - 140 - $("div.dv_loading").height()) / 2 + $(document).scrollTop()).ajaxStart(function () {
        //
        $(this).css("left", ($(document).width() - $("div.dv_loading").width()) / 2 + "px").css("top", (screen.availHeight - 140 - $("div.dv_loading").height()) / 2 + $(document).scrollTop()).show();
    }).ajaxStop(function () {
        $(this).hide();
    });
};

//折扣码使用
var applycode = function (code, info, fn) {
    var discount = '';
    if (typeof code == 'object') {
        discount = $(code).val();
    }
    else {
        discount = code;
    }
    //
    if (discount.trim().length) {
        $.getJSON("ashx/code.ashx", { "action": "code", "code": discount, "gid": info.GameID, "sid": info.ProductType, 'random': Math.random() }, function (data) {
            data = eval(data);
            if (data.length) {
                var obj = data[0];
                if (obj.Game.indexOf("," + info.GameID + ",")) {
                    if (!obj.Refad) {
                        //来源广告不可以使用
                        if (obj.IsSearchEngine) {
                            alert("Invalid Code!");
                            if ($("#lbl_price").attr("title")) {
                                var price = $("#lbl_price").attr("title");
                                $("#lbl_price").html($(".sel_currency").attr("s") + " " + price);
                            }
                            $("#li_discount").empty();
                            $("#tb_discount").val("");
                            return;
                        }
                    }
                    if (obj.Refactive) {
                        //活动可以使用
                    }
                    var gold = 0;
                    var price = 0;
                    var point = 0;
                    var rpoint = 0;
                    var itemname = "";
                    if (obj.Appfixedgold) {
                        //附赠金币
                        gold += obj.Appfixedgold;
                    }
                    if (obj.Apprategold) {
                        //赠送百分比金币
                        gold += (info.Gold || 0) * obj.Apprategold * 0.01;
                    }
                    if (obj.Appratecash) {
                        //减免百分比现金
                        price = getDecimal(price + info.SalePrice * (obj.Appratecash * 0.01), 2);
                    }
                    if (obj.Appfixedcash) {
                        //减免固定现金
                        price = getDecimal(parseFloat(price) + parseFloat(obj.Appfixedcash), 2);
                    }
                    if (obj.Appfixedpoint) {
                        //固定积分 
                        point += obj.Appfixedpoint;
                    }
                    if (obj.Appratepoint) {
                        //百分比积分
                        rpoint += obj.Appfixedpoint;
                    }
                    if (obj.Appitem) {
                        itemname = obj.ItemName;
                    }                 
                    fn({ Invalid: 0, Gold: gold, Price: price, Point: point, Item: itemname, rPoint: rpoint, rCash: obj.Appratecash }, info);
                }
            }
            else {
                alert("Invalid Code!");
                fn({ Invalid: 1 }, info);
            }
        });
    }
    else {
        fn({ Invalid: 1 }, info);
    }
};

//初始化下单信息
var initOrderInfo = function () {
    if ($("div#loginon span#username").length && $("div#loginon span#username").html() != "") {
        //
        if ($("tr#freegold-tips").length) {
            $("tr#freegold-tips").hide();
        }
        //
        if ($("#tb_character").length) {
            $("#tb_character").val($("#hdnCharacter").val());
        }
        if ($("#tb_contact").length) {
            if ($("div#loginon span#username").length) {
                $("#tb_contact").val($("div#loginon span#username").text());
            }
        }
        if ($("#tb_phone").length) {
            $("#tb_phone").val($("#hdnTelephone").val());
        }
    }
//    else {
//        if ($.cookie('OrderInfo') != null) {
//            var OrderInfo = $.cookie('OrderInfo');
//            if ($("#hdnGameID").length) {
//                $("#hdnGameID").val(OrderInfo.split('|')[0]);
//            }
//            if ($("#hdnAlpha").length) {
//                $("#hdnAlpha").val(OrderInfo.split('|')[1]);
//            }
//            if ($("#hdnServerID").length) {
//                $("#hdnServerID").val(OrderInfo.split('|')[2]);
//            }
//            if ($("#hdnClassID").length) {
//                $("#hdnClassID").val(OrderInfo.split('|')[3]);
//                $("#sel_gameclass").val(OrderInfo.split('|')[3]);
//            }
//            if ($("#tb_character").length) {
//                $("#tb_character").val(OrderInfo.split('|')[4]);
//            }
//            if ($("#tb_contact").length) {
//                $("#tb_contact").val(OrderInfo.split('|')[5]);
//                $("#hdnContact").val(OrderInfo.split('|')[5]);
//            }
//            if ($("#tb_phone").length) {
//                $("#tb_phone").val(OrderInfo.split('|')[6]);
//            }
//            if ($("#tb_code").length) {
//                $("#tb_code").val(OrderInfo.split('|')[7] == "undefined" ? "" : OrderInfo.split('|')[7]);
//                $("#hdnCode").val(OrderInfo.split('|')[7] == "undefined" ? "" : OrderInfo.split('|')[7]);
//            }
//            if ($("#hdnLastQuantity").length) {
//                $("#hdnLastQuantity").val(OrderInfo.split('|')[8]);
//            }
//            //
//            if ($("div.gold_panel").length) {
//                if ($("#sel_alpha").length) {
//                    //
//                    _gold = new goldclass();
//                    _gold.changeGame();
//                }
//            }
//        }
//    }
};

//
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(" <label class=\"redtip\">" + $(el).attr("msg") + "</label>");
                    flag = false;
                }
                break;
            case "email":
                $(".redtip", $(el).parent()).remove();
                if (!/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/.test($(el).val())) {
                    $(el).after(" <label class=\"redtip\">" + $(el).attr("msg") + "</label>");
                    flag = false;
                }
                break;
            case "repeat":
                $(".redtip", $(el).parent()).remove();
                if ($("#" + $(el).attr("to")).val() != $(el).val()) {
                    $(el).after(" <label class=\"redtip\">" + $(el).attr("msg") + "</label>");
                    flag = false;
                }
                break;
            case "number":
                $(".redtip", $(el).parent()).remove();
                if (!/^\d+$/.test($(el).val())) {
                    $(el).after(" <label class=\"redtip\">" + $(el).attr("msg") + "</label>");
                    flag = false;
                }
                break;
            case "phone":
                $(".redtip", $(el).parent()).remove();
                if (!/^[0-9()\-]+$/.test($(el).val())) {
                    $(el).after(" <label class=\"redtip\">" + $(el).attr("msg") + "</label>");
                    flag = false;
                }
                break;
            case "password":
                $(".redtip", $(el).parent()).remove();
                if (!/^[a-zA-Z0-9_]{6,15}$/.test($(el).val())) {
                    $(el).after(" <label class=\"redtip\">" + $(el).attr("msg") + "</label>");
                    flag = false;
                }
                break;
            case "decimal":
                $(".redtip", $(el).parent()).remove();
                if (!/^\d+(\.)?(\d{1,3})?$/.test($(el).val())) {
                    $(el).after(" <label class=\"redtip\">" + $(el).attr("msg") + "</label>");
                    flag = false;
                }
                break;
            case "date":
                $(".redtip", $(el).parent()).remove();
                if (!/^(\d{1,2})([-\.])(\d{1,2})\2((\d{4})|(\d{2}))$/.test($(el).val())) {
                    $(el).after(" <label class=\"redtip\">" + $(el).attr("msg") + "</label>");
                    flag = false;
                }
                break;
        }
        //
        if ($(el).attr("maxlength") > -1) {
            if ($(el).val().length > parseInt($(el).attr("maxlength"))) {
                $(el).after(" <label class=\"redtip\">" + $(el).attr("msg") + "</label>");
                flag = false;
            };
        }
        if ($(el).attr("minlength") > -1) {
            if ($(el).val().length < parseInt($(el).attr("minlength"))) {
                $(el).after(" <label class=\"redtip\">" + $(el).attr("msg") + "</label>");
                flag = false;
            };
        }
        if ($(el).attr("max") > -1) {
            if (parseFloat($(el).val()) > parseFloat($(el).attr("max"))) {
                $(el).after(" <label class=\"redtip\">" + $(el).attr("msg") + "</label>");
                flag = false;
            };
        }
        if ($(el).attr("min") > -1) {
            if (parseFloat($(el).val()) < parseFloat($(el).attr("min"))) {
                $(el).after(" <label class=\"redtip\">" + $(el).attr("msg") + "</label>");
                flag = false;
            };
        }
    });

    $("select", $(containerid ? "#" + containerid : "$()")).each(function (index, el) {
        switch ($(el).attr("datatype")) {
            case "mustselect":
                $(".redtip", $(el).parent()).remove();
                if ($(el).val().trim() == "") {
                    $(el).after(" <label class=\"redtip\">" + $(el).attr("msg") + "</label>");
                    flag = false;
                }
                break;
        }
    });

    $("textarea", $(containerid ? "#" + containerid : "$()")).each(function (index, el) {
        switch ($(el).attr("datatype")) {
            case "require":
                $(".redtip", $(el).parent()).remove();
                if ($(el).val().trim() == "") {
                    $(el).after(" <label class=\"redtip\">" + $(el).attr("msg") + "</label>");
                    flag = false;
                }
                break;
        }
    });

    return flag;
};

//
$.fn.dialogx = function (info, width) {
    $(this).addClass("floatBoxBg").css({ "height": $(document).height() }).after("<div id=\"floatBox\">" + info + "</div>").show();
    //
    if ($(".order_form").length) {
        $(".order_form select").hide();
    }
    if ($("#selGameClass").length) {
        $("#selGameClass").hide();
    }
    //
    var obj = $("#floatBox");
    obj.css({ "width": width });
    var t = (Event.height() / 2) - (obj.height() / 2);
    t = t < 10 ? 10 : t;
    obj.css({ "left": ($(document).width() / 2) - (obj.width() / 2), "top": (t + Event.top()) });
    if (!$().draggable) {
        $.getScript('http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js', function () {
            obj.draggable();
        });
    }
    else {
        obj.draggable();
    }
};

//
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;
};

//
Object.extend = function (destination, source) {
    for (var property in source)
        destination[property] = source[property];
    return destination;
};

Object.extend(Date.prototype, {
    format: function (format) {
        var o = {
            "M+": this.getMonth() + 1, //month   
            "d+": this.getDate(),    //day   
            "h+": this.getHours(),   //hour   
            "m+": this.getMinutes(), //minute   
            "s+": this.getSeconds(), //second   
            "q+": Math.floor((this.getMonth() + 3) / 3), //quarter   
            "S": this.getMilliseconds() //millisecond   
        }
        if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
     (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o) if (new RegExp("(" + k + ")").test(format))
            format = format.replace(RegExp.$1,
       RegExp.$1.length == 1 ? o[k] :
         ("00" + o[k]).substr(("" + o[k]).length));
        return format;
    }
});

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 json2str = function (o) {
    var arr = [];
    var fmt = function (s) {
        if (typeof s == 'object' && s != null) return json2str(s);
        if (/^(string|number)$/.test(typeof s)) {
            if (/^(string)$/.test(typeof s)) {
                return "'" + s.replace(/\'/g, "&#039;") + "'";
            }
            else {
                return "'" + s + "'";
            }
        }
        else { return s; }
    }
    for (var i in o) arr.push("'" + i + "':" + fmt(o[i]));
    return '{' + arr.join(',') + '}';
};

//
var FormatTime = function (number) {
    var result = "0 hours";
    var days = 0;
    var hours = 0;
    if (number > 24) {
        days = Math.floor(number / 24);
        hours = number % 24;
        if (hours != 0) {
            result = Math.round(days, 1) + " days " + Math.round(hours, 1) + " hours";
        }
        else {
            result = Math.round(days, 1) + " days";
        }
    }
    else {
        result = Math.round(number, 1) + " hours";
    }

    return result;
};

//
var Event = function () {
    return {
        top: function () { return document.body.scrollTop || document.documentElement.scrollTop },
        width: function () { return self.innerWidth || document.documentElement.clientWidth },
        height: function () { return self.innerHeight || document.documentElement.clientHeight }
    }
} ();

//
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();
};

var createBlankForm = function (obj, url) {
    var submitForm = document.createElement("FORM");
    document.body.appendChild(submitForm);
    submitForm.method = "POST";
    submitForm.target = "_blank";
    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();
};

//
var getDecimal = function (input, digit) {  
    return parseFloat(input).toFixed(digit);
};

//
var getInt = function (input) {
    var str = input.toString();
    return Math.round(str);
};

//
var set_thumbs = function (obj, W, H) {
    $(obj + ' img').each(function () {
        var w, h;
        var cw = $(this).width();
        var ch = $(this).height();
        if (cw > W && ch > H) {
            if ((W / H) >= (cw / ch)) {
                w = H * cw / ch;
                h = H;
            } else {
                w = W;
                h = W * ch / cw
            }
        }
        else {
            w = cw;
            h = ch;
        }
        $(this).css({'width':w , 'height': h});
        $(this).show();
    });
};

//
jQuery.cookie = function (name, value, options) {
    if (typeof value != 'undefined') {
        options = options || {};
        if (value === null) {
            value = '';
            options = $.extend({}, options);
            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();
        }
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else {
        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]);
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

//
var flashColor = function (obj, color_font, color_flash, timeout) {
    if ($(obj)) {
        if ($(obj).attr('class') == color_font) {
            $(obj).removeClass(color_font).addClass(color_flash);
        }
        else {
            $(obj).removeClass(color_flash).addClass(color_font);
        }
    }
    //
    setTimeout("flashColor('" + obj + "', '" + color_font + "', '" + color_flash + "', '" + timeout + "')", timeout);
}
