//	All of the front end JS should be kept in here
// 	Created by Tom Jenkins
//	Date 12/08/2005

//  Validations...

function valSearch(){
	if (($('searchCriteria').value=='')){alert('Please enter something to search on');return false;}
	return false;
}

function clearSearch(){
	var theForm = document.searchCriteriaForm;	
	theForm.searchCriteria.value='';
}

function clearBlogPodSearch(){
	var theForm = document.blogsearchpod;
	theForm.search.value = ''; 
}

function clearWikiSearch(){
	var theForm = document.wikisearchpod;
	theForm.search.value = ''; 
}

function checkFormContact()
{
	var theForm = document.Enquiry;
		if ( !RequiredSelect(theForm.Title,'Please select your title') ) { return false; }
		if ( !RequiredInput(theForm.FirstName,'Please enter your first name') ) { return false; }
		if ( !RequiredInput(theForm.Lastname,'Please enter your last name') ) { return false; }
		if ( !RequiredInput(theForm.Email,'Please enter an email address') ) { return false; }			
		if ( !ValidateEmail(theForm.Email,'Please enter a valid email address') ) { return false; }
		if ( !RequiredInput(theForm.Comment,'Please enter your enquiry / comment') ) { return false; }
	return true;
}

checkContactSearchForm = function() {
	var theForm = document.ContactSearchForm;
	if(
		theForm.FirstName.value == '' &&
		theForm.LastName.value == '' && 
		theForm.Department[theForm.Department.selectedIndex].value == '' &&
		theForm.Location[theForm.Location.selectedIndex].value == '' &&
		theForm.JobTitle.value == '' &&
		theForm.Keyword.value == '') {
		alert('Please enter at least one search term.');
		return false;
	}
	return true;	
}

checkContactSearchPod = function(podID) {
	return true;
	/*
	var theForm = $('contactForm'+podID);
	if(
		theForm.FirstName.value == '' &&
		theForm.LastName.value == '' && 
		theForm.Department[theForm.Department.selectedIndex].value == '' &&
		theForm.Location[theForm.Location.selectedIndex].value == '' &&
		theForm.JobTitle.value == '' &&
		theForm.Keyword.value == '') {
		alert('Please enter at least one search term.');
		return false;
	}
	return true;	*/
}

function checkFormSignup(){
	var theForm = document.UserSignUp;		
		if ( !RequiredSelect(theForm.Title,'Please select your title') ) { return false; }
		if ( !RequiredInput(theForm.FirstName,'Please enter your first name') ) { return false; }
		if ( !RequiredInput(theForm.Lastname,'Please enter your last name') ) { return false; }
		if ( !RequiredInput(theForm.Email,'Please enter an email address') ) { return false; }	
		if ( !ValidateEmail(theForm.Email,'Please enter a valid email address') ) { return false; }
		if ( !RequiredInput(theForm.Password,'Please enter a password') ) { return false; }
		if ( !RequiredInput(theForm.CPassword,'Please confirm your password') ) { return false; }
		if ( theForm.CPassword.value != theForm.Password.value){
			alert('Please make sure your passwords match');
			return false;
		}
		if ( !RequiredSelect(theForm.Country,'Please select a country') ) { return false; }			
	return true;
}

function subscribeForm()
{
	var theForm = document.subscribe;	
	if ( !RequiredInput(theForm.SubcribeEmail,'Please enter an email to subscribe') ) { return false; }
	if ( !ValidateEmail(theForm.SubcribeEmail,'Please enter a valid email address') ) { return false; }
	if ( theForm.SubcribeEmail.value=='Enter Email' ){	
	alert('Please enter an email to subscribe');
	theForm.SubcribeEmail.focus();
	return false;
	}
	return true;
}

function checkLogin()
{
	var theForm = document.Login;	
	if ( !RequiredInput(theForm.username,'Please enter your username') ) { return false; }
	if ( !ValidateEmail(theForm.username,'Please check to make sure this is a valid email address') ) { return false; }
	if ( !RequiredInput(theForm.password,'Please enter your password') ) { return false; }	
	return true;
}

//	Image Rollovers...

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_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.01
  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 && d.getElementById) x=d.getElementById(n); return x;
}

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 LightBoxSwitch(lightLink){
	if(document.getElementById('lightBoxLink')){
		//Lightbox enabled
		document.getElementById('lightBoxLink').href=lightLink
   	}
}
	

