// 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";
	}
}

function toggleInfoDetails(option){
	if(option == 0){
		document.getElementById("personalMoreInfo").style.display ='block';
		document.getElementById("employerMoreInfo").style.display ='none';
	} else if(option == 1){
		document.getElementById("personalMoreInfo").style.display ='none';
		document.getElementById("employerMoreInfo").style.display ='block';
	}
	$('moreinfoDiv').parentNode.style.height = 'auto';
}
function closeInfoDetails(){
	document.getElementById("personalMoreInfo").style.display ='none';
	document.getElementById("employerMoreInfo").style.display ='none';
	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
 */
var sitemapLongInfoSlide; // need to declare globally so sitemap event can see the var

function doSitemap() {
	window.addEvent('domready', function() {
		var sitemapCookie = Cookie.read('sitemapStatus');

		if (sitemapCookie == 'closed') {
			sitemapLongInfoSlide = new Fx.Slide('sitemapLongInfo').hide();
			$('secondaryOpenSitemap').style.display = 'inline';
		} else {
			sitemapLongInfoSlide = new Fx.Slide('sitemapLongInfo');
			if (sitemapLongInfoSlide.open) $('openSitemap').className = 'open';
			$('secondaryOpenSitemap').style.display = 'none';
		}
		$('openSitemap').addEvent('click', function(e){
			e = new Event(e);
			sitemapLongInfoSlide.toggle();
			e.stop();

			// change css based on whether open or not
			if (!sitemapLongInfoSlide.open) {
				$('openSitemap').className = 'open';
				$('secondaryOpenSitemap').style.display = 'none';
				var sitemapCookie = Cookie.write('sitemapStatus', 'open', {path: '/'});
			} else {
				$('openSitemap').className = '';
				$('secondaryOpenSitemap').style.display = 'inline';
				var sitemapCookie = Cookie.write('sitemapStatus', 'closed', {path: '/'});
			}
		});
		$('secondaryOpenSitemap').addEvent('click', function(e){
			e = new Event(e);
			sitemapLongInfoSlide.toggle();
			e.stop();

			// change css based on whether open or not
			if (!sitemapLongInfoSlide.open) {
				$('openSitemap').className = 'open';
				$('secondaryOpenSitemap').style.display = 'none';
				var sitemapCookie = Cookie.write('sitemapStatus', 'open', {path: '/'});
			} else {
				$('openSitemap').className = '';
				$('secondaryOpenSitemap').style.display = 'inline';
				var sitemapCookie = Cookie.write('sitemapStatus', 'closed', {path: '/'});
			}
		});
	});
}

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

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

/**
 * Executes code contained in a input elements defined by either a class or ID
 *
 * @param idToExecute if we want to execute one bit of code pass the ID
 * @return            nothing, this is procedure
 */
function executeJS(idToExecute) {
	if (idToExecute != '') {
		// if we have an id then execute it
		var inputElement = document.getElementById(idToExecute);
		if ((inputElement.className == 'executeMe') && (inputElement.value != '')) eval(inputElement.value);
	} else {
		// no id so execute all matching elements
		var inputElements = document.getElementsByTagName("input");
		var inputElementsLength = inputElements.length;

		// loop through and find only those with matching classname
		for (var a = 0; a < inputElementsLength; a++) {
			// make sure have correct class
			if ((inputElements[a].className == 'executeMe') && (inputElements[a].value != '')) eval(inputElements[a].value);
		}
	}
}
function executeScriptBlock(divId) {
	var x = document.getElementById(divId).getElementsByTagName("script");
	for(var i=0;i<x.length;i++) {
		alert(x[i].text);
	}
}

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) {
	var 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');
	}
	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 = '';
	// micro level tracking
	s.tl(true,'o',pathToFetch.replace(/\/v\/[^\/]*/, ""));
	// macro level tracking
	macroLevelTracking(pathToFetch.replace(/\/v\/[^\/]*/, ""));

	var myRequest = new Request({
		url: pathToFetch+'.d.'+currentDiv+'.p.'+currentPath+'.i.'+idToExecuteOnReturn+'.ed.'+extraData,
		method: 'get',
		autoCancel: true,
		onSuccess: function(responseText, responseXML){
			try {
				// get the text, set it, then alter the height of the container div to match
				// the new content
				$(currentDiv).set('html', responseText);
				var codeToExecute = document.getElementById(idToExecute).value;
				if (codeToExecute != '') eval(codeToExecute);
				$(currentDiv).style.height = "auto";
			} catch (e) {
				alert("error: "+e.description);
				changeVisibility(loaderName, 'off');
			}
		},
		onFailure: function(instance){
			changeVisibility(loaderName, 'off');
			alert('fail');
		}
	}).send();
}

