/**
 * Setup for global web site behaviours 
 */
window.onload = function() 
{
	anchorSetup();
	formatTablesSetup();
	
	//set up method for in page navigation
	inPageNavSetup();
	
	//set up method for faq pages
	faqSetup();
	
	formatButtonList();
	
	// Webtrends Live - DCS Multi Track for all document links
	webtrendsLiveDCSMultiTrack_DocumentLinks();
	
	// Webtrends Live - DCS Multi Track for all application form fields
	webtrendsLiveDCSMultiTrack_ApplicationFormFields();
}

/*
 * ---------------------------- Constants -----------------------------
 */
var ELEMENT_DFN = "dfn";
var ELEMENT_SPAN = "span";
var ATT_TITLE = "title";

/*
 * ---------------------------- Global Variables -----------------------------
 */
 
var inPageNavSelectNone = false;

/*
 * ----------------------------------- General --------------------------------
 */

/**
 * Makes all links with certain rel values
 * open in a new window
 */
function anchorSetup()
{
	var REL_EXTERNAL = "external";
	var REL_DOCUMENT = "document";
	var REL_PRINT = "print";
	var REL_PAYMENTS = "payments";
	var REL_POPUP="popup";

	var allAnchors = document.getElementsByTagName("a");
	//set up anchors	
	for (var i=0; i < allAnchors.length; i++) 
	{
		//new window behaviours
		var currentAnchor = allAnchors[i];
		
		//standard new windows
		if(currentAnchor.getAttribute("rel") == REL_EXTERNAL || 
		   currentAnchor.getAttribute("rel") == REL_DOCUMENT) 
		{
			currentAnchor.target = "_blank";
		}
		
		//print stuff
		if(currentAnchor.getAttribute("rel") == REL_PRINT)
		{
			var printTarget = currentAnchor.getAttribute("href") + "&print=true";
			
			currentAnchor.onclick = function() {	
				var printPreview = window.open(printTarget, "printPreview", 
					"scrollbars=1,menubar=1,resizable=1,toolbar=0,location=0,status=1");

				var windowLeft = (screen.availWidth - 850) / 2;
				var windowHeight = screen.availHeight - 100;
								
				printPreview.resizeTo(850, windowHeight);								
				printPreview.moveTo(windowLeft, 50);
				
				printPreview.focus();
				printPreview.print();
				return false;	
			}
		}
		
		
		//payment popups
		if(currentAnchor.getAttribute("rel") == REL_PAYMENTS)
		{	
			currentAnchor.target = "_blank";
		
			/*
			var target = currentAnchor.getAttribute("href");
					
			currentAnchor.onclick = function() {
				console.log(target);
				var paymentsWindow = window.open(target, "paymentsWindow", 
				"width=600,height=600,scrollbars=1,menubar=0,resizable=1,toolbar=0,location=0,status=1");	
				paymentsWindow.focus();
				return false;	
			}
			*/
		}

	}
}

/**
 * Formats CSS of visible tables to look better. Even row colouring, for example
 */
function formatTablesSetup()
{
	var allTables = document.getElementsByTagName("table");
	
	var visibleTables = new Array();
	for (var i=0; i < allTables.length; i++) 
	{
		var currentTable = allTables[i];
		if(currentTable.className.indexOf("visibleTable1") != -1 &&
    	   currentTable.className.indexOf("noFormat") == -1) 
		{
			var rows = currentTable.getElementsByTagName("tr")
			
			for(var j = 2; j < rows.length; j = j + 2)
			{
				rows[j].className = "even";
			}
		}
	}
}

/*
 * ----------------------------- In Page Nav ----------------------------------
 */

/**
 * Initial setup for in page navigation
 */
