﻿

var Common = {};

//定义命名空间,需要先引用jquery类库
$.ns = function() {
    var o, d;
    var args = $.makeArray(arguments);
    $.each(args, function(i, v) {
        d = v.split(".");
        o = window[d[0]] = window[d[0]] || {};
        $.each(d.slice(1), function(j, v2) {
            o = o[v2] = o[v2] || {};
        });
    });
    return o;
}
/*  示例 
$.ns('YanQSoft.Common')
*/

//定义工具类的命名空间
$.ns('Common');




//------------------String类扩展------------------------
//字符串格式化处理
String.prototype.format = function() {
    var args = $.makeArray(arguments);
    return this.replace(/\{(\d+)\}/g, function(m, i) {
        return args[i];
    });
}
//去左空格
String.prototype.ltrim = function() {
    return this.replace(/^\s*/, "");
}
//去右空格; 
String.prototype.rtrim = function() {
    return this.replace(/\s*$/, "");
}
//去左右空格;
String.prototype.trim = function() {
    return this.rtrim().ltrim();
}
//------------------End String类扩展---------------------




//------------------时间类扩展格式化---------------------------
//new Date().format("yyyy-MM-dd");
//new Date("january 12 2008 11:12:30").format("yyyy-MM-dd hh:mm:ss");
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;
}
//------------------End 时间格式化---------------------------




//------------------Select 控件操作类------------------------

Common.Select = {};

//绑定Araay数据源(source为数据源，cmd为下拉框jqury对象，value为数据源中每项的作为value值的属性名，text为数据源中每项的作为text值的属性名)
Common.Select.bindSource = function(source, cmd, value, text) {
    if (value == undefined || value == "") { value = "key"; }
    if (text == undefined || text == "") { text = "value"; }
    cmd[0].options.length = 0;
    // cmd[0].options.add(new Option("", ""));
    for (var i = 0; i < source.length; i++) {
        var varItem = new Option(source[i][text], source[i][value]);
        cmd[0].options.add(varItem);
    }
}

//判断select选项中 是否存在Value="paraValue"的Item   
Common.Select.selectIsExitItem = function(objSelect, objItemValue) {
    var isExit = false;
    for (var i = 0; i < objSelect.options.length; i++) {
        if (objSelect.options[i].value == objItemValue) {
            isExit = true;
            break;
        }
    }
    return isExit;
}

// 向select选项中 加入一个Item        
Common.Select.addItemToSelect = function(objSelect, objItemText, objItemValue) {
    var varItem = new Option(objItemText, objItemValue);
    objSelect.options.add(varItem);
}
//从select选项中 删除一个value值为objItemValue的Item
Common.Select.removeItemFromSelect = function(objSelect, objItemValue) {
    for (var i = 0; i < objSelect.options.length; i++) {
        if (objSelect.options[i].value == objItemValue) {
            objSelect.options.remove(i);
            break;
        }
    }
}
//删除select中选中的项
Common.Select.removeSelectedItemFromSelect = function(objSelect) {
    var length = objSelect.options.length - 1;
    for (var i = length; i >= 0; i--) {
        if (objSelect[i].selected == true) {
            objSelect.options[i] = null;
        }
    }
}

//修改select选项中 value="paraValue"的text为"paraText"
Common.Select.updateItemToSelect = function(objSelect, objItemText, objItemValue) {
    for (var i = 0; i < objSelect.options.length; i++) {
        if (objSelect.options[i].value == objItemValue) {
            objSelect.options[i].text = objItemText;
            break;
        }
    }
}
//设置select中text="paraText"的第一个Item为选中
Common.Select.selectItemByText = function(objSelect, objItemText) {
    for (var i = 0; i < objSelect.options.length; i++) {
        if (objSelect.options[i].text == objItemText) {
            objSelect.options[i].selected = true;
            break;
        }
    }
}

//设置select中value="paraText"的第一个Item为选中
Common.Select.selectItemByValue = function(objSelect, objItemValue) {
    objSelect.value = objItemValue;
}

//得到select的当前选中项的value
Common.Select.currSelectValue = function(objSelect) {
    return objSelect.value;
}

