/********************************************
 *** Villa Louise website and booking system ***
 ** Written by Ian Collier, Autumn/Winter 2008 **
 ******** This work copyright Ian Collier ********
 *** Please do not copy or modified this work ***
 ** without seeking the express permission of **
 ** the author beforehand.  Thank you *********
 ********************************************/
// array of colours
 var colours=new Array("#B77A3D","#DED6D6","#FFCC00");

function setday(daycount) {
	// sets the background colour according to the selected option
	// set the option according to the selected index
	switch (document.frmadmin['selrateday'+daycount].selectedIndex) {
		case  0 :
			document.frmadmin['selrateday'+daycount].style.backgroundColor=colours[0];
			break;
		case 1 :
			document.frmadmin['selrateday'+daycount].style.backgroundColor=colours[1];
			break;
		case 2 :
			document.frmadmin['selrateday'+daycount].style.backgroundColor=colours[2];
			break;
//		default :
//			document.frmadmin['selrateday'+daycount].style.backgroundColor=colours[0];
		}
	// set focus on selection
//	document.frmadmin['selrateday'+daycount].setfocus();	
}

function setmonth(selmonth,endday,startday) {
	// set the entire month uplift colour
	// get the current selected index
	var selindex=document.frmadmin[selmonth].selectedIndex;
	// set the colour of the selmonth select list
	switch (selindex) {
		case  0 :
			document.frmadmin[selmonth].style.backgroundColor=colours[0];
			break;
		case 1 :
			document.frmadmin[selmonth].style.backgroundColor=colours[1];
			break;
		case 2 :
			document.frmadmin[selmonth].style.backgroundColor=colours[2];
			break;
//		default :
//			document.frmadmin[selmonth].style.backgroundColor=colours[0];
	}
	// set the selected index and background color for all the set day selects within the date range
	for(var x=startday;x<=endday;x++) {
		// set the selected index in the appropriate selrateday
		document.frmadmin['selrateday'+x].options[selindex].selected=true;
		// set the background colour
		switch (selindex) {
			case  0 :
				document.frmadmin['selrateday'+x].style.backgroundColor=colours[0];
				break;
			case 1 :
				document.frmadmin['selrateday'+x].style.backgroundColor=colours[1];
				break;
			case 2 :
				document.frmadmin['selrateday'+x].style.backgroundColor=colours[2];
				break;
//			default :
//				document.frmadmin['selrateday'+x].style.backgroundColor=colours[0];
		}
	}
	// set focus on selection
//	document.frmadmin[selmonth].setfocus();	
}

function addCommas(nStr,prefix) {
	// adds comma separators to nStr which will be a numeric value
    var prefix=prefix || '';
    nStr+= '';
    x=nStr.split('.');
    x1=x[0];
    x2=x.length>1 ? '.'+x[1] : '';
    var rgx=/(\d+)(\d{3})/;
    while (rgx.test(x1))
        x1=x1.replace(rgx, '$1'+','+'$2');
    return (prefix+x1+x2);
}

function lowestvalue(arrObj) {
	// Iterate through the elements, 
	// and return the lowest
  var lowest = arrObj[0];
  for (var i=1;i<arrObj.length;i++) {
    lowest=(arrObj[i]<lowest ? arrObj[i] : lowest);
  }
  return (lowest);  
}

function removeArrayElement(arrObj,item) {
	// removes item from arrObj, as well as blank items
	var tmparrObj=new Array();
	for(n=0;n<arrObj.length;n++) {
		if((arrObj[n]!=item) && (arrObj[n]!='')) {
			tmparrObj.push(arrObj[n]);
		}
	}
	return (tmparrObj);
}

function addDays(myDate,days) {
	// adds days to myDate and returns the new date
   var ret=new Date(myDate.getTime()+days*24*60*60*1000);
   // format date
   var day=ret.getDate();
   var month=ret.getMonth()+1;
   var year=ret.getFullYear();
   // if the month is only one digit preceed value with a 0
   if(month.length==1) { 
   	if(day.length==1) {
    		// set return value
			return "0"+day.toString()+"/0"+month.toString()+"/"+year.toString();
		}
		else {
			return day.toString()+"/0"+month.toString()+"/"+year.toString();
		} 
	}
   else {
   	if(day.length==1) {
    		 // set return value
			return "0"+day.toString()+"/"+month.toString()+"/"+year.toString();
    	}
    	else {
    		// set return value
			return day.toString()+"/"+month.toString()+"/"+year.toString();
		} 
	}
}

