// Generic AJAX applicator
//
// Example: 
//
// var show_tabbed_panel = function (text) { document.getElementById('tabbed_panel').innerHTML = text); };
// AJAXRequest(show_tabbed_panel, "audio/tabbed_panel");
//
// The page ajax.php must return something for elem=audio/tabbed_panel

function BadResponse(msg) {
	this.name    = "BadResponseFromServer";
	this.message = msg;
}


function AJAXRequest(fn, elem)
{
	// September 26, 2007
	// BUGFIX: Fetches the ajax page in a domain-independent way. Otherwise it breaks when you
	//         access the site at cititune.com instead of www.cititune.com.
	var url = "ajax.php?elem=" + elem;

	var xmlHttp = getXmlHttpObject();
	if (xmlHttp == null)
	{
		alert("This browser does not support AJAX");
		return false;
	}

	xmlHttp.onreadystatechange = function () {
		if(xmlHttp.readyState == 4  ||  xmlHttp.readyState == "complete") {
			if(xmlHttp.status == 200) {
				fn(xmlHttp.responseText);
			} else {
				// fixme: This doesn't show the error object in Firefox's error console
				throw new BadResponse(xmlHttp.status);
			}
		}
	}

	try {
		xmlHttp.open("GET",url,true);
		xmlHttp.send(null);
	} catch(e) {
		alert('failed to fetch dynamic content.\nError name: ' + e.name + '\nError message: ' + e.message + "\nurl: " + url);
	}
}

function getXmlHttpObject()
{
	var xmlHttp = null;
	try
	{
		// Firefox, Opera 8.0+, Safari
		xmlHttp = new XMLHttpRequest();
	}
	catch (e)
	{
		try
		{
			// Internet Explorer
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
	}

	return xmlHttp;
}

// Helper function for when calling AJAXRequest
function insertContent(elementid) {
	return function(text) {
		document.getElementById(elementid).innerHTML = text;
	}
}

