function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && document.getElementById) x=document.getElementById(n); return x;
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function cuteSubmit(cuteObjName){
	document.getElementById('CE_'+ cuteObjName +'_ID').NotifySelectionChange();
}

function SavedCourses(option){
	switch (option) {
	case "he":
		var pars="type=runSearch&searchtype=saved_list&typeProvider=he";
		new Ajax.Request('/AjaxSearch.asp', {
			method: 'post', parameters: pars,
			onComplete: function() {
				window.location.href='/search/results/higher_education';
			}});
		break;
	case "courses":
		var pars="type=runSearch&searchtype=saved_list";
		new Ajax.Request('/AjaxSearch.asp', {
			method: 'post', parameters: pars,
			onComplete: function() {
				window.location.href='/search/results';
			}}
		);
		break;
	default:
		var pars="type=checkSavedCourses";
		new Ajax.Request('/AjaxSearch.asp', {
			onLoading: function() {
			},
			onComplete: function(t) {
				if (t.responseText.indexOf("Error: Redirect to login page")!=-1) {
					window.location.href=t.responseText.replace("Error: Redirect to login page ","");
				} else if (t.responseText==',') {
					alert('You have no courses saved');
				} else {
					var arrResult=t.responseText.split(",")
					if ((arrResult[0]!='0') && (arrResult[1]!='0')) ajaxPopup('saved_check.asp?width=320&height=120&lb=1&he='+arrResult[1]+'&c='+arrResult[0],false);
					else if (arrResult[0]!='0') { //courses, apprenticeships and diplomas
						SavedCourses('courses');
					}
					else if (arrResult[1]!='0') { //higher education
						SavedCourses('he');
					}
					else alert('You have no courses saved');
				}
			}
			,method: 'post',parameters:pars});
	}
}

	// Opens a lightbox with course_info or course_enquiry, used in xsl courses and myhomepage_savedcourses.xsl
	function CourseOption(data_id,page) {
		var strWidth=650;
		var strHeight=470;
		var idCourse=0;
		var schoolkeyid=0;//Use to get contact details etc for a provider
		if (arguments[2]!=undefined) strWidth=arguments[2];
		if (arguments[3]!=undefined) strHeight=arguments[3];
		if (arguments[4]!=undefined) idCourse=arguments[4];
		if (arguments[5]!=undefined) schoolkeyid=arguments[5];
		if ($('lightbox')) $('lightbox').setStyle({border:'1px Solid Black'});
		
		ajaxPopup('/'+page+'.asp?width='+strWidth+'&height='+strHeight+'&c='+data_id+'&lb=1&id='+idCourse+'&sid='+schoolkeyid,false);
		fixLightbox(0);
	}

	// Triggers the search for courses, used in the search page and the search courses widget
	function submitSearch(checkKeyword) {
		if (checkKeyword && $('txtKeyword').present()==false) alert('You must enter a search term');
		else if (checkKeyword && $('txtKeyword').present()==true && $('txtKeyword').value.length<3) alert('You must enter a longer keyword');
		else {
			$('process').value='1';
			var pars = Form.serialize("frmSearch");
			pars+="&type=runSearch";
			new Ajax.Request('/AjaxSearch.asp', {
				onLoading: function() {
					if ($('lightbox')) $('lightbox').setStyle({border:'0px solid black'});
					ajaxPopup('/loading_pop.asp?width=200&height=80',true);
				},
				onComplete: function(t) {
						if (t.responseText.indexOf('Error: ')!=-1) {
							lightbox.prototype.deactivate();
							alert(t.responseText);
							alert("There was a problem with the search term entered - please try again");
						} else {
							if ($("isDiploma") && $("ctype")) {
								if (($F('ctype')=="22" || $F('ctype')=="27") && $("isDiploma")) $("isDiploma").value='1';
							}
							if ($('searchType').value=="he") document.frmSearch.action='/search/results/higher_education';
							else document.frmSearch.action='/search/results';
							lightbox.prototype.deactivate();

							document.frmSearch.submit();
						}
					}
				,method: 'post',parameters:pars});
		}
	}

	function TextHeight(text,points,family){
		test=document.getElementById("dummyText")
		test.style.fontFamily=family;
		test.style.fontSize=points;
		test.innerHTML=text;
		return test.clientHeight;
	}

	function submitProvidersSearch(estid,provtype) {
		var url="/search/results";
		if (provtype=='he') url+='/higher_education';

		var pars="type=runSearch&searchestid="+estid+"&typeProvider="+provtype+"&searchtype=prov_list";
		new Ajax.Request('/AjaxSearch.asp', {
			onLoading: function() {
				if ($('lightbox')) $('lightbox').setStyle({border:'0px solid black'});
				ajaxPopup('/loading_pop.asp?width=200&height=80',true);
			},
			onComplete: function() {
					window.location.href=url;
				}
			,method: 'post',parameters:pars});
	}

	function initPopupEnquiry() {
		if($('txtName')){
			$("txtName").focus();
			Event.observe("txtName", "keydown", function(event) {
				if (event.keyCode == 13 && $("txtEmail")) $("txtEmail").focus();
			});
		}
		if($('txtEmail')){
			Event.observe("txtEmail", "keydown", function(event) {
				if (event.keyCode == 13 ){
					($("txtSubject"))?$("txtSubject").focus():$("txtPhone").focus();
				}
			});
		}
		if($('txtPhone')){
			Event.observe("txtPhone", "keydown", function(event) {
				if (event.keyCode == 13 && $("txtPostcode") )$("txtPostcode").focus();
			});
		}
		if($('txtPostcode')){
			Event.observe("txtPostcode", "keydown", function(event) {
				if (event.keyCode == 13 && $("txtEnquiry") )$("txtEnquiry").focus();
			});
		}
		if($('txtSubject')){
			Event.observe("txtSubject", "keydown", function(event) {
				if (event.keyCode == 13 && $("txtEnquiry")) $("txtEnquiry").focus();
			});
		}
		if ($('radReplyEmail')) Event.observe("radReplyEmail","click",function(){$('phonerequired').hide()});
		if ($('radReplyPhone')) Event.observe("radReplyPhone","click",function(){$('phonerequired').show()});
	}

	function switchListProviders(obj){
		if ($(obj).hasClassName('rhSearchButtons') && ($('listMode').value!=obj))
		{
			var myOptions = $$('.rhSearchButtonsActive');
			myOptions.each(function(elem) {
					$(elem).addClassName('rhSearchButtons');
					$(elem).removeClassName('rhSearchButtonsActive');
			});

			$(obj).toggleClassName('rhSearchButtonsActive');
			$('listMode').value=obj;
			getProviders();
		}
	}

	function ValidateSearch() {
		var isError=true;
		var msg='';

		//empty hash, don't validate the form
		if (hValidation.inspect()=="#<Hash:{}>") isError=false;
		else {
				$H(hValidation).each(function(hashList){
						hashList.each(function(elem,i) {
								if(elem.obj!=undefined){
									if (($(elem.obj).present()) && ($(elem.obj).getValue()!='0')) {
										isError=false;
										throw $break;
									} else if (elem.msg!=undefined) msg=elem.msg;
								}
						});
				});
		}
	
		if (!isError) submitSearch(false);
		else if (msg!="") alert(msg);
		else alert('You must select at least one search filter to be able to search.');
	}

	function NewSearch() {
		$('newsearch').value='1';	
		var strSearchUrl='/search/';
		switch ($('searchType').value)
		{
			case "a": 
				strSearchUrl+='advanced';
				break;
			case "he": 
				strSearchUrl+='higher_education';
				break;
			default:
				strSearchUrl+='basic';
				break;
		}

		$("frmSearch").action=strSearchUrl;
		$("frmSearch").submit();
	}

	function drawMap(url){
		if (!$('mapwin'))
		{
			$('divMap').update('<iframe id="mapwin" name="mapwin" frameborder="0" style="display:block;margin-top:10px;width:400px%;height:600px;" src="'+url+'"></iframe>');
		}

		$('statusMessage').show();
		
		// Get handle on target.
		var objTarget = $('containerLA');

		// Calculate position + dimensions.
		var objDimensions = objTarget.getDimensions();
		var intHeight = objDimensions.height-20;
		var intWidth = (Prototype.Browser.IE) ? objDimensions.width-10 : objDimensions.width;

		var objPosition = objTarget.cumulativeOffset();
		var intX = (Prototype.Browser.IE) ? objPosition.left+5 : objPosition.left;
		var intY = objPosition.top;

		// Move 'mapwin' and set size to match (and display).
		$('divMap').setStyle({display:''});
		$('mapwin').setStyle({height:intHeight+'px',width:intWidth+'px',position:'absolute',top:intY+'px',left:intX+'px'});
	}

	function GetSelectedTab() {
		//Make sure the la and tab are selected to call the maps scripts properly
		$('lea').value=$$('#tabnavLA li a.active')[0].id.replace('tabLa','');
		$('tab').value=$$('#tabnav li a.active')[0].id.replace('tab','');
	}


	/*  XLS upload v2.20 functionality */
	function XLS_Options(option) {
		switch (option) {
			case "b_tmpl": //blank spreadsheet
				go("/admin/files/area prospectus courses.xls","_blank");
				break;
			case "year_tmpl": //download courses: current provider, select academic year
				sendRequest('/admin/AjaxXLScourses.asp?type=getXLScourses','This is some test data');
				break;
			case "upload": //upload spreadsheet
				IsPopupBlocker('/admin/upload_courses.asp',640,160,1,0);
				break;
			case "year_tmpl_est": //download courses: select provider and academic year
				sendRequest('/admin/AjaxXLScourses.asp?type=getXLScourses','This is some test data');
				break;
		}
	}

	function openresource(url){
		document.location.href = url;
	}

	function go(url,target){
		if (url.indexOf('binary_get.asp')>=0 && url.indexOf('res=')>0) { //is a resource, count the hit first
			var ajaxurl='/ajaxResources.asp';
			var pars='type=counthit&resource='+getQueryVariable('res',url);

			new Ajax.Request(ajaxurl, {method: 'get',parameters:pars,onComplete:openresource(url)});
		} else { //normal redirection
			if((target == undefined) || (target == '')){
				  try {
						document.location.href = url;
				  }
				  catch (e)
				  {}
			} else {
				  try {
					window.open(url,target);
				  }
				  catch (e)
				  {}
			}
		}
	}

  var remotingDiv;
  function createRemotingDiv(id,url) {
	var rDiv = document.createElement('div');
	rDiv.id = 'remotingDiv';
	var style = 'border:0;width:0;height:0;';
	//onload='ifrmLoaded();'
	rDiv.innerHTML = "<iframe name='"+id+"'  id='"+id+"' style='"+style+"'></iframe>";
	document.body.appendChild(rDiv);
	rDiv.iframe = document.getElementById(id);
	rDiv.form = document.createElement('form');
	rDiv.form.setAttribute('id', id+'RemotingForm');
	rDiv.form.setAttribute('action', url);
	rDiv.form.setAttribute('target', id);
	rDiv.form.target = id;
	rDiv.form.setAttribute('method', 'post');
	rDiv.form.innerHTML = '<input type="hidden"  name="data" id="'+id+'Data">';
	rDiv.appendChild(rDiv.form);
	rDiv.data = document.getElementById(id+'Data');
	return rDiv;
  }

   function ifrmLoaded(){
	   alert("here");
   }

   function  sendRequest(url,payload) {
		ajaxPopup('/loading_pop.asp?width=200&height=80&msg=Loading',true);

		//I can't find how to check if the xls has been loaded to close the lightbox so the code below will do for now
		new PeriodicalExecuter(function(pe) {
		  if ($('lightbox')){
			lightbox.prototype.deactivate();
			pe.stop();
		  }
		}, 15);

		if (!remotingDiv) {
			remotingDiv = createRemotingDiv('remotingFrame','blank.html');
		}
		remotingDiv.form.action = url;
		remotingDiv.data.value = payload;
		remotingDiv.form.submit();

	}