function inPageNavSetup()
{
	//make the anchors' onclicks work
	var allAnchors = document.getElementsByTagName("a");
	
	for(var i=0; i < allAnchors.length; i++)
	{
		var currentAnchor = allAnchors[i];
		if(currentAnchor.className == "inPageNavAnchor") 
		{
			currentAnchor.onclick = inPageNavDisplay;
		}
		else if (currentAnchor.className == "region")
		{
			currentAnchor.onclick = inPageNavDisplay;
		}
	}

	//look for an id to jump to 
	//set selectNone = true elsewhere to have none selected on startup
	var jumpId = window.location.hash.substr(1);
	var skipFirst = true;
	if(document.getElementById(jumpId) || inPageNavSelectNone)
	{
		skipFirst = false
	}
	
	//hide either first in page nav item or jumpid
	var allDivs = document.getElementsByTagName("div");
	var inPageNavCount = 0;
	for (var i=0; i < allDivs.length; i++) 
	{
		var currentContent = allDivs[i];
		if(currentContent.className == "inPageNavContent") 
		{			
			/** original
			if(currentContent.id != jumpId && !skipFirst)
			{
				currentContent.style.display = "none";
			}
			else
			{
				var inPageNavAnchors = document.getElementById("inPageNavItems").getElementsByTagName("a");
				inPageNavAnchors[inPageNavCount].className = "selected";
			}
			*/
			
            if(currentContent.id == jumpId || skipFirst)
            {
                var inPageNavAnchors = document.getElementById("inPageNavItems").getElementsByTagName("a");
                inPageNavAnchors[inPageNavCount].className = "selected";
                currentContent.style.display = "block";
            }
            else
            {
            	currentContent.style.display = "none";
            }
			
			
			inPageNavCount++;
			skipFirst = false;
		}
	}
}

/**
 * Displays the specified In Page Nav content for an in page nav item onclick event
 * @param elementId the element ID of the div to display
 */
function inPageNavDisplay(e)
{	
	var eventSource = getEventSource(e);

	//set all in page nav anchors to unselected
	var inPageNavList = document.getElementById("inPageNavItems");
	var inPageNavAnchors = inPageNavList.getElementsByTagName("a");
	for (var i=0; i < inPageNavAnchors.length; i++) 
	{
		inPageNavAnchors[i].className = "";
	}
	//set the selected in page nav item to selected
		
	eventSource.className = "selected";
	
	var href = eventSource.getAttribute("href");
	var elementId = href.slice(href.indexOf("#") + 1);
	
	//hide all in page nav content
	var allDivs = document.getElementsByTagName("div");
	for (var i=0; i < allDivs.length; i++) 
	{
		var currentContent = allDivs[i];
		if(currentContent.className == "inPageNavContent") 
		{
			currentContent.style.display = "none";
		}
	}
	//show the one to be selected
	document.getElementById(elementId).style.display = "block";
}

/*
 * ------------------------------- FAQ ----------------------------------------
 */

/**
 * Hides all faq answers on a page
 */
function faqSetup()
{
	var allDefLists = document.getElementsByTagName("dl");
	for (var i=0; i < allDefLists.length; i++) 
	{
		var currentDefList = allDefLists[i];
		if(currentDefList.className == "faqList") 
		{
			var faqQuestions = currentDefList.getElementsByTagName("dt");
			for(var j = 0; j < faqQuestions.length; j++)
			{
				faqQuestions[j].onclick = displayFaqAnswer;
			}
			
			
			var faqAnswers = currentDefList.getElementsByTagName("dd");
			for(var j = 0; j < faqAnswers.length; j++)
			{
				faqAnswers[j].style.display = "none";
			}
		}
	}	
}

/**
 * Displays the FAQ answer element (a <dd>) directly following the event source question.
 */	
function displayFaqAnswer(e)
{
	var eventSource = getEventSource(e);

	
	//change question apperance
	if(eventSource.className == "answerVisible")
	{
		eventSource.className = "answerHidden";
	}
	else
	{
		eventSource.className = "answerVisible";		
	}	
	
	//find the next answer
	var answer = eventSource.parentNode;
	while(answer.tagName != "DD")
	{
		answer = answer.nextSibling;
	}
	
	//hide or display the answer 
	if(answer.style.display != "block")
	{
		answer.style.display = "block";
	}
	else
	{
		answer.style.display = "none";
	}
}

/*
 * ----------------------------------- History Module ----------------------------
 */

