// Derived from a product title: Gurt Calendar JavaScript
var browser;

function yearView (year, propertyName, currency, monthsDataStr, pricesList, exRates)
// Build a yearView obj for given year and display it
// Fetch seasonal information from server
{
	if (!browser) 
		browser = new userAgent();

	yrVu = this;
	this.sDivName = 'clsDiv';
	this.sTitleName = 'clsTitle';
	this.yrSelId = 'clsYrSel';
	this.currSelId = 'clsCurrSel';
	this.year = year;
	this.property = propertyName;
	this.currency = currency;
	this.xRate = 1;
	this.weekdays = new Array ('Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'); 
	this.months = new Array ('January','February','March','April','May','June','July','August','September','October','November','December');
	this.cellColrs = new Array ('#99BCFF', '#FFF081', '#FFAA11', '#EA75D6');

	// Month data contains 12 strings each with one digit for every day in the month
	// The digits are: 0: low season, 1: mid season, 2: high season
	this.monthsData = new Array();
	this.monthsData = this.monthsData.concat (monthsDataStr);
	this.prices = new Array();
	this.prices = this.prices.concat (pricesList);
	this.xRates = new Array();
	this.xRates = this.xRates.concat (exRates);
	buildControl (this);
	buildYearView (this);
//	initGridEvents (this);	//Not needed for view only calendar
}

function buildControl (yrVu) 
// Build the year selector.
{
	var buf = new writer();
	buf.into ('<table ><tr style="height:30px"><td>', getYrSelectorHtml (yrVu), 
					'</td><td align="right">', getCurrSelHtml (yrVu),
					'</td></tr><tr><td colspan="2"><div id="Prices" name="Prices" style="line-height:20px">',
					getPrices (yrVu),
					'</div></td></tr><tr valign="bottom" style="height:40px"><td style="width:140px">&nbsp;</td>',
					'<td align="right">', getKeyHtml (),
					'</td></tr></table><br clear="all" />'); 
	document.write(buf.out());
}

function buildYearView (yrVu)
{
	document.write ('<span name="YearGrid" id="YearGrid">');
	document.write (getYearGrid (yrVu));
	document.write('</span>');
}

function getYearGrid (yrVu)
{
	var mon;
	var buf = new writer();
	buf.into ('<table><tr>');
	for (mon = 0; mon < 12; mon++)
	{
		buf.into (getMonthView (mon, yrVu));
//		if ((mon == 2) || (mon == 5) || (mon == 8))
		if ((mon == 3) || (mon == 7))
			buf.into ('</tr><tr>');
	}
	buf.into ('</tr></table>');
	return buf.out();
}

function getMonthView (mon, yrVu)
// Build the given month View & return it
{
	var buf = new writer();
	buf.into ('<td style= "vertical-align: top"><div style="background-color:white; width:165px; height:175px">',
						'<table  width="100%" cellpadding="0px" cellspacing="1px" border="0px" class="clsOuterFrame">',
						'<tr><td ><table width="100%" cellpadding="0px" cellspacing="0px" border="0px" class="clsInnerFrame">',
						'<tr><td colspan="3" class="clsTopPartNavpanel">',
						'<img src="../assets/Cal/spacer.gif" width="1px" height="1px" /></td></tr>',
						'<tr><td width="100%" colspan="3"><table cellpadding="1px" cellspacing="1px" border="0px" style="width:163px">',
						'<tr><td width="100%" class="clsInfoTitle">', 
						yrVu.months[mon], '&nbsp;',
						'</td></tr></table></td></tr><tr><td colspan="3" class="clsBottomPartNavpanel">',
						'<img src="../assets/Cal/spacer.gif" width="1 px" height="1 px"></td></tr><tr class="clsMidRow">',
						'<td><img src="../assets/Cal/spacer.gif"  width="4 px"height="1 px"></td>',
						'<td align="center" >',	getGridHtml(mon, yrVu), 
						'</td><td width="4px"><img src="../assets/Cal/spacer.gif"  width="4px" height="1px"></td></tr>',
						'<tr><td colspan="3" class="clsBottomPartNavpanel">',
						'<img src="../assets/Cal/spacer.gif" width="1 px" height="1 px" /></td></tr></table></td ></tr></table></div></td>');

	return buf.out();
}

