// AJAX
// based on standard ajax function (downloaded)

function ajax(file, params, target_id, method, load_id, runscript) {

	if(!method)		{ var method = 'GET'; }
	if(!load_id)	{ var load_id = false; }
	if(!runscript)	{ var runscript = handleRequest; }

	if(method != 'POST' && method != 'GET') {

		for(var i=0; i < method.length; i++){
			if(method[i].name) {
				if(method[i].type == 'checkbox' || method[i].type == 'radio') {
					if(method[i].checked == true) {
						params += '&'+method[i].name+'='+urlstring.encode(method[i].value);
					}
				} else {
					params += '&'+method[i].name+'='+urlstring.encode(method[i].value);
				}
			}
		}

		var method = method.method.toUpperCase();
	} else {
//		params = urlstring.encode(params);
	}

	sendRequest(file, params, runscript, target_id, method, load_id);
}


// request, called by the application
function sendRequest(url, params, callback, target_id, method, load_id, runscript) {
//alert(url);
//alert(params);
//alert(callback);
//alert(target_id);
//alert(method);
//alert(load_id);
//alert(runscript);

//alert(' url: '+url+'\n params: '+params+'\n target_id:'+target_id+'\n method: '+method);

	if(load_id == true || load_id == undefined) {
		var loadDIV = document.getElementById(target_id);
		var loadgif = 'large';
		var size	= 32;
	} else if (load_id != false) {
		var loadDIV = document.getElementById(load_id);
		var loadgif = 'small';
		var size	= 16;
	}

	if (load_id != false) {
		var loadPosLeft	= (loadDIV.style.width.substr(0,loadDIV.style.width.length-2) / 2) - (size / 2);
		var loadPosTop	= (loadDIV.style.height.substr(0,loadDIV.style.height.length-2) / 2) - (size / 2);

		loadDIV.innerHTML = '<img style="position: relative; width: 16px; height: 16px; top: '+loadPosTop+'px; left: '+loadPosLeft+'px;" src="'+ajaxImagePath+'ajax_loader_'+loadgif+'.gif">';
	}

	if(method == 'GET') {
		open_url = url+'?'+params;
		postData = null;
	}
	if(method == 'POST') {
		open_url = url;
		postData = params;
	}

	var req = createXMLHTTPObject();
    if (!req) return;
    req.open(method,open_url,true);
    req.setRequestHeader('User-Agent','XMLHTTP/1.0');
    if (postData)
		req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    req.onreadystatechange = function () {
        if (req.readyState != 4) return;
        if (req.status != 200 && req.status != 304) {
//            alert('HTTP error ' + req.status);
            return;
        }
        if(typeof(loadDIV) != 'undefined') { loadDIV.innerHTML = ''; }
		callback(req,target_id);
    }
    if (req.readyState == 4) return;
    req.send(postData);
}

// factories
var XMLHttpFactories = [
    function () {return new XMLHttpRequest()},
    function () {return new ActiveXObject("Msxml2.XMLHTTP")},
    function () {return new ActiveXObject("Msxml3.XMLHTTP")},
    function () {return new ActiveXObject("Microsoft.XMLHTTP")}
];

// XML object based on factory
function createXMLHTTPObject() {
    var xmlhttp = false;
    for (var i=0;i<XMLHttpFactories.length;i++) {
        try {
            xmlhttp = XMLHttpFactories[i]();
        }
        catch (e) {
            continue;
        }
        break;
    }
    return xmlhttp;
}

// update the target
function handleRequest(req, target_id) {
	//alert('ajax: going writeroot');
    var writeroot			= document.getElementById(target_id);
    writeroot.innerHTML		= req.responseText;

	//runScripts(document.getElementById(target_id));
}

// run scripts
function runScripts(e) {

	if (e.nodeType != 1) return; //if it's not an element node, return

	if (e.tagName.toLowerCase() == 'script') {
		eval(e.text); //run the script
	}

	var n = e.firstChild;
	while ( n ) {
		if ( n.nodeType == 1 ) runScripts( n ); //if it's an element node, recurse
		n = n.nextSibling;
	}
}


// urlencoding
var urlstring = {

    // public method for url encoding
    encode : function (string) {
        return escape(this._utf8_encode(string));
    },

    // public method for url decoding
    decode : function (string) {
        return this._utf8_decode(unescape(string));
    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }
}