/****************************************************************************************
Author:	
	- Urbanet BV, Rinse Stellingwerf
	
Description:
	- Mett javascript functions.
	
Date created:
	- 09/06/09
	
Update log:
	- 10/06/09: Added resizeHeader().
	- 11/06/09: Added menu toggle options.
	- 03/07/09: Perfected the menu toggle function.
	- 08/07/09: Added toggle support for inline/block display.
	- 05/08/09: Added loadHeader() function.
	- 06/08/09: Added extra checks to loadHeader() function.
	- 25/08/09: Added fix for Firefox bug.
	- 31/08/09: Added template support to toggleState() function.
	- 21/09/09: Added getProjectInformation() function.
	- 22/09/09: Added default header width & height to loadHeader() & resizeHeader().
	- 23/09/09: Removed default header width & height ;). Added initialize() function.
	- 05/10/09: Added getPaging() function.
	- 08/10/09: Reposition footer after header load (IE6 fix).
	- 09/10/09: Added toggleMenuBullets() function.
	- 12/10/09: Improved toggleMenuBullets(), added getElementsByClassName() function.
	- 12/10/09: Added showError() function;
	- 15/10/09: Improved showError() function, so it's able to show multiple errors.
	- 16/10/09: Added setFormPreferences(), submitFormOnEnter() & resetError() functions.
	- 19/10/09: Added clickButton() function.
	- 26/10/09: Disabled loadHeader() & repositionFooter().
	- 12/11/09: Added getTabs(), initializeTab() & openTab() functions.
	- 13/11/09: Added some extra checks to tabs functions.
	- 23/12/09: Added toggleClass() & clickLink() functions.
	- 21/01/10: Added extra checks to initialize() function.
	- 22/01/10:	Added extra checks to getPaging() function.
	- 08/03/10: Added clickCell() function.
	- 11/03/10: Added getIcon() function.
	- 01/04/10: Added getContent() function.
	- 26/04/10: Rewrote clickButton, clickLink & clickCell() functions for FireFox.
	- 12/05/10: Added getLinks() function.
	- 14/05/10: Added createSelectList() function.
	- 31/05/10: Added copyContent() function.
	- 02/06/10: Added extra checks to copyContent() and createSelectList() functions.
	- 02/06/10: Added showIfNotEmpty() function.
	- 14/06/10: Added extra option to copyContent() function.
	- 21/06/10: Added toggleFiles() function.
	- 01/07/10: Kick-ass rewrite of toggleFiles() function.
	- 05/07/10: Added functionality to getElementsByClassName() function.
	- 12/07/10: Added extra margin to paging container.
	- 17/08/10: Added return value to setFormPreferences().
	- 19/08/10: Added some extra checks to setFormPreferences() & submitFormOnEnter().
	- 07/09/10: Added ID's to getProjectInformation() function.
****************************************************************************************/

/****************************************************************************************
Initialize
****************************************************************************************/

// Initialize.
window.onload = initialize;

// Create image.
// var headerImage = new Image();
// headerImage.src = headerLocation;

// Run the following functions on load.
function initialize()
{	
	// Load (random) header.
	// loadHeader(headerLocation, headerContainer, headerCount, menuTopContainer, menuTopHeight);
	
	// Reposition footer.
	// repositionFooter(bottomContainer);
	
	// Toggle (sub)menu bullets.
	if (typeof(menuLeftContainer) == "string" && typeof(menuLeftItemClassName) == "string")
	{
		toggleMenuBullets(menuLeftContainer, menuLeftItemClassName);
	}
}

/****************************************************************************************
Functions
****************************************************************************************/

