﻿var isIE = !!document.all;
/*
window.WindowLoadEvent = [];
window.attachLoadEvent = function(fun) {
this.WindowLoadEvent[this.WindowLoadEvent.length] = fun;
}
window.onload = function() {
for (var i = 0; i < WindowLoadEvent.length; i++) {
eval(WindowLoadEvent[i]);
}
}
*/

/*================创建XMLHttpRequest对象=========================================*/
function CreateXMLHttpRequest() {
    var http_request = false;
    //开始初始化XMLHttpRequest对象
    if (window.XMLHttpRequest) { //Mozilla 浏览器
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {//设置MiME类别
            http_request.overrideMimeType("text/xml");
        }
    }
    else if (window.ActiveXObject) { // IE浏览器
        try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) { }
        }
    }
    if (!http_request) {   // 异常，创建对象实例失败
        throw "不能创建XMLHttpRequest对象实例。";
    }
    return http_request;
}

/*================获取网页内容====================================================*/
function RequestPage(url, method, params, async, eventCallback, context, errorCallback) {

    var http_request = CreateXMLHttpRequest();

    if (typeof (async) == "undefined")
        async = false;

    http_request.open(method, url, async);
    if (method == "POST")
        http_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    http_request.onreadystatechange = function() {
        if (http_request.readyState == 4) {
            if (http_request.status == 200) {
                if (eventCallback) {
                    eventCallback(http_request.responseText, context);
                }
            }
            else if (errorCallback) {
                errorCallback(http_request.responseText, context);
            }
            else {
                alert(http_request.responseText);
            }
        }
    }

    http_request.send(params);

    if (!async) {
        var returnValue = "";
        if (http_request.readyState == 4 && http_request.status == 200)
            returnValue = http_request.responseText;
        else
            throw "请求页面出错。";
        return returnValue;
    }

    return true;
}

/*================获取URL参数值====================================================*/
function QueryString(key) {
    return ParseQueryString(key, location.search);
}

/*================获取name=value&name1=value1格式的值====================================================*/
function ParseQueryString(key, query) {
    var re = new RegExp(key + "=([^&]*)", "ig");
    var arr = re.exec(query);
    if (arr != null)
        return decodeURIComponent(arr[1]);
    else return "";
}

/*================全选复选框或单选按扭====================================================*/
function SelectAll(control) {
    if (!control) return;
    if (typeof (control.length) != "undefined") {
        for (var i = 0; i < control.length; i++) {
            if (!control[i].disabled)
                control[i].checked = true;
        }
    }
    else {
        if (!control.disabled)
            control.checked = true;
    }
}
/*================取消所有复选框或单选按扭选择====================================================*/
function CancelAllSelect(control) {
    if (!control) return;
    if (typeof (control.length) != "undefined") {
        for (var i = 0; i < control.length; i++) {
            if (!control[i].disabled)
                control[i].checked = false;
        }
    }
    else {
        if (!control.disabled)
            control.checked = false;
    }
}
/*================判断是否有选择其中的选项====================================================*/
function HasSelected(control) {
    if (typeof (control.length) != "undefined") {
        for (i = 0; i < control.length; i++) {
            if (control[i].checked && !control[i].disabled)
                return true;
        }
    }
    else {
        if (control.checked && !control.disabled)
            return true;
    }
    return false;
}