//  Collapse frontend code ...

var enablepersist="off" //Enable saving state of content structure using session cookies? (on/off)
var collapseprevious="yes" //Collapse previously open content when opening present? (yes/no)

if (document.getElementById){
document.write('<style type="text/css">')
document.write('.switchcontent{display:none;}')
document.write('</style>')
}

function getElementbyClass(classname){
ccollect=new Array()
var inc=0
var alltags=document.all? document.all : document.getElementsByTagName("*")
for (i=0; i<alltags.length; i++){
if (alltags[i].className==classname)
ccollect[inc++]=alltags[i]
}
}

function contractcontent(omit){
var inc=0
while (ccollect[inc]){
if (ccollect[inc].id!=omit)
ccollect[inc].style.display="none"
inc++
}
}

function expandcontent(cid){
if (typeof ccollect!="undefined"){
if (collapseprevious=="yes")
contractcontent(cid)
document.getElementById(cid).style.display=(document.getElementById(cid).style.display!="block")? "block" : "none"
}
}

function revivecontent(){
contractcontent("omitnothing")
selectedItem=getselectedItem()
selectedComponents=selectedItem.split("|")
for (i=0; i<selectedComponents.length-1; i++)
document.getElementById(selectedComponents[i]).style.display="block"
}

function get_cookie(Name) { 
var search = Name + "="
var returnvalue = "";
if (document.cookie.length > 0) {
offset = document.cookie.indexOf(search)
if (offset != -1) { 
offset += search.length
end = document.cookie.indexOf(";", offset);
if (end == -1) end = document.cookie.length;
returnvalue=unescape(document.cookie.substring(offset, end))
}
}
return returnvalue;
}

function getselectedItem(){
if (get_cookie(window.location.pathname) != ""){
selectedItem=get_cookie(window.location.pathname)
return selectedItem
}
else
return ""
}

function saveswitchstate(){
var inc=0, selectedItem=""
while (ccollect[inc]){
if (ccollect[inc].style.display=="block")
selectedItem+=ccollect[inc].id+"|"
inc++
}

document.cookie=window.location.pathname+"="+selectedItem
}

function do_onload(){
getElementbyClass("switchcontent")
if (enablepersist=="on" && typeof ccollect!="undefined")
revivecontent()
}


if (window.addEventListener)
window.addEventListener("load", do_onload, false)
else if (window.attachEvent)
window.attachEvent("onload", do_onload)
else if (document.getElementById)
window.onload=do_onload

if (enablepersist=="on" && document.getElementById)
window.onunload=saveswitchstate


function isFilled( elm ) { 
	if (  elm != null ) {
		if ( elm.value == "" || elm.value == null ) {
			return false									;
		}
		else {
			return true									;
		}
	}
}

function TopLevel(SectionID, RealURL){
	document.AccessMenu.TopSecID.value=SectionID;
	document.AccessMenu.TopSubID.value='';
	document.AccessMenu.TopSubPageID.value='';
	document.AccessMenu.TopPageID.value='';
	document.AccessMenu.action=RealURL;
	document.AccessMenu.submit();
}
function SubLevel(SectionID, RealURL){
	document.AccessMenu.TopSubID.value=SectionID;
	document.AccessMenu.TopSubPageID.value='';
	document.AccessMenu.TopPageID.value='';
	document.AccessMenu.action=RealURL;
	document.AccessMenu.submit();
}
function SubPageLevel(PageID, RealURL){
	document.AccessMenu.TopSubPageID.value=PageID;
	document.AccessMenu.TopSubID.value='';
	document.AccessMenu.TopPageID.value='';
	document.AccessMenu.action=RealURL;
	document.AccessMenu.submit();
}
function SubHomePageLevel(PageID, SectionID, RealURL){
	document.AccessMenu.TopSubPageID.value=PageID;
	document.AccessMenu.TopSubID.value=SectionID;
	document.AccessMenu.TopPageID.value='';
	document.AccessMenu.action=RealURL;
	document.AccessMenu.submit();
}
function PageLevel(PageID, RealURL){
	document.AccessMenu.TopPageID.value=PageID;
	document.AccessMenu.action=RealURL;
	document.AccessMenu.submit();
}