/* TOOLTIP FUNCTIONS */

/*
Determine the page render mode.

0: Quirks mode.
1: Strict mode.
*/
var pageMode = getPageMode(); // Private field

function getPageMode() { // Private method
  if (document.compatMode) {
    switch (document.compatMode) {
      case "BackCompat":
        return 0;
      case "CSS1Compat":
        return 1;
      case "QuirksMode":
        return 0;
    }
  }
  else {
    if (ie5) {
      return 0;
    }
    if (safari) {
      return 1;
    }
  }
  return 0;
}

function getClientWidth() { // Private method
  switch (pageMode) {
    case 0:
      return document.body.clientWidth;
    case 1:
      if (safari) {
        return self.innerWidth;
      }
      else {
        if (!opera && document.documentElement && document.documentElement.clientWidth > 0) {
          return document.documentElement.clientWidth;
        }
        else {
          return document.body.clientWidth;
        }
      }
  }
}

function createToolTip(){
	//Create new tooltip element
	tt = document.createElement('div');
	tt.setAttribute('id', 'gtooltip');
	tt.className = 'ttbox';
	tt.style.position = "absolute";
	tt.style.display = 'none';
	tt.style.width = '150px';
	document.body.appendChild(tt);
}

function updateToolTip(a){ 
	tt = document.getElementById("gtooltip");
	if (tt.style.display="none"){

		var toolTipContent = "";
		var toolTipHeader = "";
		if (arguments.length>1){
			groupInfo = "<ul class='ttList' id='ttList'>";
			for (var x = 3; x < arguments.length; x++) {
				if(x==arguments.length-1){
					//Hide underline from last group in list
					toolTipContent += "<li style='border-bottom:none;' id='lastgroup'>"+ arguments[x] +"</li>";
				} else {
					toolTipContent += "<li>"+ arguments[x] +"</li>";
				}
			};
			toolTipContent += "</ul>"
		} else {
			toolTipContent = "(No groups found)";
		}

		if(arguments[2]!="") toolTipHeader = "<div class='tthead'>"+arguments[2]+"</div>"

		//Add height marker to test tooltip height
		groupInfo += "<span id='heightmarker'></span>"
		
		//Update tooltip content
		tt.style.width=arguments[1]+'px'; //change the width of the tooltip
		tt.innerHTML = toolTipHeader +"<div class='ttbody'>"+ toolTipContent +"</div>";
		
		e = arguments[0]

		//Update tooltip position
		scrollXY = getScrollXY();
		var posx = e.clientX + scrollXY[0] +15;
		var posy = e.clientY + scrollXY[1] -30;
		//Check tooltip will fit on screen - if not adjust position accordingly
		tt_width = parseInt(tt.style.width)
		tt_height = arguments.length * 20 //estimate tt height (based on group count)
		if((posx + tt_width) > getClientWidth()) posx = posx - tt_width -40;
		if((posx + tt_height) > getClientWidth()) posy = posy - tt_height +20;
		tt.style.left = posx + "px";
		tt.style.top = posy + "px";

		//Clear effects queue
		var queue = Effect.Queues.get('ttscope');
		queue.each(function(e) { e.cancel() });
		//Fade tooltip in
		Effect.Appear(tt,{duration:0.1, queue: {position:'end', scope: 'ttscope', limit:1} });
		//var ttt;
		//ttt=setTimeout("hideGroupsToolTip()", 8000);
		
	}
}		
function hideToolTip(){
	tt = document.getElementById("gtooltip");

	//Clear effects queue
	var queue = Effect.Queues.get('ttscope');
	queue.each(function(e) { e.cancel() });

	//Fade tooltip out
	Effect.Fade('gtooltip',{duration:0.5, queue: {position:'end', scope: 'ttscope', limit:1} }); 
	//tt.innerHTML = "";
}	

function IEassignAnchorEvents(){
	if (Prototype.Browser.IE6) {
		$$('a[href="javascript:void(0)"]').each(function(i) {
			$(i).href="#";
		});
		$$('a[href="javascript:void(0);"]').each(function(i) {
			$(i).href="#";
		});
	}
}
