
/**
 * JavaScript to run AJAX query and build random featured widgets.  To use this, the calling page must:
 * 1.  Include validation.js and this script
 * 2.  Build a list with list items defined as:
 *		<li class='featured_widget'>
 */

// attach an onload event listener
if(typeof window.addEventListener != 'undefined')
{
	//.. gecko, safari, konqueror and standard
	window.addEventListener('load', showFeaturedWidget, false);
}
else if(typeof document.addEventListener != 'undefined')
{
	//.. opera 7
	document.addEventListener('load', showFeaturedWidget, false);
}
else if(typeof window.attachEvent != 'undefined')
{
	//.. win/ie
	window.attachEvent('onload', showFeaturedWidget);
}
else
{
	//.. mac/ie5 and anything else that gets this far
	
	//if there's an existing onload function
	if(typeof window.onload == 'function')
	{
		//store it
		var existing = onload;
		
		//add new onload handler
		window.onload = function()
		{
			//call existing onload function
			existing();
			
			//call generic onload function
			showFeaturedWidget();
		};
	}
	else
	{
		//setup onload function
		window.onload = generic;
	}
}


var xmlHttp;

var i;
var elements;

function showFeaturedWidget() {
	var bigElems = cssQuery("LI[class~='featured_widget_big']");
	var smallElems = cssQuery("LI[class~='featured_widget_small']");
	elements = bigElems.concat(smallElems);
	if (elements && elements.length > 0) {
		i = -1;
		runAjax();
	}
}

function runAjax() {
	i++;
	if (i < elements.length) {
		xmlHttp = GetXmlHttpObject();
		if (xmlHttp == null) {
			alert("Browser does not support HTTP Request");
			return;
		}
		var width = elements[i].className.indexOf('featured_widget_big') >= 0 ? 82 : 41;
		var height = elements[i].className.indexOf('featured_widget_big') >= 0 ? 78 : 39;
		var url = siteurl + "/mediamanage/featured_widget_ajax?img_width=" + width + "&img_height=" + height;
		xmlHttp.onreadystatechange = stateChanged;
		xmlHttp.open("GET", url, true);
		xmlHttp.send(null);
	}
}

function stateChanged() {
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
		//document.getElementById("featured_media").innerHTML = xmlHttp.responseText;
		elements[i].innerHTML = xmlHttp.responseText;
		runAjax();
	}
}

function GetXmlHttpObject() {
	var xmlHttp = null;
	try { // Firefox, Opera 8.0+, Safari
		xmlHttp = new XMLHttpRequest();
	} catch(e) { //Internet Explorer
		try {
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e) {
			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	return xmlHttp;
}