//得到select的当前选中项的text
Common.Select.currSelectText = function(objSelect) {
    return objSelect.options[document.all.objSelect.selectedIndex].text;
}
//得到select的当前选中项的Index
Common.Select.currSelectIndex = function(objSelect) {
    return objSelect.selectedIndex;
}

//清空select的项
Common.Select.clear = function(objSelect) {
    objSelect.options.length = 0;
}
//$('#cmdSelect option:selected');
//$('#cmdSelect option:selected').text();
//------------------End Select 控件操作类--------------------





//------------------效验类-----------------------------------
Common.ChkUtil = {};

//校验是否为空(先删除二边空格再验证)
Common.ChkUtil.isNull = function(str) {
    if (null == str || "" == str.trim()) {
        return true;
    } else {
        return false;
    }
};
//校验是否全是数字
String.prototype.isDigit = function() {
    var patrn = /^\d+$/;
    return patrn.test(this);
};
//校验是否是整数
String.prototype.isInteger = function () {
    var patrn = /^([+-]?)(\d+)$/;
    return patrn.test(this);
};
//校验是否为正整数
String.prototype.isPlusInteger = function () {
    var patrn = /^([+]?)(\d+)$/;
    return patrn.test(this);
};
//校验是否为负整数
String.prototype.isMinusInteger = function () {
    var patrn = /^-(\d+)$/;
    return patrn.test(this);
};
//校验是否为浮点数
String.prototype.isFloat = function () {
    var patrn = /^([+-]?)\d+(\.\d+)?$/;
    return patrn.test(this);
};
//校验是否为正浮点数
String.prototype.isPlusFloat = function () {
    var patrn = /^([+]?)\d+(\.\d+)?$/;
    return patrn.test(this);
};
//校验是否为负浮点数
String.prototype.isMinusFloat = function () {
    var patrn = /^-\d+(\.\d+)?$/;
    return patrn.test(this);
};
//校验是否为最多2位小数点的正小数
String.prototype.isPlusTwoFiguresFloat = function () {
    var patrn = /^([+]?)(\d+)(\.\d{1,2})?$/;
    return patrn.test(this);
}
//校验是否为最多4位小数点的正小数
String.prototype.isPlusFourFiguresFloat = function () {
    var patrn = /^([+]?)(\d+)(\.\d{1,4})?$/;
    return patrn.test(this);
}

//校验是否仅中文
String.prototype.isChinese = function () {
    var patrn = /[\u4E00-\u9FA5\uF900-\uFA2D]+$/;
    return patrn.test(this);
};
//校验是否仅ACSII字符
String.prototype.isAcsii = function () {
    var patrn = /^[\x00-\xFF]+$/;
    return patrn.test(this);
};
//校验QQ
String.prototype.isQqnum = function () {
    var patrn = /^[1-9]\d{4,12}$/;
    return patrn.test(this);
};
//校验手机号码
String.prototype.isMobile = function () {
    var patrn = /^0?1(3|5|8){1}[0-9]{9}$/;
    return patrn.test(this);
};
//校验电话号码
String.prototype.isPhone = function () {
    var patrn = /^(0[\d]{2,3}-)?\d{6,8}(-\d{3,4})?$/;
    return patrn.test(this);
};
//校验URL地址
String.prototype.isUrl = function () {
    var patrn = /^http[s]?:\/\/[\w-]+(\.[\w-]+)+([\w-\.\/?%&=]*)?$/;
    return patrn.test(this);
};
//校验电邮地址
String.prototype.isEmail = function () {
    var patrn = /^[.\w-]+@[\w-]+(\.[\w-]+)+$/;
    return patrn.test(this);
};
//校验邮编
String.prototype.isZipCode = function () {
    var patrn = /^\d{6}$/;
    return patrn.test(this);
};
//校验纯字母或数字
String.prototype.isNumOrZm = function () {
    var patrn = /^[A-Za-z]+$|^\d+$/;
    return patrn.test(this);
}

