/**
 * XML HTTP Request emulation layer for icefaces.  Enables ajax style communication through hidden iframes to
 *
 */

goog.require('goog.net.IframeIoWf');
goog.require('goog.events');
goog.require('goog.structs.Map');

var doDebug = false;
var count = 0;

var isFunction = function(o) {
    return typeof(o) == 'function' && (!Function.prototype.call ||
                                       typeof(o.call) == 'function');
};

function debugNode(obj,prefix) {
    if(!prefix) prefix = "";
    if (doDebug) {
        var dbg = document.getElementById("myDebugArea");
        dbg.appendChild(document.createTextNode(prefix+" DebugNode: "+obj));

        //create the debug container if needed
        if (!dbg) { //create the debug container if needed
            dbg = document.createElement("div");
            dbg.id = "myDebugArea";
            document.body.appendChild(dbg);
            t = document.createElement("h2");
            t.appendChild(document.createTextNode("DEBUG"));
            dbg.appendChild(t);
        }

        dbg.appendChild(document.createTextNode(" type: "+obj.nodeType));
        dbg.appendChild(document.createTextNode(" name: "+obj.nodeName));
        dbg.appendChild(document.createTextNode(" text: "+obj.text));
        dbg.appendChild(document.createTextNode(" xml: "+obj.xml));
        dbg.appendChild(document.createTextNode(" value: "+obj.nodeValue));
        dbg.appendChild(document.createTextNode(" children: "+obj.childNodes.length));
        var txt = "";
        for (prop in obj) {
            txt += prop +", ";
        }
        dbg.appendChild(document.createTextNode(txt));
        dbg.appendChild(document.createElement("br"));

        for(var i=0; i<obj.childNodes.length; i++) {
            dbg.appendChild(document.createElement("br"));
        }
    }

}


// ******************************************
function debug(msg, obj, tablevel) {

    if(tablevel == null) {
        tablevel = 0;
    }

    if (doDebug) {
        var dbg = document.getElementById("myDebugArea");

        //create the debug container if needed
        if (!dbg) { //create the debug container if needed
            dbg = document.createElement("div");
            dbg.id = "myDebugArea";
            document.body.appendChild(dbg);
            t = document.createElement("h2");
            t.appendChild(document.createTextNode("DEBUG"));
            dbg.appendChild(t);
        }

        //add the message to the debug container
        dbg.appendChild(document.createTextNode(msg));
        dbg.appendChild(document.createElement("br"));

        if (obj) {
            var txt = "***** Object Dump *****";
            dbg.appendChild(document.createTextNode(txt));
            dbg.appendChild(document.createElement("br"));

            for (prop in obj) {
                var txt = prop + ": " + obj[prop];
                dbg.appendChild(document.createTextNode(txt));
                dbg.appendChild(document.createElement("br"));
                //        debugObject(1,obj[prop],dbg);
            }

            var txt = "***** END of Object Dump ******************";
            dbg.appendChild(document.createTextNode(txt));
            dbg.appendChild(document.createElement("br"));
        }
    }
}

function debugObject(tabLevel,obj,dbg) {
    var prefix = "";
    for(var i=0; i<tabLevel; i++) {
        prefix += "-";
    }
    for(prop in obj) {
        if(obj[prop] != undefined) {
            if(!isFunction(obj[prop])) {
                var txt2 = prefix+" " + prop + ": " + obj[prop];
                dbg.appendChild(document.createTextNode(txt2));
                dbg.appendChild(document.createElement("br"));
                if(tabLevel+1 < 2) {
                    debugObject(tabLevel+1,obj[prop],dbg);
                }
            }
        }
    }
}


function getContentDocument(frameElement) {
    if(frameElement.contentWindow && frameElement.contentDocument == null) return frameElement.contentWindow.document;
    return frameElement.contentDocument;
}

function xmlError(e) {
    //there was an error, show the user
    alert(e);
}

if (window.ActiveXObject && !window.XMLHttpRequest) {

    var nativeXmlParser = new DOMImplementation();

    window.XMLHttpRequest = function() {

        var self = this;

        this._init = function() {
//            debug('Init request '+count);
            self._need_send = false;
            self._send_arg = null;
            self._timer_id = 0;
            self.readyState = 0;
            self.onreadystatechange = null;
            self.statusText = 'OK';
            self.responseText = null;
            self.responseXML = null;
            self.parser = null;
            self.parsing = false;
            self.status = 0;
            self._id = count++;
        };

        this.open = function(method, action, async) {

//            debug('Request open');

            if (self.form) return;

            self.method = method;
            self.action = action;
            self.async = async;

            self.onreadystatechange = function() {
                if (self.readyState == 4) {
                    this.onreadystatechange = null;
                    if (self._need_send) self.form.submit();
                    self._timer_id = setInterval(function(e){
                        if (self.isReady()) {
                            clearInterval(self._timer_id);
                            self._timer_id = 0;
                            self.status = 200;
                            self.readyState = 4;
                            if (self.onreadystatechange) self.onreadystatechange();
                        }
                    }, 100);
                }
            };

            self.readyState = 4;
            self.onreadystatechange();
        };

        this.send = function(data) {                                         
//            debug(this._id+': Iframe preparation '+data+' status='+self.status);
            self._send_arg = data;

            //google iframeio has been customised as map cannot take multiple same params
            //which are used by multiple select boxes
            var params = self._send_arg.split("&");
            this.iframe = new goog.net.IframeIoWf();
            this.iframe._id = this._id;
            goog.events.listen(this.iframe, goog.net.EventType.ERROR, function() { self.status = 500; });
            this.iframe.send(self.action,'POST',true,params);

//            debug(this._id+': Iframe sent status is '+self.status);
        };

        this.isReady = function() {
            if(this.iframe.isComplete()) {
                self.responseText = this.iframe.getResponseHtml();
                self.responseXML = this.iframe.getResponseText();
//                debug(this._id+': Response ready '+self.responseText+" error code is "+this.iframe.getLastErrorCode()+' self status='+self.status);
                return true;
            }
            return false;
        };

        this.abort = function() {
            if (self._timer_id) {
                clearInterval(self._timer_id);
                self._timer_id = 0;
            }
        };

        this.setRequestHeader = function(name, value) {
            // not implemented
        };

        this.getAllResponseHeaders = function() {
            return "Content-Type: text/xml; charset=utf-8\n";
        };

        this.getResponseHeader = function(name) {
            if(name == 'Content-Type') return "text/xml; charset=utf-8";
            return null;
        };

        this.contentAsDOM = function() {
            return this.responseText;
        };

        this._init();
    };

}