function ExpandSub(SectionID){

	var DivID='SubSection'+SectionID;
	var DivElement=document.getElementById(DivID);	
	var DivElements = document.getElementsByTagName("div");
	var currentDiv;
	var mySubSectionExp;
	var Count=0;

	mySubSectionExp = /SubSection([0-9]+)/g;
	
	for (currentDiv in DivElements)
	{
		Count ++ ;
		var varDiv='SubSection'+Count;		
		if(varDiv.search(mySubSectionExp) == 0)
		{				
			var var1=document.getElementById(String(varDiv));
			
			if (var1 != null){		
				var1.style.display='none';				
			}
		}
	}

	if (DivElement.style.display=='none'){
		DivElement.style.display=''
	}else{
		DivElement.style.display='none'
	}

}

function Quantity(id,dir){								
	var i='quantity'+id;						
	var a=document.getElementById(String(i));								
	if(a.value==''){a.value=1;return false;}									
	//Increment
	if(dir==1){																	
		if(a.value>=0){									
			var b=Number(a.value)+1;
			if(b<100){a.value=Number(a.value)+1;}else{alert('You can only order a maximum of 99 items at any one time.');}								
		}else{alert('This is not a real quantity. Please enter a numeric quantity.');}									
	} 
	//decrement								
	if(dir==2){																
		if(a.value<=99){									
			var b=Number(a.value)-1;
			if(b>0){a.value=Number(a.value)-1;}							
		}else{alert('This is not a real quantity. Please enter a numeric quantity.');}									
	}					
}

function QuantityCheck(StockID,Quantity,SubID){
	if(confirm('Are you sure you wish to remove this product from your basket?')){
		window.location='/frontend/shop/basket/Basket-Add.cfm?ID='+StockID+'&quantity='+Quantity+'&SubID='+SubID;
	}
}

function ReturnLoginForm()
{
	var theForm = document.Form;
	if ( !RequiredInput(theForm.ReturnUsername,'Please enter your email address') ) { return false; }
	if ( !ValidateEmail(theForm.ReturnUsername,'Please enter a valid email address ') ) { return false; }
	if ( !RequiredInput(theForm.ReturnPassword,'Please enter your password') ) { return false; }
	return true;
}

function NewLoginForm(){
	var theForm = document.Form;
	if ( !RequiredInput(theForm.NewUsername,'Please enter your email address') ) { return false; }
	if ( !RequiredInput(theForm.NewPassword,'Please enter your password') ) { return false; }
	if ( !RequiredInput(theForm.NewConfirmPassword,'Please confirm your password') ) { return false; }
	if ( theForm.NewPassword.value != theForm.NewConfirmPassword.value){
		alert('Please make sure your passwords match');
		theForm.NewPassword.value='';
		theForm.NewConfirmPassword.value='';
		return false;
	}
	return true;
}

function UserForm(no)
{
	var theForm = document.Form;
	
	if ( !RequiredInput(theForm.UserTitle,'Please select a title') ) { return false; }
	if ( !RequiredInput(theForm.FirstName,'Please enter your firstname') ) { return false; }
	if ( !RequiredInput(theForm.Surname,'Please enter your surname') ) { return false; }
	if ( !RequiredInput(theForm.DayPhone,'Please enter your daytime telephone') ) { return false; }
	if ( !RequiredInput(theForm.EmailAddress,'Please enter your email address') ) { return false; }
	if ( !ValidateEmail(theForm.EmailAddress,'Please enter a valid email address ') ) { return false; }
	if ( !RequiredInput(theForm.Address1,'Please enter the firstline of your address ') ) { return false; }
	if ( !RequiredInput(theForm.Town,'Please enter the town where you live') ) { return false; }
	if ( !RequiredInput(theForm.PostCode,'Please enter your postcode') ) { return false; }
	if ( !RequiredInput(theForm.Country,'Please select the country in which you reside ') ) { return false; }
	if(no==1){
		if ( !RequiredInput(theForm.CreatePass,'Please enter a password') ) { return false; }
		if ( !RequiredInput(theForm.Password,'Please enter a password') ) { return false; }
		if (theForm.CreatePass.value!=theForm.Password.value){
			alert('Please make sure your 2 passwords match');
			return false;
		}
	}
	
	return true;
}


function changeIssue(DDvalue){
	if((DDvalue==2)||(DDvalue==4)){
		document.getElementById('issue').style.visibility='visible';
	}else{
		document.getElementById('issue').style.visibility='hidden';
	}
}

