/*
* ynhtm.com System Public Utils V1.0
*
* (C) 2011 XiaoDao
*/

Object.isString = function (obj) {
    return typeof (obj) == "string";
};
Object.isNumber = function (obj) {
    return typeof (obj) == "number";
};
Object.isBoolean = function (obj) {
    return typeof (obj) == "boolean";
};
Object.isFunction = function (obj) {
    return typeof (obj) == "function";
};
Object.isUndefined = function (obj) {
    return typeof (obj) == "undefined";
};

/* RegExp */
RegExp.encode = function (s) {
    return s.toString().replace(/(\\|\*|\+|\?|\||\{|\[|\(|\)|\^|\$|\.)/g, function ($0, $1) { return "\\" + $1; });
};

/* Date */
Date.prototype.format = function () {
    if (arguments.length == 0) return this.toLocaleString();
    var s = "";
    var pad = function (n) { if (n > 9) return n; return "0" + n; };
    var sys = function (h) { return h > 12 ? h - 12 : h; };
    var date = {
        "yy": this.getFullYear().toString().substr(2),
        "yyy": this.getFullYear().toString(),
        "yyyy": this.getFullYear().toString(),
        "M": (this.getMonth() + 1).toString(),
        "MM": pad(this.getMonth() + 1).toString(),
        "d": this.getDate().toString(),
        "dd": pad(this.getDate()).toString(),
        "h": sys(this.getHours()).toString(),
        "hh": pad(sys(this.getHours())).toString(),
        "H": this.getHours().toString(),
        "HH": pad(this.getHours()).toString(),
        "m": this.getMinutes().toString(),
        "mm": pad(this.getMinutes()).toString(),
        "s": this.getSeconds().toString(),
        "ss": pad(this.getSeconds()).toString()
    };
    $(arguments).each(function () { s += date[this.toString()] || this; });
    return s;
};

/* String */
String.trimValues = function (arr) {
    var s = "";
    $(arr).each(function () {
        if (s != "") s += "|";
        s += RegExp.encode(this);
    });
    return s;
};

$.extend(String.prototype, {
    trim: function () {
        if (arguments.length > 0) {
            var t = String.trimValues(arguments);
            return this.replace(new RegExp("^(" + t + ")+|(" + t + ")+$", "g"), "");
        }
        return this.replace(/^\s+|\s+$/g, "");
    },
    trimStart: function () {
        if (arguments.length > 0) {
            var t = String.trimValues(arguments);
            return this.replace(new RegExp("^(" + t + ")+", "g"), "");
        }
        return this.replace(/^\s+/g, "");
    },
    trimEnd: function () {
        if (arguments.length > 0) {
            var t = String.trimValues(arguments);
            return this.replace(new RegExp("(" + t + ")+$", "g"), "");
        }
        return this.replace(/\s+$/g, "");
    },
    htmlEncode: function () {
        var div = document.createElement("div");
        var text = document.createTextNode(this);
        div.appendChild(text);
        return div.innerHTML;
    },
    htmlEncode: function () {
        var element = document.createElement("DIV");
        var n = "textContent";
        if ("innerText" in element) n = "innerText";
        element[n] = this;
        var s = element.innerHTML;
        element = null;
        return s;
    },
    htmlDecode: function () {
        var element = document.createElement("DIV");
        var n = "textContent";
        if ("innerText" in element) n = "innerText";
        element.innerHTML = this;
        var s = element[n];
        element = null;
        return s;
    }
});

/* Cookie */
$.Cookie = {
    get: function (name, defaultValue) {
        var cookie = document.cookie;
        if (cookie.length > 0) {
            name += "=";
            var start = cookie.indexOf(name);
            if (start != -1) {
                start += name.length;
                var end = cookie.indexOf(";", start);
                if (end == -1) end = cookie.length;
                defaultValue = unescape(cookie.substring(start, end))
            }
        }
        return defaultValue;
    },
    set: function (name, value, expire) {
        var s = name + "=" + escape(value);
        if (expire) s += "; expires=" + expire.toGMTString();
        document.cookie = s;
    }
};

$.Url = {
    hasQuery: function (name, val) {
        if (location.search.length < 2) return false;
        var s = "(\\?|&)" + RegExp.encode(name) + "=";
        if (typeof (val) == "string") s += RegExp.encode(val) + "(&|$)";
        return new RegExp(s, "ig").exec(location.search) != null;
    },
    getQuery: function (name) {
        if (location.search.length < 2) return null;
        var s = "(\\?|&)" + RegExp.encode(name) + "=([^&]+)";
        var arr = new RegExp(s, "ig").exec(location.search);
        if (arr != null) return arr[2];
        return null;
    }
};

$.Authcode = {
    url: "/API/Authcode.ashx",
    refresh: function (clear) {
        $("img.authcode").attr("src", this.url + "?" + Math.random());
        if (clear) $("input.authcode").val("").focus();
    },
    create: function () {
        document.write('<img src="" onload="javascript:this.style.visibility = \'visible\';" align="absmiddle" width="80" height="26" class="authcode" style="visibility:hidden;" alt="验证码"/><br /><a href="" onclick="$.Authcode.refresh(true);return false;">看不清楚，换一张？</a>');
        $("input.authcode").one("focus", function () { $.Authcode.refresh(); });
    }
};

$.Msg = {
    speed: 500,
    time: 10000,
    container: "body",
    doShow: function () { },
    doHide: function () { },
    show: function (type, msg) {
        $(".msg").stop(true).hide();
        $(function () {
            $.Msg.doShow(this);
            $('<span class="msg"/>').css("opacity", 0).addClass(type).html(msg).appendTo($.Msg.container).fadeTo($.Msg.speed, 1).animate({ opacity: 1 }, $.Msg.time).fadeTo($.Msg.speed, 0, function () { $(this).hide(); $.Msg.doHide(this); });
        });
    },
    info: function (s) {
        this.show("info", s);
    },
    error: function (s) {
        this.show("error", s);
    },
    alert: function (s) {
        this.show("alert", s);
    },
    validationSummaryOnSubmit: function (validationGroup) {
        for (i = 0; i < Page_Validators.length; i++) {
            var control = Page_Validators[i];
            if (!control.isvalid && IsValidationGroupMatch(control, validationGroup)) {
                window.scroll(0, 0);
                $.Msg.error(control.errormessage);
                return true;
            }
        }
        return false;
    }
};

$.Validate = {
    isEmail: function (s) {
        if (!Object.isString(s)) return true;
        return s.match(/^[a-zA-Z0-9_]+([-+.'a-zA-Z0-9_]+)*@[a-zA-Z0-9_]+([-.a-zA-Z0-9_]+)*\.[a-zA-Z0-9_]+([-.a-zA-Z0-9_]+)*$/) != null;
    },
    isEmpty: function (s) {
        if (!Object.isString(s)) return true;
        return s.length == 0;
    },
    isWhiteSpace: function (s) {
        if (!Object.isString(s)) return true;
        return s.trim().length == 0;
    }
};

$.ajax.getData = function (context) {
    var data = new Object();
    $(":hidden[name],:text[name],:password[name],:checkbox[name]:checked,:radio[name]:checked,select[name],textarea[name]", $(context)).each(function () {
        data[this.name.toLowerCase()] = this.value;
    });
    return data;
};

$.Comment = {
    complete: function (result) {
        alert(result.Msg);
        if (result.Code == -1) $("[name='authcode']").val("");
        if (result.Code == 0) location.reload(false);
    },
    post: function (options) {
        options = $.extend({}, { complete: this.complete, context: document }, options);
        var data = $.ajax.getData(options.context);
        if (this.validate(data)) {
            $.ajax({
                url: "/API/Comment.ashx?Action=Post&Ajax=1",
                data: data,
                dataType: "json",
                error: function (request) {
                    alert(request.responseText);
                },
                success: options.complete
            });
        }
    },
    validate: function (data) {
        if ($.Validate.isWhiteSpace(data.content)) {
            alert("评论内容不能为空！");
            $("[name='content']").focus();
            return false;
        }
        return true;
    }
};

$.Job = {
    Try: {
        complete: function (result) {
            alert(result.Msg);
            if (result.Code == -1) $("[name='authcode']").val("");
            if (result.Code == 0) location.reload(false);
        },
        init: function (options) {
            options = $.extend({}, { frameID: "frame-post-form", complete: this.complete }, options);
            document.write('<iframe name="' + options.frameID + '" style="display:none;"></iframe>');
            $.Job.Try._complete = function (result) {
                options.complete.apply(options, [result]);
            };
            $(options.form).attr({ target: options.frameID, action: "/API/Job.ashx?Action=TryPost&Frame=1" }).submit(function () {
                return $.Job.Try.validate($.ajax.getData(this));
            });
        },
        validate: function (data) {
            if ($.Validate.isWhiteSpace(data.realname)) {
                alert("姓名不能为空！");
                $("[name='realname']").focus();
                return false;
            }
            if ($.Validate.isWhiteSpace(data.contact)) {
                alert("联系方式不能为空！");
                $("[name='contact']").focus();
                return false;
            }
            return true;
        }
    }
};

$.Popup = {
    onPopup: function (options) {
        var pos = $(options.anchor).offset();
        var height = $(options.anchor).outerHeight();
        var width = $(options.anchor).outerWidth();
        $(options.content).mousedown(function () { $(this).data("isDown", true); }).mouseup(function () { $(this).data("isDown", null); }).data("isDown", null).css({ position: "absolute", left: pos.left, top: pos.top + height, display: "inline-block" });
    },
    onHide: function (options) {
        var content = $(options.content);
        if (content.data("isDown") != true) content.css("display", "none");
    },
    show: function (options) {
        options = $.extend({}, { anchor: "$(body)", content: "", onPopup: this.onPopup, onHide: this.onHide }, options);
        options.onPopup(options);
        $(document).mousedown(function () { options.onHide(options); })
    }
};

$.OAuth = {
    qzoneLogin: function () {
        open("/API/OAuthQzone.ashx", "_blank", "width=450,height=320,menubar=0,scrollbars=0,resizable=1,status=0,titlebar=0,toolbar=0,location=1");
    }
};

$.User = {
    complete: function (result) {
        if (result.Code != 0) alert(result.Msg);
    },
    info: function (options) {
        options = $.extend({}, { complete: this.complete }, options);
        $.ajax({
            url: "/API/User.ashx?Action=Info",
            dataType: "json",
            error: function (request) {
                alert(request.responseText);
            },
            success: options.complete
        });
    },
    logout: function (options) {
        options = $.extend({}, { complete: function () { } }, options);
        $.get("/API/User.ashx?Action=Logout", options.complete);
    }
};