/**
 * 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) {
	var loaderTopName = 'loadertop'+idToExecute.substr(1);
	var loaderBottomName = 'loaderbottom'+idToExecute.substr(1);
	changeVisibility(loaderTopName, 'on');
	changeVisibility(loaderBottomName, 'on');
	// micro level tracking

	s.tl(true,'o',pathToFetch.replace(/\/v\/[^\/]*/, ""));
	// macro level tracking
	macroLevelTracking(pathToFetch.replace(/\/v\/[^\/]*/, ""));
	var myRequest = new Request({
		url: pathToFetch+'.d.'+currentDiv,
		autoCancel: true,
		method: 'get',
		onSuccess: function(responseText, responseXML){
			try {
				// get the text, set it, then alter the height of the container div to match
				// the new content
				$(currentDiv).set('html', responseText);
				var codeToExecute = document.getElementById(idToExecute).value;
				if (codeToExecute != '') eval(codeToExecute);
				$(currentDiv).style.height = "auto";
			} catch (e) {
				alert("error: "+e.description);
				changeVisibility(loaderTopName, 'off');
				changeVisibility(loaderBottomName, 'off');
			}
		},
		onFailure: function(){
			changeVisibility(loaderTopName, 'off');
			changeVisibility(loaderBottomName, 'off');
			alert('fail');
		}
	}).send();
}

/**
 * Turn a set of links/divs into an accordion based on CSS selector, open selected item
 * - togglers must have a class of 'toggleLinks', divs must have a class of 'toggleDivs'
 *
 * @param aType         1, 2 or 3 (1/3 width, 2/3 width or full width)
 * @param containerID   name of the container id which contains the accordion
 * @param openIndex     the index (0 upwards) of the item to section on load, -1 to start all closed
 * @param resizeThisDiv div to resize it's parent to for inner accordions
 * @return              nothing, this is procedure
 */