function AddToDash(url,a,b){
	if(a==1){
		Modalbox.show('/assets/includes/front/pods/addDash.cfm?rssurl='+url, {closeBox: true, overlayClose: true, title: 'Add a pod to a dashboard', width: 500, height: 200});
	}
	if(a==2){		
		var postBody='PodTypeID=1&addPodID=0&CurrentDashboardID='+b+'&AddFeed='+url+'&NumberItemsSideBar=5&DisplayOptionsSideBar=1';
		new Ajax.Request('/assets/resources/front/ajax.cfm?FrontendAddPod=1',{
		  method: 'post',
		  postBody: postBody ,
		  onFailure:function(failure){
				alert('There was a problem adding the pod.\n\nAdministrators have been notified. Please try again.')
			  },
		  onSuccess: function(success){					
			var HTML=success.responseText;
			var	HTML=HTML.split(":::");				
			if(b==5){var dashURL='/ICAEW'}
			else if(b==185){var dashURL='/Staff'}
			else if(b==220){var dashURL='/My_Area'}
			else {var dashURL='/Departments'}			
			Modalbox.show('/assets/includes/front/pods/addDash.cfm?added=1&dashURL='+dashURL, {closeBox: true, overlayClose: true, title: 'RSS Pod succesfully added', width: 300, height: 120});
			
		 }			  
		});			
	}
}

function checkSearch(){	
	if($('PageSearchCriteria').disabled==false){
		if($('PageSearchCriteria').value==''){alert('Please enter something to search on.');$('PageSearchCriteria').focus();return false;}
	}
	return true;
}

function advancedSearch(){		
	Effect.toggle('advancedSearch','blind');		
	if($('advancedSearch').style.display==''){
		//hidden
		$('AdvancedSearchClick').value=0
		$('PageSearchCriteria').disabled=false;
		$('PageSearchCriteria').className='';
		$('PageSearchCriteria').value=$('hiddenPageSearchCriteria').value
		$('hiddenPageSearchCriteria').value=''
		$('SearchOptionALL').value=''
		$('SearchOptionEXACT').value=''
		$('SearchOptionLEASTONE').value=''
	}else{
		//shown
		$('AdvancedSearchClick').value=1
		$('PageSearchCriteria').disabled=true;
		$('PageSearchCriteria').className='disabled';
		$('hiddenPageSearchCriteria').value=$('PageSearchCriteria').value
		$('PageSearchCriteria').value=''
	}
}	

function clearAdvanced(a){
	if(a==1){$('SearchOptionEXACT').value='';$('SearchOptionLEASTONE').value='';}
	if(a==2){$('SearchOptionALL').value='';$('SearchOptionLEASTONE').value='';}	
	if(a==3){$('SearchOptionEXACT').value='';$('SearchOptionALL').value='';}
}

function CheckCommentForm(){	
	if($('comment').value==''){alert('Please enter a comment for your selected page');$('comment').focus();return false;}
	return true
}

function submitCommentForm(PageID){	
	if($('comment').value==''){alert('Please enter a comment for your selected page');$('comment').focus();return false;}
	var postBody='Comment='+$('comment').value;
	new Ajax.Request('/assets/resources/front/ajax.cfm?SubmitCommentPage=1&PageID='+PageID,{
	  method: 'post',
	  postBody: postBody ,
	  onFailure:function(failure){
			alert('There was a problem adding the pod.\n\nAdministrators have been notified. Please try again.')
		  },
	  onSuccess: function(success){		
			Modalbox.show('/assets/includes/front/page/inc-CommentPage.cfm?PageID='+PageID+'&SubmitSuccessful=1', {closeBox: true, overlayClose: true, title: 'Comment succesfully added', width: 550, height: 200});
		  }			  
	});		
}

//VENUE STUFF
function changeImages(iName,nPic){$('SmallMap').src=nPic;}	     

