//	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=='')||($('searchCriteria').value=='Search site...'))){return false;}
	return true;
}

function clearSearch(){
	$("searchCriteria").value = "";
}

function valueSearch(){
	if ($("searchCriteria").value==''){$("searchCriteria").value = "";}
}

function clearBlogPodSearch(){
	var theForm = document.blogsearchpod;
	theForm.search.value = ''; 
}

function clearWikiSearch(){
	var theForm = document.wikisearchpod;
	theForm.search.value = ''; 
}

//	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 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 DeliveryDetailsCheckForm()
{
	var theForm = document.personalise;
	
if ( !RequiredInput(theForm.UserTitle,'Please enter a title') ) { return false; }
if ( !RequiredInput(theForm.FirstName,'Please enter a last name') ) { return false; }
if ( !RequiredInput(theForm.Surname,'Please enter a last name') ) { return false; }
if ( !RequiredInput(theForm.Address1,'Please enter a first address line') ) { return false; }
if ( !RequiredInput(theForm.Town,'Please enter a town') ) { return false; }
if ( !RequiredInput(theForm.PostCode,'Please enter a postcode') ) { return false; }
if ( !RequiredInput(theForm.Country,'Please select a delivery contry') ) { return false; }

return true;
}

function TandC(){
	var a=document.getElementById('Terms');
	var b=document.getElementById('check');						
	
	if(a.value==0){
		a.value=1;
		b.className='payment_tc_checked';
	}else if(a.value==1){
		a.value=0;
		b.className='payment_tc_unchecked';
	}
}

function PayementDetailsCheckForm(ValidFrom, ValidTo, m, CurYear, CurMonth, CC)
{
	var theForm = document.payment;
	var outp = 0;
	var t = ""; 
	var n = 0;
	var ValidLen = String(ValidFrom).length;
	var ValidYear = String(ValidFrom).substring(ValidLen, ValidLen - m);
	var ValidMonth = String(ValidFrom).substring(0,m);
	var iLen = String(ValidTo).length;
	var ExpYear = String(ValidTo).substring(iLen, iLen - m);
	var ExpMonth = String(ValidTo).substring(0,m);
	
	if ( !RequiredInput(theForm.CCType,'Please select a credit card') ) { return false; }
	if ( !RequiredInput(theForm.CardNumber,'Please enter your credit card number') ) { return false; }
	
	  var CC = CC.replace(/ /g, "");
	
	  for (i = 0; i <= CC.length; i++) { 
		outp = CC.charAt (i) + outp 
	  }   
	  
	  for (i = 0; i < outp.length; i++) {
		c = parseInt(outp.charAt(i), 10);
		if (i % 2 != 0)
		  c *= 2;
		t = t + c;
	  }
	
	  for (i = 0; i < t.length; i++) {
		c = parseInt(t.charAt(i), 10);
		n = n + c;
	  }
	
	if (n != 0 && n % 10 == 0){
			
	}else{
		alert('Your credit card number has been entered incorrectly. Please double check this.');  
		return false;
	}	
	if ( !RequiredInput(theForm.CardHolder,'Please enter the name on your credit card') ) { return false; }
	if (ValidFrom != ''){
	
		if (ValidLen != 5){
			alert("Your expiry date must be entered MM/YY");
			theForm.ValidFrom.focus();
			return false
		}
			
		if ( (ValidMonth > CurMonth) && (ValidYear >= CurYear)){
			alert('The valid from date you have entered is in the future.  Please check and enter this again.');
			theForm.ValidFrom.focus();
			return false
		}
		
		if ( ValidYear > CurYear ){
			alert('The valid from date you have entered is in the future.  Please check and enter this again.');
			theForm.ValidFrom.focus();
			return false
		}
	}		
	if ( !RequiredInput(theForm.ValidTo,'Please enter the expiry date on the credit card') ) { return false; }
	if (iLen != 5){
		alert("Your expiry date must be entered MM/YY");
		return false
	}
	if ( (ExpMonth < CurMonth) && (ExpYear <= CurYear)){
		alert('The expiry date you have entered is in the past.  Please check and enter this again.');
		return false
	}
	if ( ExpYear < CurYear ){
		alert('The expiry date you have entered is in the past.  Please check and enter this again.');
		return false
	}	
	if ( !RequiredInput(theForm.SecurityNumber,'Please enter the security number as shown on your credit card') ) { return false; }
	if ( (theForm.CCType.value == 1) && (String(theForm.SecurityNumber.value).length != 4) ){
		alert('American express requires a 4 digit security code. Please make sure you have entered the correct number');
		return false
	}	
	if ( (theForm.CCType.value != 1) && (String(theForm.SecurityNumber.value).length != 3) ){
		alert('This credit card requires a 3 digit security code. Please make sure you have entered the correct number');
		return false
	}	
	
	if ( !RequiredInput(theForm.BillingFirstname,'Please enter a first name') ) { return false; }
	if ( !RequiredInput(theForm.BillingLastname,'Please enter a surname') ) { return false; }
	if ( !RequiredInput(theForm.Address1,'Please enter a first address line') ) { return false; }
	if ( !RequiredInput(theForm.Town,'Please enter a town') ) { return false; }
	if ( !RequiredInput(theForm.PostCode,'Please enter a postcode') ) { return false; }
	if ( !RequiredInput(theForm.Country,'Please select a country') ) { return false; }
	
	if ( theForm.check.checked==false){
		alert('Please check that you have read our terms and conditions and tick the box to proceed');
		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});
		  }			  
	});		
}


