window.onload=systemSetup;
//window.onscroll = recordScroll;

//global vars
var oldtabid='';
var oldtab='';
var piccounter=2;
var opac=0;
var opacstep=true;
var doc_id;
var speed=2;
var pause=3;
var pics=new Array;
var descs=new Array;
var pauseSlideShow=false;
var delay=20;
var datecount=0;
var daysToStart=0;
var miniscrollspeed=0;
var miniSearchResultsheight=100;
var currency;
var curmultiplyer=1;

function systemSetup(){
	curmultiplyer=1;
	if(cookieGet('currency')){
		currency=cookieGet('currency');
		if(document.getElementById('currencyselector')){
			document.getElementById('currencyselector').value=currency;
			if(currency=="&euro;"){document.getElementById('currencyselector').value="€";}
		}
	}
	//if(cookieGet('scrollpos')){
		//window.scroll(0,cookieGet('scrollpos'));
	//}	
	
	//multi currency
	if(currency){
		if(document.getElementById('currency_base')){
			var basecurrency=document.getElementById('currency_base').value;
			
			if((basecurrency=="£" && currency=="&euro;") || (basecurrency=="&euro" && currency=="£") || (basecurrency=="$" && currency=="&euro;")){
				curmultiplyer=	document.getElementById('currency_rate1').value;
			}
			if((basecurrency=="£" && currency=="$") || (basecurrency=="&euro;" && currency=="$") || (basecurrency=="$" && currency=="£")){
				curmultiplyer=	document.getElementById('currency_rate2').value;
			}
			
			if((basecurrency=="$" && currency=="&euro;") || (basecurrency=="&euro" && currency=="£") || (basecurrency=="$" && currency=="&euro;")){
				curmultiplyer=	document.getElementById('currency_rate1').value;
			}
			if((basecurrency=="$" && currency=="£") || (basecurrency=="&euro;" && currency=="$") || (basecurrency=="$" && currency=="£")){
				curmultiplyer=	document.getElementById('currency_rate2').value;
			}
			
			if((basecurrency=="€" && currency=="£") || (basecurrency=="&euro" && currency=="£") || (basecurrency=="$" && currency=="&euro;")){
				curmultiplyer=	document.getElementById('currency_rate1').value;
			}
			if((basecurrency=="€" && currency=="$") || (basecurrency=="&euro;" && currency=="$") || (basecurrency=="$" && currency=="£")){
				curmultiplyer=	document.getElementById('currency_rate2').value;
			}
		}
		//alert(basecurrency+"*"+curmultiplyer+"="+currency);
	}
	
	thumbnails_on_page();
	activateCalendars();
	miniScrollerSetup();
	availCalSetup();
	if(document.getElementById('quote_arrival_date')){
		if(document.getElementById('quote_arrival_date').value && document.getElementById('quote_departure_date').value){
			updateQuote();	
		}
	}	
}

function recordScroll(){
	if(window.pageYOffset){	
		var scrollpos=window.pageYOffset;//firefox	
	}	
	else if(document.documentElement.scrollTop ){
		var scrollpos=document.documentElement.scrollTop;//ie	
	}
	if(scrollpos){
		cookieAdd("scrollpos",scrollpos);	
	}
}

function updatecurrency(elem){
	if(elem.value=="€"){currency="&euro;";}else{currency=elem.value;}
	cookieAdd("currency",currency);
	var temp=window.location;
	window.location=temp;
}

function autoFormValidate(formid){
	var thisform=document.getElementById(formid);
	if(thisform){
		var errorcount=0;
		var formelems=thisform.elements;
		for(i=0;i<formelems.length;i++){
			if(formelems[i].type.toLowerCase()!="hidden" && formelems[i].className=="formmandatory" && formelems[i].value=="" ){
				formelems[i].style.border="1px solid red";	
				errorcount++;		
			}	
		}	
		if(errorcount==1){
			alert ("The form field marked in red must be completed before submitting this form.");
			return;		
		}
		if(errorcount>1){
			alert ("The form fields marked in red must be completed before submitting this form.");
			return;		
		}
		
	}
	if(document.getElementById('tcconfirm') && !document.getElementById('tcconfirm').checked){
		alert('You must agree to our terms and conditions before proceeding');
	}else{
		document.getElementById(formid).submit();
	}	
}

function vtOpen(address){
	window.open("/processing/vtframe.php?a="+escape(address),"vt","screenX=0,screenY=0,height=490,width=650,resizable=yes")
	
}

function setCookieAndGo(villaId,path){
	cookieAdd("villaId",villaId);
	window.location=path;
}

function endVilla(villaid){
	if(confirm('Are you sure you want to end this subscription?')){
		window.location.href="/processing/?func=endVilla&villaid="+villaid;
	}	
}

function activateCalendars(){

	//alert(document.getElementById('avail_arrival_date_button').offsetTop);		
	
	
	var Targets=document.getElementsByTagName("div");
	var calpos=new Array;	
	for(i=0;i<Targets.length;i++){
		if(Targets[i].className.substr(0,11)=="qs_calendar"){
			var buttonName=Targets[i].id;
			var divElements=Targets[i].childNodes;
			for(j=0;j<divElements.length;j++){
				if(divElements[j].tagName=="INPUT"){
					var inputField=divElements[j].id;
					calpos=vp_findPos(Targets[i]);
					Calendar.setup({inputField:inputField,ifFormat:"%d/%m/%Y",button:buttonName,align:"BC",singleClick:true,disableFunc:calStopHistory,position:calpos});	
				}
			}
		}
	}
}

