﻿//readyState Status Codes:
var RS_UNINITIALIZED=0;
var RS_LOADING=1;
var RS_LOADED=2;
var RS_INTERACTIVE=3;
var RS_COMPLETE=4;

String.prototype.trim  =  function(){
    return  this.replace(/(^\s*)|(\s*$)/g,  "");
}
function $G(id) {
    return document.getElementById(id);
}
function $V(id) {
    var c = $G(id);
    if(c) return c.value;
    else return null;
}

function Ajax() {
    if (typeof (Ajax.initMethod) == "undefined") {
        Ajax.prototype.GetHttpRequestObject = function() {
            if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
            else if (window.XMLHttpRequest) return new XMLHttpRequest();
            try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { };
            return null;
        }

        Ajax.prototype.EncodeUrlParam = function(param){
            var params = param.split('&');
            var rp = "";
            for(var i = 0;i< params.length;i++){
               var nv = params[i].split('=');
               if(rp != "") rp += "&";
               rp += nv[0] + "=";
               rp += encodeURIComponent(nv[1]);
            }
            return rp;
        }
        // callback is defined outside with two params
        // first param shows that the request complete successfully or not
        // second shows the response text
        Ajax.prototype.Get = function(url, callback) {
            var xmlHttp = Ajax.prototype.GetHttpRequestObject();
            if (xmlHttp == null) {
                alert("create ajax error");
                return;
            }
            xmlHttp.onreadystatechange = function() {
                if (xmlHttp.readyState == RS_COMPLETE) {
                    if (xmlHttp.status == 200) callback(true, xmlHttp.responseText);
                    else callback(false, xmlHttp.responseText);
                    xmlHttp = null;
                }
            }
            xmlHttp.open("GET", url, true);
            xmlHttp.send(null);
        }

        Ajax.prototype.Post = function(url, param, callback) {
            var xmlHttp = Ajax.prototype.GetHttpRequestObject();
            if (xmlHttp == null) {
                alert("create ajax error");
                return;
            }
            xmlHttp.onreadystatechange = function() {
                if (xmlHttp.readyState == RS_COMPLETE) {
                    if (xmlHttp.status == 200) callback(true, xmlHttp.responseText);
                    else callback(false, xmlHttp.responseText);
                    xmlHttp = null;
                }
            }
            xmlHttp.open("POST", url, true);
            xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;');
            xmlHttp.send(Ajax.prototype.EncodeUrlParam(param));
        }
    }
    Ajax.initMethod = true;
}
 