function DateAdd(ItemType, DateToWorkOn, ValueToBeAdded){
	switch (ItemType)
	{
		//date portion        
		case 'd': //add days
			DateToWorkOn.setDate(DateToWorkOn.getDate() + ValueToBeAdded)
			break;
		case 'm': //add months
			DateToWorkOn.setMonth(DateToWorkOn.getMonth() + ValueToBeAdded)
			break;
		case 'y': //add years
			DateToWorkOn.setYear(DateToWorkOn.getFullYear() + ValueToBeAdded)
			break;
		//time portion        
		case 'h': //add days
			DateToWorkOn.setHours(DateToWorkOn.getHours() + ValueToBeAdded)
			break;
		case 'n': //add minutes
			DateToWorkOn.setMinutes(DateToWorkOn.getMinutes() + ValueToBeAdded)
			break;
		case 's': //add seconds
			DateToWorkOn.setSeconds(DateToWorkOn.getSeconds() + ValueToBeAdded)
			break;
	}
	return DateToWorkOn;
}


setColumnValues = function(column,string,clear,day){		
	var theArray2 = string.split(']');
	
	var theArray1 = theArray2[1].split('@');
	var theArray;
	// two arrays of first is of rooms
	// 2nd is room class
	
	var CombinationRoomID;
	var RoomType;
	var sAdd;
	
	for (var j=0;j<theArray1.length;j++){
		var theRoomTypes = theArray1[j].split('~');
		
		theArray = theRoomTypes[0].split('|');
		theRoomTypes = theRoomTypes[1].split('|');
		CombinationRoomID = theRoomTypes[0];
		RoomType=theRoomTypes[1];
		
		if (clear!=1 && theArray2[0]!='1'){updateHeading(j+1,column,'',theArray2[0]);}
								
		for (var i=0;i<theArray.length;i++){
			if (clear==1){
				
				sAdd='';
				if (seldate){sAdd = '-grey';}
				
				if ($('col'+column+'_'+(j+1)+'_'+(i+1))){$('col'+column+'_'+(j+1)+'_'+(i+1)).innerHTML = '<img src="/Booking/assets/images/booking/ajax-loader'+sAdd+'.gif" />';}
				
			}else{
				if (rtrim(theArray[i])!='-1'){
					
					if (day==undefined){
						
						if ($('col'+column+'_'+(j+1)+'_'+(i+1))){
							$('col'+column+'_'+(j+1)+'_'+(i+1)).innerHTML = '<div><input type="radio" onclick="addToBasket('+(j+1)+','+(i+1)+',\''+theArray2[0]+'\','+rtrim(theArray[i])+','+CombinationRoomID+','+RoomType+');hilite(\'col' + column + '\');" id="'+(j+1)+'_'+(i+1)+'_'+(column)+'" name="room' + (j+1) + '" value="'+(i+1)+'|'+theArray2[0]+'|'+rtrim(theArray[i])+'|'+CombinationRoomID+'|'+RoomType+'"/><label for="'+(j+1)+'_'+(i+1)+'_'+(column)+'"> &pound; '+ rtrim(theArray[i]) +'</label></div>';
						}
					}else{
						if ($('col'+column+'_'+(j+1)+'_'+(i+1))){
							$('col'+column+'_'+(j+1)+'_'+(i+1)).innerHTML = '<div><input type="radio" onclick="addToBasket(\''+theArray2[0]+'\','+rtrim(theArray[i])+');" id="'+(j+1)+'_'+(i+1)+'_'+(column)+'" name="room1" value="DAY|'+theArray2[0]+'|'+rtrim(theArray[i])+'|'+'"/><label for="'+(j+1)+'_'+(i+1)+'_'+(column)+'"> &pound; '+ rtrim(theArray[i]) +'</label></div>';
						}
						
					
					}

				}else{
					if ($('col'+column+'_'+(j+1)+'_'+(i+1))){
						if (RoomType!=-2){
							$('col'+column+'_'+(j+1)+'_'+(i+1)).innerHTML = 'Not Available';
						}else{
							$('col'+column+'_'+(j+1)+'_'+(i+1)).innerHTML = 'Unable to Check';
						}
					}
				}
			}
		}
	}
}