// Load header.
function loadHeader(headerLocation, headerContainer, headerCount, menuContainer, menuHeight)
{	
	if (headerLocation != "")
	{	
		if (headerCount > 1)
		{
			// Get header extension.
			var headerExtension = headerLocation.substring(headerLocation.length - 4, headerLocation.length);
		
			// Get (random) header number.
			var headerNumber = Math.floor(Math.random() * headerCount) + 1;
			
			// Get selected header.
			var headerSelected = headerLocation.substring(0, headerLocation.length - 5) + headerNumber + headerExtension;
		}
		else
		{
			// Only 1 header, use input location.
			var headerSelected = headerLocation;
		}
		
		// Place header in container.
		document.getElementById(headerContainer).style.backgroundImage = "url(" + headerSelected + ")";
		
		// Resize header.
		resizeHeader(headerSelected, menuContainer, menuHeight);
	}
}

// Resize (already loaded) header.
function resizeHeader(headerSelected, menuContainer, menuHeight)
{	
	if (headerLocation != "")
	{		
		// Set header container height.
		document.getElementById(headerContainer).style.height = headerImage.height + "px";
		
		// Set menu padding from top.
		if (document.getElementById(menuContainer))
		{
			document.getElementById(menuContainer).style.padding = (headerImage.height - menuHeight) + "px 0px 0px 0px";
		}
	}	
}

// Reposition footer.
function repositionFooter(bottomContainer)
{
	if (document.getElementById(bottomContainer))
	{
		// Reposition footer.
		document.getElementById(bottomContainer).style.bottom = "0px";
	}
}

// Toggle (menu or webbox) state.
function toggleState(toggler, containerID, classOpen, classClosed)
{	
	if(document.getElementById(containerID))
	{	
		var display = document.getElementById(containerID).style.display;
		
		if (display == "none")
		{			
			// Menu should have display "inline", all other elements "block".
			if (document.getElementById(containerID).id.indexOf("menu") > -1)
			{
				display = "inline";
			}
			else
			{
				display = "block";
			}
			
			// Open.
			document.getElementById(containerID).style.display = display;
			
			// Change class.		
			toggler.className = classOpen;
		}
		else
		{
			// Close.
			document.getElementById(containerID).style.display = "none";
			
			// Change class.
			toggler.className = classClosed;
		}		
	}	
}

// Toggle menu bullets.
function toggleMenuBullets(menuContainer, menuItemClassName)
{
	if (document.getElementById(menuContainer))
	{
		// Configuration.
		var menuItemTagName = "a";	
		var menuItemParentTagName = "li";
		var menuItemCurrentClassName = menuItemClassName + "_Current";
		var menuItemClassNameBulletClosed = menuItemClassName + "BulletClosed";
		var menuItemClassNameBulletOpen = menuItemClassName + "BulletOpen";
		
		// Get all currently opened menu items.		
		var menuItemObjects = getElementsByClassName(menuContainer, menuItemTagName, menuItemCurrentClassName);
		
		if (menuItemObjects.length > 0)
		{
			var i = 1;
			var parentObject = menuItemObjects[0].parentNode;
			
			// Loop through menu items untill the menu container is reached.
			while(parentObject.id != menuContainer)
			{  
				if (parentObject.tagName.toLowerCase() == menuItemParentTagName)
				{
					if (i > 1)
					{
						// Replace closed bullet by an open bullet.
						parentObject.innerHTML = parentObject.innerHTML.replace(menuItemClassNameBulletClosed, menuItemClassNameBulletOpen);
					}
					
					i++;
				}
				
				// Go to next parent.
				parentObject = parentObject.parentNode;
			}
		}
	}
}

// Conditional class toggler.
function toggleClass(containerID, newClassName, conditionContainerID, conditionOperator, conditionText)
{	
	if (document.getElementById(containerID))
	{		
		var container = document.getElementById(containerID);
		var toggleClass = false;
		
		if (conditionContainerID != "" && conditionText != "")
		{
			// Conditional toggle.
			if (document.getElementById(conditionContainerID))
			{
				var conditionContainerHTML = document.getElementById(conditionContainerID).innerHTML.toLowerCase();
				
				if ((conditionOperator == "==") && (conditionContainerHTML.indexOf(conditionText.toLowerCase()) != -1))
				{	
					// Condition has been met, toggle class.
					toggleClass = true;					
				}
				else if ((conditionOperator == "!=") && (conditionContainerHTML.indexOf(conditionText.toLowerCase()) == -1))
				{
					// Condition has been met, toggle class.
					toggleClass = true;
				}
			}
		}
		else
		{
			// Always toggle (no condition).
			toggleClass = true;
		}
		
		if (toggleClass)
		{
			container.className = newClassName;
		}
	}
}