/*================全选/取消选择控件====================================================*/
function SelectControl(button, controlId, buttonType, container) {
    var isAllSelect = false;
    var control = null;
    var linkButton;
    if (typeof (button) == "string") {
        if (buttonType == "button") {
            if (container) {
                var btn = document.createElement("INPUT");
                btn.id = button;
                btn.type = "BUTTON";
                btn.value = "全选";
                container.appendChild(btn);
            }
            else {
                document.write("<input type='button' id='" + button + "' value='全选' />");
            }
        }
        else {

            if (container) {
                var btn = document.createElement("A");
                btn.id = button;
                btn.innerHTML = "全选";
                btn.href = "javascript:;";
                container.appendChild(btn);
            }
            else {
                document.write("<a href='javascript:;' id='" + button + "'>全选</a>");
            }
        }
        linkButton = document.getElementById(button);
    }
    else {
        linkButton = button;
    }
    linkButton.onclick = function() {
        control = FindControl(document, controlId);
        if (isAllSelect) {
            CancelAllSelect(control);
            buttonType == "button" ? linkButton.value = "全选" : linkButton.innerHTML = "全选";
            isAllSelect = !isAllSelect;
        }
        else {
            SelectAll(control);
            buttonType == "button" ? linkButton.value = "取消" : linkButton.innerHTML = "取消";
            isAllSelect = !isAllSelect;
        }
    }

    linkButton.ChangeSelectState = function() {
        control = FindControl(document, controlId);
        isAllSelect = true;
        if (typeof (control.length) != "undefined") {
            for (i = 0; i < control.length; i++) {
                if (!control[i].checked) {
                    isAllSelect = false;
                    break;
                }
            }
        }
        else {
            if (!control.checked)
                isAllSelect = false;
        }
        if (isAllSelect) {
            buttonType == "button" ? linkButton.value = "取消" : linkButton.innerHTML = "取消";
        }
        else {
            buttonType == "button" ? linkButton.value = "全选" : linkButton.innerHTML = "全选";
        }
    }

    linkButton.Init = function() {
        control = FindControl(document, controlId);
        if (!control) return;
        if (typeof (control.length) != "undefined") {
            for (i = 0; i < control.length; i++) {
                control[i].Parent = linkButton;
                control[i].onclick = function() {

                    this.Parent.ChangeSelectState();
                }
            }
        }
        else {
            control.Parent = linkButton;
            control.onclick = function() {
                this.Parent.ChangeSelectState();

            }
        }
    }
}

/*================创建全选控件====================================================*/
function CreateSelectedAllButton(button, chkBoxId, buttonType, container) {
    var selAll = new SelectControl(button, chkBoxId, buttonType, container);
    var id = button;
    if (typeof (button) == "object") {
        id = button.id;
    }
    AttachEvent(window, "load", new Function("document.getElementById('" + id + "').Init();"));

}

/*================删除提示=====================================*/
function CheckDeleteSelected(ctlName) {
    if (!HasSelected(FindControl(document, ctlName))) {
        alert("很抱歉，至少要选一条记录才能删除…");
        return false;
    }
    return true;
}

/*================选择提示=====================================*/
function CheckSelectedItem(ctlName) {
    if (!HasSelected(FindControl(document, ctlName))) {
        alert("无法进行操作，请先选择记录！");
        return false;
    }
    return true;
}

//删除字串两端空格
String.prototype.trim = function() {
    var m = this.match(/^\s*(\S+(\s+\S+)*)\s*$/);
    return (m == null) ? "" : m[1];
}
//子字串是否匹配开始位置
String.prototype.startsWith = function(value) {
    var re = new RegExp("^" + value + ".*$", "ig");
    return re.test(this);
}
//子字串是否匹配结尾位置
String.prototype.endsWith = function(value) {
    var re = new RegExp("^.*" + value + "$", "ig");
    return re.test(this);
}
//格式化字符串
String.prototype.format = function() {
    var str = this;
    var args = arguments;

    if (args.length == 1 && isArray(args[0]))
        args = args[0];
    if (args.length > 0) {
        for (var i = 0; i < args.length; i++) {
            var re = new RegExp("\\{" + i + "\\}", "ig");
            str = str.replace(re, args[i]);
        }
        return str;
    }
    return str;
}

if (!Number.prototype.toFixed) {
    Number.prototype.toFixed = function(pos) {
        return Math.round(this * Math.pow(10, pos)) / Math.pow(10, pos);
    }
}

//判断对象是否为数组
function isArray(o) {
    return Object.prototype.toString.call(o) === '[object Array]';
}