function getYrSelectorHtml (yrVu)
// Return the HTML for the year selector
{
	var yr, reqYr, buf = new writer();

	var today = new Date ();
	var thisYr = today.getFullYear();
	reqYr = yrVu.year;

	buf.into ('<select name= "', yrVu.yrSelId, '" id= "', yrVu.yrSelId, '" onChange="changeYear(this)">');
	
	for (yr = thisYr; yr <= (thisYr + 10); yr++)
	{
		buf.into ('<option value= "', yr, '"');
		if (yr == reqYr)
			buf.into (' selected = "selected"');
		buf.into ('>', yr, '</option>');
	}

	buf.into ('</select>');
	return (buf.out());
}

function getCurrSelHtml (yrVu)
// Return the HTML for the year selector
{
	var buf = new writer();

	buf.into ('<select name= "', yrVu.currSelId, '" id= "', yrVu.currSelId, '" onChange="changeCurrency()">');

	var currs = new Array ("Pounds sterling", "Euros", "US dollars", "Canadian dollars");

	for (c in currs)
	{
		buf.into ('<option value= "', currs[c], '">', currs[c], '</option>');
	}

	buf.into ('</select>');
	return (buf.out());
}

function getKeyHtml ()
{
	var html = '<b>Key:-</b> &nbsp;&nbsp;&nbsp;Low season: <img src="../assets/PageAssets/LoSeasonKey.jpg" /> ' + 
						'&nbsp;&nbsp;&nbsp;&nbsp;Mid season: <img src="../assets/PageAssets/MidSeasonKey.jpg" /> ' +
						'&nbsp;&nbsp;&nbsp;&nbsp;High season: <img src="../assets/PageAssets/HiSeasonKey.jpg" /> ' +
						'&nbsp;&nbsp;&nbsp;&nbsp;Peak season: <img src="../assets/PageAssets/PkSeasonKey.jpg" />';
	return html;
}

function getPrices (yrVu)
{
	var buf = new writer();
	var sym = getSymbol (yrVu.currency);
	var pricesCount = yrVu.prices.length;
	var localPrices = new Array (pricesCount);

	for (i = 0; i < pricesCount; i++)
	{
		localPrices[i] = yrVu.prices[i] * yrVu.xRate;
		localPrices[i] = localPrices[i].toFixed(2);
	}
	
	buf.into ('Low season: ', sym, localPrices[0], ' per day.<br />Mid season: ', sym, 
										localPrices[1], ' per day.<br />High season: ', sym, 
										localPrices[2], ' per day.<br />Peak season: ', sym, 
										localPrices[3], ' per day.<br />');
	buf.into ('Optional pool heating (recommended Oct to Apr): ', sym, localPrices[4], ' per week. &nbsp;&nbsp;Cleaning: ', 
																											 sym, localPrices[5], ' per week.<br />');
	buf.into ('A security deposit of ', sym, localPrices[7], ' is required. This is refundable one week after return.<br />');
	buf.into ("To see our Terms and Conditions click <a href='../web/Terms%20%26%20Conditions.php'>here</a>.");
	return (buf.out());
}

function getGridHtml (mon, yrVu)
// Return the HTML for the table containing the day names & the grid of dates
{
	var buf = new writer();
	buf.into ('<table cellpadding="2" cellspacing="1" border="0" width="100%" class="clsDateGrid">');
	buf.into (getDaysHtml(yrVu));
	buf.into (getDateGridHtml(mon, yrVu));
	buf.into ('</table>');
	return (buf.out());
}