//校验合法时间
String.prototype.isDate = function (str) {
    if (!/\d{4}(\.|\/|\-)\d{1,2}(\.|\/|\-)\d{1,2}/.test(this)) {
        return false;
    }
    var r = this.match(/\d{1,4}/g);
    if (r == null) { return false; };
    var d = new Date(r[0], r[1] - 1, r[2]);
    return (d.getFullYear() == r[0] && (d.getMonth() + 1) == r[1] && d.getDate() == r[2]);
};
//校验字符串：只能输入6-20个字母、数字、下划线(常用手校验用户名和密码)
String.prototype.isString6_20 = function () {
    var patrn = /^(\w){6,20}$/;
    return patrn.test(this);
};

String.prototype.isLegal = function () {
    var patrn = /^[\w-]+$/;
    return patrn.test(this);
};
//------------------End 效验类-----------------------------------


//------------------Ajax 操作类-----------------------------------------
Common.Ajax = {};
Common.Ajax.invoke = function(wsUrl, params, successMethod, errorMethod, context) {
    $.ajax({
        type: "POST",
        contentType: "application/json",
        url: wsUrl,
        data: params,         //這裏是要傳遞的參數，格式爲 data: "{paraName:paraValue}",下面將會看到       
        dataType: 'json',
        success: function(result) {
            successMethod(result.d, context);
        },
        error: function(e) {
            errorMethod(e, context);
        }
    });
}
//------------------End Ajax 操作类-------------------------------------

//-----------------排序功能---------------------------------------------

Common.BubbleSort = function(arr) { //交换排序->冒泡排序
    var st = new Date();
    var temp;
    var exchange;
    for (var i = 0; i < arr.length; i++) {
        exchange = false;
        for (var j = arr.length - 2; j >= i; j--) {
            if ((arr[j + 1]) < (arr[j])) {
                temp = arr[j + 1];
                arr[j + 1] = arr[j];
                arr[j] = temp;
                exchange = true;
            }
        }
        if (!exchange) break;
    }
    status = (new Date() - st) + ' ms';
    return arr;
}

//-----------------排序功能---------------------------------------------