function vp_findPos(obj) {
	var r=new Array;
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	r[0]=curleft;
	r[1]=curtop;
	
	return r;
}



function availCalSetup(){
	if(document.getElementById('availabilitytabpanel') && document.getElementById('availId')){
		var savingData="func=getDates_Ajax&"+buildPOST('availCalInfo');	
		var myConn = new XHConn();
		if (myConn){
			myConn.connect("/processing/", "POST", savingData, writeCalDate);
		}	
	}	
}

function calchange(year){
	cookieAdd("calyear",year);
	var temp=window.location;
	window.location=temp;
}

function writeCalDate(Data){
	
	//alert(Data.responseText);
	var bookingData=eval(Data.responseText);
	var calDates=document.getElementsByTagName('TD');
	var calString="";
	if(bookingData){
		for(i=0;i<calDates.length;i++){
			if(calDates[i].id && calDates[i].id.substr(0,1)=="c"){
				for(j=0;j<bookingData.length;j++){
					var tdDate=calDates[i].id.substr(1);
					if(parseInt(tdDate)>parseInt(bookingData[j].from_date) && parseInt(tdDate)<parseInt(bookingData[j].to_date)){
						if(bookingData[j].type=="1"){
							calDates[i].className=calDates[i].className+"ucf";
						}else{
							calDates[i].className="cf";
						}
					}
					if(tdDate==bookingData[j].from_date){
						if(bookingData[j].type=="1"){
							calDates[i].className=calDates[i].className+"ucf1";
						}else{
							calDates[i].className=calDates[i].className+"cf1";
						}
					}
					if(tdDate==bookingData[j].to_date){
						if(bookingData[j].type=="1"){
							calDates[i].className=calDates[i].className+"ucf2";
						}else{
							calDates[i].className=calDates[i].className+"cf2";
						}
					}
				} 	
			}
			if(calDates[i].className){
				calString+=calDates[i].id+"="+calDates[i].className+"\n";
			}
		}
	}
	
}

function showTab(tabselected,tabid,colcount){
	var Targets=document.getElementsByTagName("div");
	//var tabselected=window.event.srcElement;
	tabselected.style.lineHeight='21px';	
	tabselected.parentNode.style.marginTop='1px';
	tabselected.parentNode.style.borderBottom='0px';
	if(!oldtabid){
		var allTabs=tabselected.parentNode.parentNode.childNodes;
		for(i=0;i<allTabs.length;i++){
			if(allTabs[i].className=="active"){
				oldtabid=allTabs[i];
				oldtabid.className="";	
			}
		}
	}
	tabselected.parentNode.className="active";
	if(oldtabid && oldtabid!=tabselected.parentNode){
		oldtabid.className="";
	}

	oldtabid=tabselected.parentNode;
	for(i=0;i<Targets.length;i++){
		if(Targets[i].className.substring(0,13)=="villatabpanel"){
			Targets[i].style.display="none";	
		}
	}
	document.getElementById(tabid).style.display="block";
	cookieAdd("tabselected",colcount);
	cookieAdd("tabpanelselected",tabid);
	if(tabid=='quotetabpanel' && document.getElementById('bookingid') && document.getElementById('quote_departure_date')){
		document.getElementById('bookingid').value='';updateQuote();
	}else if(tabid=='quotetabpanel'){
		if(document.getElementById('request_booking_button')){
			document.getElementById('request_booking_button').value=" request information ";
			writeToId('request_booking_title','Request More Information');
		}			
	}
}
//= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
function editvilla(path){
	cookieAdd('editvilla','1');//set cookie
	window.location=path;
}

function saving(){
	document.getElementById('savingData').style.display="block";
	
}

function stopEditvilla(path){
	if(confirm('Are you sure you want to close without saving?')){
		cookieAdd('editvilla','');//set cookie
		window.location=path;
	}
}

function deleteBooking(qs){
	if(confirm('Are you sure you want to delete this booking, this it not reversible')){
		var path='/form/calendar.php?func=deleteEvent&'+qs;
		window.location=path;
	}	
}

function confirmBooking(qs){
	if(confirm('Are you sure you want to change the status of this booking?')){
		var path='/form/calendar.php?func=changeType'+qs;
		window.location=path;
	}
}