function setupHistory()
{
	//hide all content
	var lastHistoryContent = hideAllHistoryContent();
	lastHistoryContent.style.display = "block";
	
	//make the links work
	var linkList = document.getElementById("historyLinks");
	var historyLinks = document.getElementsByTagName("a");
	
	var lastHistoryLink;
	for(var i = 0; i < historyLinks.length; i++)
	{
		var currentHistoryLink = historyLinks[i];
		currentHistoryLink.onclick = historyContentDisplay;
		lastHistoryLink = currentHistoryLink;
	}
	lastHistoryLink.className = "selected";
}

function hideAllHistoryContent()
{
	//hide all history content divs
	var allDivs = document.getElementsByTagName("div");

	var lastHistoryContentBox;
	for (var i=0; i < allDivs.length; i++) 
	{
		var currentContent = allDivs[i];
		if(currentContent.className == "historyContentBox") 
		{
			currentContent.style.display = "none";
		}
		lastHistoryContentBox = currentContent;
	}
	
	//reset all links
	var linkList = document.getElementById("historyLinks");
	var historyLinks = linkList.getElementsByTagName("a");
	
	for(var i = 0; i < historyLinks.length; i++)
	{
		var currentHistoryLink = historyLinks[i];
		currentHistoryLink.className = "";
	}
	return lastHistoryContentBox;
}

function historyContentDisplay(e)
{
	var eventSource = getEventSource(e);
	
	hideAllHistoryContent()
	eventSource.className = "selected";
	var href = eventSource.getAttribute("href");
	var targetId = href.slice(href.indexOf("#") + 1);
	document.getElementById(targetId).style.display = "block";
	return false;
}

/**
 * Link Button List alternating colours
 */
function formatButtonList()
{
	var allButtons = document.getElementsByTagName("button");
	
	for (var i=0; i < allButtons.length; i++) 
	{
		if(i%2 == 1)
		{
			allButtons[i].className = "even";
		}
	}
}


/**
 * 	Quick cross browser compatible function to get an event's source
 */
function getEventSource(e)
{
	var eventSource;
	if (!e)
	{
		e = window.event;
		eventSource = e.srcElement;
	}
	else
	{
		eventSource = e.target;
	}
	
	return eventSource;
}


/**
 * Creates a tooltip for <dfn> tags, using the dfn's title attribute
 */
function definitionsTooltipSetup()
{
	var dfns = document.getElementsByTagName(ELEMENT_DFN);

	for(var i = 0; i < dfns.length; i++)
	{
		var dfn = dfns[i];
		var descriptionNode = document.createElement(ELEMENT_SPAN);
		descriptionNode.className = "description";
		var descriptionTextNode = document.createTextNode(dfn.getAttribute(ATT_TITLE));
		descriptionNode.appendChild(descriptionTextNode);
		dfn.removeAttribute(ATT_TITLE);
		

		
		dfn.onmousemove = function(e) {
			e = e || window.event;
			dfn.appendChild(descriptionNode);
			
			descriptionNode.style.left = (descriptionNode.offsetLeft) + "px";
			descriptionNode.style.top = (descriptionNode.offsetTop) + "px";
		}
		
		dfn.onmouseout = function(e) {
			e = e || window.event;
			dfn.removeChild(descriptionNode);
		}
	}
}


/**
 * Pop-up window event
 *
 */
 function popup(target, fullScreen){
	var windowLeft = (screen.availWidth - 850) / 2;
	var windowHeight = screen.availHeight - 100;

	// The reason using this way is because preview.resizeTo and moveTo cause 
	// IE access denied error message if the popup domain is different from based one.
	// see: http://www.dannyg.com/ref/jsminifaq.html#q15
	var preview;
	if (fullScreen){
		preview= window.open(target, '', 'width=' + screen.width + ',height=' + screen.height + ',scrollbars=yes,directories=no,menubar=no,resizable=yes,status=no,toolbar=no');
	}else{
		preview= window.open(target, 'Legal', 'width=850,height=' + windowHeight + ',top=50,left='+windowLeft+',scrollbars=yes,directories=no,menubar=no,resizable=yes,status=no,toolbar=no');
	}
	preview.focus();
	return false;
 }	