// Toggle files.
function toggleFiles(toggler, togglerParent, className, classOpen, classClosed)
{	
	if (togglerParent)
	{		
		// Get the ID of the containers that match the specified tag.
		var toggleContainers = getElementsByClassName(togglerParent, "span", className);
		
		if (toggleContainers.length > 1)
		{
			// Toggle multiple containers.
			for(i = 0; i < toggleContainers.length; i++)
			{
				// Get containerID.
				var containerID = toggleContainers[i].id;
				
				// Show or hide files.
				if (toggler.className == classOpen)
				{
					// Hide container.
					document.getElementById(containerID).style.display = "none";
				}
				else
				{
					// Show container.
					document.getElementById(containerID).style.display = "block";
				}
			}
			
			// Change toggler icon.
			if (toggler.className == classOpen)
			{				
				toggler.className = classClosed;
			}
			else
			{
				toggler.className = classOpen;
			}
			
			// Change container icons (the toggleIcons array comes from "downloads_downloadsmsection.ascx").
			for(j = 0; j < toggleIcons.length; j++)
			{
				if ((toggleIcons[j].className == classOpen) || (toggleIcons[j].className == classClosed))
				{
					// Change container icon into the same icon as the "show all" toggler.
					toggleIcons[j].className = toggler.className;
				}
			}
		}
		else if (toggleContainers.length == 1)
		{			
			// Get containerID.
			var containerID = toggleContainers[0].id;
			
			// Prepare container for toggle.
			if (document.getElementById(containerID).style.display == "" || document.getElementById(containerID).style.display == "none")
			{
				document.getElementById(containerID).style.display = "none";
			}
			
			// Toggle container with toggleState function.
			toggleState(toggler, containerID, classOpen, classClosed);
			
			// Change toggler child icon if "show all" toggler is clicked.
			if (toggleIcons.length == 1)
			{
				toggleIcons[0].className = toggler.className;
			}			
		}
	}
}

// Show error.
function showError(containerIDs)
{	
	for(i = 0; i < containerIDs.length; i++)
	{		
		if (document.getElementById(containerIDs[i]))
		{		
			// Get the input field that has an error.
			var errorContainer = document.getElementById(containerIDs[i]);
			var errorInputField = errorContainer.getElementsByTagName("input");
			
			// Get the (hidden) div, to show the error sign.
			var errorDiv = errorContainer.getElementsByTagName("div");
			
			// Add error class to the input field.
			// errorInputField[0].className = errorInputField[0].className + " " + errorInputField[0].className + "Error";
			
			// Clear input field with error.
			errorInputField[0].value = "";
			
			// Focus on input field with error.
			errorInputField[0].focus();
			
			// Show the error sign + message.
			errorDiv[0].style.display = "block";
			
			// Reset error message after unfocus.
			errorInputField[0].onblur = resetError;
		}
	}
}

// Reset error.
function resetError()
{
	// Get error objects.
	var errorObjects = getElementsByClassName("contentCenterMiddle", "div", "error");
	
	for(i = 0; i < errorObjects.length; i++)
	{
		// Hide error objects.
		errorObjects[i].style.display = "none";
	}
}