function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

updateHeading=function(room,column,date,string){
				
	if (string==''){
		var theday = date.getDate();
		var themonth = date.getMonth()+1;
		if (theday<10){theday='0'+theday;}
		if (themonth<10){themonth='0'+themonth;}
	
		$('header_'+column+'_'+room).innerHTML = day_names[date.getDay()]+' '+theday+'/'+themonth+'/'+date.getFullYear();
	}
	else{
		$('header_'+column+'_'+room).innerHTML = string;
	}
}


function imposeMaxLength(Object, MaxLen,e)
{
  var key = window.event ? e.keyCode : e.which;
  if (key==8){return true;}
  
  return (Object.value.length < MaxLen);
}

function checkLength(Object,MaxLen){
	document.getElementById('charsRemaining').innerHTML = MaxLen- Object.value.length;
}


var day_names = new Array ( );
day_names[day_names.length] = "Sun";
day_names[day_names.length] = "Mon";
day_names[day_names.length] = "Tue";
day_names[day_names.length] = "Wed";
day_names[day_names.length] = "Thu";
day_names[day_names.length] = "Fri";
day_names[day_names.length] = "Sat";

setRooms = function(){
		if ($('optGuests').value==1){
			$('optRooms').value=1;
		}
		if ($('optGuests').value==3){
			$('optRooms').value=2;
		}
		if ($('optGuests').value==4){
			$('optRooms').value=2;
		}
	}
	
function checkRooms(){
	if ($('optRooms').options[$('optRooms').selectedIndex].value > $('optGuests').options[$('optGuests').selectedIndex].value){
        $('optRooms').value=$('optGuests').options[$('optGuests').selectedIndex].value;
    }
}

checkPricing=function(){	
			if($('optPriceFrom').options[$('optPriceFrom').selectedIndex].value >= $('optPriceTo').options[$('optPriceTo').selectedIndex].value){
				$('optPriceFrom').selectedIndex=0;
				$('optPriceTo').selectedIndex=2;
				}
		}