//-----------------转换功能---------------------------------------------
/* extension of JSON, type for jQuery
* AUTHOR: xushengs@gmail.com
* LICENSE: http://www.opensource.org/licenses/mit-license.php
* WEBSITE: http://ooboy.net/
*/
(function($) {
    // the code of this function is from 
    // http://lucassmith.name/pub/typeof.html
    $.type = function(o) {
        var _toS = Object.prototype.toString;
        var _types = {
            'undefined': 'undefined',
            'number': 'number',
            'boolean': 'boolean',
            'string': 'string',
            '[object Function]': 'function',
            '[object RegExp]': 'regexp',
            '[object Array]': 'array',
            '[object Date]': 'date',
            '[object Error]': 'error'
        };
        return _types[typeof o] || _types[_toS.call(o)] || (o ? 'object' : 'null');
    };
    // the code of these two functions is from mootools
    // http://mootools.net
    var $specialChars = { '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"': '\\"', '\\': '\\\\' };
    var $replaceChars = function(chr) {
        return $specialChars[chr] || '\\u00' + Math.floor(chr.charCodeAt() / 16).toString(16) + (chr.charCodeAt() % 16).toString(16);
    };
    $.toJSON = function(o) {
        var s = [];
        switch ($.type(o)) {
            case 'undefined':
                return 'undefined';
                break;
            case 'null':
                return 'null';
                break;
            case 'number':
            case 'boolean':
            case 'date':
            case 'function':
                return o.toString();
                break;
            case 'string':
                return '"' + o.replace(/[\x00-\x1f\\"]/g, $replaceChars) + '"';
                break;
            case 'array':
                for (var i = 0, l = o.length; i < l; i++) {
                    s.push($.toJSON(o[i]));
                }
                return '[' + s.join(',') + ']';
                break;
            case 'error':
            case 'object':
                for (var p in o) {
                    s.push(p + ':' + $.toJSON(o[p]));
                }
                return '{' + s.join(',') + '}';
                break;
            default:
                return '';
                break;
        }
    };
    $.evalJSON = function(s) {
        if ($.type(s) != 'string' || !s.length) return null;
        return eval('(' + s + ')');
    };
})(jQuery);

Common.Convert = {};
Common.Convert.deep_clone = function(obj) {
    eval("var tmp = " + Common.Convert.toJSON(obj));
    return tmp;
}
Common.Convert.toJSON = function(obj) {
    return $.toJSON(obj);
}
//-----------------End 装换功能-----------------------------------------


Common.STATE = {};
Common.STATE.VIEW = 1;
Common.STATE.ADD = 2;
Common.STATE.EDIT = 3;
Common.STATE.NODEFINE = 4;



/* 
* 用来遍历指定对象所有的属性名称和值 
* obj 需要遍历的对象 
* author: Jet Mah 
* website: http://www.javatang.com/archives/2006/09/13/442864.html  
*/
Common.allPrpos = function(obj) {
    // 用来保存所有的属性名称和值 
    var props = new Array();
    // 开始遍历 
    for (var p in obj) {
        // 方法 
        if (typeof (obj[p]) == "function") {
        } else {
            // p 为属性名称，obj[p]为对应属性的值
            props.push(p);
        }
    }
    // 最后显示所有的属性
    return props;
}
//弹出层
Common.tipsWindown = function(divID, width, hight, title) {
    if (width == undefined) {
        width = 600;
    }
    if (hight == undefined) {
        hight = 350;
    }
    if (title == undefined) {
        title = "";
    }
    tipsWindown(title, $('#' + divID), width, hight, "true", "", "true", "msg", false);
}
//序列化 Author:weny
Common.serialization = function(value) {
    var Parameters = $.param(value);
    var obj = {};
    obj.Parameters = Parameters;
    return Common.Convert.toJSON(obj);
}

//清空tbody(tableid 为TABLEID，colums为列数)
Common.clearTable = function(tableid, colums) {
    var tbody = $("#" + tableid + " tbody").html("");
    var str = "<tr class='tdbg' align='center' style='height: 100px;'>";
    str += "<td colspan='" + colums + "'>{0}</td></tr>";
    var tr = $(str.format('  暂无任何数据！'));
    tbody.append(tr);
}


Common.setReadWrite = function(obj) {
    obj.attr('disabled', '');
    obj.attr('readOnly', '');
    obj.removeClass();
    obj.addClass('borderInput2');
}

Common.setReadOnly = function(obj) {
    obj.attr('readOnly', 'readonly');
    obj.removeClass();
    obj.addClass('borderInput');
}

Common.setVisible = function(obj) {
    obj.attr('disabled', 'disabled');
    obj.removeClass();
    obj.addClass('borderInput');
}

//绑定文本框在各种事件中的样式  Author:weny
Common.ExtendedPrettifyButton = function(textBoxID) {
    var inputObj = $('#' + textBoxID);
    inputObj.focus(function() {
        this.isfocus = true;
        var me = $(this);
        me.removeClass();
        me.addClass('inputtext_focus');
    }).mouseover(function() {
        if (!this.isfocus) {
            var me = $(this);
            me.removeClass();
            me.addClass('inputtext_hover');
        }
    }).blur(function() {
        this.isfocus = false;
        var me = $(this);
        me.removeClass();
        me.addClass('inputtext');
    }).mouseout(function() {
        if (!this.isfocus) {
            var me = $(this);
            me.removeClass();
            me.addClass('inputtext');
        }
    });
}


if (jQuery) {
    jQuery(function() {
        jQuery(':button').addClass("inputbutton").hover(function() {
            jQuery(this).addClass('inputbutton_hover');
        }, function() {
            jQuery(this).removeClass('inputbutton_hover');
        });

    });
}

Common.getScrollTop = function() {
    var scrollPos = 0;
    if (typeof window.pageYOffset != 'undefined') {
        scrollPos = window.pageYOffset;
    }
    else if (typeof window.document.compatMode != 'undefined' && window.document.compatMode != 'BackCompat') {
        scrollPos = window.document.documentElement.scrollTop;
    }
    else if (typeof window.document.body != 'undefined') {
        scrollPos = window.document.body.scrollTop;
    }
    return scrollPos;
}
Common.getScrollLeft = function() {
    var scrollPos = 0;
    if (typeof window.pageYOffset != 'undefined') {
        scrollPos = window.pageYOffset;
    }
    else if (typeof window.document.compatMode != 'undefined' && window.document.compatMode != 'BackCompat') {
        scrollPos = window.document.documentElement.scrollLeft;
    }
    else if (typeof window.document.body != 'undefined') {
        scrollPos = window.document.body.scrollLeft;
    }
    return scrollPos;
}
//类哈希表
function Hashtable() {
    this._hash = new Object();
    this.add = function(key, value) {
        if (typeof (key) != "undefined") {
            if (this.contains(key) == false) {
                this._hash[key] = typeof (value) == "undefined" ? null : value;
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
    this.remove = function(key) { delete this._hash[key]; }
    this.count = function() {
        var i = 0;
        for (var k in this._hash) {
            i++;
        }
        return i;
    }
    this.keys = function() {
        var arr = new Array();
        for (var k in this._hash) {
            arr.push(k);
        }
        return arr;
    }
    this.values = function() {
        var arr = new Array();
        for (var k in this._hash) {
            arr.push(this.items(k));
        }
        return arr;
    }
    this.items = function(key) { return this._hash[key]; }
    this.contains = function(key) { return typeof (this._hash[key]) != "undefined"; }
    this.clear = function() { for (var k in this._hash) { delete this._hash[k]; } }
    this.tostring = function() { var output = ""; for (var k in this._hash) { if (output) output += "&"; output += k + ":" + this._hash[k]; } return output; }
}

function AddFavorite(url, name) {
    if (document.all) {
        window.external.addFavorite(url, name);
    }
    else if (window.sidebar) {
        window.sidebar.addPanel(name, url, "");
    }
}



/*---------------------------
功能:停止事件冒泡
---------------------------*/
function stopBubble(e) {
    //如果提供了事件对象，则这是一个非IE浏览器
    if (e && e.stopPropagation)
    //因此它支持W3C的stopPropagation()方法
        e.stopPropagation();
    else
    //否则，我们需要使用IE的方式来取消事件冒泡
        window.event.cancelBubble = true;
}
//阻止浏览器的默认行为
function stopDefault(e) {
    //阻止默认浏览器动作(W3C)
    if (e && e.preventDefault)
        e.preventDefault();
    //IE中阻止函数器默认动作的方式
    else
        window.event.returnValue = false;
    return false;
}

Math.round2 = function (num, figures) {
    switch (figures) {
        case 2:
            strNum = (num + 0.005).toString();
            if (strNum.indexOf('.') >= 0 && strNum.length - strNum.indexOf('.') - 1 > 2) {
                strNum = strNum.substring(0, strNum.indexOf('.') + 1 + 2)
            }
            num = parseFloat(strNum);
            break;
        case 4:
            strNum = (num + 0.00005).toString();
            if (strNum.indexOf('.') >= 0 && strNum.length - strNum.indexOf('.') - 1 > 4) {
                strNum = strNum.substring(0, strNum.indexOf('.') + 1 + 4)
            }
            num = parseFloat(strNum);
            break;
    }
    return num;
}


//从url中获取值
function getQueryString(queryName, url) {
    if (!url) {
        url = location.href;
    }
    var questionIndex = url.indexOf('?');
    if (questionIndex < 0) {
        return null;
    }
    var arrQuery = url.substr(questionIndex + 1).split('&');
    queryName = queryName + '=';
    for (var i = 0; i < arrQuery.length; i++) {
        if (arrQuery[i].indexOf(queryName) == 0) {
            return arrQuery[i].substr(queryName.length);
        }
    }
    return null;
}

//刷新框架的主Frame页
function RefreshMainFrame() {
    var url = top.frmMain.location.href;
    if (url.indexOf('#') >= 0) {
        url = url.substring(0, url.indexOf('#'))
    }
    rnd = new Date();
    if (url.indexOf('?') < 0) {
        url += '?rnd=' + rnd;
    }
    else if (url.indexOf('?rnd=') < 0 && url.indexOf('&rnd=') < 0) {
        url += '&rnd=' + rnd;
    }
    else {
        url = url.replace(/([?&]rnd)=.*/, '$1=' + rnd);
    }
    top.frmMain.location = url;
    //top.tb_remove();
}