function getDaysHtml (yrVu)
// Return the HTML code for a table row containing 7 cells each with the name of a day of the week
{
	var buf = new writer();
	buf.into('<tr  class="clsWeekDay">');
	for (var wkDay = 0; wkDay < 7; wkDay++) 
		buf.into('<td style="width:10px; font: bold 9px Verdana, Arial Narrow, sans-serif">', 
							yrVu.weekdays[(wkDay + 1) % 7], '</td>');

	buf.into('</tr>');
	return(buf.out());
}

function getDateGridHtml (mon, yrVu)
// Return the html for the grid of dates
{
	var buf = new writer();
	var firstDay = new Date();
	firstDay.setDate(1);
	firstDay.setMonth(mon);
	firstDay.setYear(yrVu.year);
	firstDay.setDate(1 - ((6 + firstDay.getDay()) % 7));
	var currDay = new Date(firstDay);
	while ((currDay.getMonth() == mon) || (currDay.getMonth() == firstDay.getMonth())) 
	{
		buf.into('<tr>');
		for (var wkDay = 0; wkDay < 7; wkDay++) 
		{
			buf.into(getDayCellHtml(yrVu, currDay, mon));
			currDay.setDate(currDay.getDate() + 1);
		}
		buf.into('</tr>\n');
	}
	return(buf.out());
}

function getDayCellHtml (yrVu, inDate, mon) 
// Get the HTML for the yearView cell with the given date
{
	var classId, sLink, cellHtml;
	var day = inDate.getDate ();
	var year = yrVu.year;
	var dataStr = new String(yrVu.monthsData[mon]);
	var season = dataStr.charAt(day - 1);
	var dateType = getDateType (mon, year, inDate);

	if (dateType & 8) 
		classId = 'none';
	else
	{
		if (season == 0) 
			classId = 'loSea';
		else if (season == 1)
			classId = 'midSea';
		else if (season == 2) 
			classId = 'hiSea';
		else if (season == 3) 
			classId = 'pkSea';
	}
	
	var availableId = "availableDay";

//	sLink = 'javascript: dayClick(this, ' + season + ', ' + inDate.valueOf() + ');';
//	cellHtml = '<a href="" class="' + availableId + '" name="' + cellId + '">' + inDate.getDate() + '</a>';
	var cellIdTxt = "";
	if (dateType & 8)
		cellHtml = "&nbsp;";
	else
	{
		cellHtml = inDate.getDate();
		var cellId = "Cell" + padNum (mon) + padNum (day);
		cellIdTxt = 'name="' + cellId + '" id="' + cellId + '"';
	}


	cellHtml = '<td class="' + classId + '" align="center"' + cellIdTxt + '>' + cellHtml + '</td>';
	return cellHtml;
}

function updatePrices (yrVu)
{
	var pricesDiv = getObject ("Prices");
	pricesDiv.innerHTML = '&nbsp;'; 
	pricesDiv.innerHTML = getPrices (yrVu);	
}

function updateGrid (yrVu)
{
	var yearGrid = getObject("YearGrid");
	yearGrid.innerHTML = '&nbsp;';
	yearGrid.innerHTML = getYearGrid (yrVu);
	initGridEvents (yrVu);
}

function dayClick () 
// Called when a user clicks on a yearView cell
// Season indicates the current setting - this is incremented and stored in the months data
// Cell backround colr changes accordingly
{
	if (yrVu)
	{
		var cellId = this.id;
		var mon = Number (cellId.substr(4,2));
		var day = Number (cellId.substr(6,2));
		var dataStr = new String(yrVu.monthsData[mon]);
		var season = dataStr.charAt(day - 1);
		season = (Number(season) + 1) % 4;
		strlen = dataStr.length;
		var startStr = (day == 1) ? "" : dataStr.substr(0, day - 1);
		var endStr = (day == 31) ? "" : dataStr.substr(day, strlen - day);
		dataStr = startStr + season + endStr;
		yrVu.monthsData[mon] = dataStr;
		this.style.backgroundColor = yrVu.cellColrs[season];
		this.blur();
	}
}

