// JavaScript Document

// Creates the new object
var Ad;
if (!Ad) Ad = {}
else if (typeof Ad != "object") throw new Error("'Ad' already exists and is not an object");

// Sets the display time per ad, in seconds
Ad.homeDisplayTime = 10;
Ad.sidebarDisplayTime = 6;
Ad.displayTime = Ad.homeDisplayTime;

// Sets the script URL and ad image directory
Ad.scriptURL = "/ajax/ads.aspx";
Ad.imageURL = "/cms/ads/";

// Set up URLs for loading and error icons
Ad.loaderIconURL = "/images/icons/loading_wheel.gif";
Ad.errorIconURL = "/images/icons/error.gif";

// Set up control image URLs
Ad.controlImg = new Array('/images/buttons/ctl_play.gif',
						  '/images/buttons/ctl_play1.gif',
						  '/images/buttons/ctl_play2.gif',
						  '/images/buttons/ctl_play3.gif',
						  '/images/buttons/ctl_play4.gif',
						  '/images/buttons/ctl_play5.gif',
						  '/images/buttons/ctl_play6.gif',
						  '/images/buttons/ctl_stop.gif',
						  '/images/buttons/ctl_stop1.gif',
						  '/images/buttons/ctl_stop2.gif',
						  '/images/buttons/ctl_stop3.gif',
						  '/images/buttons/ctl_stop4.gif',
						  '/images/buttons/ctl_stop5.gif',
						  '/images/buttons/ctl_stop6.gif');

// Declare properties
Ad.playStatus = false;
Ad.listTimer = null;
Ad.dissolveTimer = null;
Ad.playTimer = null;
Ad.waitTimer = null;
Ad.firstLoad = true;
Ad.index = 0;
Ad.opacity = 0;
Ad.statusMode = 0;
Ad.list = new Array();
Ad.session = (new Date).getTime();

// Sets up the ad contoller
Ad.setupControls = function() {
	var controller = document.getElementById("adcontrol");
	var map = document.getElementById("AdControls");
	if (controller && map) {
		controller.style.cssText = '-moz-outline: 0; outline: 0;';
		map.style.cssText = '-moz-outline: 0; outline: 0;';
		// Preload all controller images
		for (var x = 1; x < Ad.controlImg.length; x++) (new Image()).src = Ad.controlImg[x];
		// Preload status and error icons
		(new Image()).src = Ad.loaderIconURL;
		(new Image()).src = Ad.errorIconURL;
		// Creates image map area items
		map.style.outline = '0';
		var adprev = document.createElement("area");
		adprev.id = "AdPrev";
		Ad.setRollover(adprev, controller, 0, 1, 4);
		adprev.setAttribute("shape", "rect");
		adprev.setAttribute("coords", "0,0,18,17");
		//adprev.setAttribute("href", "javascript:Ad.goPrev();");
		adprev.setAttribute("href", "javascript:void(0);");
		adprev.onclick = Ad.goPrev;
		adprev.setAttribute("alt", "Previous");
		adprev.style.cssText = '-moz-outline: 0; outline: 0;';
		map.appendChild(adprev);
		var adps = document.createElement("area");
		adps.id = "AdPlayStop";
		Ad.setRollover(adps, controller, 0, 2, 5);
		adps.setAttribute("shape", "rect");
		adps.setAttribute("coords", "18,0,67,17");
		//adps.setAttribute("href", "javascript:Ad.playStop();");
		adps.setAttribute("href", "javascript:void(0);");
		adps.onclick = Ad.playStop;
		adps.setAttribute("alt", "Play");
		adps.style.cssText = '-moz-outline: 0; outline: 0;';
		map.appendChild(adps);
		var adnext = document.createElement("area");
		adnext.id = "AdNext";
		Ad.setRollover(adnext, controller, 0, 3, 6);
		adnext.setAttribute("shape", "rect");
		adnext.setAttribute("coords", "67,0,84,17");
		//adnext.setAttribute("href", "javascript:Ad.goNext();");
		adnext.setAttribute("href", "javascript:void(0);");
		adnext.onclick = Ad.goNext;
		adnext.setAttribute("alt", "Next");
		adnext.style.cssText = '-moz-outline: 0; outline: 0;';
		map.appendChild(adnext);
		return true;
	}
	else return false;
}