var initialResizeDone = false; // have we done initial page load resize of inner accordion?
function ufiAccordion(aType, containerID, openIndex, resizeThisDiv, h2Accordion) {
	var togglersSelector;
	var elementsSelector;
	var myAccordion;

	togglersSelector = '#'+containerID+' .toggleLinks';
	elementsSelector = '#'+containerID+' .toggleDivs';

	if (aType == 3) {
		togglersSelector += 'Inner';
		elementsSelector += 'Inner';
	}

	// run through the togglers adding an event to the link to prevent it firing and going to the URL
	var togglers = $$(togglersSelector);
	for (var tCount = 0; tCount < togglers.length; tCount++) {
		togglers[tCount].addEvent('click', function(e){
			e = new Event(e);
			e.stop();
		});
	}

	// create an accordion based on the type. different classes and stuff dependent on the type
	if (aType == 1) {
		myAccordion = new Accordion($$(togglersSelector), $$(elementsSelector), {
			display: openIndex,
		    alwaysHide: true,
		    opacity: false,
			onBackground: function(toggler, element) {
				try {
					if (this.togglers[this.togglers.length - 1] == toggler) {
						toggler.className = 'courseListItem lastListItem';
					} else if (this.togglers[0] == toggler) {
						toggler.className = 'courseListItem firstListItem';
					} else {
						toggler.className = 'courseListItem';
					}
				} catch (e) {
				}
			},
			onActive: function(toggler, element) {
				try {
					if (this.togglers[0] == toggler) {
						toggler.className = 'courseListItem firstListItemSelected';
					} else {
						toggler.className = 'courseListItem listItemSelected';
					}
				} catch (e) {
				}
				// micro level tracking
				//s.tl(true,'o',toggler.getAttribute('href'));
				// macro level tracking
				//macroLevelTracking(toggler.getAttribute('href'));
			}
		}, $(containerID));
	} else if (aType == 2) {
		myAccordion = new Accordion($$(togglersSelector), $$(elementsSelector), {
			display: openIndex,
		    alwaysHide: true,
		    opacity: false,
			onBackground: function(toggler, element) {
				try {
					if (h2Accordion == 'true') {
						if (this.togglers[this.togglers.length - 1] == toggler) {
							toggler.className = 'fullbar fullbarbottomclosed';
						} else if (this.togglers[0] == toggler) {
							toggler.className = 'fullbar fullbartopclosed';
						} else {
							toggler.className = 'fullbar fullbarmidclosed';
						}
					} else {
						if (this.togglers[this.togglers.length - 1] == toggler) {
							toggler.className = 'lastSubjectArea';
						} else {
							toggler.className = '';
						}
					}
				} catch (e) {
				}
			},
			onActive: function(toggler, element) {
				try {
				
					if (h2Accordion == 'true') {
	
						if (this.togglers[0] == toggler) {
							toggler.className = 'fullbar fullbartopstandardopen';
						} else {
							toggler.className = 'fullbar fullbarlightblueopen';
						}
					} else {
						toggler.className = 'subjectAreaSelected';
					}
				} catch (e) {
				}
				var re = new RegExp("http://([^/]+)");
				var iereplacedomain = toggler.getAttribute('href');
				try{
					iereplacedomain = toggler.getAttribute('href').replace(re,"");	
				}catch (e) {
					iereplacedomain = "/contact/"+toggler.getAttribute('id');
				}
				// micro level tracking
				s.tl(true,'o',iereplacedomain);
				// macro level tracking
				
				macroLevelTracking(iereplacedomain);
			},
			onComplete: function() {
				try {
					// if we have an inner accordion we must see if we need to try a resize
					if (!initialResizeDone && (resizeThisDiv != '')) {
						$(resizeThisDiv).parentNode.style.height = 'auto';
						initialResizeDone = true;
					}
				} catch (e) {
				}
			}
		}, $(containerID));
	} else if (aType == 3) {
		myAccordion = new Accordion($$(togglersSelector), $$(elementsSelector), {
			display: openIndex,
		    alwaysHide: true,
		    opacity: false,
			onBackground: function(toggler, element) {
				try {
					if ((this.togglers[this.togglers.length - 1] == toggler) && (toggler.id == 'finalInnerAccordion')) {
						toggler.className = 'innerSubjectAreaBottom';
					} else {
						toggler.className = '';
					}
				} catch (e) {
				}
			},
			onActive: function(toggler, element) {
				try {
					toggler.className = 'innerSubjectAreaSelected';
				} catch (e) {
				}
				var re = new RegExp("http://([^/]+)");
				var iereplacedomain = toggler.getAttribute('href');
				try{
					iereplacedomain = toggler.getAttribute('href').replace(re,"");	
				}catch (e) {
					iereplacedomain = "/contact/"+toggler.getAttribute('id');
				}
				// micro level tracking
				s.tl(true,'o',iereplacedomain);
				// macro level tracking
				macroLevelTracking(iereplacedomain);
			},
			onComplete: function() {
				try {
					$(containerID).style.height = 'auto';
				} catch (e) {
				}
				//try scroll through togglers and open openIndex if first time
			}
			
		}, $(containerID));
			
		
		}else if (aType == 4) {
		myAccordion = new Accordion($$(togglersSelector), $$(elementsSelector), {
			display: openIndex,
		    alwaysHide: true,
		    opacity: false,
			onBackground: function(toggler, element) {
				try {
					if (this.togglers[this.togglers.length - 1] == toggler) {
						toggler.className = 'businessListItem lastListItemBusiness';
					} else if (this.togglers[0] == toggler) {
						toggler.className = 'businessListItem firstListItemBusiness';
					} else {
						toggler.className = 'businessListItem';
					}
				} catch (e) {
				}
			},
			onActive: function(toggler, element) {
				try {
					if (this.togglers[0] == toggler) {
						toggler.className = 'businessListItem firstListItemSelectedBusiness';
					} else {
						toggler.className = 'businessListItem listItemSelectedBusiness';
					}
				} catch (e) {
				}
				// micro level tracking
				//s.tl(true,'o',toggler.getAttribute('href'));
				// macro level tracking
				//macroLevelTracking(toggler.getAttribute('href'));
			}
		}, $(containerID));
		
	}
	

	return myAccordion;
}