// Set various form preferences.
function setFormPreferences(focusContainerID, submitContainerID)
{	
	// Set focus.
	if (document.getElementById(focusContainerID))
	{		
		var focusContainer = document.getElementById(focusContainerID);
		var focusInputField = focusContainer.getElementsByTagName("input");
		
		if (focusInputField.length > 0)
		{
			// Set focus on the input field.
			focusInputField[0].focus();
		}
		else
		{
			// Set focus directly on the input field.
			focusContainer.focus();
		}
	}
	
	// Set on <enter> submit action.
	if (document.getElementById(submitContainerID))
	{		
		var submitContainer = document.getElementById(submitContainerID);
		var submitLink = submitContainer.getElementsByTagName("a");
		submitLink = submitLink[0].href.toLowerCase();
		submitLink = submitLink.replace(/%22/gi, "\"");
		
		// Postback without options.
		if (submitLink.indexOf("__dopostback") != -1)
		{
			
			var beginPosition = submitLink.indexOf("'");
			var endPosition = submitLink.indexOf("'", beginPosition + 1);			
		}		
		
		// Postback with options.
		if (submitLink.indexOf("_dopostbackwithoptions") != -1)
		{
			var beginPosition = submitLink.indexOf("\"");			
			var endPosition = submitLink.indexOf("\"", beginPosition + 1);			
		}
		
		if (beginPosition > -1)
		{			
			var eventTarget = submitLink.substring(beginPosition + 1, endPosition);			
		
			if(typeof(eventTarget) == "string")
			{
				// Set form event target.
				theForm.__EVENTTARGET.value = eventTarget;
				
				// Check pressed keys.
				document.onkeypress = submitFormOnEnter;
			}
		}
	}
	
	return true;
}

// Submit form on <enter>.
function submitFormOnEnter(e) 
{
	var keyCode;
	var targetType;
	
	if (window.event)
	{
		keyCode = window.event.keyCode;
		targetType = event.srcElement.type;
	}
	else if (e)
	{
		keyCode = e.which;
		targetType = e.target.type;
	}
	
	// Is the pressed key the <enter> key and is it pressed outside a textarea? 
	if (keyCode == 13 && targetType != "textarea")
	{
		// Submit the page form.
		theForm.submit();
	}
}

// Click specified button.
function clickButton(buttonContainer)
{
	if (document.getElementById(buttonContainer))
	{		
		var button = document.getElementById(buttonContainer).getElementsByTagName("input")[0];
		
		if (button)
		{			
			// Click button.
			button.click();
		}
	}
}

// Click specified link.
function clickLink(linkContainer)
{
	if (document.getElementById(linkContainer))
	{		
		var link = document.getElementById(linkContainer).getElementsByTagName("a")[0];
		
		if (link)
		{			
			// Redirect to link.
			document.location.href = link;
		}		
	}
}

// Click link in list cell.
function clickCell(rowID, linkID)
{	
	var link = rowID.getElementsByTagName("a")[linkID];
	
	if (link)
	{
		// Redirect to link.
		document.location.href = link;
	}
}

// Get elements by classname.
function getElementsByClassName(containerID, tagName, className)
{
	// Custom getElementsByClassName function().
	document.getElementsByClassName = function ()
	{	
		var i = 0;
		var objects = new Array();
		
		if (typeof (containerID) == "string")
		{
			var elementsContainer = document.getElementById(containerID);			
		}
		else
		{
			var elementsContainer = containerID;
		}
		
		var foundObjects = elementsContainer.getElementsByTagName(tagName);
		
		// Check if found tags have the specified classname.
		for(j = 0; j < foundObjects.length; j++)
		{
			if (foundObjects[j].className.indexOf(className) != -1)
			{ 
				objects[i] = foundObjects[j]; i++; 
			} 
		}
		
		// Return objects.
		return objects;
	}
	
	var returnObjects = document.getElementsByClassName();
	
	// Return objects.
	return returnObjects;
}

// Get project title and domain.
function getProjectInformation()
{
	var returnValue = "";
	
	// Get document title and domain.
	var projectTitle = document.title.substring(0, document.title.indexOf(" - ") + 1);
	var projectDomain = document.domain;
	
	projectTitle = "<h1 id=\"projectTitle\">" + projectTitle + "</h1>";
	projectDomain = "<a href=\"http://" + projectDomain + "\" id=\"projectURL\">" + projectDomain + "</a>";
	
	returnValue = projectTitle + projectDomain;
	
	// Return project information.
	return returnValue;
}

