var xmlPending = false;
//based on prototype's ajax class
//to be used with prototype.lite, moofx.mad4milk.net.
//updated by andre, webeffekt.no
var ajax = Class.create();
ajax.prototype = {
    initialize: function (url, options) {
        if (xmlPending) return;
        xmlPending = true;
        this.transport = this.getTransport();
        this.callbackDiv = options.callbackDiv || null;
        this.callbackFunction = options.callbackFunction || null;
        this.postBody = options.postBody || null;
        this.method = (options.method) ? options.method.toUpperCase() : 'GET';
        this.onComplete = options.onComplete || null;
        this.update = (options.update) ? $(options.update) || null : null;
        this.request(url);
    },

    request: function (url) {
        this.transport.open(this.method, url, true);
        this.transport.onreadystatechange = this.onStateChange.bind(this);
        if (this.method == 'POST') {
            this.transport.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=UTF-8');
            if (!jQuery.browser.webkit && this.transport.overrideMimeType) {
                this.transport.setRequestHeader('Connection', 'close');
            }
        }
        this.transport.send(this.postBody);
    },

    onStateChange: function () {
        if (this.transport.readyState == 4 && (this.transport.status == 200 || this.transport.status == 0)) {
            xmlPending = false;
            if (this.onComplete) {
                setTimeout(function () { this.onComplete(this); } .bind(this), 10);
            }
            else if (this.update) {
                var oTmp = this.transport.responseXML.getElementsByTagName('description')
                if (oTmp.length == 1)
                    this.descHTML = oTmp[0].firstChild.data;
                setTimeout(function () { this.update.innerHTML = this.descHTML; } .bind(this), 10);
                //setTimeout(function(){this.update.innerHTML = this.transport.responseText;}.bind(this), 10);
            }
            this.transport.onreadystatechange = function () { };
        }
        else if (this.transport.readyState == 4) {
            xmlPending = false;
            alert(this.transport.status + ':' + this.transport.statusText);
        }
    },

    getTransport: function () {
        if (window.ActiveXObject) {
            var types = ['MSXML2.XMLHTTP', 'Microsoft.XMLHTTP'];
            for (var i = 0; i < types.length; i++) {
                try {
                    return new ActiveXObject(types[i]);
                } catch (e) { }
            }
            return false;
        } else if (window.XMLHttpRequest) {
            return new XMLHttpRequest();
        } else { return false; }
    }
};