function ontheflycalcbookings(dayindex,price,advance) {
	// calculate and show booking price, deposit and when deposit is due
	// get the current booking counter
	var bookingcounter=parseInt(document.getElementById('txtbookingcount').innerHTML);
	// get the depositpercent
	var depositpercent=parseInt(document.getElementById('txtshowdeposit').innerHTML);
	// get price so far
	var totalprice=parseInt(document.forms[0]['txtbookingcosthidden'].value);
	// get the number of days balance is due by
	var daysbalancedueby=parseInt(document.forms[0]['txtdaysuntilbalanceduehidden'].value);
	// get the days ticked so far, convert to an array, taking out any leading/trailing spaces
	var tickeddaystext=document.forms[0]['tickeddays'].value;
	// check if the booking counter is >= 0
	if(bookingcounter<0) {
		bookingcounter=0;
	}
	// create an array from the tickedaystext value
	// if the string is empty then create a new array
	if (tickeddaystext=='') {
		var tickeddays=new Array();
	}
	else {
		var tickeddays=tickeddaystext.split(',');
	}	
	// detrimine if the box is ticked
	if(document.forms[0]['bookdate'+dayindex].checked) {
		// push the current index onto ticked days
		tickeddays.push(dayindex.toString());
		// remove any blank elements
		tickeddays=removeArrayElement(tickeddays,'');
		// increment booking counter
		bookingcounter++;
		// recalculate the price
		totalprice+=parseInt(price);
	}
	else {
		// rebuild the tickeddays array removing the current dayindex
		tickeddays=removeArrayElement(tickeddays,dayindex);
		// decrement booking counter
		bookingcounter--;
		totalprice-=parseInt(price);
	}
	// ensure booking counter is 0 if necessary, removes any negative values
	// if booking counter is 0 reset all values
	if(bookingcounter<0) {
		bookingcounter=0;
		totalprice=0;
		depositpercent=0;
		daysbalancedueby=0;
		balance=0;
		balanceduedate="N/A";
		strtickeddays="";
	}
	else {
		// update the tickedboxes field
		var strtickeddays='';	
		for(p=0;p<tickeddays.length;p++) {
			// check for blank array elements
			if(tickeddays[p]!='') {
				strtickeddays=strtickeddays+tickeddays[p].toString()+',';
			}
		}
		// get the lowest item in tickeddays - this is the earliest day
		var firstday=parseInt(lowestvalue(tickeddays));
		// check to make sure that firstday is dayindex if necessary
		// only if we are ticking
		if(document.forms[0]['bookdate'+dayindex].checked) { 
			if(dayindex<firstday) {
				firstday=dayindex;
			}
		}
		// deposit changes to 100% if the first day of the booking before the number of days the total balance is to be paid
		// determine at which day index the balance is due
		// we know that the first day of the month is going to be 1, therefore the first day of the index range is going to be 1-1, i.e. 0
		// therefore we know that today's index value is going to be todays' date (day) less 1
		var currentday=new Date().getDate()-1;
		var daydue=(firstday-daysbalancedueby);
		// check to see if the day index is before the day due
		// if so, then set the deposit to 100 and balance to zero
		// otherwise calculate the deposit and balance
		if(currentday>=daydue) {
			// set deposit percent to 100
			var depositpercent=100;
			// set depost to the total price
			var deposit=totalprice;
			// set balance to 0
			var balance=0;
			// set date balance due - the minum number of days to book in advance setting
			var d=new Date();
	//		var balanceduedate=addDays(d,0);
			var balanceduedate=addDays(d,advance);
		}
		else {
			// reset the deposit
			var depositpercent=parseInt(document.forms[0]['txtprevdeposit'].value);
			// calculate the deposit
			var deposit=totalprice*(depositpercent/100);
			// calculate balance
			var balance=(totalprice-deposit);
			// set datebalance due - the number of days prior to first day of stay
			if(bookingcounter==0) {
				var balanceduedate='N/A';
			}
			else {
				// get the date of the first ticked day  in the first month - that is the current month
				var d=new Date();
				var daystoadd=(daydue-currentday);
				var balanceduedate=addDays(d,parseInt(daystoadd)).toString();
			}	
		}	
	}
	// set deposit if necessary
	if(deposit==null) {
		deposit=0;
	}
	// convert balance and deposits to integers
	deposit=Math.round(deposit);
	balance=Math.round(balance);
	// update page with new values
	// hidden tickeddays textbox
	document.forms[0]['tickeddays'].value=strtickeddays;
	// booking counter
	document.getElementById('txtbookingcount').innerHTML=bookingcounter;	
	// totlal price
	document.forms[0]['txtbookingcosthidden'].value=totalprice;
	document.getElementById('txtbookingcost').innerHTML=addCommas(totalprice,'');
	// deposit percent
	document.getElementById('txtshowdeposit').innerHTML=depositpercent;
	document.forms[0]['txtcurrentdeposit'].value=depositpercent;
	// deposit value
	document.getElementById('txtdepositvalue').innerHTML=addCommas(deposit,'');
	// days balance due by
	document.forms[0]['txtdaysuntilbalanceduehidden'].value=daysbalancedueby;
	// balance
	document.getElementById('txtbalance').innerHTML=addCommas(balance);
	// date balance due
	document.getElementById('txtbalanceduedate').innerHTML=balanceduedate;
}