// Get generic paging.
function getPaging(pagingContainerSource)
{
	var returnValue = "";
	
	if (document.getElementById(pagingContainerSource))
	{
		// Parse paging content.
		var pagingContent = document.getElementById(pagingContainerSource);
		pagingContent = pagingContent.getElementsByTagName("table");
		
		// Get the innerHTML of the last table.		
		if (pagingContent.length > 0)
		{			
			// Get paging destination container.
			var pagingContainerDestination = getElementsByClassName("contentCenterMiddle", "div", "paging");
			
			if (pagingContainerDestination.length > 0)
			{
				// Add extra margin to paging container.
				pagingContainerDestination[0].style.marginBottom = "50px";
			}
			
			// Parse paging content.
			var parsedPagingContent = pagingContent[pagingContent.length - 1].innerHTML;
			
			parsedPagingContent = parsedPagingContent.replace(/<tr>/gi, "<ul>");
			parsedPagingContent = parsedPagingContent.replace(/<\/tr>/gi, "</ul>");
			parsedPagingContent = parsedPagingContent.replace(/<td>/gi, "<li>");
			parsedPagingContent = parsedPagingContent.replace(/<\/td>/gi, "</li>");
			parsedPagingContent = parsedPagingContent.replace("[", "<strong>");
			parsedPagingContent = parsedPagingContent.replace("]", "</strong>");
			parsedPagingContent = parsedPagingContent.replace("<span>", "");
			parsedPagingContent = parsedPagingContent.replace("<TBODY>", "");
			parsedPagingContent = parsedPagingContent.replace("</TBODY>", "");
			parsedPagingContent = parsedPagingContent.replace("<tbody>", "");
			parsedPagingContent = parsedPagingContent.replace("</tbody>", "");
			
			returnValue = parsedPagingContent;			
		}		
	}
	
	// Return parsed paging.
	return returnValue;	
}

// Conditional get icon function.
function getIcon(valueToCheck, conditionValue, iconLocation, iconNew, iconDefault)
{	
	var returnValue = "";
	var icon;
	
	// Check for condition value.	
	if (valueToCheck.indexOf(conditionValue) != -1)
	{
		icon = iconNew;
	}
	else
	{
		icon = iconDefault;
	}
	
	// Create icon string.
	returnValue = "<img src=\"" + iconLocation + icon + "\" width=\"16\" height=\"16\" />";
	
	// Return icon.
	return returnValue;
}

// Get generic tabs.
function getTabs(tabsContainer)
{
	var returnValue = "";
	
	if (document.getElementById(tabsContainer))
	{
		// Parse tabs.
		var parsedTabs = "";
		var tabs = document.getElementById(tabsContainer);
		tabs = tabs.getElementsByTagName("a");
		
		// Get tab links.
		for(i = 0; i < tabs.length; i++)
		{		
			// Create new tab.
			parsedTabs = parsedTabs + "<a href=\"" + tabs[i] + "\" id=\"tab" + i + "\" class=\"tab\">" + tabs[i].innerHTML + "</a>";
		}
		
		// Replace showPanel() function with openTab() function.
		parsedTabs = parsedTabs.replace(/showPanel/gi, "openTab");
		
		returnValue = parsedTabs;
	}
	
	// Return parsed tabs.
	return returnValue;
}

// Get content from ID.
function getContent(containerID)
{
	var returnValue = "";
	
	if (document.getElementById(containerID))
	{
		returnValue = document.getElementById(containerID).innerHTML;
	}
	
	// Return innerHTML.
	return returnValue;
}

// Get links from ID.
function getLinks(containerID)
{	
	var returnValue = new Array();
	
	if (document.getElementById(containerID))
	{		
		var foundObjects = document.getElementById(containerID).getElementsByTagName("a");
		
		// Check if links exist, if so place in array.
		if (foundObjects.length > 0)
		{
			returnValue = foundObjects;
		}
	}
	
	// Return links.
	return returnValue;
}

