/*global window */

var ajax = {};


ajax.GetXmlHttp = function () {
    var xmlhttp = false;
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        try {
            xmlhttp = new window.ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                xmlhttp = new window.ActiveXObject("Microsoft.XMLHTTP");
            } catch (E) {
                xmlhttp = false;
            }
        }
    }
    return xmlhttp;
};


ajax.setInnerHTMLFromAjaxResponse = function (url, obj_id, method) {
    var xmlhttp = new ajax.GetXmlHttp(),
        async = true;

    if (!xmlhttp) {
        return;
    }
    
    if (!method) {
        method = 'post';
    }

    xmlhttp.onreadystatechange = 
        function onReadStateChange() {
            try {
                if (xmlhttp && xmlhttp.readyState === 4) {
                    if (xmlhttp.status === 200) {
                        if (typeof obj_id === 'object') {
                            obj_id.innerHTML = xmlhttp.responseText;
                        } else {
                            document.getElementById(obj_id).innerHTML = xmlhttp.responseText;
                        }
                    }
                }
            } catch (ex) {
                alert('onReadStateChange()\n' + ex.message);
            }
        };
    
    // add random number, to prevent IE from caching
    url += '&random_number=' + Math.random();
    xmlhttp.open(method, url, async);
    xmlhttp.send(null);
};


ajax.callFunctionWithResponse = function (url, method, f) {
    var xmlhttp = new ajax.GetXmlHttp(),
        async = true;

    if (!xmlhttp) {
        return;
    }
    
    if (!method) {
        method = 'post';
    }

    xmlhttp.onreadystatechange = 
        function onReadStateChange2() {
            try {
                if (xmlhttp && xmlhttp.readyState === 4) {
                    if (xmlhttp.status === 200) {
                        if (f) {
                            f(xmlhttp.responseText);
                        }
                    }
                }
            } catch (ex) {
                alert('onReadStateChange2()\n' + ex.message);
            }
        };
    
    // add random number, to prevent IE from caching
    url += '&random_number=' + Math.random();
    xmlhttp.open(method, url, async);
    xmlhttp.send(null);
};

