function instanceOf(obj,objConstructor) {
    return (obj && objConstructor && typeof(obj) == 'object' && typeof(objConstructor) == 'function' && obj instanceof objConstructor);
}

/** CW
 * Call wrapper for async function and method calls
 */
function CW(callDef,aArguments) {
    this.mId = 'CW_'+(CW.mCounter++);
    this.callDef = callDef;
    this.mTimerId = null;
    this.mIntervalId = null;
    this.aArguments = aArguments;
    CW.mPendingCalls[this.mId] = this;
}

CW.prototype.execute = function(keepAfter,aArguments) {
    if (aArguments && aArguments.length) {
        var tArgs = aArguments;
    } else if (this.aArguments) {
        var tArgs = this.aArguments;
    } else {
        var tArgs = new Array();
    }
    if (typeof(this.callDef) == 'object' && typeof(this.callDef[0][this.callDef[1]]) == 'function') {
        this.callDef[0][this.callDef[1]].apply(this.callDef[0],tArgs);
    } else if (typeof(this.callDef) == 'function') {
        this.callDef.apply(null,tArgs);
    } else if (typeof(this.callDef) == 'string') {
        eval(this.callDef);
    } else {
        alert('Invalid call:\n'+(this.callDef.toSource ? this.callDef.toSource() : this.callDef.toString()));
    }
    if (!keepAfter) {
        delete(CW.mPendingCalls[this.mId]);
    }
}

CW.prototype.clear = function() {
    delete(CW.mPendingCalls[this.mId]);
}

CW.clearInterval = function(callwrapper) {
    if (instanceOf(callwrapper,CW) && CW.mPendingCalls[callwrapper.mId]) {
        clearInterval(CW.mPendingCalls[callwrapper.mId].mIntervalId);
    }
}

CW.setInterval = function(callwrapper,mInterval) {
    if (instanceOf(callwrapper,CW) && CW.mPendingCalls[callwrapper.mId]) {
        CW.mPendingCalls[callwrapper.mId].mIntervalId = setInterval('CW.mPendingCalls["' + callwrapper.mId + '"].execute(true)', mInterval);
    }
}

CW.clearTimeout = function(callwrapper) {
    if (instanceOf(callwrapper,CW) && CW.mPendingCalls[callwrapper.mId]) {
        clearTimeout(CW.mPendingCalls[callwrapper.mId].mTimerId);
    }
}

CW.setTimeout = function(callwrapper,mDelay) {
    if (instanceOf(callwrapper,CW) && CW.mPendingCalls[callwrapper.mId]) {
        CW.mPendingCalls[callwrapper.mId].mTimerId = setTimeout('CW.mPendingCalls["' + callwrapper.mId + '"].execute()', mDelay);
    }
}

CW.mCounter = 0;
CW.mPendingCalls = {};

/** AJAX
 * Asynchronous JavaScript & XMLHTTP
 */
function AJAX() {
}
    
AJAX.prototype.getXMLHTTP = function(parentObj) {
    var ret = new Object();
    try {
        ret.xmlhttp = new ActiveXObject('Msxml2.XMLHTTP');
    } catch(e) {
        try {
            ret.xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
        } catch(oc) {
            ret.xmlhttp = null;
        }
    }
    if (!ret.xmlhttp && typeof XMLHttpRequest != 'undefined') {
        ret.xmlhttp = new XMLHttpRequest();
    }
    ret.parentObj = parentObj;
    ret.ajax = this;
    if (ret.xmlhttp) {
        return ret;
    } else {
        return null;
    }
}

AJAX.prototype.getURL = function(base_url,params_str,method) {
    return ((method == 'GET' || method == 'get') && params_str ? base_url+'?'+params_str : base_url);
}

AJAX.prototype.syncRun = function(base_url,params,method) {
    method = this.validateMethod(method);
    var ret = false;
    var x = this.getXMLHTTP();
    if (x) {
        var params_str = this.formParamString(params);
        
        x.xmlhttp.open(method,this.getURL(base_url,params_str,method),false);
        if (method != 'GET') {
            x.xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        }
        
        x.xmlhttp.send((method == 'GET' ? null : params_str));
        if (x.xmlhttp.responseText) {
            ret = this.decode(x.xmlhttp.responseText);
        }
    }
    return ret;
}

