﻿/* 错误常量定义 */
var ERR_OK                              = 0;
var ERR_UNKNOWN_EXCEPTION               = 1;
var ERR_SERVER_SCRIPT                   = 2;
var ERR_XMLHTTPREQUEST_FAILURE          = 3;
var ERR_XML_NOTFORMED                   = 4;
var ERR_CALLBACK_FAIL                   = 5;

/*
 * ajax类定义
 */
function JoAjax( url , xml, callback)
{
    try{
        this.HttpRequest = null;
        this.Debug  = false;
        this.Url = url;
        this.ContentType = "text/xml";
        this.CallbackFunction = callback;
        this.bXml = xml;
        this.Error = ERR_OK;

        this.HttpRequest = this.createXMLHttpRequest();

        if ( this.HttpRequest == null )
        {
            this._debug("XMLHttpRequest create failure!");
            this.Error = ERR_XMLHTTPREQUEST_FAILURE;
            return;
        }

        var xhReq = this.HttpRequest;
        xhReq.onreadystatechange = function (){
            JoAjax._OnReadyStateChange( xhReq, xml, callback );
        }

    } catch(e){
        this.Error = ERR_UNKNOWN_EXCEPTION;
        this._debug( "JoAjax: " + e.message );
    }
}

/*
 * get 方法提出请求
 */
JoAjax.prototype.Get = function() {

    this.SetContentType( "text/html" );
    this._get();
}

/*
 * post 方法提出请求
 */
JoAjax.prototype.Post = function( arrKey, arrValue ) {

    var data = '';
    this.SetContentType( "application/x-www-form-urlencoded" );
    for( i = 0; i < arrKey.length; i ++)
    {
        data += "&" + encodeURIComponent(arrKey[i]) + "=" + encodeURIComponent(arrValue[i]);
    }
    data = data.replace(/^&/g, "");
    this._post(data);
}

/*
 * call 服务器端函数
 * 参数是任意的
 */
JoAjax.prototype.Call = function() {

    var data = '';
    var i = 0;
    this.SetContentType( "text/xml" );

    this._assert( arguments.length >= 1, "There is no specified function name");

    data = "<Request>\n<methodName>"+ arguments[0] +"</methodName>\n";

    for ( i = 1; i < arguments.length; i ++)
    {
        data = data + "<param" + i + ">"+ arguments[i] + "</param"+ i +">\n";
    }
    data = data + "</Request>";
    this._post(data);
}


JoAjax.ScalarValue = function ( xmlobj ) {

    if ( xmlobj )
    {
        try
        {
            return xmlobj.getElementsByTagName('Response')[0].firstChild.nodeValue;
        }
        catch (e)
        {
            return null;
        }
    }
    return null;
}

/*
 * 将MXL对象以数组的方式返回
 */
JoAjax.ArrayValue = function ( xmlobj ) {

    var array = new Array();
    if ( xmlobj )
    {
        try
        {
            var i = 0;
            var response = xmlobj.getElementsByTagName('Response')[0];
            var element = response.firstChild;
            array[i] = element.firstChild.nodeValue;

            while ( element = element.nextSibling )
            {
                i ++;
                array[i] = element.firstChild.nodeValue;
            }
            return array;
        }
        catch (e)
        {
            return array;
        }
    }
    return array;
}

/*
 * 初始化AJAX类
 */
JoAjax.prototype.Init = function() {
    // initialization
}

/*
 * 改变所请求的URL
 */
JoAjax.prototype.SetUrl = function( url ) {
    this.Url = url;
}

/*
 * 设置HTTP请求发送类型
 */
JoAjax.prototype.SetContentType = function( type ) {
    this.ContentType = type;
}

JoAjax.prototype.createXMLHttpRequest = function() {

    try { return new ActiveXObject("Msxml2.XMLHTTP");    } catch(e) {}
    try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {}
    try { return new XMLHttpRequest();                   } catch(e) {}
    return null;
}

/*
 * 调试信息
 */
JoAjax.prototype._debug = function(message) {

    if ( this.Debug )
    {
    //    alert(message);
    }
}

/*
 * 这个不用讲了，一看就明白了。 
 */
JoAjax._OnReadyStateChange = function( xreq, xml, callback ){

    if ( xreq == null )
    {
        return;
    }
    
    /*完成 */
    if ( xreq.readyState == 4)
    {
        // OK
        
        if ( xreq.status == 200 )
        {
            if ( xml )
            {
                var responseXML = xreq.responseXML;
                
                try
                {
                    if ( responseXML.xmlText == "" )
                    {
                    //    alert('Server Script Error!' + "\n" + JoAjax.StripTags(xreq.responseText) );
                        this.Error = ERR_SERVER_SCRIPT;
                    } else {

                        try
                        {
                            callback ( responseXML );
                        }
                        catch (e)
                        {
                            this.Error = ERR_CALLBACK_FAIL;
                          //  alert( "Callback " + e.name + " : " + e.message + "\n" + callback);
                        }
                        
                    }
                }
                catch (e)
                {
                   // alert('Xml not well-formed : ' + responseXML.xmlText );
                    this.Error = ERR_XML_NOTFORMED;
                    return;
                }
            } else {
                
                try
                {
                    callback ( xreq.responseText );
                }
                catch (e)
                {
                    this.Error = ERR_CALLBACK_FAIL;
                   // alert( "Callback " + e.name + " : " + e.message + "\n" + callback);
                }
                
            }
        }
    } else {
        // Others
    }
}

/*
 * 发送HTTP请求到服务器
 * 参数:
 *      HttpMethod: POST, GET, PUT, HEAD, etc.
 *      data: HTTP 的实体数据 . 当请求方法是GET, PUT and HEAD的时候可以为空   
 * 返回:
 *      true 成功, 否则 false
 */
JoAjax.prototype._SendRequest = function(HttpMethod, data){

    this._debug( 'Send Request ' + HttpMethod + data );
    this._assert ( this.HttpRequest != null , "XMLHttpRequest should not be NULL");

    if ( this.HttpRequest != null )
    {
       // this.HttpRequest.open(HttpMethod, this.Url+'randid='+Math.random(1,100), true);
		this.HttpRequest.open(HttpMethod, this.Url, true);
        if ( this.ContentType != null )
        {
            //  <FORM> MIME type: application/x-www-form-urlencoded
            this.HttpRequest.setRequestHeader("Content-Type", this.ContentType);
        }
        this.HttpRequest.send(data);
        return true;
    }
    return false;
}


JoAjax.prototype._get = function () {

    this._debug( 'GET' );
    return this._SendRequest("GET", null);
}


JoAjax.prototype._post = function (data) {

    this._debug( 'POST' );
    return this._SendRequest("POST", data);
}

/*
 * 用于检查函数参数
 */
JoAjax.prototype._assert = function(condition, errmsg) {

    if ( !condition )
    {
        this._debug("JoAjax ASSERT(): " + errmsg);
    }
}


JoAjax.HtmlEntity = function ( html ) {

    html = html.replace(/&/g, "&amp;");
    html = html.replace(/</g, '&lt;');
    html = html.replace(/>/g, '&gt;');
    return html;
}


JoAjax.StripTags = function ( html ){
    html = html.replace(/<[^>]+>/g, "");
    return html;
}