function resetvalues(depositpercent) {
	// resets default values on the booking form
	document.forms[0]['tickeddays'].value="";
	// booking counter
	document.getElementById('txtbookingcount').innerHTML=0;	
	// totlal price
	document.forms[0]['txtbookingcosthidden'].value=0;
	document.getElementById('txtbookingcost').innerHTML=0;
	// deposit percent
	document.getElementById('txtshowdeposit').innerHTML=depositpercent;
	document.forms[0]['txtcurrentdeposit'].value=depositpercent;
	// deposit value
	document.getElementById('txtdepositvalue').innerHTML=0;
	// days balance due by
	document.forms[0]['txtdaysuntilbalanceduehidden'].value=0;
	// balance
	document.getElementById('txtbalance').innerHTML=0;
	// date balance due
	document.getElementById('txtbalanceduedate').innerHTML="N/A";
}

function setlanguage(n) {
	// to set the language we need delete the villalouiselanguage cookie
	// and then recreate the same cookie with the new value
	// use current date & time
	var cookie_date = new Date ( );
	// set cookie time to be 1 second ago
	cookie_date.setTime (cookie_date.getTime()-1);
	// delete cookie
	document.cookie="villalouiselanguage=';expires="+cookie_date.toGMTString();
	// set cookie to expire 1 year from now	(excluding any leapyears
	cookie_date.setTime (cookie_date.getTime()+(1*60*60*24*365));
	// recreate cookie
	document.cookie="villalouiselanguage="+n+";expires="+cookie_date.toGMTString();
	// reload the page
	self.location=self.location;
}

function pausecomp(millis) {
	// pause function	
	var date=new Date();
	var curDate=null;
	do {
		curDate=new Date();
	}
	while((curDate-date)<millis);
}

function doindexpresentation() {
	// show the presentation on the index page
	document.getElementById("indexmovie").innerHTML='<table class="animations"><tr><td><object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0" width=320px height=240px><param name=movie value="videos/indexmovie12.swf"><param name=quality value=high><param name=bgcolor value="#F9C666"><embed src="videos/indexmovie12.swf" title="Villa Louise" quality=high bgcolor="#F9C666"  width=320px height=240px type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash"></embed></object></td></tr></table>';
}

function settime() {
	// sets the current time
	var curtime=new Date();
	var timeoffset=(curtime.getTimezoneOffset()/60);
	var diff=4;
	// Dubai is 4 hours ahead of GMT (UTC)
	var curhour=curtime.getHours()+timeoffset+diff;
	var curmin=curtime.getMinutes();
	var cursec=curtime.getSeconds();
	var time="";
	// adjust hour for dubai time
	if(curhour>=24) {
		curhour=curhour-24;
	}
//	if(curhour==0) {
//		curhour=12;
//	}
	time=(curhour>12 ? curhour-12 : curhour)+":"+
         (curmin<10 ? "0":"")+curmin+":"+
         (cursec<10 ? "0":"")+cursec+" "+
         (curhour>12 ? "PM":"AM");
	// display the me in the appropriate place
	document.getElementById('clocktext').innerHTML=time;
}