function initGridEvents (yrVu)
{
	// Set the event handler for each cell
	var day, mon, maxDays, cell, cellId;
	
	for (mon = 0; mon < 12; mon++)
	{
		maxDays = getDaysInMon (mon, yrVu.year);
		for (day = 1; day <= maxDays; day++)
		{
			cellId = "Cell" + padNum (mon) + padNum (day);
			cell = getObject (cellId);
			cell.onclick = dayClick;
		}
	}
}

function getDateType (mon, year, inDate) 
// Return to type of date as a 4 bits:
// Bit 1 always set, bit 2 is not set
// Bit 3 set if this is Sat or Sun, bit 4 set if this day is not in the current month
{
	var nResType = 1, tmpDate = new Date(inDate);

	if ((tmpDate.getMonth() != mon) || (tmpDate.getFullYear() != year))	
		nResType |= 8;
	if ((tmpDate.getDay() == 0) || (tmpDate.getDay() == 6))	
		nResType |= 4;
	return nResType;
}

function padNum (num)
{
	// Pad the given number to two digits
	numStr = num.toString();
	if (numStr.length == 1)
		numStr = "0" + numStr;
	
	return numStr;
}

function fillMonthsData (monthsDataStr)
{
	// Fill an array with month arrays each containing an integer for each day that represents its status
	// monthsDataStr is an array of strings where each character is this same integer

	var monthsData = new Array(12);
	for (var i = 0; i < 12; i++)
	{
//		var mon !!!!KEEP AS STRINGS!!!!
		monthsData[i] = monthsDataStr[i].split ("");
	}

	return monthsData;
}

function getSymbol (currency)
{
	switch (currency)
	{
		case "US dollars" :
		return "$";
		
		case "Pounds sterling" :
		return "£";
		
		case "Canadian dollars" :
		return "C$";
		
		case "Euros" :
		return "&euro;";
		
		default :
		return "?";
	}
}

function getDaysInMon (mon, year)
{
	// Return the number of days in the given month and year
	var maxDays;
	var monLengths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
	
	if ((mon == 1) && ((year % 4) == 0))
		return 29;		// It's Feb in a leap year
	else
		return monLengths[mon];
}

function getObj (yrVu, objId) 
// Return the object with the given ID
{
	if (document.images && document.images[objId]) 
		return document.images[objId];
	else if (yrVu.formName &&  document.forms[yrVu.formName].elements[objId])  
		return document.forms[yrVu.formName].elements[objId];
	else if (document.all && document.all[objId])  
		return document.all[objId];
	else if (document.getElementById)  
		return document.getElementById(objId);
	else 
		return null;
}

function userAgent ()
// Create object holding browser identification variables
{
	var br = navigator.appName, v = this.version = navigator.appVersion;
	var ua = this.uas = navigator.userAgent.toLowerCase(), re_num = /opera/;
	this.op = re_num.exec(ua) ? true : false;
	this.ie = (br == "Microsoft Internet Explorer");
	if (this.op) 
		this.ie = false;
		
	this.v = parseInt(v);
	if (this.ie) 
	{
		this.ie4 = this.ie5 = this.ie55 = this.ie6 = false;
		if (v.indexOf('MSIE 6') > 0) 
			this.ie6 = true; this.v = 6;
	}
	this.win32 = (ua.indexOf("win") > -1);
	this.mac = (ua.indexOf("mac") > -1);
}

function writer() 
// Object for concatenating strings
// Feed it a series of strings using the "into" method N.B. this takes a variable number of arguments
// Retrieve them concatenated using the "out" method
{
	this.bufArray = [];
	this.into = function () 
	{
		var n = arguments.length;
		for (var i = 0; i < n; i++)
			this.bufArray[this.bufArray.length] = arguments[i];
	};

	this.out = function () 
	{
		return this.bufArray.join('');
	};
}

