﻿function Loader(url, async) {
    this.url = url;
    this.async = async;
    this._callbacks = new Array();
    if (typeof XMLHttpRequest != 'undefined') {
        this._xmlHttpRq = new XMLHttpRequest();
    }
    else {
        try {
            this._xmlHttpRq = new ActiveXObject('Microsoft.XMLHTTP');
        }
        catch (e) { }
    }
    var me = this;
    this._onreadystatechange = function() {
        if (me._xmlHttpRq.readyState == 4) {
            for (var i = 0; i < me._callbacks.length; i++) {
                if (me._callbacks[i].code == me._xmlHttpRq.status || me._callbacks[i].code == -1) {
                    me._callbacks[i].func(me._xmlHttpRq.responseXML);
                }
            }
        }
    };
    if (async)
        this._xmlHttpRq.onreadystatechange = this._onreadystatechange;
}

/**** Prototype ****/
Loader.prototype.addCallback = Loader_addCallback;
Loader.prototype.removeCallback = Loader_removeCallback;
Loader.prototype.sendRequest = Loader_sendRequest;

/**** Implementation ****/
function Loader_addCallback(status, callback) {
    if (!status) {
        status = -1;
    }
    this._callbacks[this._callbacks.length] = { code: status, func: callback };
}

function Loader_removeCallback(status, callback) {
    var i = 0;
    for (obj in this._callbacks) {
        if (obj.code == status && obj.func == callback) break;
        else
            i++;
    }
    if (i < this._callbacks.length)
        this._callbacks.splice(i, 1);
}

function Loader_sendRequest(pars) {
    var p = this.url;
    if (pars && pars.length) {
        for (var i = 0; i < pars.length; i++) {
            p = p + (i == 0 ? '?' : '&') + pars[i].name + '=' + pars[i].value;
        }
    }
    this._xmlHttpRq.open('GET', p, this.async);
    this._xmlHttpRq.send(null);
    if (!this.async) {
        this._onreadystatechange();
    }
}
