﻿/* 去除头尾空格 */
String.prototype.Trim = function () {
    return $.trim(this);
};

/* 移除Array中的元素 */
Array.prototype.Remove = function (dx) {
    if (isNaN(dx) || dx > this.length) { return false; }
    for (var i = 0, n = 0; i < this.length; i++) {
        if (this[i] != this[dx]) {
            this[n++] = this[i];
        }
    }
    this.length -= 1
};

/* 去除Array中重复的值 */
Array.prototype.Distinct = function () {
    for (var a = {}, i = 0; i < this.length; i++) {
        if (typeof (a[this[i]]) == "undefined") a[this[i]] = 1;
    }
    this.length = 0;
    for (i in a) this[this.length] = i; return this;
};

jQuery.extend({
    /*  cookie相关操作,参数：[name]cookie键名,[value]键值,[options]选项
    例：
    $.cookie('name', 'value'); //设置
    $.cookie('name', 'value', {expires: 7, path: '/', domain: 'jquery.com', secure: true}); //设置
    $.cookie('name', null); //删除
    var account= $.cookie('name'); //获取
    */
    cookie: function (name, value, options) {
        if (typeof value != 'undefined') {
            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 * 60 * 60 * 1000)); //hour
                } 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 = '';
            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));
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
    },

    /* 获取随机数 参数：[n]个数 */
    ran: function (n) {
        if (typeof n == 'undefined') { n = 10000; };
        return Math.floor(Math.random() * n + 1);
    },

    /* 获取指定范围随机数 参数：[min]范围最小值,[max]范围最大值 */
    ranRec: function (min, max) {
        return Math.floor(min + Math.random() * (max - min));
    },

    /* 四舍五入 参数：[input]传入的数值,[length]小数位数 */
    Round: function (input, length) { return ((input * 1).toFixed(length + 1) * 1).toFixed(length); },

    /* 获取URL中的参数值 参数：[name]键名,[urlPara]在指定的url字符中查找,不传入则从当前请求的url中查找 */
    QueryString: function (name, urlPara) {
        var quer = (typeof (urlPara) == "undefined") ? window.location.search.substr(1) : urlPara;
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = quer.match(reg);
        if (r != null) return r[2];
        return "";
    },

    /* checkbox相关操作 */
    CheckBox: {
        /* 全选 参数：[name]checkbox的name属性,[selected]选中状态 */
        SelAll: function (name, selected) {
            $("input[name=" + name + "]").each(function () { this.checked = selected; });
        },
        /* 反选 参数：[name]checkbox的name属性 */
        Inverse: function (name) {
            $("input[name=" + name + "]").each(function () { this.checked = !this.checked; });
        },
        /* 获选中的值,逗号分隔(例:1,3,8) 参数：[name]checkbox的name属性 */
        GetValue: function (name) {
            var values = "";
            $("input[name=" + name + "]").each(function () {
                if (this.checked) values += "," + this.value;
            });
            if (values != "") values = values.substr(1);
            return values;
        }
    },

    /* 动态添加select元素中的option 参数：[objSelect]待操作的select元素(JQ对象),[text]option显示文本,[value]option的值 */
    AddSelectItem: function (objSelect, text, value) {
        var item = new Option(text, value);
        objSelect[0].options.add(item);
    },

    /* 根据字节数获取相关显示单位 参数：[size]字节数 */
    GetSizeType: function (size) {
        if (size < 1024)
            return parseInt(size * 100) / 100 + "字节";
        if (size < 1048576)
            return parseInt((size / 1024) * 100) / 100 + "KB";
        if (size < 1073741824)
            return parseInt((size / 1048576) * 100) / 100 + "MB";
        return parseInt((size / 1073741824) * 100) / 100 + "GB";
    },

    /* 根据秒数获取时分秒数据 参数：[second]总秒数 函数返回对象：{ Day:天,Hour:小时,Min:分钟,Sec:秒 } */
    GetSecPart: function (second) {
        second = second * 1;
        var mday = 0; var mhour = 0; var mmin = 0; var msec = 0;
        if (second < 60) {
            msec = second;
        }
        else if (second < 3600) {
            mmin = parseInt(second / 60);
            msec = second % 60;
        }
        else if (second < 86400) {
            mhour = parseInt(second / 3600);
            var mod = second % 3600;
            if (mod > 60) {
                mmin = parseInt(mod / 60);
                msec = mod % 60;
            }
            else
                msec = mod;
        }
        else {
            mday = parseInt(second / 86400);
            var mod = second % 86400;
            mhour = parseInt(mod / 3600);
            mod = mod % 3600;
            if (mod > 60) {
                mmin = parseInt(mod / 60);
                msec = mod % 60;
            }
            else {
                msec = mmin;
                mmin = 0;
            }
        };
        var T = {
            Day: mday,
            Hour: mhour,
            Min: mmin,
            Sec: msec
        };
        return T;
    },

    /* 注册指定区域的回车事件 参数：[P]触发回车的区域(JQ对象),[Fun]回车后要运行的函数 或 指定铵钮(JQ对象)  */
    RegEnter: function (Panel, Fun) {
        if (Panel.length == 0) return;
        Panel.bind("keydown", function (event) {
            if (event.keyCode == 13) {
                if (typeof (Fun) == "function") Fun();
                else Fun.click();
            }
        });
    },

    /* 动态加载Script文件 参数：[src]文件地址,[id]指定加载到<script>标签的ID */
    loadScriptFile: function (src, id) {
        setTimeout(function () {
            if (typeof (id) == "undefined") id = "script_" + new Date().getTime();
            var objS = $("#" + id);
            if (objS.length > 0) objS.attr("src", src);
            else $("<script type='text/javascript' id=\"" + id + "\" src=\"" + src + "\"></script>").appendTo("head");
        }, 1);
    },

    /* 注册元素可拖动 参数：[dragObj]触发拖动的元素((JQ对象)),[moveObj]要移动的元素(JQ对象),[doc]要操作的document对象,不传入为当前document */
    RegDrag: function (dragObj, moveObj, doc) {
        doc = doc || document;
        dragObj.bind("mousedown", function (event) {
            if ($.browser.msie) moveObj[0].setCapture();
            else event.preventDefault();
            var ev = $.event.fix(event);
            var objOffset = moveObj.offset();
            var mouseTop = ev.pageY;
            var mouseLeft = ev.pageX;
            var dragFlag = true;
            var moveListener = function (event) {
                if (dragFlag) {
                    var ev = $.event.fix(event);
                    var top = ev.pageY - mouseTop;
                    var left = ev.pageX - mouseLeft;
                    moveObj.css("top", objOffset.top + top);
                    moveObj.css("left", objOffset.left + left);
                }
                return false;
            };
            var upListener = function (event) {
                dragFlag = false;
                if ($.browser.msie) moveObj[0].releaseCapture();
                $(doc).unbind("mousemove", moveListener);
                $(doc).unbind("mouseup", upListener);
            };
            $(doc).bind("mousemove", moveListener);
            $(doc).bind("mouseup", upListener);
        });
    },

    /* 跳转到指定url,为了在目标页中获取本页的url信息 参数：[url]目标url地址,[win]要操作的window对象,不传入为当前window */
    GotoUrl: function (url, win) {
        win = win || window;
        var fakeLink = win.document.createElement("a");
        if (typeof (fakeLink.click) == 'undefined') {
            win.location = url;
        } else {
            fakeLink.href = url;
            win.document.body.appendChild(fakeLink);
            fakeLink.click();
        }
    },
    /* 正则表达式相关验证 */
    ReV: {
        /* 可带正负号整数 */
        IsInt: function (value) {
            if (value.length > 9) return false;
            var reg = /^[\-+]?[0-9]\d*$/;
            return reg.test(value);
        },
        /* 大于零整数 */
        IsUInt: function (value) {
            if (value.length > 9) return false;
            var reg = /^[1-9]\d*$/;
            return reg.test(value);
        },
        /* 金额型,小数在两位以内或可省 */
        IsMoney: function (value) {
            var reg = /^\d+(\.\d{1,2})?$/;
            return reg.test(value);
        },
        /* 大于零浮点数 */
        IsUFloat: function (value) {
            var reg = /^\d+[.]?\d*$/;
            return reg.test(value);
        },
        /* 验证Email */
        IsEmail: function (email) {
            var reg = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-za-z]{2,4}|[0-9]{1,3})(\]?)$/;
            return reg.test(email);
        },
        /* 验证手机 */
        IsMobile: function (num) {
            var reg = /^0{0,1}(13[0-9]|15[0-9]|18[0-9])[0-9]{8}$/;
            return reg.test(num);
        },
        /* 验证电话 */
        IsTel: function (num) {
            var reg = /^\(?\d+[\.\-\)]?\d+$/g;
            return reg.test(num);
        },
        /* 验证邮编 */
        IsZip: function (num) {
            var reg = /^[1-9]\d{5}$/g;
            return reg.test(num);
        }
    }
});