//浏览器属性开始
function WindowInfo() {
    var scrollX = 0, scrollY = 0, width = 0, height = 0, contentWidth = 0, contentHeight = 0;
    if (typeof (window.pageXOffset) == 'number')
    { scrollX = window.pageXOffset; scrollY = window.pageYOffset; }
    else if (document.body && (document.body.scrollLeft || document.body.scrollTop))
    { scrollX = document.body.scrollLeft; scrollY = document.body.scrollTop; }
    else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop))
    { scrollX = document.documentElement.scrollLeft; scrollY = document.documentElement.scrollTop; }

    if (typeof (window.innerWidth) == 'number')
    { width = window.innerWidth; height = window.innerHeight; }
    else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight))
    { width = document.documentElement.clientWidth; height = document.documentElement.clientHeight; }
    else if (document.body && (document.body.clientWidth || document.body.clientHeight))
    { width = document.body.clientWidth; height = document.body.clientHeight; }

    if (document.documentElement && (document.documentElement.scrollHeight || document.documentElement.offsetHeight)) {
        if (document.documentElement.scrollHeight > document.documentElement.offsetHeight)
        { contentWidth = document.documentElement.scrollWidth; contentHeight = document.documentElement.scrollHeight; }
        else
        { contentWidth = document.documentElement.offsetWidth; contentHeight = document.documentElement.offsetHeight; }
    }
    else if (document.body && (document.body.scrollHeight || document.body.offsetHeight)) {
        if (document.body.scrollHeight > document.body.offsetHeight)
        { contentWidth = document.body.scrollWidth; contentHeight = document.body.scrollHeight; }
        else
        { contentWidth = document.body.offsetWidth; contentHeight = document.body.offsetHeight; }
    }
    else
    { contentWidth = width; contentHeight = height; }

    if (height > contentHeight)
        height = contentHeight;

    if (width > contentWidth)
        width = contentWidth;

    var rect = new Object(); rect.ScrollX = scrollX; rect.ScrollY = scrollY; rect.Width = width; rect.Height = height; rect.ContentWidth = contentWidth; rect.ContentHeight = contentHeight; return rect;
}


