jQuery(document).ready(function() {
	// get channel cookie
	var channelCookieValue = getCheckChannelCookie();

	// if we're direct delivery then change all home links to planner and update help and contact links
	if ((typeof(channelCookieValue) != 'undefined') && (channelCookieValue !== null) && (channelCookieValue != '')) {
		if ((channelCookieValue == 'DIRECT_DELIVERY_INDIVIDUAL') && so2) {
			jQuery("a[href='/']").attr("href", "/planner/");
			jQuery("a[href='/help/']").attr("href", "/planner/help/");
			jQuery("a[href='/contact/']").attr("href", "/planner/contact");
		}

		var communityLink = '<li><a href="' + ldCommunityURL + '">Community</a></li>';
		jQuery(communityLink).insertAfter("#primaryNav ul li:eq(4)");
	}
	
	// make all matching links open in new windows
	jQuery("a[rel=external]").attr("target", "_blank");
});

/**
 * Clean up cookies then redirect to Url
 * @param logoutUrl
 */
function logout(logoutUrl) {
	try {
		// try deleting community Id cookie
		jQuery.cookie(communityID, null, {path: '/'});
	} catch (cIdE) {}
	try {
		// are we in read only mode
		jQuery.cookie(readOnlyCookieName, null, {path: '/'});
	} catch (rOE) {}
	try {
		// checking first login cookie
		jQuery.cookie(sessionCookieName, null, {path: '/'});
	} catch (sE) {}

	// redirect to Url
	document.location.href = logoutUrl;
}

// Get the channel cookie
function getCheckChannelCookie() {
	var returnValue = '';
	try {
		var channelCookieData = jQuery.cookie("Channel");

		// make sure we have a cookie and split it
		if ((typeof(channelCookieData) != 'undefined') && (channelCookieData != '')) {
			returnValue = channelCookieData;
		}
	} catch (channelCookieDataE) {}
	
	return returnValue;
}

/**
 * Display the logout/login area in the top RHS
 * @param editLink		edit URL in ARC
 * @param notYouUrl		'Not you' login ARC url
 * @param loginLink		login link for ARC
 * @param ddLogoutUrl	Direct Delivery logout link
 * @param logoutUrl		standard logout link
 * @param lseHomeUrl	LSE home page link
 */
function createLoginArea(editLink, notYouUrl, loginLink, ddLogoutUrl, logoutUrl, lseHomeUrl) {
	var html = '';
	var channelCookieValue = getCheckChannelCookie();
	var encodedHref = jQuery.URLEncode(window.location.href);
	var gotoUrl = '';
	var realLogoutUrl = '';

	// set the goto URL if required
	if (window.location.pathname != '/') {
		gotoUrl = '?goto=' + encodedHref;
	}

	if ((typeof(channelCookieValue) != 'undefined') && (channelCookieValue !== null) && (channelCookieValue != '')) {
		// check if we're on the front of the main site where this may be undefined
		if (typeof(learnerName) == 'undefined') {
			learnerName = '';
		}

		try {
			var lnCookieData = jQuery.cookie("loggedInName");

			if ((typeof(lnCookieData) != 'undefined') && (lnCookieData !== null) && (lnCookieData != '')) {
				learnerName = lnCookieData.replace(/\+/g, " ");
			}
		} catch (lnCookieNameE) {}

		// planner could be in read only mode
		try {
			if ((typeof(ron) != 'undefined') && (ron != '')) {
				learnerName = ron;
				learnerName = learnerName.replace(/\+/g, " ");
				learnerName = learnerName.replace(/\%20/g, " ");
			}
		} catch (ronE) {}

		if ((channelCookieValue == 'DIRECT_DELIVERY_INDIVIDUAL') && so2) {
			html += '<div id="mylearndirect">';
			html += '<div><p>Welcome back <span id="learnerName">' + learnerName + '</span></p>';
			html += '<p class="notYou">(<a href="' + notYouUrl + encodedHref + '" class="learnerOnly" title="Login with your username and password">Not you</a>?)</p>';
			html += '</div><a href="#" id="logoutLink" class="learnerOnly logMeOut">Log out</a>';
			html += '</div>';
			realLogoutUrl = ddLogoutUrl;
		} else if ((typeof(learnerName) != 'undefined') && (learnerName !== null) && (learnerName != '')) {
			html += '<div id="mylearndirectnondd">';
			html += '<p><a href="' + editLink + '">Edit your details</a></p>';
			html += '<p><a id="logoutnondd" class="logMeOut" href="#">Log out</a><a id="logintolearningnondd" href="' + lseHomeUrl + '" style="margin-top: 6px;">Access your learning</a></p>';
			html += '<p>Welcome back, ' + learnerName + '</p>';
			html += '</div>';
			realLogoutUrl = logoutUrl;
		} else {
			html += '<div id="mylearndirectnondd"><p><a href="' + loginLink + gotoUrl + '" id="logintolearningnondd" class="learnerOnly">Access your learning</a></p></div>';
		}
	} else {
		// no cookie, not logged in
		html += '<div id="mylearndirectnondd"><p><a href="' + loginLink + gotoUrl + '" id="logintolearningnondd" class="learnerOnly">Access your learning</a></p></div>';
	}
	
	jQuery("#mylearndirectnondd").replaceWith(html);
	
	// now attach event
	if (realLogoutUrl != '') {
		jQuery(".logMeOut").bind("click keypress", function() {
			logout(realLogoutUrl);
			return false;
		});
	}
}