// This array contains all the sliders created on a page, it's global scope is required so the toggle
// functions event can see them
var slidersArray = new Array();

/**
 * Toggler function for attaching to open/close divs/links
 *
 * @param element     passed in from the bindToEvent function
 * @param slider      a mootools Fx.Slide object that this action is applied to
 * @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
 * @return            nothing, this is procedure
 */
function ufiToggleAttach(element, slider, openClass, closedClass) {
	// only required for centre details page
	if (element.target.id == 'courseResultsLink') {
		if (!slider.open) {
			try {
				$('mapviewer').style.display = 'block';
			} catch (e) {
			}
		} else {
			try {
				$('mapviewer').style.display = 'none';
			} catch (e) {
			}
		}
	}
	e = new Event(element);
	slider.toggle();
	e.stop();

	// change css based on whether open or not
	if (!slider.open) {
		element.target.className = openClass;

		if (element.target.id == 'courseResultsLink') {
			try {
				$('mapviewer').style.display = 'block';
			} catch (e) {
			}
		}
	} else {
		element.target.className = closedClass;

		if (element.target.id == 'courseResultsLink') {
			try {
				$('mapviewer').style.display = 'none';
			} catch (e) {
			}
		}
	}
}

/**
 * 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
 * @return            nothing, this is procedure
 */
function ufiToggle(toggleID, divID, openClass, closedClass, hide) {
	// create a slider, stick it on the array and add an event to the toggler
	var slider;

	if (hide) {
		slider = new Fx.Slide(divID).hide();
	} else {
		slider = new Fx.Slide(divID);
	}
	slidersArray.push(slider);
	$(toggleID).addEvent('click', ufiToggleAttach.bindWithEvent(toggleID, [slidersArray[slidersArray.length - 1], openClass, closedClass]));

	return slidersArray[slidersArray.length - 1];
}

/**
 * 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') {
		$(id).style.display = 'inline';
	} else {
		$(id).style.display = 'none';
	}
}

/**
 * Shows the logout / access learning buttons if cookie present
 * 
 */
function showLoggedIn(logoutLink, editLink) {
	var loggedInName = Cookie.read("loggedInName");
	
	if ((loggedInName != null) && (loggedInName != '')) {
		loggedInName = loggedInName.replace("+", " ");
		var myLearndirectDiv = $('mylearndirect');
		var accessAnchor = $('logintolearning');
		accessAnchor.set('html', 'Access your learning');
		accessAnchor.setStyle('margin-top', 6); // move back into correct location
		var firstPara = new Element('p');
		var thirdPara = new Element('p', {'html':'Welcome back, '+loggedInName});
		var editAnchor = new Element('a', {'href':editLink, 'html':'Edit your details'});
		var logoutAnchor = new Element('a', {'href':logoutLink, 'html':'Log out', 'id':'logout'});
		// Delete the cookie on logout
		logoutAnchor.addEvent('click', function(){
			Cookie.dispose("loggedInName", {domain: 'learndirect.co.uk', path:'/'});
		});
		
		firstPara.inject(myLearndirectDiv, 'top');
		editAnchor.inject(firstPara);
		logoutAnchor.inject(accessAnchor, 'before');
		thirdPara.inject(myLearndirectDiv);
	}
}