function saveEditvilla(path){
	cookieAdd('editvilla','');//set cookie
	var savingData=buildPOST('villaupdate');
	//add description to col1 for dlists
	if(document.getElementById('villa_descriptionui')){
		var col1=document.getElementById('villa_descriptionui').value;
		for (thumbcount=0; document.getElementById('filenamecheckbox'+thumbcount); thumbcount++){
			if(document.getElementById('filenamecheckbox'+thumbcount).checked){		
				var mainimage =document.getElementById('filenamecheckbox'+thumbcount).src;
				var pageid= document.getElementById('villaedit_pageid').value;
				col1+='<img src="/images/villas/'+pageid+'/file'+thumbcount+'.jpg" />';
				thumbcount=100;
			}
		}
	savingData+="&col1="+escape(col1);
	}	
	//alert (col1);
	//document.write (savingData);
	xmlhttp.open("POST", "/form/form2page.php",true);
	xmlhttp.onreadystatechange=function() {
		if (xmlhttp.readyState==4) { 
			//alert(xmlhttp.responseText);
			document.getElementById('villaupdate').submit(); //submit again to upload images	
		} 
	} 	
	xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	saving(); 
	xmlhttp.send(savingData+"&ajax=1");
}
//= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
function quoteAddDate(currency){
	var quoteDateTable=document.getElementById('quoteDateTable');
	//var newHtml=quoteDateTable.innerHTML+'\n<TR>\n<TD>'+currency+' <INPUT name="" value=""></TD>\n<TD><INPUT name="" value=""></TD></TR>';	
	var newrow = document.createElement('tr');
	var col1=newrow.appendChild(document.createElement("TD"));
	var col2=newrow.appendChild(document.createElement("TD"));
	col1.innerHTML=currency+' <INPUT name="quotenewprice'+datecount+'" value="">';
	col2.innerHTML='<div class="qs_calendar quote_cal" id="quotenewdate'+datecount+'_button"> <INPUT id="quotenewdate'+datecount+'" name="quotenewdate'+datecount+'" value=""></div>';
	quoteDateTable.appendChild(newrow);
	datecount++;
	activateCalendars();
}

function getQuoteQs(){
	if(document.getElementById('quote_arrival_date')){
		var fromDay=escape(document.getElementById('quote_arrival_date').value);
		var toDay=escape(document.getElementById('quote_departure_date').value);
		if(fromDay && toDay){
			cookieAdd('quote_arrival_date',document.getElementById('quote_arrival_date').value);
			cookieAdd('quote_departure_date',document.getElementById('quote_departure_date').value);
			var pageid=document.getElementById('quote_pageid').value;
			var qsData="fromDay="+fromDay+"&toDay="+toDay+"&pageid="+pageid;
			return qsData;
		}else{
			return false;	
		}
	}else{
		return false;	
	}
}

function requestBooking(){
	var data=new Object;//data object to contain booking info
	data.days=getInnerHTML('numberOfDays');
	data.totalRent=getInnerHTML('totalRent');
	if(getCheckboxValue('include_pool_heat')){data.pool_heat=getInnerHTML('pool_heat');}
	if(getCheckboxValue('include_midterm_clean')){data.midterm_clean=getInnerHTML('midterm_clean');}
	if(getCheckboxValue('include_cot_hire')){data.cot_hire=getInnerHTML('cot_hire');}
	if(getCheckboxValue('include_foodpack')){data.foodpack=getInnerHTML('foodpack');}
	data.lmd=getInnerHTML('lmd');
	data.lsd=getInnerHTML('lsd');
	data.total=getInnerHTML('total');
	data.deposit=getInnerHTML('deposit');
	data.bookingNotes=escape(getInnerHTML('bookingNotes'));
	var savingData="func=addBooking&"+getQuoteQs()+"&"+buildPOST('ownerAddBooking')+"&data="+data.toJSONString();	
	xmlhttp.open("POST", "/processing/",true);
	xmlhttp.onreadystatechange=function() {
		if (xmlhttp.readyState==4) { 
			//alert(xmlhttp.responseText);
			var Data = eval('(' + xmlhttp.responseText+')');
			if(Data.error){ alert(Data.error);}
			if(Data.info){
				document.getElementById('bookingArea').style.display="none";
				if(Data.info=='The booking information has been changed as requested'){
					window.location.reload(true);					
				}				
				writeToId('messageArea','<p>'+Data.info+'</p>');
			}
		} 
	} 	
	xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xmlhttp.send(savingData);
}