// function prototype to prevent errors due to slow sitecatalyst code loading
// function to report accordions as custom links (micro level)
var s = "true";
s.tl = function(delay,object,link) {};

// function to report accordions as page views (macro level)
function macroLevelTracking(macroPageName){
	vars = new Object();
	vars.pageName = macroPageName;
	vars.server = 'learndirect';
	vars.channel = macroPageName; 

	s.t(vars);
}

// function to insert doubleclick code images into page
function doubleClickImage(src, type, cat, ord) {
	var a = Math.random() * 10000000000000;
	var dcpix = new Image(); 
	dcpix.src = 'http://ad.uk.doubleclick.net/activity;src='+src+';type='+type+';cat='+cat+';ord='+ord+';num='+ a + '?';
	return true;
}

function quote() { doubleClickImage('869889', 'conversn', 'click01', '1'); }
function quoteRequestInfo() { doubleClickImage('869889', 'conversn', 'submit01', '1'); }

// JS window opener from http://www.sitepoint.com/article/standards-compliant-world
function externalLinks() {
	/*if (!document.getElementsByTagName) return;
	var anchors = document.getElementsByTagName("a");
	for (var i=0; i<anchors.length; i++) {
		var anchor = anchors[i];
		if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external") anchor.target = "_blank";
	}*/
	jQuery("a[rel=external]").attr("target", "_blank");
}

function toggleInfoDetails(option){
	if(option == 0){
		jQuery("#personalMoreInfo").show();
		jQuery("#employerMoreInfo").hide();
	} else if(option == 1){
		jQuery("#personalMoreInfo").hide();
		jQuery("#employerMoreInfo").show();
	}
}
function closeInfoDetails(){
	jQuery("#personalMoreInfo").hide();
	jQuery("#employerMoreInfo").hide();
	document.getElementById("flagpersonal").checked = false;
	document.getElementById("flagemployer").checked = false;
}

//Launch taster window
function launchTaster(href){
	var vScrollbar=40;
	var hScrollbar=30;
	newWin = window.open(href,'learndirect_taster','resizable=1,height=592,width=760,toolbar=no,scrolling=auto,location=no,menubar=no');
	var x= ((self.screen.width/2)-((760+hScrollbar+10)/2))
	var y=((self.screen.height/2)-((592+vScrollbar+55)/2))
	if (y<=0 || x<=0){
		x=0;
		y=0;
	}
	newWin.moveTo(x,y);
	newWin.focus();
}

// launch screenshot window
function launchScreenshot(href, width, height){
	if (width == 0)	width = 640;
	if (height == 0) height = 480;
	newWin = window.open(href,'learndirect_screenshot','resizable=1,height=' + (height + 30) + ',width=' + (width + 20) + ',toolbar=no,scrolling=auto,location=no,menubar=no');
}

function divPopup(input, action) {
	var thisParentNode = input.parentNode;
	var numChildNodes = thisParentNode.childNodes.length;

	for (var node = 0; node < numChildNodes; node++){
		nodeClassName = thisParentNode.childNodes[node].className;

		if (action == 'open') {
			if (nodeClassName == 'comparePopup') {
				thisParentNode.childNodes[node].className = 'comparePopupOpen';
				break;
			}
		} else {
			if (nodeClassName == 'comparePopupOpen') {
				thisParentNode.childNodes[node].className = 'comparePopup';
				break;
			}
		}
	}
}

/**
 * Toggle the sitemap
 */