// Initialize tab.
function initializeTab(tabID)
{
	if (document.getElementById(tabID))
	{
		var selectedTab = document.getElementById(tabID);
		
		// Get selected tab content container.	
		var beginPosition = selectedTab.href.indexOf("'");
		var endPosition = selectedTab.href.indexOf("'", beginPosition + 1);		
		var selectedTabContentID = selectedTab.href.substring(beginPosition + 1, endPosition);
		
		// Select & open tab.
		openTab(selectedTabContentID);
	}
}

// Open tab content.
function openTab(tabContentID)
{
	if (document.getElementById(tabContentID))
	{
		// Get all the tab content panels.
		var tabContentPanels = getElementsByClassName("contentCenterMiddle", "div", "tabContentPanel");
		
		if (tabContentPanels.length > 0)
		{			
			for(i = 0; i < tabContentPanels.length; i++)
			{			
				if (tabContentPanels[i].id == tabContentID)
				{					
					var selectedTab = document.getElementById("tab" + i);
					
					// Check if tab isn't already selected.
					if (selectedTab.className != "tabSelected")
					{					
						// Set selected class on tab.
						document.getElementById("tab" + i).className = selectedTab.className + "Selected";
						
						// Show content.
						tabContentPanels[i].style.display = "block";
					}
				}
				else
				{
					var unSelectedTab = document.getElementById("tab" + i);
					
					// Set default class on tab.
					document.getElementById("tab" + i).className = "tab"
					
					// Hide content.
					tabContentPanels[i].style.display = "none";
				}
			}
		}
	}
}

// Create select list from array.
function createSelectList(optionValues, optionFirstText)
{	
	var returnValue = "";
	var options = new Array();
	
	var selectList = document.createElement("select");	
	var optionFirst = document.createElement("option");
	
	optionFirst.text = optionFirstText;
	optionFirst.value = document.location.href;
	
	// Add first option to array.
	options[0] = optionFirst;
	
	// Create options.	
	for(i = 0; i < optionValues.length; i++)
	{		
		// Create new option.
		var option = document.createElement("option");
		
		option.text = optionValues[i].innerHTML;
		option.value = optionValues[i];
		
		// Add option to array.
		options[i + 1] = option;		
	}
	
	// Add options to the select list.
	for (j = 0; j < options.length; j++)
	{
		try
		{
			// All browsers except IE.
			selectList.add(options[j], selectList.options[j]);
		}
	
		catch(ex)
		{
			// IE only.
			selectList.add(options[j], selectList.options.length);
		}
	}
	
	returnValue = selectList;
	
	// Return select list.
	return returnValue;
}

// Copy content from one container to another.
function copyContent(sourceContainerID, destinationContainerID, copyMode)
{
	if (document.getElementById(sourceContainerID) && document.getElementById(destinationContainerID))
	{
		var sourceContainer = document.getElementById(sourceContainerID);
		var destinationContainer = document.getElementById(destinationContainerID);
		
		// Check if there is content.
		if (sourceContainer.innerHTML.length > 0)
		{		
			if (copyMode == "add")
			{
				// Add content to existing content.				
				destinationContainer.innerHTML = destinationContainer.innerHTML + sourceContainer.innerHTML;
			}
			else
			{
				// Replace existing content.
				destinationContainer.innerHTML = sourceContainer.innerHTML;
			}
			
			// Empty source container.
			sourceContainer.innerHTML = "";
			
			// Show destination container.
			destinationContainer.style.display = "block";
		}
	}
}

// Show container if not empty.
function showIfNotEmpty(containerID)
{
	if (document.getElementById(containerID))
	{
		var container = document.getElementById(containerID);
		
		// Remove whitespaces (needed for Firefox).
		var containerContent = container.innerHTML.replace(/^\s+$/, "");
		
		// Check if there is content.
		if (containerContent.length > 0)
		{			
			// Show container.
			container.style.display = "block";
		}
	}
}