//浏览器对象属性
var lBrowser = {};
lBrowser.agt = navigator.userAgent.toLowerCase();
lBrowser.isW3C = document.getElementById ? true : false;
lBrowser.isIE = ((lBrowser.agt.indexOf("msie") != -1) && (lBrowser.agt.indexOf("opera") == -1) && (lBrowser.agt.indexOf("omniweb") == -1));
lBrowser.isNS6 = lBrowser.isW3C && (navigator.appName == "Netscape");
lBrowser.isOpera = lBrowser.agt.indexOf("opera") != -1;
lBrowser.isGecko = lBrowser.agt.indexOf("gecko") != -1;
lBrowser.ieTrueBody = function() {
    return (document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body;
};
lBrowser.window = new WindowInfo();


//查找子控件
function FindControl(control, childControlIdClip) {
    var tagNames = new Array("INPUT", "SELECT", "DIV", "SPAN", "A", "IFRAME", "XML", "IMG", "TEXTAREA", "TABLE", "TR", "TD");
    var controls = [];
    for (var i = 0; i < tagNames.length; i++) {
        var allControls = control.getElementsByTagName(tagNames[i])
        for (var j = 0; j < allControls.length; j++) {
            if (allControls[j].id && allControls[j].id.endsWith(childControlIdClip))
                controls[controls.length] = allControls[j];
        }
    }
    if (controls.length == 0)
        return null;
    else if (controls.length == 1)
        return controls[0];
    return controls;
}

//日期检测
function jIsDate(str) {
    var reg1 = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/;
    var reg2 = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/;
    var r = str.match(reg1);
    var d;
    if (r == null) {
        r = str.match(reg2);
        if (r == null) return false;
        d = new Date(r[1], r[3] - 1, r[4], r[5], r[6], r[7]);
        return parseInt(r[1], 10) == d.getFullYear() &&
			parseInt(r[3], 10) == d.getMonth() + 1 &&
			parseInt(r[4], 10) == d.getDate() &&
			parseInt(r[5], 10) == d.getHours()
        parseInt(r[6], 10) == d.getMinutes()
        parseInt(r[7], 10) == d.getSeconds();
    }
    else {
        d = new Date(r[1], r[3] - 1, r[4]);
        return parseInt(r[1], 10) == d.getFullYear() &&
			parseInt(r[3], 10) == d.getMonth() + 1 &&
			parseInt(r[4], 10) == d.getDate();
    }
}

//清除HTML代码
function ClearHtmlCode(str) {
    value = str.replace(/<br>|<p>/ig, "\n").replace(/<.*?>/ig, "").replace(/&nbsp;/ig, " ");
    return value;
}

//HTML编码
function HtmlEncode(str) {
    return str.replace(/</ig, "&lt;").replace(/>/ig, "&gt;").replace(/\"/g, "&quot;").replace(/&/g, "&amp;");
}

//HTML解码
function HtmlDecode(str) {
    return str.replace(/&lt;/ig, "<").replace(/&gt;/ig, ">").replace(/&quot;/g, "\"").replace(/&amp;/g, "&");
}

/*=======================为非IE的浏览器的XMLDocument对象增加selectSingleNode和selectNodes方式=====================*/
if (!isIE) {
    var ex;

    //xml属性
    XMLDocument.prototype.__proto__.__defineGetter__("xml", function() {
        try {
            return new XMLSerializer().serializeToString(this);
        } catch (ex) {
            var d = document.createElement("div");
            d.appendChild(this.cloneNode(true));
            return d.innerHTML;
        }
    });
    Element.prototype.__proto__.__defineGetter__("xml", function() {
        try {
            return new XMLSerializer().serializeToString(this);
        } catch (ex) {
            var d = document.createElement("div");
            d.appendChild(this.cloneNode(true));
            return d.innerHTML;
        }
    });

    //text属性
    XMLDocument.prototype.__proto__.__defineGetter__("text", function() {
        return this.firstChild.textContent
    });
    Element.prototype.__proto__.__defineGetter__("text", function() {
        return this.textContent
    });



    //selectSingleNode方法
    XMLDocument.prototype.selectSingleNode = Element.prototype.selectSingleNode = function(xpath) {
        var x = this.selectNodes(xpath)
        if (!x || x.length < 1) return null;
        return x[0];
    }

    //selectNodes方法
    XMLDocument.prototype.selectNodes = Element.prototype.selectNodes = function(xpath) {
        var xpe = new XPathEvaluator();
        var nsResolver = xpe.createNSResolver(this.ownerDocument == null ?
             this.documentElement : this.ownerDocument.documentElement);
        var result = xpe.evaluate(xpath, this, nsResolver, 0, null);
        var found = [];
        var res;
        while (res = result.iterateNext())
            found.push(res);
        return found;
    }

    //outerHTML属性
    HTMLElement.prototype.__defineSetter__("outerHTML", function(sHTML) {
        var r = this.ownerDocument.createRange();
        r.setStartBefore(this);
        var df = r.createContextualFragment(sHTML);
        this.parentNode.replaceChild(df, this);
        return sHTML;
    });

    HTMLElement.prototype.__defineGetter__("outerHTML", function() {
        var attr;
        var attrs = this.attributes;
        var str = "<" + this.tagName.toLowerCase();
        for (var i = 0; i < attrs.length; i++) {
            attr = attrs[i];
            if (attr.specified)
                str += " " + attr.name + '="' + attr.value + '"';
        }
        if (!this.canHaveChildren)
            return str + ">";
        return str + ">" + this.innerHTML + "</" + this.tagName.toLowerCase() + ">";
    });

    //canHaveChildren属性
    HTMLElement.prototype.__defineGetter__("canHaveChildren", function() {
        switch (this.tagName.toLowerCase()) {
            case "area":
            case "base":
            case "basefont":
            case "col":
            case "frame":
            case "hr":
            case "img":
            case "br":
            case "input":
            case "isindex":
            case "link":
            case "meta":
            case "param":
                return false;
        }
        return true;
    });

    //inertText属性
    HTMLElement.prototype.__defineGetter__("innerText",
     function() {
         return this.textContent;
     }
     );
    HTMLElement.prototype.__defineSetter__("innerText",
     function(sText) {
         this.textContent = sText;
     }
     );

    //增加insertAdjacentElement方法
    HTMLElement.prototype.insertAdjacentElement = function(where, parsedNode) {
        switch (where) {
            case "beforeBegin":
                this.parentNode.insertBefore(parsedNode, this);
                break;
            case "afterBegin":
                this.insertBefore(parsedNode, this.firstChild);
                break;
            case "beforeEnd":
                this.appendChild(parsedNode);
                break;
            case "afterEnd":
                if (this.nextSibling)
                    this.parentNode.insertBefore(parsedNode, this.nextSibling);
                else
                    this.parentNode.appendChild(parsedNode);
                break;
        }
    }
}

/*=======================为非IE的浏览器的XMLDocument对象增加selectSingleNode和selectNodes方式=====================*/


/*=============================动态创建一个Form=================================*/
function DynamicForm(name, method, action) {
    var form = document.createElement("FORM");
    document.body.appendChild(form);
    form.name = name;

    if (method)
        form.method = method;
    if (action)
        form.action = action;

    form.style.display = "none";

    form.AddInput = function(name, value) {
        var input = document.createElement("INPUT");
        form.appendChild(input);
        input.name = name;
        input.value = value;
        return input;
    }

    return form;
}

//格式化字符串
function formatString(str, arrVal) {
    for (var i = 0; i < arrVal.length; i++) {
        str = str.replace("{" + i + "}", arrVal[i]);
    }
    return str;
}

//创建XMLDocument
function CreateDocument() {
    if (isIE) {
        return new ActiveXObject("Microsoft.XMLDOM");
    } else if (document.implementation && document.implementation.createDocument) {
        return document.implementation.createDocument("", "", null);
    }
    return null;
}

//加载XML
LoadXML = function(s) {
    var doc = null;
    if (isIE) {
        doc = CreateDocument();
        doc.loadXML(s);
    } else {
        doc = new DOMParser().parseFromString(s, "text/xml");
    }
    return doc;
}

//加载XML从URL
LoadXmlFile = function(url) {
    var xmlHttpRequest = CreateXMLHttpRequest();
    xmlHttpRequest.open("GET", url, false);
    xmlHttpRequest.send(null);
    return xmlHttpRequest.responseXML;
}

//只允许输入数字
function onkeydownOnlyNumber(evt, integerOnly) {
    if (evt.keyCode == 13 || evt.keyCode == 9 || evt.keyCode == 8 || evt.keyCode == 37 || evt.keyCode == 38 || evt.keyCode == 39 || evt.keyCode == 40)
        return true;

    if ((evt.keyCode > 47 && evt.keyCode < 58) || (evt.keyCode > 95 && evt.keyCode < 106))
        return true;

    if (!integerOnly && (evt.keyCode == 190 || evt.keyCode == 110))
        return true;

    if (document.all) {
        evt.cancelBubble = true;
    }
    else {
        evt.stopPropagation();
        evt.preventDefault();
    }

    return false;
}


//为对象注册事件
function AttachEvent(object, evt, func) {
    if (isIE) {
        object.attachEvent('on' + evt, func);
    }
    else {
        object.addEventListener(evt, func, false);
    }
}

//为Form注册事件
function AttachFormOnsubmitEvent(form, func) {
    if (form.onsubmit) {
        if (typeof (func) == "function") {
            func = func.toString();
            func = func.substring(func.indexOf(" ") + 1, func.indexOf("{"));
        }
        var s = form.onsubmit.toString();
        s = s.substring(s.indexOf("{") + 1);
        s = "form.onsubmit=function (){" + func + ";" + s;
        s = s.trim();
        if (s.substring(s.length - 1) != "}") {
            s += "}";
        }
        eval(s);
    }
    else {
        form.onsubmit = func;
    }
}

//计算Element的位置
function GetElementPosition(elm) {
    var x = 0, y = 0;
    for (var obj = elm; obj; obj = obj.offsetParent) {
        x += parseInt(obj.offsetLeft);
        y += parseInt(obj.offsetTop);
    }
    var o = new Object();
    o.x = x;
    o.y = y;
    return o;
}

//动态加载JS
var includeJSXmlHttp;
function IncludeFile(url, type) {
    if (type == "css" && isIE) {
        var oStyle = document.createElement("link");
        oStyle.setAttribute("rel", "stylesheet");
        oStyle.setAttribute("type", "text/css");
        oStyle.setAttribute("href", url);
        document.getElementsByTagName("head")[0].appendChild(oStyle);
        return;
    }

    if (!includeJSXmlHttp) {
        if (window.XMLHttpRequest)
            includeJSXmlHttp = new XMLHttpRequest();
        else
            includeJSXmlHttp = new ActiveXObject("MsXml2.XmlHttp");
    }

    includeJSXmlHttp.open('GET', url, false);
    includeJSXmlHttp.send(null);

    if (includeJSXmlHttp.readyState == 4) {
        if (includeJSXmlHttp.status == 200 || includeJSXmlHttp.status == 304) {
            var text = includeJSXmlHttp.responseText;

            var parent = null;
            var heads = document.getElementsByTagName("head");
            if (heads)
                parent = heads[0];
            if (parent == null) {
                var bodys = document.getElementsByTagName("body");
                if (bodys)
                    parent = bodys[0];
            }
            if (parent == null) {
                parent = document.getElementsByTagName("html")[0];
            }

            if (type == "js") {
                var oScript = document.createElement("script");
                oScript.language = "javascript";
                oScript.type = "text/javascript";
                oScript.defer = true;
                oScript.text = text;
                parent.appendChild(oScript);
            }
            if (type == "css") {
                var oStyle = document.createElement("style");
                oStyle.setAttribute("type", "text/css");
                oStyle.innerText = text;
                parent.appendChild(oStyle);
            }
        }
        else {
            alert('加载失败:' + includeJSXmlHttp.statusText + '(' + includeJSXmlHttp.status + ')');
        }
    }
}

//StringBuilder类
var StringBuilder = function() {
    this._buffer = [];
    this._arg1 = "";
    this._arg2 = "";
    if (arguments.length > 0) this._arg1 = String(arguments[0]);
    if (arguments.length > 1) this._arg2 = String(arguments[1]);
}
StringBuilder.prototype.append = function(str) {
    //    this._buffer.push(String(str));                                //这个速度没有下面这个快
    this._buffer[this._buffer.length] = String(str);
    //    this._buffer[this._buffer.length] = str;            //去掉强制转换将更快，但是下面的表格输出就要修改了
}
StringBuilder.prototype.getLength = function() {
    return this._buffer.length;
}
StringBuilder.prototype.remove = function(i) {
    this._buffer.splice(i, 1);
}
StringBuilder.prototype.replace = function(i, str) {
    this._buffer.splice(i, 1, str);
}
StringBuilder.prototype.toString = function() {
    return (this._arg2 ? this._arg1 : "") + this._buffer.join(this._arg2 + this._arg1) + this._arg2;
}
StringBuilder.prototype.clear = function() {
    this._buffer = [];
}
StringBuilder.prototype.add = StringBuilder.prototype.append;


//JsCookie操作
var JsCookie = {

    setCookie: function(name, value) {
        var expdate = new Date();
        var argv = arguments;
        var argc = arguments.length;
        var expires = (argc > 2) ? argv[2] : null;
        var path = (argc > 3) ? argv[3] : null;
        var domain = (argc > 4) ? argv[4] : null;
        var secure = (argc > 5) ? argv[5] : false;
        if (expires != null) expdate.setTime(expdate.getTime() + (expires * 1000));
        document.cookie = name + "=" + escape(value) + ((expires == null) ? "" : (";  expires=" + expdate.toGMTString()))
                                + ((path == null) ? "" : (";  path=" + path)) + ((domain == null) ? "" : (";  domain=" + domain))
                                + ((secure == true) ? ";  secure" : "");
    }
    ,
    getCookie: function(name) {
        var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
        if (arr != null) return unescape(arr[2]); return null;

    }
    ,
    delCookie: function(name) {
        var exp = new Date();
        exp.setTime(exp.getTime() - 1);
        var cval = JsCookie.getCookie(name);
        if (cval != null) document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
    }

}


//WebService
function __WebService() {
    this.ShowProgress = null;
    this.HideProgress = null;
    this.Send = function(url, params, eventCallback, context, errorCallback) {
        var me = this;
        if (me.ShowProgress)
            me.ShowProgress();

        if (typeof (params) == "object" && params != null) {
            params = JSON.stringify(params);
        }

        var returnValue = "";
        var http_request = CreateXMLHttpRequest();
        http_request.open("POST", url, true);
        http_request.setRequestHeader("Content-Type", "application/json; charset=utf-8");

        http_request.onreadystatechange = function() {
            if (http_request.readyState == 4) {
                if (http_request.status == 200) {
                    if (eventCallback) {
                        var json = http_request.responseText;
                        var exp = json.replace(new RegExp('(^|[^\\\\])\\"\\\\/Date\\((-?[0-9]+)\\)\\\\/\\"', 'g'), "$1new Date($2)");
                        var result = eval("(" + exp + ")");
                        eventCallback(result.d, context);
                    }
                }
                else if (errorCallback) {
                    errorCallback(http_request.responseText, context);
                }
                else {
                    alert(http_request.responseText);
                }
            }
            if (me.HideProgress)
                me.HideProgress();
        }

        http_request.send(params);

    }
}
var WebService = new __WebService();

function ___WebForm() {
    var me = this;
    this.ShowProgress = null;
    this.HideProgress = null;
    this.DoCallback = function(method, options) {
        if (!options.callbackId)
            options.callbackId = "__Page";

        var postData = { Method: method, Params: (options.params ? options.params : null) };

        var json = JSON.stringify(postData);
        window.setTimeout(function() {
            if (me.ShowProgress)
                me.ShowProgress();
            WebForm_DoCallback(options.callbackId, json, callbackSuccess, { options: options }, callbackFailed, true);
        }, 0);
    }
    function callbackSuccess(args, context) {
        var exp = args.replace(new RegExp('(^|[^\\\\])\\"\\\\/Date\\((-?[0-9]+)\\)\\\\/\\"', 'g'), "$1new Date($2)");
        var result = eval("(" + exp + ")");
        context.options.succeeded(result, context.options.context);
        if (me.HideProgress)
            me.HideProgress();
    }
    function callbackFailed(args, context) {
        if (context.options.failed)
            context.options.failed(args, context.options.context);
        else
            alert(args);
        if (me.HideProgress)
            me.HideProgress();
    }
}
var WebForm = new ___WebForm();

function ___AJAX() {
    this.WebService = WebService;
    this.WebForm = WebForm;
}

var AJAX = new ___AJAX();

//JSON对象
if (typeof (JSON) == "undefined")
    var JSON = {};

(function() {

    function f(n) {
        return n < 10 ? '0' + n : n;
    }

    if (typeof Date.prototype.toJSON !== 'function') {

        Date.prototype.toJSON = function(key) {

            return this.getUTCFullYear() + '-' +
                 f(this.getUTCMonth() + 1) + '-' +
                 f(this.getUTCDate()) + 'T' +
                 f(this.getUTCHours()) + ':' +
                 f(this.getUTCMinutes()) + ':' +
                 f(this.getUTCSeconds()) + 'Z';
        };

        String.prototype.toJSON =
        Number.prototype.toJSON =
        Boolean.prototype.toJSON = function(key) {
            return this.valueOf();
        };
    }

    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        gap,
        indent,
        meta = {
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"': '\\"',
            '\\': '\\\\'
        },
        rep;


    function quote(string) {
        escapable.lastIndex = 0;
        return escapable.test(string) ?
            '"' + string.replace(escapable, function(a) {
                var c = meta[a];
                return typeof c === 'string' ? c :
                    '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
            }) + '"' :
            '"' + string + '"';
    }


    function str(key, holder) {

        var i,          // The loop counter.
            k,          // The member key.
            v,          // The member value.
            length,
            mind = gap,
            partial,
            value = holder[key];

        // If the value has a toJSON method, call it to obtain a replacement value.

        if (value && typeof value === 'object' &&
                typeof value.toJSON === 'function') {
            value = value.toJSON(key);
        }

        if (typeof rep === 'function') {
            value = rep.call(holder, key, value);
        }

        switch (typeof value) {
            case 'string':
                return quote(value);

            case 'number':

                // JSON numbers must be finite. Encode non-finite numbers as null.

                return isFinite(value) ? String(value) : 'null';

            case 'boolean':
            case 'null':

                return String(value);

            case 'object':

                if (!value) {
                    return 'null';
                }


                gap += indent;
                partial = [];


                if (Object.prototype.toString.apply(value) === '[object Array]') {

                    length = value.length;
                    for (i = 0; i < length; i += 1) {
                        partial[i] = str(i, value) || 'null';
                    }

                    v = partial.length === 0 ? '[]' :
                    gap ? '[\n' + gap +
                            partial.join(',\n' + gap) + '\n' +
                                mind + ']' :
                          '[' + partial.join(',') + ']';
                    gap = mind;
                    return v;
                }

                if (rep && typeof rep === 'object') {
                    length = rep.length;
                    for (i = 0; i < length; i += 1) {
                        k = rep[i];
                        if (typeof k === 'string') {
                            v = str(k, value);
                            if (v) {
                                partial.push(quote(k) + (gap ? ': ' : ':') + v);
                            }
                        }
                    }
                } else {


                    for (k in value) {
                        if (Object.hasOwnProperty.call(value, k)) {
                            v = str(k, value);
                            if (v) {
                                partial.push(quote(k) + (gap ? ': ' : ':') + v);
                            }
                        }
                    }
                }

                v = partial.length === 0 ? '{}' :
                gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
                        mind + '}' : '{' + partial.join(',') + '}';
                gap = mind;
                return v;
        }
    }

    if (typeof JSON.stringify !== 'function') {
        JSON.stringify = function(value, replacer, space) {

            var i;
            gap = '';
            indent = '';

            if (typeof space === 'number') {
                for (i = 0; i < space; i += 1) {
                    indent += ' ';
                }

            } else if (typeof space === 'string') {
                indent = space;
            }

            rep = replacer;
            if (replacer && typeof replacer !== 'function' &&
                    (typeof replacer !== 'object' ||
                     typeof replacer.length !== 'number')) {
                throw new Error('JSON.stringify');
            }

            return str('', { '': value });
        };
    }


    if (typeof JSON.parse !== 'function') {
        JSON.parse = function(text, reviver) {

            var j;

            function walk(holder, key) {

                var k, v, value = holder[key];
                if (value && typeof value === 'object') {
                    for (k in value) {
                        if (Object.hasOwnProperty.call(value, k)) {
                            v = walk(value, k);
                            if (v !== undefined) {
                                value[k] = v;
                            } else {
                                delete value[k];
                            }
                        }
                    }
                }
                return reviver.call(holder, key, value);
            }

            cx.lastIndex = 0;
            if (cx.test(text)) {
                text = text.replace(cx, function(a) {
                    return '\\u' +
                        ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                });
            }

            if (/^[\],:{}\s]*$/.
test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

                j = eval('(' + text + ')');

                return typeof reviver === 'function' ?
                    walk({ '': j }, '') : j;
            }

            throw new SyntaxError('JSON.parse');
        };
    }
} ());

//回车键按下时动作
function EnterKeyDown(evt, fun) {
    evt = evt || event;
    if (evt.keyCode == 13) {
        evt.returnValue = false;
        if (evt.preventDefault)
            evt.preventDefault();
        fun();
    }
}

//if (!Object.prototype.toJSONString) {
//    Object.prototype.toJSONString = function(filter) {
//        return JSON.stringify(this, filter);
//    };
//    Object.prototype.parseJSON = function(filter) {
//        return JSON.parse(this, filter);
//    };
//}