/**
 * Sets up DCSMultiTrack for all document links
 */
function webtrendsLiveDCSMultiTrack_DocumentLinks()
{
	// Only do this if jQuery and WebTrends javascript file has been loaded
	if (typeof(jQuery) != "undefined" && typeof(dcsMultiTrack) != "undefined")
	{
		// Work out whether the current page is an application form
		
		var url = window.location.href;
		var httpsUrl = url.indexOf("https") == -1;
		var dotdoUrl = url.indexOf(".do") == -1;
		var sdformUrl = url.indexOf("sdform") == -1;
		var sdform = document.getElementById('sdForm') == null;
		var isNonApplicationForm = httpsUrl && dotdoUrl && sdformUrl && sdform 
		
		// Get the current pages meta data and put into dcs string
		
		var dcs = "";
		
		jQuery("meta").each(function()
		{
			var metaname = jQuery(this).attr('name');
			var metavalue = jQuery(this).attr('content');
			
			if (metaname && metaname != "keywords" && metaname != "description" && 
			metaname != "DCSext.language" && metaname != "WT.cg_n" && 
			metaname != "WT.cg_s" && metaname.substring(0,7) != "WT.seg_")
			{
				dcs += ", '" + metaname + "', ''"; 
			}
		});
		
		if (dcs.substring(0,2) == ", ")
		{
			dcs = dcs.substring(2);
		}
		
		// Updates each document link
		
		jQuery("a.downloadLink").each(function()
		{
			var childCount = jQuery(this).children("span.document").length;
			var documentTitle = "";
			var documentUrl = jQuery(this).attr('href');
			
			if (childCount == 0)
			{
				documentTitle = jQuery(this).html();
			}
			else
			{
				var span = jQuery(this).find("span.document:eq(0)");
				documentTitle = span.html();
			}
			
			// Checks whether non application form
			if (isNonApplicationForm)
			{
				jQuery(this).click(function()
				{
					dcsMultiTrack('DCS.dcsuri', documentUrl, 'WT.ti', documentTitle);
				});
			}
			else
			{
				jQuery(this).click(function()
				{
					var fullDcs = "dcsMultiTrack('DCS.dcsuri', '" + documentUrl + "', 'WT.ti', '" + documentTitle + "', " + dcs + ");";
					eval(fullDcs);
				});
			}
		});
	}
}

/**
 * Sets up DCSMultiTrack for all application form fields
 */
function webtrendsLiveDCSMultiTrack_ApplicationFormFields()
{
	// Only do this if jQuery and WebTrends javascript file has been loaded
	if (typeof(jQuery) != "undefined" && typeof(dcsMultiTrack) != "undefined")
	{
		// Work out whether the current page is an application form
		
		var isApplicationForm = document.getElementById('sdForm') != null;
		
		if (isApplicationForm)
		{
			var url = window.location.href;
			var documentTitle = document.title;
			var metaTitle = jQuery("meta[@name=WT.si_n]").attr("content");
			var title = "";

			// Create title
			
			if (!metaTitle)
			{
				if (!documentTitle)
				{
					title = "";
				}
				else
				{
					title = documentTitle;
				}
			}
			else
			{
				title = metaTitle;
			}
			
			// Gets all fields which start with current_
			
			jQuery("#sdForm *[@name^=current_]").each(function()
			{
				var name = jQuery(this).attr("name").substring(8);
				
				var type = jQuery(this).attr("type");
				
				if (type == "radio" || type == "checkbox")
				{
					var value = jQuery(this).attr("value");
					name += "_" + value;
				}
				
				// Shorten name if longer than 70 characters (we're checking for 67 and adding ... at the end)
				if (name.length > 67)
				{
					name = name.substring(0, 67) + "...";
				}
				
				jQuery(this).change(function()
				{
					var fullDcs = "dcsMultiTrack('DCS.dcsuri', '" + url + "', 'WT.ti', '" + title + "', 'DCSext.form', '1', 'DCSext.formfield', '" + name + "', 'WT.si_n', '" + title + "', 'WT.si_p', '" + name + "');";
					eval(fullDcs);
				});
			});
		}
	}	
}