// JS ajax microlibrary
// Programmed by Ben in 2007

function InitAjax(){
	var ajax=false;
	if(document.all){
		try {
			ajax = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				ajax = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (E) {
				ajax = false;
			}
		}
	}
	else if (!ajax && typeof XMLHttpRequest!='undefined') {
		ajax = new XMLHttpRequest();
	}
	return ajax;
}

function html_entities_decode(v){
	var o = document.createElement("textarea");
	o.innerHTML = v.replace(/</g,"&lt;").replace(/>/g,"&gt;");
	return o.value;
}

function ajax_call(url, div_name, div_loading, binded_action){
	if(div_loading!=null){ document.getElementById(div_loading).style.display = 'inline'; }	
	if(typeof(url) == 'undefined'){ return false; }
	var ajax = InitAjax();
	ajax.open("GET", url, true);
 	ajax.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
	ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	ajax.send(null);
	ajax.onreadystatechange = function() {
		if(ajax.readyState == 4 && ajax.status == 200) {
			var d = document.getElementById(div_name);
			var c = html_entities_decode(ajax.responseText);
			if(div_loading!=null){ document.getElementById(div_loading).style.display = 'none'; }
			if(document.all) { // IE QUICKFIX ONLY
				if(ajax.responseText.indexOf('<option') === 0 || ajax.responseText.indexOf('<OPTION') === 0){
					d.innerHTML = '<option>1</option>' + c;
				}
   				else{
					d.innerHTML = c;
				}
				d.outerHTML = document.getElementById(div_name).outerHTML;
			}
			else{
				d.innerHTML = c;
			}
			
			// Clean up content
			repl = new RegExp('//.*?$', 'gm');
			c = c.replace(repl, '\n');
			repl = new RegExp('[\n\r]', 'g');
			c = c.replace(repl, ' ');
			
			// Match anything inside <script> tags
			src = new RegExp('<script.*?</script>', 'g');
			matches = c.match(src);
			
			// For each match that is found...
			if(matches != null){
				for(i = 0; i < matches.length; i++){
					// Remove begin/end tag
					var repl = new RegExp('<script.*?>', 'gm');
					var script = matches[i].replace(repl, '');
					repl = new RegExp('</script>', 'gm');
					script = script.replace(repl, '');
					
					// Insert script tags in the HEAD section (needed under IE for function calls)
					var head = document.getElementsByTagName('head').item(0);
					var s = document.createElement('script');
					s.type = 'text/javascript';
					s.text = script;
					head.appendChild(s);
					
					// Execute commands
					setTimeout(script, 200);
				}
			}
			if(typeof(binded_action) != 'undefined'){ eval(binded_action); }
		}
	}
}