// Gets the list of ads from the server and display the first one
Ad.getData = function() {
	var ad = document.getElementById("ad");
	var type = (ad.className == "spot-ad") ? "H" : "S";
	Ad.displayLoader();
	if (Ad.listTimer != null) {
		clearTimeout(Ad.listTimer);
		Ad.listTimer = null;
	}
	if (request.readyState == 0 || request.readyState == 4) {
		// Determine if this is for home page or sidebar ads
		request.open("POST", Ad.scriptURL, true);
		request.onreadystatechange = Ad.parseData;
		request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		request.send("t=" + escape(type));
	} else Ad.listTimer = setTimeout(Ad.getData, 0);
}

// Parses the XML list and turns it into a JavaScript object
Ad.parseData = function() {
	if (request.readyState == 4) {
		// Display ad list table
		if (request.status == 200) {
			// Process the resulting XML and turn it into a JavaScript object
			// Get the XML response
			var xmlDoc = request.responseXML;
			var rs = xmlDoc.getElementsByTagName("Ads");
			for (var x = 0; x < rs.length; x++) {
				var id = (rs[x].getElementsByTagName("ID")[0]) ? rs[x].getElementsByTagName("ID")[0].firstChild.nodeValue : "";
				var index = (rs[x].getElementsByTagName("IndexID")[0]) ? rs[x].getElementsByTagName("IndexID")[0].firstChild.nodeValue : "";
				var description = (rs[x].getElementsByTagName("Description")[0]) ? rs[x].getElementsByTagName("Description")[0].firstChild.nodeValue : "";
				var url = (rs[x].getElementsByTagName("LinkURL")[0]) ? rs[x].getElementsByTagName("LinkURL")[0].firstChild.nodeValue : "";
				var target = (rs[x].getElementsByTagName("LinkTarget")[0]) ? rs[x].getElementsByTagName("LinkTarget")[0].firstChild.nodeValue : "";
				Ad.list.push({"ID": id, "IndexID": index, "Description": description, "LinkURL": url, "LinkTarget": target });
			}
			// Determine if we should autoplay
			if (rs.length > 1) {
				var controller = document.getElementById("adcontrol");
				if (controller.getAttribute("defaultplay")=="true") Ad.toggleControllerStatus();
			}
			// Display the first ad
			Ad.display(Ad.index);
		} else {
			// Get failed status error message
			var message = "";
			message = request.statusText;
			if (message.length == 0) message = "Unspecified error " + request.status.toString();
			// Display error message
			Ad.displayError(message);
		}
	}
}

