// JavaScript Document

// Creates the new object
var FP;
if (!FP) FP = {}
else if (typeof FP != "object") throw new Error("'FP' already exists and is not an object");

// Sets the script URL and image directory
FP.scriptURL = "/ajax/featured_products.aspx";
FP.imageURL = "/cms/featured/";

// Set up URLs for loading and error icons
FP.loaderIconURL = "/images/icons/loading_wheel.gif";
FP.errorIconURL = "/images/icons/error.gif";
FP.blankImageURL = "/images/interface/spacer.gif";

// Declare paging and animation values
FP.itemsPerPage = 5;
FP.pageWidth = 750;
FP.framesPerSecond = 50;
FP.scrollTime = 0.5;
FP.easingFactor = 0.5;

// Delcare other properties with default values
FP.numPages = 0;
FP.currentPage = 1;
FP.itemsLoaded = 0;
FP.statusMode = 0;
FP.listTimer = null;
FP.scrollTimer = null;
FP.waitTimer = null;
FP.list = new Array();
FP.session = (new Date).getTime();

// Gets the list of featured products from the server
FP.getData = function() {
	FP.displayLoader();
	if (FP.listTimer != null) {
		clearTimeout(FP.listTimer);
		FP.listTimer = null;
	}
	if (request.readyState == 0 || request.readyState == 4) {
		request.open("POST", FP.scriptURL, true);
		request.onreadystatechange = FP.parseData;
		request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		request.send("a=g");
	} else FP.listTimer = setTimeout(FP.getData, 0);
}

// Parses the XML list and turns it into a JavaScript object
FP.parseData = function() {
	if (request.readyState == 4) {
		// Display 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("FeaturedProducts");
			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 name = (rs[x].getElementsByTagName("Name")[0]) ? rs[x].getElementsByTagName("Name")[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 : "";
				FP.list.push({"ID": id, "IndexID": index, "Name": name, "LinkURL": url, "LinkTarget": target });
			}
			// Determine the number of pages
			FP.numPages = Math.ceil(FP.list.length / FP.itemsPerPage) + 1;
			// Load items into the table
			FP.loadItems();
		} else {
			// Get failed status error message
			var message = "";
			message = request.statusText;
			if (message.length == 0) message = "Unspecified error " + request.status.toString();
			// Display error message
			FP.displayError(message);
		}
	}
}

// Loads the page of items and determines how they appear
FP.loadItems = function() {
	// Reset the number of items loaded to zero (if it isn't already)
	FP.itemsLoaded = 0;
	// Get the container div, remove all child elements
	var container = document.getElementById("fp");
	while (container.firstChild) container.removeChild(container.firstChild);
	container.style.cssText = "filter: alpha(opacity=0); -moz-opacity: 0; opacity: 0;";
	// Create the the table in which the items will sit
	var table = document.createElement("table");
	table.cellSpacing = 0;
	table.cellPadding = 0;
	table.border = 0;
	container.appendChild(table);
	var tbody = document.createElement("tbody");
	table.appendChild(tbody);
	// Table row
	var tr = document.createElement("tr");
	tbody.appendChild(tr);
	// Load the full list of featured products into the table as individual cells
	for (var x=0; x < FP.list.length; x++) FP.setupItem(x, tr);
	// If the number of items isn't exactly divisible by the items per page, then create some blank spaces
	var blanks = FP.itemsPerPage - (FP.list.length % FP.itemsPerPage);
	if (blanks < FP.itemsPerPage) for (var x=0; x < blanks; x++) FP.setupItem("blank", tr);
	// Load a redundant set of the first page items
	for (var x=0; x < FP.itemsPerPage; x++) FP.setupItem(x, tr);
}

// Load an individual item into the list
FP.setupItem = function(x, tr) {
	var td = document.createElement("td");
	td.className = "bodyitem";
	tr.appendChild(td);
	if (x == "blank") {
		var img = document.createElement("img");
		img.src = FP.blankImageURL;
		img.width = 120;
		img.height = 90;
		img.setAttribute("border", 0);
		img.setAttribute("galleryimg", "no");
		td.appendChild(img);
	} else {
		var itemlink = document.createElement("a");
		if (FP.list[x].LinkURL.length > 0) {
			itemlink.setAttribute("href", FP.list[x].LinkURL);
			if (FP.list[x].LinkTarget.length > 0) itemlink.setAttribute("target", FP.list[x].LinkTarget);
		} else itemlink.setAttribute("href", "javascript:void(0);");
		td.appendChild(itemlink);
		var img = document.createElement("img");
		img.src = FP.imageURL + FP.list[x].ID + ".jpg?t=" + escape(FP.session);
		img.width = 120;
		img.height = 90;
		img.setAttribute("alt", FP.list[x].Name);
		img.setAttribute("border", 0);
		img.setAttribute("galleryimg", "no");
		itemlink.appendChild(img);
		itemlink.appendChild(document.createTextNode(FP.list[x].Name));
		// Display the image if it's loaded, otherwise assign its display to the onload event and display the "loading" message
		img.onload = function() { }
		if (img.complete) FP.checkLoadProgress(td);
		else {
			FP.displayLoader();
			img.onload = function() { FP.checkLoadProgress(td); }
		}
	}
}