function doSitemap() {
	jQuery(document).ready(function() {
		// open/close sitemap depending on last status from cookie
		var sitemapCookie = jQuery.cookie('sitemapStatus');

		if (sitemapCookie == 'closed') {
			jQuery('#sitemapLongInfo').hide();
			jQuery('#secondaryOpenSitemap').show();
		} else {
			jQuery('#openSitemap').addClass('open');
			jQuery('#secondaryOpenSitemap').hide();
		}

		// attach open/close to relevant links
		jQuery('#openSitemap,#secondaryOpenSitemap').bind('keypress click', function() {
			var currentStatus = jQuery('#sitemapLongInfo').css('display');

			// change css based on whether open or not
			if (currentStatus == 'none') {
				jQuery('#openSitemap').addClass('open');
				jQuery('#secondaryOpenSitemap').hide();
				var sitemapCookie = jQuery.cookie('sitemapStatus', 'open', {path: '/'});
			} else {
				jQuery('#openSitemap').removeClass('open');
				jQuery('#secondaryOpenSitemap').show();
				var sitemapCookie = jQuery.cookie('sitemapStatus', 'closed', {path: '/'});
			}

			jQuery('#sitemapLongInfo').slideToggle();

			return false;
		});
	});
}

function doOnLoad() {
	//externalLinks();
	processRequestQueue();
	trackPage();
	var mainForm = document.getElementById("frmSearch");
	if (mainForm != null && mainForm['query'].value == '') mainForm['query'].value = 'Search';
}

function emptySearch(input) {
	if (input.value == 'Search') input.value = '';
}

function checkCompares(input) {
	var form = input.form;
	var numberChecked = 0;

	for (i = 0; i < form.coursePath.length; i++) {
		if (form.coursePath[i].checked) {
			numberChecked++;
			if (numberChecked > 2) form.coursePath[i].checked = false; // deselect if more than 2
		}
	}

	if (numberChecked > 2) alert('You can only compare 2 courses');
}

/**
 * Take data from a course compare form and send it to the course compare page using ajax
 *
 * @param input               the document.forms[X] to check
 * @param pathToFetch         where to fetch page from
 * @param currentPath         the path of this page to come back to from the page we're fetching
 * @param currentDiv          the div in this page that will reload the category data
 * @param idToExecute         the id of the hidden form element with JS code in to execute when the page loads
 * @param idToExecuteOnReturn the id of the hidden form element with JS code in to execute when the current page is loaded in the reload fn
 * @return                    nothing, this is procedure
 */
function doCompare(input, pathToFetch, currentPath, currentDiv, idToExecute, idToExecuteOnReturn, extraData) {
	//var extraData = '';
	if (extraData == null) extraData = '';
	
	var numberChecked = 0;

	for (i = 0; i < input.coursePath.length; i++) {
		if (input.coursePath[i].checked) {
			numberChecked++;
			if (numberChecked > 2) input.coursePath[i].checked = false; // deselect if more than 2
			extraData = extraData + '&coursePath=' + input.coursePath[i].value;
		}
	}

	if (numberChecked == 2) {
		fetchDetail('', pathToFetch, currentPath, currentDiv, idToExecute, idToExecuteOnReturn, extraData);
	} else if (numberChecked < 2) {
		alert('You must select 2 courses to compare');
	} else {
		alert('You can only compare 2 courses');
	}
	
	//calls COI tag function
	coi_container_track({action:'compare'});
	
	return false;
}

/**
 * Fetch a detail page and load it into a div
 *
 * @param element             passed in from the bindToEvent function
 * @param pathToFetch         where to fetch page from
 * @param currentPath         the path of this page to come back to from the page we're fetching
 * @param currentDiv          the div in this page that will reload the category data
 * @param idToExecute         the id of the hidden form element with JS code in to execute when the page loads
 * @param idToExecuteOnReturn the id of the hidden form element with JS code in to execute when the current page is loaded in the reload fn
 * @param extraData           any extra data to pass through
 * @return                    nothing, this is procedure
 */
function fetchDetail(element, pathToFetch, currentPath, currentDiv, idToExecute, idToExecuteOnReturn, extraData) {

	var loaderName = 'loader'+idToExecuteOnReturn.substr(1)+'_'+idToExecute.substr(1);
	changeVisibility(loaderName, 'on');
	if (extraData == null) extraData = '';
	
	if(pathToFetch.toLowerCase().indexOf('monster') < 0) {
	  // micro level tracking
	  s.tl(true,'o',pathToFetch.replace(/\/v\/[^\/]*/, ""));
	  // macro level tracking
	  macroLevelTracking(pathToFetch.replace(/\/v\/[^\/]*/, ""));
	}	
	
	jQuery.ajax({
		url: pathToFetch+'.d.'+currentDiv+'.p.'+currentPath+'.i.'+idToExecuteOnReturn+'.ed.'+extraData,
		dataType: 'html',
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			changeVisibility(loaderName, 'off');
			showAjaxError(XMLHttpRequest, textStatus, errorThrown);
		},
		success: function(responseText) {
			try {
				jQuery("#" + currentDiv).html(responseText);
			} catch (e) {
				changeVisibility(loaderName, 'off');
			}
		}	
	});
	//calls COI tags function
	coi_container_track({action:'details'});
}

