/* Browser identification */

var bSaf = (navigator.userAgent.indexOf('Safari') != -1);
var bOpera = (navigator.userAgent.indexOf('Opera') != -1);
var bMoz = (navigator.appName == 'Netscape');

var bAJAX = window.XMLHttpRequest || window.ActiveXObject;

var spinCount = 0;

function startSpinner () {
	if (spinCount == 0) {
		document.getElementById ("spinner").style.display = "block";
	}
	spinCount = spinCount + 1;
}

function stopSpinner () {
	if (spinCount == 0) alert ("INTERNAL ERROR: Spinner underrun");
	spinCount = spinCount - 1;
	if (spinCount == 0) {
		document.getElementById ("spinner").style.display = "none";
	}
}

function ahah(url,target,method) {
	startSpinner ();
	document.getElementById(target).className = 'fetching';

	if (window.XMLHttpRequest) {
		req = new XMLHttpRequest();
		req.onreadystatechange = function() {ahahDone(target);};
		req.open(method, url, true);
		req.send(null);
	}
	else if (window.ActiveXObject) {
		req = new ActiveXObject("Microsoft.XMLHTTP");
		if (req) {
			req.onreadystatechange = function() {ahahDone(target);};
			req.open(method, url, true);
			req.send();
		}
	}
}

function execJS(node) {
	var st = node.getElementsByTagName('SCRIPT');
	var strExec;
	for(var i=0;i<st.length; i++) {     
		if (bSaf) {
			strExec = st[i].innerHTML;
		}
		else if (bOpera) {
			strExec = st[i].text;
		}
		else if (bMoz) {
			strExec = st[i].textContent;
		}
		else {
			strExec = st[i].text;
		}
		try {
			eval(strExec);
		} catch(e) {
			alert("INTERNAL ERROR: " + e);
		}
	}
}

function doFade (target,index) {
	if (index > fadeColours.length) {
		/* We are done */
		document.getElementById(target).style.backgroundColor = "transparent";
	}
	else {
		document.getElementById(target).style.backgroundColor = fadeColours[index];
		setTimeout ("doFade('" + target + "'," + (index+1) + ")", 1000 / fadeColours.length);
	}
}

function ahahDone(target) {
	// only if req is "loaded"
	if (req.readyState == 4) {
		stopSpinner ();
		// only if "OK"
		if (req.status == 200 || req.status == 304) {
			results = req.responseText;
			document.getElementById(target).innerHTML = results;
			execJS (document.getElementById (target));
			document.getElementById(target).className = "normal";
			doFade (target,1);
		} else {
			/* FIXME: Better error handling */
			alert ("NETWORK ERROR: " + req.status + ": " + req.statusText);
			document.getElementById(target).className = "normal";
		}
	}
}

function htmlentities (string) {
	string = string.replace(/&/g,"&amp;");
	string = string.replace(/</g,"&lt;");
	string = string.replace(/'/g,"&apos;");
	string = string.replace(/"/g,"&quot;");
	return string;	
}
