var JSON = {
    sendData : null,
    debug    : false,
    nocache  : false,
    createRequestObject : function()
    {
        var ro = null;
        if (window.XMLHttpRequest) {
            try {
                ro = new XMLHttpRequest();
            } catch(e) { JSON.debugAlert(e); }
        } else if (window.ActiveXObject) {
        	var o = ["MSXML2.XMLHTTP.6.0","MSXML2.XMLHTTP.3.0","MSXML2.XMLHTTP","Microsoft.XMLHTTP"];
            for (var ie in o) {
                try {
                    ro = new ActiveXObject(o[ie]);
                    break;
                } catch(e) { JSON.debugAlert(e); }
            }
        }
        return ro;
    },

    debugAlert : function(e)
    {
        if (JSON.debug) {
	        var out = '';
	        for (var i in e) {
	            out += i + ': ' + e[i] + '\n';
	        }
	        alert(out);
        }
    },

    setPostData : function(sendData)
    {
        JSON.sendData = sendData;
    },

    setResponseFunction : function(responseFunction)
    {
        JSON.responseFunction = responseFunction;
    },

    sndReq : function(url)
    {
        var xhr = JSON.createRequestObject();
        if (!xhr) {
            alert('Giving up :( Cannot create an XMLHTTP instance for:\n  ' + url);
            return false;
        }
        //if (xhr.overrideMimeType) {
            //xhr.overrideMimeType('text/xml');
        //}
        xhr.onreadystatechange = function() { JSON.handleResponse(xhr); };
        var method = JSON.sendData ? 'POST' : 'GET';
        xhr.open(method, url, true);
        if (method == 'POST') {
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.setRequestHeader("Content-Length", JSON.sendData.length);
        }
        /**
         * Note:
         * IE may ignore the no-cache directive so be prepared to send a
         *   'Cache-Control: no-cache'
         * directive from your server-side code to keep it in accordance.
         */
        if (JSON.nocache) {
            xhr.setRequestHeader('Cache-Control', 'no-cache');
        }
        xhr.setRequestHeader("Connection", "close");
        xhr.send(JSON.sendData);
    },

    handleResponse : function(xhr)
    {
        try {
            if (xhr.readyState == 4) {
				/**
				 *
				var d = document;
				var p = d.getElementById('todd');
				p.appendChild(d.createTextNode('readyState: ' + xhr.readyState + ' ::: Status: ' + xhr.status + ':\n'));
				p.appendChild(d.createTextNode(xhr.getAllResponseHeaders() + '\n\n'));
				 */
                if (xhr.status == 200) {
                    JSON.responseFunction(jsonParse(xhr.responseText));
                } else if (JSON.debug) {
	                alert('There was a problem with the request:\nreadyState: ' + xhr.readyState + '\nStatus: ' + xhr.status);
                }
            }
        } catch(e) {
            JSON.debugAlert(e);
        }
    }
};