FP.checkLoadProgress = function(td) {
	// Add to 'loaded' counter and display at full opacity
	FP.itemsLoaded++;
	if (FP.itemsLoaded >= FP.list.length + FP.itemsPerPage) {
		// Set the scroll offset to zero
		var container = document.getElementById("fp");
		container.style.cssText = '-moz-opacity: 1; opacity: 1;';
		container.scrollLeft = 0;
		FP.hideStatus();
	}
}

// Takes the user to another page by invoking the scrolling methods
FP.goToPage = function(num) {
	if (FP.listTimer != null) return;
	if (FP.scrollTimer != null) {
		FP.waitTimer = setTimeout(FP.goToPage(num), 0);
		return;
	}
	var container = document.getElementById("fp");
	// Determine current and target page number, resetting scroll position if necessary if we are at one end or the other
	if (num > FP.numPages) {
		FP.currentPage = 1;
		num = 2;
		container.scrollLeft = 0;
	} else if (num < 1) {
		FP.currentPage = FP.numPages;
		num = FP.currentPage - 1;
		container.scrollLeft = FP.numPages * FP.pageWidth;
	}
	if (num > FP.currentPage) FP.scrollEasing(container, container.scrollLeft, container.scrollLeft + FP.pageWidth); //container.scrollLeft = container.scrollLeft + FP.pageWidth;
	else FP.scrollEasing(container, container.scrollLeft, container.scrollLeft - FP.pageWidth); //container.scrollLeft = container.scrollLeft - FP.pageWidth;
	FP.currentPage = num;
}

// Initiates the scroll to another page
FP.scrollEasing = function(elem,startPos,endPos) {
	if (FP.scrollTimer != null) {
		clearInterval(FP.scrollTimer);
		FP.scrollTimer = null;
	}
	var actStep = 0;
	var interval = 1000 / FP.framesPerSecond;
	var steps = Math.round(FP.scrollTime * FP.framesPerSecond);
	FP.scrollTimer = setInterval(function() {
										  elem.scrollLeft = FP.easeInOut(startPos,endPos,steps,actStep,FP.easingFactor);
										  actStep++;
										  if (actStep > steps) {
											  clearInterval(FP.scrollTimer);
											  FP.scrollTimer = null;
										  }}, interval)
}

// Determines next position of scroller based on easing settings
FP.easeInOut = function(minValue,maxValue,totalSteps,actualStep,powr) {
	var delta = maxValue - minValue; 
	var stepp = minValue+(Math.pow(((1 / totalSteps) * actualStep), powr) * delta);
	return Math.ceil(stepp);
}

// Button event to go to the previous page
FP.goLeft = function() {
	FP.goToPage(FP.currentPage - 1);
}

// Button event to go to the next page
FP.goRight = function() {
	FP.goToPage(FP.currentPage + 1);
}

// Displays the loading message in the status screen
FP.displayLoader = function() {
	if (FP.statusMode == 1) return;
	var divStatus = document.getElementById("fp-status");
	if (divStatus) {
		// Remove all existing items
		while (divStatus.firstChild) divStatus.removeChild(divStatus.firstChild);
		// Update status image
		var img = document.createElement("img");
		img.src = FP.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.left = "347px";
		divStatus.style.width = "85px";
		FP.statusMode = 1;
	}
}

// Displays an error message in the status screen
FP.displayError = function(msg) {
	if (FP.statusMode == 2) return;
	var divStatus = document.getElementById("fp-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.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.left = "275px";
		divStatus.style.width = "250px";
		FP.statusMode = 2;
	}
}

// Hides the status message
FP.hideStatus = function() {
	if (FP.statusMode == 0) return;
	var divStatus = document.getElementById("fp-status");
	if (divStatus) {
		divStatus.style.display = "none";
		FP.statusMode = 0;
	}
}

// OnLoad directive
FP.doOnLoad = function() { FP.getData(); }

if (window.addEventListener) window.addEventListener("load", FP.doOnLoad, false);
else if (window.attachEvent) window.attachEvent("onload", FP.doOnLoad);