Ajax = {};


Ajax.createXMLHttpRequest = function(anotherWindow) {
    var http_request = false;
    if (!anotherWindow)
    	anotherWindow = window;

    //alert('location: ' + anotherWindow.location);
    
    //if (anotherWindow.XMLHttpRequest) { // Mozilla, Safari,...
    if (Browser.getEngine() != 'ie'){
        http_request = new anotherWindow.XMLHttpRequest();
        if (http_request.overrideMimeType) {
            http_request.overrideMimeType('text/xml');
        }
    } else if (anotherWindow.ActiveXObject) { // IE
        try {
            http_request = new anotherWindow.ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {
            try {
            	http_request = new anotherWindow.ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {}
        }
    }

    if (!http_request) {
        alert('Giving up :( Cannot create an XMLHTTP instance');
    }
    return http_request;
};

Ajax.ajaxCall = function(source, mode, params, callback){
    var req = Ajax.createXMLHttpRequest(); 
    
    var ajaxArgs = arguments;
    
    function processRequest() { 
        // readyState of 4 signifies request is complete 
        if (req.readyState == 4) { 
            // status of 200 signifies sucessful HTTP call 
            if (req.status == 200) {
                try {
                    var xml = req.responseXML;
                    var root = Ajax.selectNodes(xml, null, '/response');
                    if (root != null)
                    	root = root[0];
                    var type = root == null ? null : root.getAttribute("type");
                    if (type == "xml" || type == "html"){
                        if (callback) {
                            if(ajaxArgs.length > 4 || typeof(callback) == "string") {
                                var call = 'callback(req';
                                for(var i = 4; i < ajaxArgs.length; i++)
                                    call += ', ajaxArgs[' + i + ']';
                                call += ')';
                                eval(call);
                            } else {
                                callback(req);
                            }
                        }
                    } else if (type == "redirect") {
                        window.location = root.firstChild.nodeValue;
                    }
                } finally {
                    if(Browser.getEngine() == 'opera') {
                        req.abort();
                    }
                    
                }
            }
        }
    }
    req.onreadystatechange = processRequest;
    
    var parameters = 'action=ajax&source=' + source + '&mode=' + mode + '&' + params;
    req.open('POST', window.location.pathname, true);
    req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    req.setRequestHeader('Content-length', parameters.length);
    req.setRequestHeader('Connection', 'close');
    req.send(parameters);
};


Ajax.selectNodes = function(doc, contextNode, xpath){
    if(Ajax.isEmpty(doc))
        return null;
    if (Browser.getEngine() == 'ie') {
        if(contextNode)
            return contextNode.selectNodes(xpath) ;
        else
            return doc.selectNodes(xpath);
            //doc.documentElement.selectNodes(xpath) ;
    }
    else {
    	if (Ajax.isEmpty(doc.documentElement))
    		return null;
        var aNodeArray = new Array();
        var xPathResult = doc.evaluate(xpath, contextNode ? contextNode : doc.documentElement, 
            null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null) ;
        if (xPathResult) {
            var oNode = xPathResult.iterateNext() ;
            while( oNode ) {
                aNodeArray[aNodeArray.length] = oNode ;
                oNode = xPathResult.iterateNext();
            }
        } 
        return aNodeArray ;
    }
};


Ajax.nodeValue = function(doc, current, path) {
    var res = null;
    try {
        var node = Ajax.selectNodes(doc, current, path)[0];
        // большие текстовые ноды разбиваются на множество фрагментов!
        // в FF по 4 килобайта, в Опере по 32
        res = '';
        node = node.firstChild;
        while(node) {
            res += node.nodeValue;
            node = node.nextSibling;
        }
    }
    catch(e){}
    return res;
};

Ajax.selectNodeText = function(doc, path) {
    return Ajax.nodeValue(doc, null, path);
};

Ajax.quote = function(text){
    if (encodeURIComponent) {
        return encodeURIComponent(text);
    } else {
        return escape(text);
    }
};

Ajax.extractHtml = function(req){
	var xml = req.responseXML;
	var response = Ajax.selectNodes(xml, null, "/response")[0];
	var res = "";
	for (var i=0; i<response.childNodes.length; i++)
		res += response.childNodes[i].nodeValue;
	return res;
};

Ajax.trim = function(s) {
    if(!s)
        return '';
    return s.replace(/(^\s+)|(^\u00A0+)|(^\u00A0+)|(\s+$)/g, ''); 
};

Ajax.isEmpty = function(s) {
    if(s == null || typeof(s) == "undefined")
        return true;
    if(s instanceof Array)
        return s.length == 0;
    if(typeof(s) == "string")
        return Ajax.trim(s).length == 0;
    return false;
};