jQuery.fn.extend({
    /*
    功能：指定区域普通Tab切换(Tab按钮对应内容区域显示)
    说明：
    1.同组Tab按钮，ID前缀需相同，如"tab_1","tab_2","tab_3"
    2.Tab按钮对应的内容区,ID规则为：固定前缀"c_"加上按钮ID,如"c_tab_1","c_tab_2","c_tab_3"
    3.样式规则说明：非当前样式，在原样式名前加"un",如：当前选中样式为"select"，非选中则应为"unselect",Tab按钮与内容区都一样
    4.函数所操作的对象，需包含Tab按钮与内容区
          
    参数：prefixID ID前缀,
    eventType 事件，默认为mouseover
    duration 同$().show()的特效参数
          
    调用示例：$("#tabBox").tab("tab_");
    $("#tabBox").tab("tab_","click");
    $("#tabBox").tab("tab_","mouseover","fast");
    */
    tab: function (prefixID, eventType, duration) {
        if (this.length == 0) return;
        if (prefixID == "") return;
        if (typeof (eventType) == "undefined" || eventType == null) eventType = "mouseenter";
        if (typeof (duration) == "undefined") duration = "";
        var tabBtns = this.find("[id^=" + prefixID + "]");
        var contents = this.find("[id^=c_" + prefixID + "]");
        tabBtns.each(function () {
            $(this).unbind(eventType);
            $(this).bind(eventType, function () {
                if (this.className.substr(0, 2) != "un") return;
                contents.each(function () {
                    $(this).hide();
                    this.className = this.className == "" ? "un" : (this.className.substr(0, 2) == "un" ? this.className : "un" + this.className);
                });
                var _content = $("#c_" + this.id);
                _content.show(duration);
                _content.attr("class", _content.attr("class").substr(2));

                tabBtns.each(function () {
                    this.className = this.className == "" ? "un" : (this.className.substr(0, 2) == "un" ? this.className : "un" + this.className);
                });
                this.className = this.className.substr(2);

                _content.find("img[hidesrc]").each(function () {
                    $(this).attr("src", $(this).attr("hidesrc"));
                    $(this).removeAttr("hidesrc");
                });
            });
        });
    },
    /*
    功能：Iframe式Tab切换(Tab按钮中的A标签href以Iframe显示在内容区，Tab按钮也可以是A标签 )
    说明：
    1.同组Tab按钮，ID前缀需相同，如"tab_1","tab_2","tab_3"
    2.对应内容区只有一个,ID规则为："c_"加上ID前缀,如"c_tab_"
    3.样式规则说明：非当前样式，在原样式名前加"un",如：当前选中样式为"select"，非选中则应为"unselect",只适用Tab按钮
    4.如不想参与tab切换的按钮，在A标签中加上 rel="untab"
    5.函数所操作的对象，需包含Tab按钮与内容区
          
    参数：prefixID ID前缀,
    eventType 事件，默认为click
          
    调用示例：
    $("#tabBox").tabI("tab_");
    $("#tabBox").tabI("tab_","mouseover");
    */
    tabI: function (prefixID, eventType) {
        if (this.length == 0) return;
        if (prefixID == "") return;
        if (typeof (eventType) == "undefined" || eventType == null) eventType = "click";
        var tabBtns = this.find("[id^=" + prefixID + "]");
        var contents = this.find("[id=c_" + prefixID + "]");
        var defaultHTML = contents.html();
        tabBtns.each(function () {
            var objBtn = this;
            var objA = null;
            if (this.tagName.toLowerCase() == "a") objA = $(this);
            else objA = $(this).find("a");
            if (objA.length == 0) return false;
            if (objA.attr("rel") == "untab") return false;
            objA.unbind(eventType);
            objA.bind(eventType, function () {
                tabBtns.each(function () {
                    this.className = this.className == "" ? "un" : (this.className.substr(0, 2) == "un" ? this.className : "un" + this.className);
                });
                objBtn.className = objBtn.className.substr(2);

                var href = $(this).attr("href");
                href = href.replace(/^http:\/\/[^\/]+\//i, "http://" + window.location.host + "/");

                if (href.toLowerCase() == "#default") {
                    contents.html(defaultHTML);
                }
                else {
                    contents.html("");
                    var waitObj = $("<div><span style='background:url(/images/loading.gif) no-repeat;padding-left:20px;height:15px;'>正在加载...</span></div>").appendTo(contents);
                    var iframe = contents.find("#" + prefixID + "iframe");
                    if (iframe.length > 0) iframe.attr("src", "about:blank");
                    iframe.remove();
                    iframe = $("<iframe width='100%' id='" + prefixID + "iframe' name='" + prefixID + "iframe' frameborder=0 marginwidth=0 frameSpacing=0 marginheight=0 noResize=true scrolling=no vspale=0 borderWidth='0px'></iframe>").appendTo(contents);
                    iframe.unbind("load");
                    iframe.bind("load", function () {
                        waitObj.remove();
                        iframe.height($(iframe[0].contentWindow.document).height() + 10);
                        //iframe.width($(iframe[0].contentWindow.document).width());
                    });
                    href += (href.indexOf("?") == -1 ? "?" : "&") + "t=" + (new Date().getTime());
                    iframe.attr("src", href);
                }
                return false;
            });
        });
    }

});

jQuery.Win = {
    CSS: {
        BgCSS: "WinBG",             //遮罩层DIV样式
        WinCSS: "WinBox",           //弹出窗口DIV样式
        TitleCSS: "WinTitle",       //标题DIV样式
        TitleCloseCSS: "WinClose",  //关闭按钮Span样式
        BodyCSS: "WinBody",         //内容区样式
        TitleHTML: "<span id='$winid$_btnClose' class='$TitleCloseCSS$'></span><div id=$winid$_Title></div>"//标题文本
    },
    ShowHTML: function (title, html, width, height, onclose, HasBg) {
        this.Show({ WinID: "AlertWin_TempHTML", Type: "html", Width: width, Height: height, Title: title, Para: html, OnClose: onclose, HasBg: HasBg });
    },
    ShowIframe: function (WinID, title, url, width, onclose, HasBg) {
        this.Show({ WinID: WinID, Type: "iframe", Width: width, Height: null, Title: title, Para: url, OnClose: onclose, HasBg: HasBg });
    },
    Show: function (winModel) {
        var winObj = $("#" + winModel.WinID + "_AlertWin");
        var isExist = (winObj.length > 0);
        var bgObj = $("#AlertWinBg");
        var titleObj = $("#" + winModel.WinID + "_TT");
        var bodyObj = $("#" + winModel.WinID + "_body");
        var titleTextObj = $("#" + winModel.WinID + "_Title");
        //bacakgroud
        if (winModel.HasBg) {
            if (bgObj.length == 0) bgObj = $("<div id='AlertWinBg' class='" + this.CSS.BgCSS + "'> </div>").appendTo("body");
            var bgResizeEvent = function () {
                bgObj.css("height", $(document).height() + ($.browser.msie ? -5 : 0));
            };
            bgResizeEvent();
            $(window).resize(bgResizeEvent);
            bgObj.show();
        }
        //winDIV
        if (winObj.length == 0)
            winObj = $('<div id="' + winModel.WinID + '_AlertWin" class="' + this.CSS.WinCSS + '" style="display:none"></div>').appendTo("body");
        if (winModel.Width) winObj.css("width", winModel.Width);
        if (winModel.Height) winObj.css("height", winModel.Height);
        //winTitle
        if (titleObj.length == 0) {
            titleObj = $('<div id="' + winModel.WinID + '_TT" class="' + this.CSS.TitleCSS + '"></div>').appendTo(winObj);
            titleObj.html(this.CSS.TitleHTML.replace(/\$winid\$/ig, winModel.WinID).replace(/\$TitleCloseCSS\$/ig, this.CSS.TitleCloseCSS));
        }
        //titleText
        if (titleTextObj.length == 0) {
            titleTextObj = $("#" + winModel.WinID + "_Title");
            $.RegDrag(titleTextObj, winObj);
        }
        titleTextObj.html(winModel.Title);
        //titleClose
        this.RegClose($("#" + winModel.WinID + "_btnClose"), bgObj, winObj, winModel.OnClose);
        //winBody
        if (bodyObj.length == 0)
            bodyObj = $('<div class="' + this.CSS.BodyCSS + '" id="' + winModel.WinID + '_body"></div>').appendTo(winObj);

        switch (winModel.Type.toLowerCase()) {
            case "iframe":
                var iframe = $("#iframe_" + winModel.WinID);
                if (iframe.length == 0)
                    iframe = $("<iframe width='99%' id='iframe_" + winModel.WinID + "' name='iframe_" + winModel.WinID + "' frameborder=0 marginwidth=0 frameSpacing=0 marginheight=0 noResize=true scrolling=no vspale=0 borderWidth='0px'></iframe>").appendTo(bodyObj);

                if ((iframe.attr("src") + "").toLowerCase() != winModel.Para.toLowerCase()) {
                    var waitObj = $("<div><span style='background:url(/images/loading.gif) no-repeat;padding-left:20px;height:15px;'>正在加载...</span></div>").prependTo(bodyObj);
                    iframe.unbind("load");
                    iframe.bind("load", function () {
                        titleTextObj.html(iframe[0].contentWindow.document.title);
                        waitObj.remove();
                        iframe.height($(iframe[0].contentWindow.document).height() + 10);
                        bodyObj.height(iframe.height() + 10);
                        winObj.height(bodyObj.height() + titleObj.height() + 50);
                        //iframe.width($(iframe[0].contentWindow.document).width());
                    });
                    iframe.attr("src", winModel.Para);
                } else {
                    titleTextObj.html(iframe[0].contentWindow.document.title);
                }
                break;
            default:
                bodyObj.html(winModel.Para);
                break;
        }
        //if (!isExist || winModel.Type.toLowerCase() != "iframe") {
            this.SetPos(winObj);
        //}

        winObj.fadeIn("fast");
    },
    Close: function (WinID) {
        if (typeof (WinID) == "undefined") WinID = "AlertWin_TempHTML";
        $("#" + WinID + "_btnClose").click();
    },
    RegClose: function (obj, bgObj, winObj, OnClose) {
        obj.unbind("click");
        obj.bind("click", function () {
            if (bgObj.length > 0) bgObj.hide();
            winObj.fadeOut("fast", OnClose);
        });
    },
    SetPos: function (winObj) {
        winObj.css({
            "position": "absolute",
            "top": (($(window).height() - winObj.height()) / 2 + $(window).scrollTop()) + "px",
            "left": (($(window).width() - winObj.width()) / 2 + $(window).scrollLeft()) + "px"
        });

    }
};