function changecarddetails() {
	// changes the values in the card form according to the values in the array
	// get the currently selected value
	var currentindex=document.forms[0]['selusepreviouscard'].selectedIndex;
	// get the string to replace existing form values
	var replacementstring=document.forms[0]['txtuserscards'+currentindex].value;
	// split the string to create an array, the separator is |, should be 0->8 elements
	var replacements=replacementstring.split("|");
	// replace the various form element values
	// card type selection
	for(var w=0;w<document.forms[0]['selcardtype'].length;w++) {
		if(document.forms[0]['selcardtype'].options[w].text==replacements[0]) {
			document.forms[0]['selcardtype'].selectedIndex=w;
		}
	}
	// card number
	// replace the first 12 digits of the card number with *s
	if(document.forms[0]['selusepreviouscard'].selectedIndex==0) {
		var cardnumber='';
	}
	else {
		var cardnumber='************'+replacements[1].substr(12,4);
	}
	document.forms[0]['txtcardnumber'].value=cardnumber;
	document.forms[0]['txthiddencardnumber'].value=replacements[1];
	// expiry date
	if(replacements[2]==0) {
		document.forms[0]['selexpirydate'].selectedIndex=0;
	}
	else {
		for(var x=0;x<document.forms[0]['selexpirydate'].length;x++) {
			if(document.forms[0]['selexpirydate'].options[x].text==replacements[2]+"/"+replacements[3]) {
				document.forms[0]['selexpirydate'].selectedIndex=x;
			}
		}
	}
	// security code (deliberately made blank)
	// document.forms[0]['txtsecuritycode'].value=replacements[4];
	document.forms[0]['txtsecuritycode'].value="";
	// issue date
	if(replacements[5]==0) {
		document.forms[0]['selissuedate'].selectedIndex=0;
	}
	else {
		for(var y=0;y<document.forms[0]['selissuedate'].length;y++) {
			if(document.forms[0]['selissuedate'].options[y].text==replacements[5]+"/"+replacements[6]) {
				document.forms[0]['selissuedate'].selectedIndex=y;
			}
		}
	}
	// issue number
	if(replacements[7]==0) {
		document.forms[0]['selissueno'].selectedIndex=0;
	}
	else {
		for(var z=0;z<document.forms[0]['selissueno'].length;z++) {
			if(document.forms[0]['selissueno'].options[z].text==replacements[7]) {
				document.forms[0]['selissueno'].selectedIndex=z;
			}
		}
	}
	// name on card
	document.forms[0]['txtnameoncard'].value=replacements[8];
}

function changeimage(button, last, pictures, desc, path) {
	// changes slideshow image, depends on the value of button
	// if button is 0 then go to the first image
	// if button is 1 then go to the previous image, if the current image is zero go to the last image
	// if button is 2 then go to the next image, is the curren image is last then to to the first image
	// if button is 3 then go to the last image
	// get the current value of tracker
	var tracker=document.getElementById("txttracker").value
	// check the value of tracker and create a new tracker reference as necessary
	switch (button) {
		case 0:
			// first button
			var newtracker=0;
			break;
		case 1:
			// previous button
			// set new tracker to last if tracker is 0, otherwise set newtracker to be tracker less 1
			if(tracker==0) {
				var newtracker=last;
			}
			else {
				var newtracker=tracker-1;
			}
			break;
		case 2:
			// next button
			// set new tracker to 0 if tracker is last, otherwise set newtracker to be tracker plus 1
			if(tracker==last) {
				var newtracker=0;
			}
			else {
				var newtracker=parseInt(tracker)+1;
			}
			break;
		case 3:
			// last button
			var newtracker=last;
			break;
	}
	// update txttracker
	document.getElementById("txttracker").value=newtracker;
	// build htmlstring to replace image
	var htmlstring="<img class='presentationimage' src='"+path+pictures[newtracker]+"' title='"+desc+"' valign='top' align='middle' />";
	// update the picture using newtracker as the array index
	document.getElementById("pictureplaceholder").innerHTML=htmlstring;
}

function setboquet(c) {
	// sets the appropriate checkbox should the user changed a value
	if(c==0) {
		// set large boquet option
		document.cardform.chklargebouquet.checked=true;
	}
	else {
		// set small boquet option
		document.cardform.chksmallbouquet.checked=true;
	}
}

function dobooking() {
	// function to capture the booked days correctly and process the booking
	// variable for booked days string
	var bookeddays=document.forms[0]['tickeddays'].value;
	// reinsert the value into the textbox
	document.forms[0]['txtdaysbooked'].value=bookeddays;
}

function allavailable() {
	// if chkall is checked then tick all boxes
	// if chkall in unchecked then simply refres the page	
	if(document.forms[0]['chkall'].checked) {
		// get the number of days to process
		var daycount=document.getElementById("txtdaycount").value;
		// process all textboxes
		for(var x=1;x<=daycount;x++) {
			// check if chekbox exists
			if(typeof(document.forms[0]["bookdate"+x])!="undefined") {
				document.forms[0]["bookdate"+x].checked=true;
				// track bookings
				ontheflycalcbookings(x,0,0);
			}	
		}
	}
	else {
		// reload page
		self.location=self.location;
	}
}