function requestOwnerBooking(){
	var data=new Object;//data object to contain booking info
	data.bookingNotes=escape(document.getElementById('bookingNotes2').value.replace(/"/g, "&quot;").replace(/'/g, "&apos;"));
	var fromDay=escape(document.getElementById('avail_arrival_date').value);
	var toDay=escape(document.getElementById('avail_departure_date').value);
	var type=document.getElementById('villaOwnerBookingType').checked;
	var savingData="func=addBooking&"+buildPOST('villaownerAddBooking')+"&type="+type+"&fromDay="+fromDay+"&toDay="+toDay+"&data="+data.toJSONString();		
	xmlhttp.open("POST", "/processing/",true);
	xmlhttp.onreadystatechange=function() {
		if (xmlhttp.readyState==4) { 
			//alert(xmlhttp.responseText);
			var Data = eval('(' + xmlhttp.responseText+')');
			if(Data.error){
				//if error show message and dont reset form
				document.getElementById('bookingArea').style.display="none";
				writeToId('messageArea2','<p>'+Data.error+'</p>');
				document.getElementById('villaownerFormButton').value='add booking';
			}
			if(Data.info){ 
				//else show message for 2 secs and redirect back to self
				writeToId('messageArea2','<p>'+Data.info+'</p>');
				document.getElementById('villaownerFormButton').value='add booking';
				temp=window.location;
				setTimeout("window.location=temp;", (2000));// timer
			
			}
		} 
	} 	
	xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xmlhttp.send(savingData);
}

function requestInformation(){
	var data=new Object;//data object to contain booking info
	var fromDay=escape(document.getElementById('quote_arrival_date').value);
	var toDay=escape(document.getElementById('quote_departure_date').value);
	var savingData="func=requestVillaInfo&"+buildPOST('requestVillaInfo')+"&fromDay="+fromDay+"&toDay="+toDay;	
	//alert (savingData);
	xmlhttp.open("POST", "/processing/",true);
	xmlhttp.onreadystatechange=function() {
		if (xmlhttp.readyState==4) { 
			//alert(xmlhttp.responseText); 
			var Data = eval('(' + xmlhttp.responseText+')');
			if(Data.error){ alert(Data.error);}
			if(Data.info){
				//alert (Data.info);
				document.getElementById('requestVillaInfo').reset();
				writeToId('requestVillaInfoMessage','<p>'+Data.info+'</p>');
			}
		} 
	} 	
	xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xmlhttp.send(savingData);
}


function updateQuote(){

	var savingData="func=getQuote&"+getQuoteQs();
	var mindays=document.getElementById('quote_min_days').value;
	var maxdays=document.getElementById('quote_max_days').value;
	var ssc_days=document.getElementById('quote_ssc_days').value;
	var ssc_price=document.getElementById('quote_ssc_price').value;
	
	if(getQuoteQs()){
		xmlhttp.open("POST", "/processing/",true);
		xmlhttp.onreadystatechange=function() {
			if (xmlhttp.readyState==4) { 
				//alert(xmlhttp.responseText );
				var Data = eval('(' + xmlhttp.responseText + ')');	
				writeToId('numberOfDays',Data['numberOfDays']);
				writeToId('totalRent',(Data['totalRent']*curmultiplyer).toFixed(2));
				daysToStart=Data['daysToStart'];
				if(Data['availability']=="0" || Data['availability']=="1" ){
					if(Data['availability']=="0"){
						if(!Data.unPricedDays){
							writeToId('isAvailable','Currently Available');
							if(ssc_days>Data['numberOfDays']){
								writeToId('isAvailable','Currently Available but includes a short stay cleaning surcharge because your stay is under '+ssc_days+' days');
							}
							
							document.getElementById('bookButton').style.display="block";
							document.getElementById('bookingArea').style.display="block";
							writeToId('messgeArea','');
						}else{
							writeToId('isAvailable','Rates are not available for your selected dates. Please contact the villa owner for up-to-date pricing.');
							writeToId('totalRent','0');
						}
					}else{
						writeToId('isAvailable','Another request has been made for those dates but not yet confirmed');
					}

				}else{
					writeToId('isAvailable','Not available - please see Availability Calendar for more dates');
					document.getElementById('bookButton').style.display="none";
				}

				if(Data['numberOfDays']>maxdays && maxdays!=0){
					writeToId('isAvailable','The maximum rental period for this villa is '+maxdays+' days. Please review your dates or contact the owner for further assistance.');
					document.getElementById('bookButton').style.display="none";
					document.getElementById('bookingArea').style.display="none";
				}
				if(Data['numberOfDays']<mindays){
					writeToId('isAvailable','The minimum rental period for this villa is '+mindays+' days. Please review your dates or contact the owner for further assistance.');
					document.getElementById('bookButton').style.display="none";
					document.getElementById('bookingArea').style.display="none";
				}				
				
				calculateQuote();
			} 
		} 	
		xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		xmlhttp.send(savingData);	
	}
}

function writeToId(id,value){
	if(document.getElementById(id)){
		document.getElementById(id).innerHTML=value;		
	}
}

function calculateQuote(){
	
	var days=document.getElementById('numberOfDays').innerHTML;
	var totalRent=(document.getElementById('totalRent').innerHTML/curmultiplyer);
	
	var cot_hire=days*document.getElementById('quote_cot_hire').value;
	var pool_heat=days*document.getElementById('quote_pool_heat').value
	var midterm_clean=document.getElementById('quote_midterm_clean').value;
	var foodpack=document.getElementById('quote_foodpack').value;

	var lsd_length=document.getElementById('quote_lsd_length').value;
	var lsd_percent=document.getElementById('quote_lsd_percent').value;
	var lmd_length=document.getElementById('quote_lmd_length').value;
	var lmd_percent=document.getElementById('quote_lmd_percent').value;	

	var fullpayment_req=document.getElementById('fullpayment_req').value;
	var deposit_percent=document.getElementById('deposit_percent').value;
	var deposit_amount=document.getElementById('deposit_amount').value;
	if(document.getElementById('refundable_security_bond').value){
		var refundable_security_bond=parseFloat(document.getElementById('refundable_security_bond').value);
	}
	
	
	var ssc_days=document.getElementById('quote_ssc_days').value;
	var ssc_price=document.getElementById('quote_ssc_price').value;
	
	var quoteTotal=addItem('foodpack',foodpack,totalRent);
	quoteTotal=addItem('cot_hire',cot_hire,quoteTotal);
	quoteTotal=addItem('pool_heat',pool_heat,quoteTotal);
	quoteTotal=addItem('midterm_clean',midterm_clean,quoteTotal);
	
	//convert to two decimal places
	if(cot_hire && !isNaN(cot_hire)){ cot_hire=parseFloat(parseFloat(cot_hire).toFixed(2));	}
	if(pool_heat && !isNaN(pool_heat)){ pool_heat=parseFloat(parseFloat(pool_heat).toFixed(2));		}
	
	if(midterm_clean && !isNaN(midterm_clean)){ midterm_clean=parseFloat(parseFloat(midterm_clean).toFixed(2));	}
	if(foodpack && !isNaN(foodpack)){ foodpack=parseFloat(parseFloat(foodpack).toFixed(2));	}

	writeToId('cot_hire',(cot_hire*curmultiplyer).toFixed(2));
	writeToId('pool_heat',(pool_heat*curmultiplyer).toFixed(2));
	writeToId('midterm_clean',(midterm_clean*curmultiplyer).toFixed(2));
	writeToId('foodpack',(foodpack*curmultiplyer).toFixed(2));
	if(refundable_security_bond){
		writeToId('refundable_sec_bond',(refundable_security_bond*curmultiplyer).toFixed(2));
		quoteTotal+=parseFloat(refundable_security_bond);
	}
	
	if(parseInt(days)>=parseInt(lsd_length)){
		var lsd=(totalRent*(lsd_percent/100)).toFixed(2);
		quoteTotal=parseFloat(quoteTotal)-parseFloat(lsd);
		lsd=(lsd*curmultiplyer).toFixed(2);	
	}else{
		var lsd='N/A';
	}	
		
	writeToId('lsd',lsd);
	if(parseInt(daysToStart)<=parseInt(lmd_length)){
		var lmd=(totalRent*(lmd_percent/100)).toFixed(2);
		quoteTotal=parseFloat(quoteTotal)-parseFloat(lmd);	
		lmd=(lmd*curmultiplyer).toFixed(2);
	}else{
		var lmd='N/A';
	}
	
	
	if(parseInt(days)<parseInt(ssc_days)){
		quoteTotal=parseFloat(quoteTotal)+parseFloat(ssc_price);
	}
	
	writeToId('lmd',lmd);
	quoteTotal=parseFloat(quoteTotal)+parseFloat(document.getElementById('cleaning_fee').value);
	
	if(quoteTotal){a=quoteTotal; quoteTotal=parseFloat(a.toFixed(2));}		
	writeToId('total',(quoteTotal*curmultiplyer).toFixed(2));
	writeToId('total2',(quoteTotal*curmultiplyer).toFixed(2));
	//work out payment sched
	if(parseInt(daysToStart)<=parseInt(fullpayment_req)){
		document.getElementById('paymentopt1').style.display="none";
		document.getElementById('paymentopt2').style.display="block";
 		var deposit=quoteTotal;
	}else{
		document.getElementById('paymentopt1').style.display="block";
		document.getElementById('paymentopt2').style.display="none";
		if(deposit_percent=="1"){
			 var deposit=(totalRent*(deposit_amount/100)).toFixed(2);
		}else{
			var deposit=Math.ceil((days/7))*deposit_amount;
		}
	}
	document.getElementById('deposit').innerHTML=(deposit*curmultiplyer).toFixed(2);	
}

function addItem(item,amount,total){
	if(document.getElementById('include_'+item)){
		if(document.getElementById('include_'+item).checked){
			total=parseFloat(total)+parseFloat(amount);	
		}
	}
	return total;	
}
function getInnerHTML(item){
	if(document.getElementById(item)){
		return document.getElementById(item).innerHTML;
	}
}

function getCheckboxValue(item){
	if(document.getElementById(item)){
		return document.getElementById(item).checked;
	}	
}

function setCheckboxValue(item,state){
	if(document.getElementById(item)){
		document.getElementById(item).checked=state;
	}	
}

function loadSavedQuote(id){
	var savingData="func=loadSavedQuote&id="+id;	
	xmlhttp.open("POST", "/processing/",true);
	xmlhttp.onreadystatechange=function() {
		if (xmlhttp.readyState==4) { 
			var Data = eval('(' + xmlhttp.responseText+')');
			document.getElementById('quotetabpanel').style.display="block";
			document.getElementById('bookButton').style.display="block";
			document.getElementById('availabilitytabpanel').style.display="none";
			document.getElementById('quote_arrival_date').value=Data.from_date;
			document.getElementById('quote_departure_date').value=Data.to_date;
			document.getElementById('bookingNotes').value=Data.data.bookingNotes;
			document.getElementById('bookingid').value=Data.id;
		
			if(Data.data.pool_heat){writeToId('pool_heat',Data.data.pool_heat); setCheckboxValue('include_pool_heat',true);	}else{ setCheckboxValue('include_pool_heat',false);}
			if(Data.data.midterm_clean){writeToId('midterm_clean',Data.data.midterm_clean); setCheckboxValue('include_midterm_clean',true);	}else{ setCheckboxValue('include_midterm_clean',false);}
			if(Data.data.cot_hire){writeToId('cot_hire',Data.data.cot_hire); setCheckboxValue('include_cot_hire',true);	}else{ setCheckboxValue('include_cot_hire',false);}
			if(Data.data.foodpack){writeToId('foodpack',Data.data.foodpack); setCheckboxValue('include_foodpack',true);	}else{ setCheckboxValue('include_foodpack',false);}
	
			writeToId('lmd',Data.data.lsd);
			writeToId('numberOfDays',Data.data.days);
			writeToId('lsd',Data.data.lmd);
			writeToId('totalRent',Data.data.totalRent);
			writeToId('total',Data.data.total);
			writeToId('isAvailable','EDITING BOOKING');
			document.getElementById('infoForm').style.display="none";	
			document.getElementById('request_booking_button').value="Update Booking";
			writeToId('request_booking_title','Update Booking');
		} 
	} 	
	xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xmlhttp.send(savingData);	
}

function ownerloadSavedQuote(id){
	var savingData="func=loadSavedQuote&id="+id;	
	xmlhttp.open("POST", "/processing/",true);
	xmlhttp.onreadystatechange=function() {
		if (xmlhttp.readyState==4) { 
			var Data = eval('(' + xmlhttp.responseText+')');
			document.getElementById('avail_arrival_date').value=Data.from_date;
			document.getElementById('avail_departure_date').value=Data.to_date;
			document.getElementById('bookingNotes2').value=Data.data.bookingNotes;
			document.getElementById('bookingid2').value=Data.id;
			document.getElementById('villaownerFormButton').value='update booking';
			if(Data.type==2){
				document.getElementById('villaOwnerBookingType').checked=true;
			}else{
				document.getElementById('villaOwnerBookingType').checked=false;
			}
		} 
	} 	
	xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xmlhttp.send(savingData);	
}



function addNewUser(){
	var formid='addNewUser';
	var thisform=document.getElementById(formid);
	if(thisform){
		var errorcount=0;
		var formelems=thisform.elements;
		for(i=0;i<formelems.length;i++){
			if(formelems[i].type.toLowerCase()!="hidden" && formelems[i].className=="formmandatory" && formelems[i].value=="" ){
				formelems[i].style.border="1px solid red";	
				errorcount++;		
			}	
		}	
		if(errorcount==1){
			alert ("The form field marked in red must be completed before submitting this form.");
			return;		
		}
		if(errorcount>1){
			alert ("The form fields marked in red must be completed before submitting this form.");
			return;		
		}
		
	}
	
	
	var data=buildPOST('addNewUser');
	var savingData="func=addNewUser_Ajax&"+data;	
	xmlhttp.open("POST", "/processing/",true);
	xmlhttp.onreadystatechange=function() {
		if (xmlhttp.readyState==4) { 
			var Data = eval('(' + xmlhttp.responseText+')');
			if(Data.error){ alert(Data.error);}
			if(Data.info){
				document.getElementById('bookingArea').style.display="none";
				writeToId('messageArea','<p>'+Data.info+'</p>');
			}
		} 
	} 	
	xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xmlhttp.send(savingData);
}

//= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
function cookieAdd(myName,myValue){
	document.cookie=myName+"="+escape(myValue)+" ; path=/";
}

function cookieGet(cookieName){
   	var thisCookie=document.cookie.split("; ")
   	if(thisCookie.length>0){
	   	for (cook=0; cook<thisCookie.length; cook++){
        	if (cookieName==thisCookie[cook].split("=")[0]){
        		return unescape(thisCookie[cook].split("=")[1]);
   	 		}
 		}
 	}
}
//= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 
function swapVillaImage(filename,desc){
	document.getElementById('mainVillaImage0').src=filename;	
	document.getElementById('mainVillaImage0').alt=desc;	
	document.getElementById('mainVillaImage0').title=desc;	
}

function thumbUpdate(inputobj){
	var thisdiv=inputobj.parentNode.parentNode;
	var tdivChildren=thisdiv.childNodes;
	for (elem=0; elem<tdivChildren.length; elem++){
		if(tdivChildren[elem].tagName){
			if(tdivChildren[elem].tagName=="A"){	
				tdivChildren[elem].href="file://"+inputobj.value;
				if(tdivChildren[elem].childNodes[0].tagName=="IMG"){	
					tdivChildren[elem].childNodes[0].src=inputobj.value;
					tdivChildren[elem].childNodes[0].style.borderColor="red";
				}
			}
		}
	}
}
//= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
//Slideshow stuff

	function thumbnails_on_page(){
		// locate thumbnails div
		if(document.getElementById('thumbnails') && document.getElementById('mainVillaImage1') && document.getElementById('mainVillaImage0') ){
			// pass childnodes to thumbs
			var thumbs=document.getElementById('thumbnails').childNodes; 
			//this loop extracts each child from thumb
			var picnum=0;
			for(var j=0; j<thumbs.length; j++){
				if(thumbs[j].tagName=="A"){
					if(thumbs[j].childNodes[0].tagName=="IMG"){
						pics[picnum]=thumbs[j].childNodes[0].src.replace('/thumbs/','/');
						descs[picnum]=thumbs[j].childNodes[0].title;
					}
					picnum++;
				}
			}
			if(piccounter >= pics.length){
				piccounter=0;//reset counter						
			}
			rotate();
		}	
	}	
	
	function change_opacity(doc_id,opac){
    	var object = document.getElementById(doc_id).style;
		if(object.opacity){ object.opacity = (opac/100); }
    	object.MozOpacity = (opac/100); 
    	object.KhtmlOpacity = (opac/100); 
    	object.filter = "alpha(opacity=" + opac + ")"; 
	}	
	function makeSlideMessage(descs,piccounter){
		piccounter--;
		if(piccounter<0){
			piccounter=	descs.length-1;
		}
		msg=descs[piccounter];
		if(msg){ 
			msg="<p>"+msg.replace(/\n/g,"<br />")+"</p>"; 
		}else{
			msg=""; 
		}
		msg="<p>"+msg.replace(/\n/g,"<br />")+"</p>";
		document.getElementById('villaThumbDescription').innerHTML=msg;	
	}
	
	// rotate function
	
	function rotate(){
		if(!pauseSlideShow){
			delay=20;
			// increment opacity
			if(opacstep){
				opac=opac+speed;
			}else{
				opac=opac-speed;
			}
			// change opacity of of forground image
			change_opacity('mainVillaImage1',opac);
			//if opac==100 then change background image+2 also reverse step
			if(opac==100){
				delay=pause*1000;
				opacstep=false;
				// assign new image to id slide2
				document.getElementById('mainVillaImage0').style.background="white url("+pics[piccounter]+") no-repeat center center";
				
				var msg=piccounter+" "+descs[piccounter-1];
				makeSlideMessage(descs,piccounter);
				
				piccounter++;
				if(piccounter == pics.length){
					//reset counter
					piccounter=0;
				}

			}
			//if opac==0 then change foreground image+2 also reverse step
			if(opac==0){
				delay=pause*1000;
				opacstep=true;
				// assign new image to id slide 1
				document.getElementById('mainVillaImage1').style.background="white url("+pics[piccounter]+") no-repeat center center";
				makeSlideMessage(descs,piccounter);
					
				piccounter++;
				if(piccounter == pics.length){
					//reset counter
					piccounter=0;
				}

			}
		}
		setTimeout("rotate()", (delay));// timer
	}
	// swap image from thumbnails
	function swapImage(swap,obj) {
		var msg=obj.title? obj.title : ""
		msg="<p>"+msg.replace(/\n/g,"<br />")+"</p>";
		// swap image src
		opac=100;
		if(document.getElementById('mainVillaImage1')){
			document.getElementById('mainVillaImage1').style.background="white url("+swap+") no-repeat center center";
			change_opacity('mainVillaImage1','100');
		}
		// pause slideShow
		pauseSlideShow=true;
		//output text here 
		document.getElementById('villaThumbDescription').innerHTML=msg;
	} 
	function unPauseSlideShow(){
		opacstep=false;
		speed=2;
		pause=2;
		delay=20;
		pauseSlideShow=false;	
	}
//textarea maxlength script
function ismaxlength(obj){
	var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : ""
	if (obj.getAttribute && obj.value.length>mlength)
	obj.value=obj.value.substring(0,mlength)
}

//= = = = = =  = =  = == 
//Search Stuff

function quickSearch(){
	var arrival_date=document.getElementById('arrival_date');	
	var departure_date=document.getElementById('departure_date');
	var numbedrooms=document.getElementById('numbedrooms');
	var reference=document.getElementById('reference');
	if(!arrival_date.value){alert('You Must Specify an Arrival Date'); return; }
	if(!departure_date.value){alert('You Must Specify a Departure Date'); return; }
	checkSearchDates(arrival_date,'');
	
	cookieAdd('arrival_date',arrival_date.value);//set cookie
	cookieAdd('departure_date',departure_date.value);//set cookie
	cookieAdd('villaid',reference.value);//set cookie
	cookieAdd('numbedrooms',numbedrooms.value);//set cookie
	
	document.getElementById('quickSearch').submit();
}

function quickSearchReset(){
	document.getElementById('arrival_date').value="Any";
	document.getElementById('departure_date').value="Any";
	document.getElementById('numbedrooms').value="";
	document.getElementById('destination').value="";
	document.getElementById('reference').value="";
	
	cookieAdd('arrival_date','');
	cookieAdd('departure_date','');
	cookieAdd('villaid','');
	cookieAdd('numbedrooms','');
	cookieAdd('search','');
	if(	document.getElementById('miniSearchResults')){
		var temp=window.location;	
		window.location=temp;
	}	
}

function checkSearchDates(obj,prefix){
	//arrival_date, departure_date 
	if(obj.id==(prefix+"arrival_date")){
		//check dept date is greater
		var departure_date=document.getElementById(prefix+'departure_date');
		if (departure_date.value){
			//turndates into comparable values
			var deparray=departure_date.value.split('/');
			var ariarray=obj.value.split('/');
			if(deparray.length==3){
				var dep_compare=deparray[2]+deparray[1]+deparray[0];
				var ari_compare=ariarray[2]+ariarray[1]+ariarray[0];
				if(dep_compare>ari_compare){
					return;
				}
			}
		}
	departure_date.value=obj.value;//if not set set to arrival_date	
	}
	if(obj.id==prefix+"departure_date"){
		//check arival date is less
		var arrival_date=document.getElementById(prefix+'arrival_date');
		if (arrival_date.value){
			//turndates into comparable values
			var ariarray=arrival_date.value.split('/');
			var deparray=obj.value.split('/');
			if(ariarray.length==3){
				var dep_compare=deparray[2]+deparray[1]+deparray[0];
				var ari_compare=ariarray[2]+ariarray[1]+ariarray[0];
				if(dep_compare>ari_compare){
					return;	
				}
			}
		}
	arrival_date.value=obj.value;//if not set set to departure_date	
	}
}

function calStopHistory(thisDay){
	var today=new Date();
	var difference = thisDay - today;
	var days = Math.round(difference/(1000*60*60*24));
	if(days<0){
		return true;
	}
}

//= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
function miniScrollerSetup(){
	if(document.getElementById){
		if(document.getElementById("miniSearchResultsInner")){
			var innerpanel=document.getElementById("miniSearchResultsInner");
			var panel=document.getElementById("miniSearchResults");
			//innerpanel.style.top="-1px";
			innerpanel.style.height="auto";
			if (document.all) {
				miniSearchResultsheight = innerpanel.offsetHeight+10;
			}else{
				miniSearchResultsheight = innerpanel.offsetHeight;
			}
		}
	}
}

function miniScroll(){
	var innerpanel=document.getElementById("miniSearchResultsInner");
	if(parseInt(innerpanel.style.top) > (0-(miniSearchResultsheight-268+parseInt(miniscrollspeed))) && parseInt(innerpanel.style.top) < 1-parseInt(miniscrollspeed)){
		innerpanel.style.top = parseInt(innerpanel.style.top)+parseInt(miniscrollspeed) + "px";
		setTimeout("miniScroll()",30);
	}else{
		document.speed=0;
	}
}

function setMiniScrollSpeed(speed){
	miniscrollspeed=speed;
	if(speed==0){
		var innerpanel=document.getElementById("miniSearchResultsInner");
		cookieAdd("miniSearchResultsTop",innerpanel.style.top);
	}else{
		miniScroll();
	}
}
	
//= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
/*
function checkForm(theFormName){
	theForm = document.getElementById(theFormName);
	for (e=0;e<theForm.elements.length;e++) {
		if (theForm.elements[e].class=='compulsory') {
			if(theForm.elements[e].value.length<1){
				theForm.elements[e].value='';			
			}
		}
	}
}
*/	
//General Functions
//= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 
function buildPOST(theFormName) {
	theForm = document.getElementById(theFormName);
	var qs = ''
	for (e=0;e<theForm.elements.length;e++) {
		if (theForm.elements[e].name!='') {
			var name = theForm.elements[e].name;
			qs+=(qs=='')?'':'&';
			if(theForm.elements[e].type=="checkbox"){
				qs+= name+'='+escape(theForm.elements[e].checked);
			}else if(theForm.elements[e].type=="radio"){
				if(theForm.elements[e].checked){
					qs+= name+'='+escape(theForm.elements[e].value);
				}
			}else{
				//euro fix
				eurofixvalue=theForm.elements[e].value.replace("€","&euro;");
				qs+= name+'='+escape(eurofixvalue);
			}	
		}
	}
	return qs
}

//AJAX SHIT...
//= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
var xmlhttp=false;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
// AJAX STYLE COMMUNICATION - WORTH A TRY EH?
// JScript gives us Conditional compilation, we can cope with old IE versions.
// and security blocked creation of the objects.
 try {  xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {  try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (E) {  xmlhttp = false; } }
@end @*/
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
	try { xmlhttp = new XMLHttpRequest();} catch (e) { xmlhttp=false;}
}
if (!xmlhttp && window.createRequest) {
	try { xmlhttp = window.createRequest();	} catch (e) { xmlhttp=false; }
}

(function () {
    var m = {
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        },
        s = {
            array: function (x) {
                var a = ['['], b, f, i, l = x.length, v;
                for (i = 0; i < l; i += 1) {
                    v = x[i];
                    f = s[typeof v];
                    if (f) {
                        v = f(v);
                        if (typeof v == 'string') {
                            if (b) {
                                a[a.length] = ',';
                            }
                            a[a.length] = v;
                            b = true;
                        }
                    }
                }
                a[a.length] = ']';
                return a.join('');
            },
            'boolean': function (x) {
                return String(x);
            },
            'null': function (x) {
                return "null";
            },
            number: function (x) {
                return isFinite(x) ? String(x) : 'null';
            },
            object: function (x) {
                if (x) {
                    if (x instanceof Array) {
                        return s.array(x);
                    }
                    var a = ['{'], b, f, i, v;
                    for (i in x) {
                        v = x[i];
                        f = s[typeof v];
                        if (f) {
                            v = f(v);
                            if (typeof v == 'string') {
                                if (b) {
                                    a[a.length] = ',';
                                }
                                a.push(s.string(i), ':', v);
                                b = true;
                            }
                        }
                    }
                    a[a.length] = '}';
                    return a.join('');
                }
                return 'null';
            },
            string: function (x) {
                if (/["\\\x00-\x1f]/.test(x)) {
                    x = x.replace(/([\x00-\x1f\\"])/g, function(a, b) {
                        var c = m[b];
                        if (c) {
                            return c;
                        }
                        c = b.charCodeAt();
                        return '\\u00' +
                            Math.floor(c / 16).toString(16) +
                            (c % 16).toString(16);
                    });
                }
                return '"' + x + '"';
            }
        };

    Object.prototype.toJSONString = function () {
        return s.object(this);
    };

    Array.prototype.toJSONString = function () {
        return s.array(this);
    };
})();

String.prototype.parseJSON = function () {
    try {
        return (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(this)) &&
            eval('(' + this + ')');
    } catch (e) {
        return false;
    }
};//= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =