/* © Copyright 2007 by Bram Bogaert - All Rights Reserved */

/* Container for the static functions. */
var Lib = {};

/* ------------------ */
/* UTILS EXTRAS START */
/* ------------------ */
/*
	Note: ObjectUtils should exist, and be included (javascript-commons) in the html page.
	
	This function always returns a string. If the object is undefined, an empty string is returned.
*/
ObjectUtils.toString = function(object) {
	if (object) {
		return "" + object;
	}
	return "";
}
/* ---------------- */
/* UTILS EXTRAS END */
/* ---------------- */

/* --------- */
/* LIB START */
/* --------- */
// Remark:
// IE and FF are _very_ sensitive about \n in front of element that is added.
// IE wants to see "<" first, so don't put "\n" at the beginning of the string.
// FF wants an element to start on a new line, so add "\n" at the end of each previously added string.
// FF also doesn't like "<tbody>" to be added to a table.

/* COMMON START */
/*
	Get a dom element using the jQuery guidelines:
		1) Get element by name
		2) Get element by id
		3) On top of the guidelines, also try to get the element with the provided name-value.
*/
Lib.getElement = function(name) {
	if (name == undefined) {
		return;
	}
	var result;
	
	var el = $("[@name=" + name + "]");
	if (el.size() == 0) {
		el = $("#" + name);
	}
	if (el.size() == 0) {
		el = $(name);
	}
	
	if (el.size() > 0) {
		result = el;
	}
	return result;
}

/*
	Append "Hello" to a dom-element.
	If no dom-element with the given name/id exists, "Hello" is alerted.
*/
Lib.hello = function(name) {
	var text = "Hello";
	
	var el = Lib.getElement(name);
	if (el == undefined) {
		alert(text);
	} else {
		el.append(text);
	}
}

/*
	Run a function passed by reference (function pointer) or by name (function name as string).
*/
Lib.runFunction = function(functionRef) {
	if (functionRef) {
		if ($.isFunction(functionRef) == true) {
			functionRef();
		} else {
			window[functionRef]();
		}
	}
}

/*
	Setting the active (short) url to the longer one gets rid of frames added by ad sponsored free domain providers.
*/
Lib.noAds = function() {
	if (CONFIG.noAds.getRidOfFrames) {
		if (window != top) {
			top.location.href = CONFIG.noAds.longUrlForSite;
		}
	}
}
/* COMMON END */

/* MENU START */
/*
	Add class "selected" to ${selectedMenuItemName} of menu ${menuName}.
	That class is also removed from all other menu items in the same menu.
*/
Lib.setSelectedMenuItem = function(menuName, selectedMenuItemName) {
	var menu = $("ul[@name=" + menuName + "]");
	
	// Reset selected menuItem
	menu.find("li").removeClass("selected");
	
	// Select new menuItem
	var menuItem = menu.find("li[@name=" + selectedMenuItemName + "]");
	menuItem.addClass("selected");
}

/*
	contentContainerElementName: the name of the content element which content will be replaced.
	menuName: the name of the menu to which the activated menuItem belongs.
	menuItemName: the name of the menuItem that is activated.
	initFunctionName: optional, the name of the initFunction to run after the new contentPage was set.
*/
Lib.setContentPage = function(contentContainerElementName, menuName, menuItemName, initFunctionName) {
	// Always get a page with the same name as the menuItem, and in same directory of the current page.
	// => no grouping in subdirectories, this is supposed to be a small website (keep it simple).
	$.get("./" + menuItemName + ".html", function(data, textStatus) {
			// TODO There must be a better way to get the body
			var contentPageStart = data.indexOf("<body>") + "<body>".length;
			var contentPageEnd = data.indexOf("</body>");
			var contentPage = data.substring(contentPageStart, contentPageEnd);
			
			$("[@name=" + contentContainerElementName + "]").empty().append(contentPage);
			Lib.setSelectedMenuItem(menuName, menuItemName);
			Lib.runFunction(initFunctionName);
		});
}