AJAX.prototype.asyncRun = function(base_url,params,method,callBack,callerObj) {
    method = this.validateMethod(method);
    var params_str = this.formParamString(params);
    var x = this.getXMLHTTP(callerObj);
    if (x) {
        x.xmlhttp.open(method,this.getURL(base_url,params_str,method),true);
        if (method != 'GET') {
            x.xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        }
        x.xmlhttp.onreadystatechange = function() {
            if (x.xmlhttp.readyState == 4) {
                execFunc(callBack,[x.ajax.decode(x.xmlhttp.responseText),x.parentObj,x.xmlhttp.responseText]);
            }
        };
        x.xmlhttp.send(method == 'GET' ? null : params_str);
    }
}

AJAX.prototype.updateSelect = function(s,base_url,params,firstLine,selectedValue,method,callBack) {
    if (s) {
        var postFunc = function (new_options,s,responseText) {
            var args = new Array();
            s.options.length = 0;
            var selectedIndex = 0;
            if (firstLine) {
                s.options[0] = new Option(firstLine,'');
            }
            if (new_options && typeof(new_options) == 'object') {
                for (var i=0; i<new_options.length; i++) {
                    if (new_options[i].value == selectedValue) {
                        selectedIndex = i;
                    }
                    s.options[s.options.length] = new Option(new_options[i].label,new_options[i].value);
                }
            } else {
                args.push(new_options);
            }
            if (selectedIndex) {
                s.selectedIndex = selectedIndex;
            }
            execFunc(callBack,args);
        }
        this.asyncRun(base_url,params,method,postFunc,s);
    }
}

AJAX.prototype.validateMethod = function(method) {
    if (!method) {
        method = 'GET';
    } else {
        method = method.toString().toUpperCase();
        if (method != 'GET' && method != 'POST') {
            method = 'GET';
        }
    }
    return method;
}

AJAX.prototype.formParamString = function(params) {
    var params_str = '';
    if (typeof(params) == 'object') {
        for (var i in params) {
            params_str += escape(i) + '=' + escape(params[i]) + '&';
        }
        if (params_str[params_str.length-1] == '&') {
            params_str = params_str.substr(0,params_str.length-1);
        }
    }
    return params_str;
}

/** function encode
 * encode an arbitrary variable into JSON format
 *
 * @param    var     mixed   any number, boolean, string, array, or object to be encoded.
 *                           if var is a string, note that encode() always expects it
 *                           to be in ASCII or UTF-8 format!
 *
 * @return   string  JSON string representation of input var
 */
AJAX.prototype.encode = function(arg) {
    var i, o, u, v;

    switch (typeof arg) {
        case 'object':
            if (arg) {
                if (arg.constructor == Array) {
                    o = '';
                    for (i=0;i<arg.length;++i) {
                        v = this.encode(arg[i]);
                        if (o) {
                            o += ',';
                        }
                        if (v !== u) {
                            o += v;
                        } else {
                            o += 'null,';
                        }
                    }
                    return '[' + o + ']';
                } else if (typeof arg.toString != 'undefined') {
                    o = '';
                    for (i in arg) {
                        v = this.encode(arg[i]);
                        if (v !== u) {
                            if (o) {
                                o += ',';
                            }
                            o += this.encode(i) + ':' + v;
                        }
                    }
                    return '{' + o + '}';
                } else {
                    return;
                }
            }
            return 'null';
        case 'unknown':
        case 'undefined':
        case 'function':
            return u;
        case 'string':
            return '"' + arg.replace(/(["\\])/g, '\\$1') + '"';
        default:
            return String(arg);
    }
}

/** function decode
 * decode a JSON string into appropriate variable
 *
 * @param    str     string  JSON-formatted string
 *
 * @return   mixed   number, boolean, string, array, or object
 *                   corresponding to given JSON input string.
 *                   note that decode() always returns strings
 *                   in ASCII or UTF-8 format!
 */
AJAX.prototype.decode = function(arg) {
    if (typeof arg != 'string' || arg == '') {
        return null;
    }
    
    var ret = null;
    try {
        eval('ret = '+arg);
    } catch (ex) {
        //throw('Invalid JSON string "'+arg+'"');
        //alert('Invalid JSON string "'+arg+'"');
    }
    
    return ret;
}

function execFunc(func,args) {
    if (!instanceOf(args,Array)) {
        args = new Array(args);
    }
    var ret = null;
    if (instanceOf(func,CW)) {
        ret = func.execute(false,(func.aArguments instanceof Array ? func.aArguments.concat(args) : args));
    } else if (typeof(func) == 'function') {
        func.apply(null,args);
    } else {
        ret = eval(func);
    }
    return ret;
}