// Loads the ad according to the index number given
Ad.display = function(x) {
	// Clear the play timer if it is running
	if (Ad.playTimer != null) {
		clearTimeout(Ad.playTimer);
		Ad.playTimer = null;
	}
	// Get the currend ad and its type, the containing div, and the status message
	var divCurrentAd = document.getElementById("ad");
	var type = (divCurrentAd.className == "spot-ad") ? "H" : "S";
	Ad.displayTime = (type == "H") ? Ad.homeDisplayTime : Ad.sidebarDisplayTime;
	// Randomize x if this is the first load of a sidebar ad
	// (a random sidebar ad will display when the page is first loaded, and will loop in the normal order from the random start position chosen)
	if (type == "S" && Ad.firstLoad) {
		var x = Math.floor(Math.random() * Ad.list.length);
	}
	// Make sure we're not walking off the end of the list index
	if (x >= Ad.list.length) x = 0;
	else if (x < 0) x = Ad.list.length - 1;
	var container = divCurrentAd.parentNode;
	// Set up DIV for displaying new ad
	var divNewAd = document.createElement("div");
	// Wait for any currently-dissolving ads to finish
	if (Ad.dissolveTimer != null) {
		if (Ad.waitTimer != null) {
			clearTimeout(Ad.waitTimer);
			Ad.waitTimer = null;
		}
		Ad.waitTimer = setTimeout(function() { Ad.display(x); }, 0);
		return;
	}
	if (type=="H") divNewAd.className = "spot-ad";
	else divNewAd.className = "side-ad";
	divNewAd.style.cssText = "z-index: 2; filter: alpha(opacity=0); -moz-opacity: 0; opacity: 0;";
	container.appendChild(divNewAd);
	// Create the image node
	var imgNewAd = document.createElement("img");
	imgNewAd.setAttribute("alt", Ad.list[x].Description);
	imgNewAd.setAttribute("border", 0);
	imgNewAd.setAttribute("galleryimg", "no");
	imgNewAd.src = Ad.imageURL + Ad.list[x].ID + ".jpg?t=" + escape(Ad.session);
	divNewAd.appendChild(imgNewAd);
	// Assign the link to the link node (if this ad links anywhere)
	var adlink = document.getElementById("adlink");
	if (Ad.list[x].LinkURL.length > 0) {
		adlink.setAttribute("href", Ad.list[x].LinkURL);
		if (Ad.list[x].LinkTarget.length > 0) adlink.setAttribute("target", Ad.list[x].LinkTarget);
	} else adlink.setAttribute("href", "javascript:void(0);");
	// Set the tooltip (alt) text for the link
	adlink.setAttribute("title", Ad.list[x].Description);
	// Display the ad if it's loaded, otherwise assign its display to the onload event and display the "loading" message
	if (imgNewAd.complete) {
		if (type=="S" && Ad.firstLoad) {
			Ad.hideStatus();
			Ad.finishDissolve(divNewAd, divCurrentAd);
		} else Ad.beginDissolve(divNewAd, divCurrentAd);
	} else {
		Ad.displayLoader();
		imgNewAd.onload = function() {
			if (type=="S" && Ad.firstLoad) {
				Ad.hideStatus();
				Ad.finishDissolve(divNewAd, divCurrentAd);
			} else Ad.beginDissolve(divNewAd, divCurrentAd);
		}
	}
	Ad.index = x;
}

// Puts the image for the next ad into memory
Ad.preload = function(x) {
	// Make sure we're not walking off the end of the list index
	if (x >= Ad.list.length) x = 0;
	else if (x < 0) x = Ad.list.length - 1;
	(new Image()).src = Ad.imageURL + Ad.list[x].ID + ".jpg?t=" + escape(Ad.session);	
}

// Initiates the dissolve-infor the new ad, over the old ad
Ad.beginDissolve = function(newdiv, olddiv) {
	Ad.hideStatus();
	if (Ad.playTimer != null) {
		clearTimeout(Ad.playTimer);
		Ad.playTimer = null;
	}
	if (Ad.dissolveTimer != null) Ad.finishDissolve(newdiv, olddiv);
	Ad.dissolveTimer = setInterval(function() { Ad.dissolve(newdiv, olddiv) }, 20); 
}

// Increments the opacity of the new ad over the old ad, removing the old ad div when the new div reaches full opacity
Ad.dissolve = function(newdiv, olddiv) {
	if (Ad.opacity >= 100) Ad.finishDissolve(newdiv, olddiv);
	else {
		Ad.opacity = Ad.opacity + 5;
		newdiv.style.cssText = 'z-index: 2; filter: alpha(opacity=' + Ad.opacity + '); -moz-opacity: ' + (Ad.opacity / 100) + '; opacity: ' + (Ad.opacity / 100) + ';';
	}
}

// Clear the timer, remove the old div, set this new div to the default settings, and reset the opacity counter
Ad.finishDissolve = function(newdiv, olddiv) {
	if (Ad.dissolveTimer != null) {
		clearInterval(Ad.dissolveTimer);
		Ad.dissolveTimer = null;
	}
	if (olddiv) olddiv.parentNode.removeChild(olddiv);
	newdiv.id = "ad";
	newdiv.style.cssText = 'z-index: 1; filter: alpha(opacity=100); -moz-opacity: 1; opacity: 1;';
	Ad.opacity = 0;
	// If we are in the 'play' mode, then run the timer
	if (Ad.playStatus) Ad.playTimer = setTimeout(Ad.goNext, Ad.displayTime * 1000);
	// Preload the next ad (if there's more than one
	if (Ad.list.length > 1) Ad.preload(Ad.index + 1);
	Ad.firstLoad = false;
}