/*
	Refreshes the menu, all existing menu content is removed and the given menuItems are put in the menu.
	
	contentContainerElementName: the name of the content element which content will be replaced.
	menuName: the name of the menu to which the activated menuItem belongs.
	menuItems: a collection of menuItem objects that need to appear in the menu.
	indexOfMenuItemNameToReturn: the index of the menuItem in the menu for which the name needs to be returned
	                             (starts counting at 0).
*/
Lib.refreshMenu = function(contentContainerElementName, menuName, menuItems, indexOfMenuItemNameToReturn) {
	var result = "";
	
	var menu = $("ul[@name=" + menuName + "]");
	
	// Make menu empty
	menu.empty();
	// Fill menu and set result
	$.each(menuItems, function(i, val) {
			if (i == indexOfMenuItemNameToReturn) {
				result = val;
			}
			
			var menuItemName = val.title;
			var initFunctionName = val.initFunctionName;
			var menuItem =
					"<li name=\"" + menuItemName + "\">"
					+ Lib.createLink(
									"javascript:Lib.setContentPage("
												+ "'" + contentContainerElementName + "'"
												+ ", '" + menuName + "'"
												+ ", '" + menuItemName + "'"
												+ ", " + initFunctionName + ""
												+ ");"
									, ""
									, ""
									, menuItemName)
					+ "</li>";
			menu.append(menuItem);
		});
	// Make menu easier clickable
	$("ul[@name=" + menuName + "] li").biggerlink();
	
	// Return menuItem corresponding with the given index
	return result;
}
/* MENU END */

/* CONTENT START */
/*
	Create a link that:
		- Opens a new location in a new window or executes a JavaScript script on clicking the link.
		- Contains an image and/or a text.
*/
Lib.createLink = function(link, tooltip, imgSrc, text, popupText) {
	var target = "";
	var linkInput = ObjectUtils.toString(link);
	if (!StringUtils.isBlank(popupText)) {
		linkInput="#";
	}
	if (!StringUtils.startsWith(linkInput.toLowerCase(), "javascript:")
					&& linkInput != "#"
			) {
		target = " target=\"_blank\"";
	}
	
	var title = "";
	if (!StringUtils.isBlank(tooltip)) {
		title = " title=\"" + tooltip + "\"";
	}
	
	var onclick = "";
	if (!StringUtils.isBlank(popupText)) {
		onclick = " onclick=\""
			+ "$('[@name=sponsorDialog]').empty().append('" + popupText + "').dialog({width: 400}).dialog('open');"
			+ " return false;"
			+ "\"";
	}
	
	var img = "";
	if (!StringUtils.isBlank(imgSrc)) {
		img = "<img src=\"" + imgSrc + "\" />";
	}
	
	var linkText = "";
	if (!StringUtils.isBlank(text)) {
		if (!StringUtils.isBlank(img)) {
			img += "<br /> \n"
		}
		linkText += text;
	}
	
	var result =
			"<a href=\"" + linkInput + "\"" + target + title + onclick + ">"
			+ img + linkText
			+ "\n</a>";
	return result;
}

/*
	Add all configured partners for a certain partnerType to the partnerTable
	(that is a table with name: ${partnerType} + "Partners").
	
	amountOfPartnersPerRow: can be passed to override the default amount
	                        of partner logo's shown on the same line (in one row).
*/
Lib.initPartners = function(partnerType, partners, amountOfPartnersPerRow) {
	// Config
	var partnerTable = $("table[@name=" + partnerType + "Partners]");
	amountOfPartnersPerRow = (amountOfPartnersPerRow) ? amountOfPartnersPerRow : CONFIG.defaultAmountOfPartnersPerRow;
	
	// Make table empty
	partnerTable.empty();
	
	// Fill table
	var index = 0;
	$.each(partners, function(i, val) {
			// Start new row if needed
			if (i % amountOfPartnersPerRow == 0) {
				partnerTable.append("<tr>\n");
			}
			
			// Select last row
			partnerRow = partnerTable.find("tr:last");
			
			// Add partner to row
			var link = Lib.createLink(val.link, val.tooltip, val.imgSrc, val.text, val.popupText);
			var partner =
					"	<td align='center' valign='middle' width='20%'>"
					+ "\n		" + link
					+ "\n	</td>\n";
			partnerRow.append(partner);
			
			// Close row if needed
			index = i;
			if (i % amountOfPartnersPerRow == amountOfPartnersPerRow - 1) {
				partnerTable.append("</tr>\n");
			}
		});
	// Close row after iterating all partners if needed
	if (index % amountOfPartnersPerRow != amountOfPartnersPerRow - 1) {
		partnerTable.append("</tr>\n");
	}
}
/* CONTENT END */
/* ------- */
/* LIB END */
/* ------- */