/**
 * Fetch the overview/list page that a detail page came from and put it in the same div
 *
 * @param element     passed in from the bindToEvent function
 * @param pathToFetch where to fetch the overview from
 * @param currentDiv  the div in this page that will reload the category data
 * @param idToExecute the id of the hidden form element with JS code in to execute when the page loads
 * @return            nothing, this is procedure
 */
function reloadOverview(element, pathToFetch, currentDiv, idToExecute, extraData) {
	var loaderTopName = 'loadertop'+idToExecute.substr(1);
	var loaderBottomName = 'loaderbottom'+idToExecute.substr(1);
	changeVisibility(loaderTopName, 'on');
	changeVisibility(loaderBottomName, 'on');
	if (extraData == null) extraData = '';
	
	if(pathToFetch.toLowerCase().indexOf('monster') < 0) {
	  // micro level tracking
	  s.tl(true,'o',pathToFetch.replace(/\/v\/[^\/]*/, ""));
	  // macro level tracking
	  macroLevelTracking(pathToFetch.replace(/\/v\/[^\/]*/, ""));
	}
	
	jQuery.ajax({
		url: pathToFetch+'.d.'+currentDiv+'.p..i..ed.'+extraData,
		dataType: 'html',
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			changeVisibility(loaderTopName, 'off');
			changeVisibility(loaderBottomName, 'off');
			showAjaxError(XMLHttpRequest, textStatus, errorThrown);
		},
		success: function(responseText) {
			try {
				jQuery("#" + currentDiv).html(responseText);
			} catch (e) {
				changeVisibility(loaderTopName, 'off');
				changeVisibility(loaderBottomName, 'off');
			}
		}
	});
}

/**
 * Creates a standard accordion for the website
 * @param containerID		ID of accordion container
 * @param headerSelector	CSS selector for header
 * @param openIndex			The index of the accordion to be opened
 */
function ufiAccordion(containerID, headerSelector, openIndex) {
	var domainMatch = new RegExp("http://([^/]+)");

	jQuery("#" + containerID).accordion({
		header: headerSelector,
		active: openIndex,
		collapsible: true,
		autoHeight: false,
		clearStyle: true,
		change: function(event, ui) {
			try {
				// try and do some tracking of accordions that have proper links as well
				var href = jQuery(ui.newHeader).find("a").attr("href");

				if ((typeof(href) != 'undefined') && (href !== null) && (href != '')) {
					try {
						href = href.replace(domainMatch, "");	
					} catch (replaceE) {
						href = "/contact/" + jQuery(ui.newHeader).attr('id');
					}

					// micro level tracking
					s.tl(true, 'o', href);

					// macro level tracking
					macroLevelTracking(href);
				}
			} catch (hrefE) {}
		}
	});
}

/**
 * Toggler function for creating togglers
 *
 * @param toggleID		id of link/toggler
 * @param divID			id of div/container for toggler
 * @param openClass		the class to apply to the toggler when the item is open
 * @param closedClass	the class to apply to the toggler when the item is closed
 * @param hide		 	whether or not to start hidden
 */
function ufiToggle(toggleID, divID, openClass, closedClass, hide) {
	if (hide) {
		jQuery("#" + divID).hide()
	}

	// attach toggler to link
	jQuery("#" + toggleID).bind("keypress click", function() {
		var togglerElement = jQuery(this);

		// change css based on whether open or not
		if (jQuery('#' + divID).css('display') != 'block') {
			togglerElement.attr("class", openClass);

			if (togglerElement.attr("id") == 'courseResultsLink') {
				try {
					jQuery('#mapviewer').show();
				} catch (e) {}
			}
		} else {
			togglerElement.attr("class", closedClass);

			if (togglerElement.attr("id") == 'courseResultsLink') {
				try {
					jQuery('#mapviewer').hide();
				} catch (e) {}
			}
		}

		// swap status
		jQuery('#' + divID).slideToggle();
		
		return false;
	});
}

/**
 * Allows the setting of an IDs visibility
 *
 * @param id     id of element to set visibility
 * @param status status to set element to, on/off
 * @return       nothing, this is procedure
 */
function changeVisibility(id, status) {
	if (status == 'on') {
		jQuery("#" + id).css("display", "inline");
	} else {
		jQuery("#" + id).hide();
	}
}