// Changes the images and mouseover/down conditions for the play controls
Ad.toggleControllerStatus = function() {
	var controller = document.getElementById("adcontrol");
	var adprev = document.getElementById("AdPrev");
	var adps = document.getElementById("AdPlayStop");
	var adnext = document.getElementById("AdNext");
	if (controller && adprev && adps && adnext) {
		// Toggle controller status
		if (Ad.playStatus) {
			controller.src = controller.src.replace("stop", "play");
			Ad.setRollover(adprev, controller, 0, 1, 4);
			Ad.setRollover(adps, controller, 0, 2, 5);
			Ad.setRollover(adnext, controller, 0, 3, 6);
			adps.setAttribute("alt", "Play");
			Ad.playStatus = false;
		} else {
			controller.src = controller.src.replace("play", "stop");
			Ad.setRollover(adprev, controller, 7, 8, 11);
			Ad.setRollover(adps, controller, 7, 9, 12);
			Ad.setRollover(adnext, controller, 7, 10, 13);
			adps.setAttribute("alt", "Stop");
			Ad.playStatus = true;
		}
	}
}

// Sets the rollover/down URLs for the imagemap item
Ad.setRollover = function(maparea, controller, x, y, z) {
	maparea.onmouseout = function() { controller.src = Ad.controlImg[x]; }
	maparea.onmouseover = function() { controller.src = Ad.controlImg[y]; }
	maparea.onmousedown = function() { controller.src = Ad.controlImg[z]; }
	maparea.onmouseup = function() { controller.src = Ad.controlImg[y]; }
}

// Toggles the play/stop status of the ad
Ad.playStop = function() {
	if (Ad.playTimer != null) {
		clearTimeout(Ad.playTimer);
		Ad.playTimer = null;
	}
	Ad.toggleControllerStatus();
	if (Ad.playStatus) Ad.playTimer = setTimeout(Ad.goNext, Ad.displayTime * 1000);
}

// Goes to the next ad
Ad.goPrev = function() {
	if (Ad.list.length > 1) Ad.display(Ad.index - 1);
}

// Goes to the previous ad
Ad.goNext = function() {
	if (Ad.list.length > 1) Ad.display(Ad.index + 1);
}

// Displays the loading message in the status screen
Ad.displayLoader = function() {
	if (Ad.statusMode == 1) return;
	var divStatus = document.getElementById("ad-status");
	if (divStatus) {
		// Remove all existing items
		while (divStatus.firstChild) divStatus.removeChild(divStatus.firstChild);
		// Update status image
		var img = document.createElement("img");
		img.src = Ad.loaderIconURL;
		img.width = "16";
		img.height = "16";
		img.border = "0";
		img.setAttribute("align", "absmiddle");
		divStatus.appendChild(img);
		divStatus.appendChild(document.createTextNode(" Loading..."));
		divStatus.style.display = "";
		divStatus.style.width = "90px";
		Ad.statusMode = 1;
	}
}

// Displays an error message in the status screen
Ad.displayError = function(msg) {
	if (Ad.statusMode == 2) return;
	var divStatus = document.getElementById("ad-status");
	var type = (divStatus.className == "spot-adstatus") ? "H" : "S";
	if (divStatus) {
		// Remove all existing items
		while (divStatus.firstChild) divStatus.removeChild(divStatus.firstChild);
		// Update status image
		var img = document.createElement("img");
		img.src = Ad.errorIconURL;
		img.width = "16";
		img.height = "16";
		img.border = "0";
		img.setAttribute("align", "absmiddle");
		divStatus.appendChild(img);
		divStatus.appendChild(document.createTextNode(" " + msg));
		divStatus.style.display = "";
		divStatus.style.width = (type=="H") ? "250px" : "138px";
		Ad.statusMode = 2;
	}
}

// Hides the status message
Ad.hideStatus = function() {
	if (Ad.statusMode == 0) return;
	var divStatus = document.getElementById("ad-status");
	if (divStatus) {
		divStatus.style.display = "none";
		Ad.statusMode = 0;
	}
}

// OnLoad directive
Ad.doOnLoad = function() {
	// Sets up image rollovers
	var f = Ad.setupControls();
	if (f) {
		// Get list of ads from server
		Ad.getData();
	}
}

if (window.addEventListener) window.addEventListener("load", Ad.doOnLoad, false);
else if (window.attachEvent) window.attachEvent("onload", Ad.doOnLoad);