// JavaScript Document

Asynchronous.prototype.loading = Asynchronous_loading;
Asynchronous.prototype.loaded = Asynchronous_loaded;
Asynchronous.prototype.interactive = Asynchronous_interactive;
Asynchronous.prototype.complete = Asynchronous_complete;

Asynchronous.prototype.call = Asynchronous_call;

/**
 * Asynchronous
 * @version 2.01
 *
 * 2.01 rozpoznawanie IE8
 */
function Asynchronous(method, convert, enctype) {
    this._req = createXMLHttpRequest();
    this.method = method ? method.toUpperCase() : 'GET';
    this.convertURL = convert;
    this.setEnctype(enctype);
}

function Asynchronous_call(url, content) {
    var instance = this;

    var goodURL;

    /* konwersja url na utf-8 */
    var ie = navigator.appName == "Microsoft Internet Explorer";
    var ie_ver = 0;
    if (ie) {
        var agent = navigator.userAgent;
        var msieIndex = agent.indexOf("MSIE") + 5;
        ie_ver = Number(agent.substr(msieIndex, 1));
    }

    if (this.convert || (ie && ie_ver < 8)) {

        var ad = url.split("?");
        goodURL = ad[0];
        if (ad[1]) goodURL += '?' + this.convertQuery(ad[1]);
    } else goodURL = url;

    this._req.open(this.method, goodURL, true);

    this._req.onreadystatechange = function() {

        switch(instance._req.readyState) {
            case 1:
                instance.loading();
                break;

            case 2:
                instance.loading();
                break;

            case 3:
                instance.interactive();
                break;

            case 4:
                instance.complete(
                instance._req.status,
                instance._req.statusText,
                instance._req.responseText,
                instance._req.responseXML,
                this
            );
                break;

        }
    }

    if (this.method == 'POST') {
//        content = this.convertQuery(content);
        this._req.setRequestHeader(
        'Content-Type', this.enctype);
    }
    this._req.send(content);
}

function Asynchronous_loading(){}
function Asynchronous_loaded(){}
function Asynchronous_interactive(){}
function Asynchronous_complete(status, statusText, responseText, responseXML, ajax){}

Asynchronous.prototype.setEnctype = function(enctype) {
   if (!enctype) this.enctype = 'application/x-www-form-urlencoded';
   else this.enctype = enctype;
}

Asynchronous.prototype.convertQuery = function(query) {

    var goodQuery = '';
    var params = query.split('&');

    var n;
    var param;
    for (n = 0; n < params.length; n++) {
        param = params[n].split('=');
        goodQuery += '&' + param[0] + '=' + encodeURIComponent(param[1]);
    }

    return goodQuery;
}