function MapZoom(a,x,y,z,r){
	//Zoom In
	if(z==1){
		var lrgImgHeight=692;													//Height of the large image
		var lrgImgWidth=605;													//Width of the large image
		new Effect.MoveAndResizeTo(a,-y,-x,lrgImgWidth,lrgImgHeight,{duration:0.5,afterFinish:function(){MapZoom(a,x,y,2,r)}});		
	}
	//Morph
	if(z==2){	
		var lrgImgSrc="/assets/images/map/large-uk.jpg";						//Src of the large image				
		var topPos=$(a).style.top;
		var leftPos=$(a).style.left;
		new Insertion.After(a, '<img id="largeMap" src="'+lrgImgSrc+'" style="z-index:1; position: absolute; top: '+topPos+'; left: '+leftPos+';"/>');
		new Effect.Fade(a,{duration:0.5});	
		new Effect.Appear('ZoomOutBttn',{duration:0.5});	
		//Get the locations
		var postBody='RegionID='+r+'&xCo='+x+'&yCo='+y;
		new Ajax.Request('ajax.cfm?getVenueLocators',{
		  method: 'post',
		  postBody: postBody,
		  onFailure:function(failure){
			alert('There was a problem loading in your venue locations.\n\nAdministrators have been notified. Please try again.');
		  },
		  onSuccess:function(success){
			var HTML=success.responseText;
			var	HTML=HTML.split(":::");
			//get venue list
			$('venue_preview').innerHTML=HTML[4];
			new Insertion.After('largeMap',HTML[1]);
			for(i=1; i<=HTML[2]; i++){				
				Effect.Appear('venue'+i,{duration:0.1, queue:'end'});	
			}
			$('filters').show()
			$('MaxCapacity').options[0].selected=true;
			$('Regions').options[HTML[3]].selected=true;
		  }
		});					
	}	
}	

function zoomOut(){
	if(($('locations')&&$('largeMap'))){
		$('locations').remove();		
		new Effect.Appear('SmallMap',{duration:0.5});		
		new Effect.MoveAndResizeTo('SmallMap', 0, 0, 314, 359);	
		setTimeout(function(){$('largeMap').remove();},500)	
		$('filters').hide()
		$('venue_preview').innerHTML=''
		$('Regions').options[0].selected=true;
		new Effect.Fade('ZoomOutBttn',{duration:0.5});
	}
}    

function selectedRegion(r){
	if(r!=''){
		if(r==1){var x=120,y=0}
		if(r==2){var x=150,y=300}			
		if(r==3){var x=220,y=150}
		if(r==4){var x=270,y=270}
		if(r==5){var x=300,y=350}
		if(r==6){var x=300,y=350}
		if(r==7){var x=300,y=350}
		if(r==8){var x=200,y=350}		
		if(($('locations')&&$('largeMap'))){
			$('locations').remove();	
			//$('venue_preview').innerHTML='<img src="/Upload/image/region_'+r+'.jpg">';
			new Effect.Appear('SmallMap',{duration:0.5});		
			new Effect.MoveAndResizeTo('SmallMap', 0, 0, 314, 359,{afterFinish:function(){MapZoom('SmallMap',x,y,1,r)}});				
			setTimeout(function(){$('largeMap').remove();},500)	
		}else{			
			//$('venue_preview').innerHTML='<img src="/Upload/image/region_'+r+'.jpg">';				
			MapZoom('SmallMap',x,y,1,r);		
		}
	}
} 

function venuePreview(pageID){
	$('venue_preview').innerHTML='<div align="center"><img class="loadingGif" border="0" src="/assets/images/loadcce.gif"></div>';
	var postBody='pageID='+pageID;
	new Ajax.Request('ajax.cfm?getVenuePreview',{
	  method: 'post',
	  postBody: postBody,
	  onFailure:function(failure){
		alert('There was a problem loading in your venue locations.\n\nAdministrators have been notified. Please try again.');
	  },
	  onSuccess:function(success){
		var HTML=success.responseText;
		var	HTML=HTML.split(":::");			
		$('venue_preview').innerHTML=HTML[1];										
	  }
	});		
}   

function goToVenue(a){
	if(a!=''){window.location=a;}
}

function filterCapacity(a){
	var locations=$A(document.getElementsByClassName('marker'));
	locations.each(function(i){
		
		var re = new RegExp ('venueCap', 'gi');
		var b = i.name.replace(re, '');
		
		if((b<a)&&(a!='')){
			if(i.style.display==''){new Effect.Fade(i.id,{duration:0.4, queue:'end'});}
		}else{
			if(i.style.display=='none'){new Effect.Appear(i.id,{duration:0.4, queue:'end'});}				
		}	
		
	});		
	
}
