var domain = 'milford.co.uk';

var dayArray = new Array(7);
dayArray[0] = 'Sunday';
dayArray[1] = 'Monday';
dayArray[2] = 'Tuesday';
dayArray[3] = 'Wednesday';
dayArray[4] = 'Thursday';
dayArray[5] = 'Friday';
dayArray[6] = 'Saturday';
	
var monthArray = new Array(12);
monthArray[0] = 'January';
monthArray[1] = 'February';
monthArray[2] = 'March';
monthArray[3] = 'April';
monthArray[4] = 'May';
monthArray[5] = 'June';
monthArray[6] = 'July';
monthArray[7] = 'August';
monthArray[8] = 'September';
monthArray[9] = 'October';
monthArray[10] = 'November';
monthArray[11] = 'December';

var currencyArray = new Array([11, 'GBP', 'Pounds Sterling'], [12, 'EUR', 'European Euros'], [13, 'USD', 'US Dollars']);

/* timers etc */
var refreshInterval;
var refreshIntervalSeconds = 6000;
var flashingButtonInterval;
var currentColour = 1;

/* cookies  */
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

/* flashing button */
function flashingButton() {

	if($('flashingButton')) {
	
		if(currentColour == 1) {
			$('flashingButton').style.background = '#009900';
			$('flashingButton').style.color = '#ffffff';
			currentColour = 2;
		} else {
			$('flashingButton').style.background = '#C0C0C0';
			$('flashingButton').style.color = '#000000';
			currentColour = 1;
		}
		
	}
	
}

function startFlashingButton() {
	flashingButtonInterval = setInterval(flashingButton, 2000);
}

function stopFlashingButton() {

	clearInterval(flashingButtonInterval);
	
	/* reset colour */
	if($('flashingButton')) {
		$('flashingButton').style.background = '#C0C0C0';
		$('flashingButton').style.color = '#000000';
		currentColour = 1;
	}
	
}

/* toggles id vivibility, and swaps + - images if one exists  */
function configurePage(id) {

	Effect.toggle(id, 'blind', {duration: 0.5});
	
	if($(id+'Img')) {
		switch(Element.visible(id)) {
			case true:
				$(id+'Img').src = '/images/logo-show.png';
				createCookie(id, 'invisible', 365);
			break
			case false:
				$(id+'Img').src = '/images/logo-hide.png';
				createCookie(id, 'visible', 365);
			break
		}
	}
	
}

/* hides all classToCascade apart from keepAlive  */
function cascade(classToCascade, keepAlive) {

	var nodes = $A(document.getElementsByClassName(classToCascade));
	
	nodes.each(function(element) {

		if((Element.visible(element.id) == true) && (element.id != keepAlive)) {
			Effect.toggle(element.id, 'blind', {duration: 0.5});
			$(element.id).innerHTML = '';
		}
		
	});

}

function hide(classToHide) {
	$A(document.getElementsByClassName(classToHide)).each(Element.hide);
}

function unhide(classToUnhide) {
	$A(document.getElementsByClassName(classToUnhide)).each(Element.show);
}

/* year calculator */
/* http://www.quirksmode.org/js/introdate.html */
function takeYear(theDate) {
	x = theDate.getYear();
	var y = x % 100;
	y += (y < 38) ? 2000 : 1900;
	return y;
}

// integer check
function isInteger(n) {
return (!isNaN(n)) && (Math.floor(n)==n)
}

/* populate date div  */
function dateSelection(id, pageId, prefix) {

	var todaysDate = new Date();
	
	var tomorrowsDate = new Date();
	tomorrowsDate.setDate(tomorrowsDate.getDate() + 1);
	
	/***** days *****/
	var days = '<strong>Select Date</strong> <select name="d" id="d" class="entryRoomfinderDay" onchange="updateSelectedDates()">';

	/* current cookie value */
	var cookie = readCookie('day');
	
	if(cookie != null) {
		var preselect = cookie;
	} else {
		var preselect = tomorrowsDate.getDate();
	}
	
	for (i = 1; i <= 31; i++) {
		days += '<option value="' + i + '"';
		days += ((i == preselect) ?  ' selected="selected"' : '');
		days += '>' + i + '</option>';
	}
	
	days += '</select>';

	/***** months and years *****/
	
	/* generate year array */
	var todayYear = takeYear(todaysDate);
	var incrementedYear = todayYear;
	
	yearArray = new Array(3);
	for (i = 0; i <= 2; i++) {
		yearArray[i] = incrementedYear;
		incrementedYear++;
	}
	
	/* current cookie value */
	var cookie = readCookie('monthYear');
	
	if(cookie != null) {
		var preselect = cookie;
		var preselectType = 'cookie';
	} else {
		var preselect = tomorrowsDate.getMonth();
		var preselectType = 'tomorrow';
	}
	
	/* generate select list for months/days */
	var todayMonth = todaysDate.getMonth();
	var tomorrowYear = takeYear(tomorrowsDate);
	
	var months = ' <select name="m" id="m" class="entryRoomfinderMonth" onchange="updateSelectedDates()">';
	var monthCount = 0;
	
	// finnish off this year
	for (i = todayMonth; i <= 11; i++, monthCount++) {
		months += '<option value="' + yearArray[0] + '-' + parseInt(i+1) + '"';
		months += (((yearArray[0] + '-' + parseInt(i+1)) == preselect) ?  ' selected="selected"' : '');
		months += '>' +  monthArray[i] + ' ' + yearArray[0] + '</option>';
	}
	
	// loop through other years
	for (i=1; i < yearArray.length ; i++) {
		for (x=0; x < monthArray.length; x++, monthCount++) {
			if(monthCount <= 24) {
				months += '<option value="' + yearArray[i] + '-' + parseInt(x+1) + '"';
				if(preselectType == 'tomorrow') {
					months += (((x == preselect) && (yearArray[i] == tomorrowYear)) ?  ' selected="selected"' : '');
				} else {
					months += (((yearArray[i] + '-' + parseInt(x+1)) == preselect) ?  ' selected="selected"' : '');
				}
				months += '>' +  monthArray[x] + ' ' + yearArray[i] + '</option>';
			}
		}
	}
	
	months += '</select>';
	
	/***** nights *****/
	
	/* current cookie value */
	var cookie = readCookie('nights');
	
	if(cookie != null) {
		var preselect = ((isInteger(cookie)) ?  cookie : 1);
	} else {
		var preselect = 1;
	}
	
	var nights = 'Nights <input type="text" name="n" id="n" value="' + preselect + '" maxlength="2" class="entryRoomfinderNights" onchange="updateSelectedDates()"/>';	
	
	/***** currency *****/
	
	/* current cookie value */
	var cookie = readCookie('currency');
	
	if(cookie != null) {
		var preselect = cookie;
	} else {
		var preselect = 0;
	}
	
	// build select
	var currency = '<select name="c" id="c" class="entryRoomfinderCurrency" onchange="updateSelectedDates()">';
	for (i = 0; i < currencyArray.length ; i++) {
		currency += '<option value="' + currencyArray[i][0] + '"' + ((currencyArray[i][0] == preselect) ? 'selected="selected"' : '') + '">' + currencyArray[i][1] + '</option>';
	}
	currency += '</select>';
	
	/***** fit it all together *****/
	var dateSelectionHtml = '<form method="post" action="#" name="entryRoomfinder' + id + '" onsubmit="submitDate(); return false;">';
	dateSelectionHtml += '<input type="hidden" name="p" id="p" value="' + pageId + '" />';
	dateSelectionHtml += '<input type="hidden" name="e" id="e" value="' + id + '" />';
	dateSelectionHtml += days + months + nights + currency;
	dateSelectionHtml += '<input type="submit" value="   Next &gt;   " name="s" class="entryRoomfinderSubmit" /> <sup><a href="/help.html?helpId=2" onclick="newWindow(this.href, \'defaultpopup\', 400, 550, 1, 1, 0, 0, 0, 1, 0); return false;">What\'s This?</a></sup>';
	dateSelectionHtml += '</form><img src="/images/animated/loading.gif" style="display: none" /><img src="/images/brands/own.jpg" style="display: none" /><img src="/images/brands/active.png" style="display: none" /><img src="/images/brands/superbreak.png" style="display: none" /><img src="/images/brands/superbreak8.png" style="display: none" /><img src="/images/brands/superbreak15.png" style="display: none" /><img src="/images/brands/ihg.png" style="display: none" /><img src="/images/brands/venere.png" style="display: none" /><img src="/images/brands/hotelclub.png" style="display: none" /><img src="/images/brands/accor.png" style="display: none" /><img src="/images/brands/alpharooms.png" style="display: none" /><img src="/images/brands/laterooms.png" style="display: none" /><img src="/images/brands/own-website.png" style="display: none" /><img src="/images/brands/jurys.png" style="display: none" /><img src="/images/brands/superbreakshortbreak.png" style="display: none" /><img src="/images/brands/hilton.png" style="display: none" /><img src="/images/brands/superbreak4.png" style="display: none" /><img src="/images/brands/superbreak21.png" style="display: none" /><img src="/images/brands/ramada.png" style="display: none" /><img src="/images/brands/milford.png" style="display: none" /><img src="/images/brands/superbreak14.png" style="display: none" /><img src="/images/brands/superbreakgolf.png" style="display: none" /><img src="/images/brands/macdonald.png" style="display: none" /><img src="/images/brands/superbreak3.png" style="display: none" /><img src="/images/brands/superbreak7.png" style="display: none" /><img src="/images/brands/calendar.png" style="display: none" /><img src="/images/brands/superbreak28.png" style="display: none" /><img src="/images/brands/diytravel.png" style="display: none" /><img src="/images/brands/ratestogo.png" style="display: none" /><img src="/images/brands/travelodge.png" style="display: none" /><img src="/images/brands/premierinn.png" style="display: none" />';			

	$('entryRoomfinder' + id + prefix).innerHTML = dateSelectionHtml;

	configurePage('entryRoomfinder' + id + prefix);
	
	cascade('entryRoomfinder', 'entryRoomfinder' + id + prefix);

}

function currencyText(currency) {

	for (i = 0; i < currencyArray.length ; i++) {
		if(currencyArray[i][0] == currency) {
			return currencyArray[i][1];
		}
	}
	
}

/* submit controls for top dropdown and booknow dropdowns  */
function updateSelectedDates(type) {

		if(type == 'top') {
			
			if($('d')) {
				$('d').value = $F('dt');
				$('m').value = $F('mt');
				$('n').value = $F('nt');
				$('c').value = $F('ct');
			}
			
		} else if(type == 'map') {

			if($('d')) {
				$('d').value = $F('dm');
				$('m').value = $F('mm');
				$('n').value = $F('nm');
				$('c').value = $F('cm');
			}
			
			if($('dt')) {
				$('dt').value = $F('dm');
				$('mt').value = $F('mm');
				$('nt').value = $F('nm');
				$('ct').value = $F('cm');
			}
			
		} else {

			if($('dt')) {
				$('dt').value = $F('d');
				$('mt').value = $F('m');
				$('nt').value = $F('n');
				$('ct').value = $F('c');
			}
			
		}

}

function submitDateTop() {

	updateSelectedDates('top');
	
	if(checkDate($F('dt'), $F('mt'))) {
		submitRoomfinderSearch($F('pt'), 0, $F('dt'), $F('mt'), $F('nt'), $F('ct'), 'top');
	}
	
}

function submitDateMap() {

	updateSelectedDates('map');
	
	if(checkDate($F('dm'), $F('mm'))) {
		submitRoomfinderSearch($F('pm'), 0, $F('dm'), $F('mm'), $F('nm'), $F('cm'), 'map');
	}
	
}

function submitDate() {

	updateSelectedDates();
	
	if(checkDate($F('d'), $F('m'))) {
		submitRoomfinderSearch($F('p'), $F('e'), $F('d'), $F('m'), $F('n'), $F('c'), 'bottom');
	}
	
}

function checkDate(day, monthYear) {

	var splitMonth = monthYear.split('-');
	
	var selectedDate = new Date();
	selectedDate.setDate(day);
	selectedDate.setMonth(splitMonth[1]-1);
	selectedDate.setYear(splitMonth[0]);
	
	var today = new Date();
	
	if (selectedDate >= today) {
		return true;
	}
	
	alert('Please enter a date in the future.');
	
	return false;

}

/* submit page to xml queue, delay user a few seconds to allow some results to filter through  */
function submitRoomfinderSearch(page, establishment, day, monthYear, nights, currency, clickedFrom) {
	
	// google analytics
	pageTracker._trackPageview();
	
	// save date
	createCookie('day', day, 14);
	createCookie('monthYear', monthYear, 14);
	createCookie('nights', nights, 14);
	createCookie('currency', currency, 14);
	
	// clear old search
	clearInterval(refreshInterval);
	
	// loading
	var nodes = $A(document.getElementsByClassName('roomfinderResults'));
	var estIdList = '';
	
	nodes.each(function(element) {
	
		if(Element.visible(element.id) == false) {
			Effect.toggle(element.id, 'blind', {duration: 0.5});
		}
		
		$(element.id).innerHTML = '<img src="/images/animated/loading.gif" class="loading center noBorder" /><span class="block small center">loading booking options<br />been waiting a while? <a href="?day=' + day + '&monthYear=' + monthYear + '&nights=' + nights + '&currency=' + currency + '">click here</a></span>';

		estIdList = estIdList + element.id.match(/^roomfinderResult([0-9]*)[a-z]?$/)[1] + ';';
		
	});

	addToQueue(page, establishment, day, monthYear, nights, currency, estIdList);
	
	prepPage();
	
	if(clickedFrom == 'top') {
	
		if($('roomfinderResultsStart')) {
			$('roomfinderResultsStart').scrollTo();
		}
		
	}
	
	// sleep for a few seconds
	setTimeout('loadRoomfinderTables(\'' + page + '\', \'' + establishment + '\', ' + day + ', "' + monthYear + '", ' + nights + ', ' + currency + ', "' + estIdList + '")', 4000);

}

function addToQueue(page, establishment, day, monthYear, nights, currency, estIdList, priority) {
	new Ajax.Request('/submitRfData.ajax.php', {method:'post', parameters:'establishmentId=' + establishment + '&pageId=' + page + '&day=' + day + '&monthYear=' + monthYear + '&nights=' + nights + '&currency=' + currency + '&estIdList=' + estIdList + '&priority=' + priority});
}

function prepPage() {

	stopFlashingButton();

	cascade('entryRoomfinder', '');
	hide('entryPrice');
	unhide('clearDates');

	var nodes = $A(document.getElementsByClassName('dateSelection'));
	
	nodes.each(function(element) {
		date = element.getElementsByTagName('input')[0];
		date.src = '/images/icons/change-dates.png';
	});
	
}

/* initialize roomfinder tables   */
function loadRoomfinderTables(page, establishment, day, monthYear, nights, currency, estIdList) {

	var splitMonth = monthYear.split('-');
	
    var selectedDate = new Date(splitMonth[0], splitMonth[1]-1, day);

	// day suffix
	if (day==1) suffix=("st");
	else if (day==2) suffix=("nd");
	else if (day==3) suffix=("rd");
	else if (day==21) suffix=("st");
	else if (day==22) suffix=("nd");
	else if (day==23) suffix=("rd");
	else if (day==31) suffix=("st");
	else suffix=("th");

	new Ajax.Request('/getRfData.ajax.php', {
		method:'post',
		parameters:'page=' + page + '&day=' + day + '&monthYear=' + monthYear + '&nights=' + nights + '&currency=' + currency + '&estIdList=' + estIdList,
		onSuccess: function(transport) {
		
			var json = transport.responseJSON;
			
			json.hotels.each(function(hotel) {
			
				['', 's', 'm', 'l'].each(function(prefix) {
				
					if(!$('roomfinderResult' + hotel.establishmentId + prefix)) {
						return;
					}
			
					var start = '<p>Arrive ' + dayArray[selectedDate.getDay()] + ' ' + day + suffix + ' ' + monthArray[selectedDate.getMonth()] + ' ' + splitMonth[0] + ' for ' + nights + ' ' + ((nights > 1) ?  'nights' : 'night') + '. Rates are ' + currencyText(currency) + ' for the room.</p><table class="rfTable"><tr><td colspan="6" class="bookthrough">You can book through the following websites:</td></tr><tr><th class="rfCol1"></th><th class="rfCol2 shade">Single</th><th class="rfCol3 shade"></th><th class="rfCol4 shade">Double</th><th class="rfCol5 shade"></th><th class="rfCol6"><sup><a href="http://www.milford.co.uk/help.html?helpId=3" onclick="newWindow(this.href, \'defaultpopup\', 425, 550, 1, 1, 0, 0, 0, 1, 0); return false;">Explain results</a></sup></th></tr>';
					var end = '<tr><td colspan="6" class="right"><a href="/hotels-on-map.html?pageId=' + page + '&day=' + day + '&monthYear=' + monthYear + '&nights=' + nights + '&currency=' + currency + '">Click here</a> to see Family rates</td></tr></table>';

					var tableHTML = '';

					hotel.rates.each(function(rate) {

						if(rate.otherLink == '1') {
							tableHTML = tableHTML + '<tr class="extraLinksHeading"><td colspan="6"><p><span> other links to try / more info </span></p></td></tr>';
						}
						
						tableHTML = tableHTML + '<tr><td class="rfCol1"><a href="' + rate.linkUrl + '" onmouseover="self.status=\'' + rate.linkStatus + '\'; return true;" onmouseout="self.status=\'\'; return true;" onclick="pageTracker._trackPageview(\'/clicked-link.html\'); window.open(this.href); return false;" rel="nofollow"><img src="/images/brands/' + rate.linkNameImg + '" alt="' + rate.linkName + '" class="noBorder" /></a></td><td id="sgpr' + hotel.establishmentId + rate.linkId + prefix + '" class="rfCol2">' + rate.singlePrice + '</td><td id="sgtt' + hotel.establishmentId + rate.linkId + prefix + '" class="rfCol3"><abbr title="' + rate.singleMealPlanFull + '">' + rate.singleMealPlan + '</abbr></td><td id="dbpr' + hotel.establishmentId + rate.linkId + prefix + '" class="rfCol4">' + rate.doublePrice + '</td><td id="dbtt' + hotel.establishmentId + rate.linkId + prefix + '" class="rfCol5"><abbr title="' + rate.doubleMealPlanFull + '">' + rate.doubleMealPlan + '</abbr></td><td class="rfCol6"><a href="' + rate.linkUrl + '" onmouseover="self.status=\'' + rate.linkStatus + '\'; return true;" onmouseout="self.status=\'\'; return true;" onclick="pageTracker._trackPageview(\'/clicked-link.html\'); window.open(this.href); return false;" rel="nofollow">' + rate.linkText + '</a></td></tr>';

					});
					
					var email = '<!-- <p class="priceNotice">Problems? Have a question? Don\'t understand? Call us on 0115 922 5413.<br /><span class="small grey">Service open during normal office hours. Note that this is not the hotel telephone number.</span></p>--><span class="block center small"><a href="/email.html?establishmentId=' + hotel.establishmentId + '&pageId=' + page + '" onclick="newWindow(this.href, \'defaultpopup\', 400, 550, 1, 1, 0, 0, 0, 1, 0); return false;">Send this page [and results] to an email address</a></span>';

					$('roomfinderResult' + hotel.establishmentId + prefix).innerHTML = start + tableHTML + end + email;
					
					if($('establishment' + establishment)) {
						$('establishment' + establishment).scrollTo();
					}
					
				});

			});

			refreshInterval = setInterval('refreshRoomfinderResults(' + page + ', ' + day + ', "' + monthYear + '", ' + nights + ', ' + currency + ', "' + estIdList + '")', refreshIntervalSeconds);
		
		}
	});

}

/* used only if dates are already set from another page - otherwise above functions do this  */
function setRefreshInterval(page, day, monthYear, nights, currency) {

	clearInterval(refreshInterval);
	
	var nodes = $A(document.getElementsByClassName('roomfinderResults'));
	var estIdList = '';
	
	nodes.each(function(element) {
		estIdList = estIdList + element.id.match(/^roomfinderResult([0-9]*)[a-z]?$/)[1] + ';';
	});

	refreshInterval = setInterval('refreshRoomfinderResults(' + page + ', ' + day + ', "' + monthYear + '", ' + nights + ', ' + currency + ', "' + estIdList + '")', refreshIntervalSeconds);

}

/* reload results   */
function refreshRoomfinderResults(page, day, monthYear, nights, currency, estIdList) {

	new Ajax.Request('/getRfData.ajax.php', {
		method:'post',
		parameters:'page=' + page + '&day=' + day + '&monthYear=' + monthYear + '&nights=' + nights + '&currency=' + currency + '&estIdList=' + estIdList,
		onSuccess: function(transport) {
		
			var json = transport.responseJSON;
			
			json.hotels.each(function(hotel) {

				hotel.rates.each(function(rate) {
				
					['', 's', 'm', 'l'].each(function(prefix) {
						
						if($('roomfinderResult' + hotel.establishmentId + prefix)) {
							$('sgpr' + hotel.establishmentId + rate.linkId + prefix).innerHTML = rate.singlePrice;
							$('sgtt' + hotel.establishmentId + rate.linkId + prefix).innerHTML = '<abbr title="' + rate.singleMealPlanFull + '">' + rate.singleMealPlan + '</abbr>';
							$('dbpr' + hotel.establishmentId + rate.linkId + prefix).innerHTML = rate.doublePrice;
							$('dbtt' + hotel.establishmentId + rate.linkId + prefix).innerHTML = '<abbr title="' + rate.doubleMealPlanFull + '">' + rate.doubleMealPlan + '</abbr>';
						}
					
					});
				
				});

			});
			
			// set search completion flag
			if(json.completed == 'YES') {
				clearInterval(refreshInterval);
			}

		}
	});
  
}

/* general centered popup   */
function newWindow(a_str_windowURL, a_str_windowName, a_int_windowWidth, a_int_windowHeight, a_bool_scrollbars, a_bool_resizable, a_bool_menubar, a_bool_toolbar, a_bool_addressbar, a_bool_statusbar, a_bool_fullscreen) {

	var int_windowLeft = (screen.width - a_int_windowWidth) / 2;
	var int_windowTop = (screen.height - a_int_windowHeight) / 2;
	var str_windowProperties = 'height=' + a_int_windowHeight + ',width=' + a_int_windowWidth + ',top=' + int_windowTop + ',left=' + int_windowLeft + ',scrollbars=' + a_bool_scrollbars + ',resizable=' + a_bool_resizable + ',menubar=' + a_bool_menubar + ',toolbar=' + a_bool_toolbar + ',location=' + a_bool_addressbar + ',statusbar=' + a_bool_statusbar + ',fullscreen=' + a_bool_fullscreen + '';
	var obj_window = window.open(a_str_windowURL, a_str_windowName, str_windowProperties)
	
    if (parseInt(navigator.appVersion) >= 4) {
      obj_window.window.focus();
    }
	
}

startFlashingButton();

/* font sizer  */

var defaultFontSize = 1;
var fontSizeCookie = readCookie('fontsize');

if(fontSizeCookie != null) {
	var textsize = fontSizeCookie;
} else {
	var textsize = defaultFontSize;
}
	
function changetextsize(upordown) {
	
	if(upordown == '+') {
		textsize = parseFloat(textsize)+0.10;
	} else if(upordown == '-') {
		textsize = parseFloat(textsize)-0.10;
	}

	$('mainContainer').style.fontSize = textsize + 'em';
	
	if(textsize == defaultFontSize) {
		eraseCookie('fontsize');
	} else {
		createCookie('fontsize', textsize, 365);
	}
	
}

function sendComment() {
	new Ajax.Updater('contactPopUp', '/sendComment.ajax.php', {parameters: { comments: $F('comment') }});
	return false;
}

/* shortlist */
function addToShortlist(establishmentId) {

	['', 'm', 'l'].each(function(prefix) {
		if($('addToShortlist' + establishmentId + prefix)) {
			$('addToShortlist' + establishmentId + prefix).replace('<p id="removeFromShortlist' + establishmentId + prefix + '" onclick="removeFromShortlist(' + establishmentId + '); return false;"><img src="/images/sl2.png" alt="Remove from Shortlist" /></p>');
		}
	});
				
	new Ajax.Request('/shortlist.ajax.php', {
		method: 'post',
		parameters: { action: 'addToShortlist', establishmentId: establishmentId },
		onSuccess: function(transport) {

			var json = transport.responseJSON;

			if(!json.shortlisted) {
				
				if($('shortlist')) {
				
					$('shortlist').insert({top: json.html});
					
					createSortable();
					Behaviour.apply();
					
				}
				
				if($('placeShortlist')) {
				
					if($('placeShortlistEmpty')) {
						$('placeShortlistEmpty').remove();
					}
					
					$('placeShortlist').insert({top: '<li id="placeShortlist' +  json.id + '"><span>' + json.name + '</span></li>'});
					
				}
				
			}
			
		}

	});

}

function removeFromShortlist(establishmentId) {

	['', 'm', 'l'].each(function(prefix) {
		if($('removeFromShortlist' + establishmentId + prefix)) {
			$('removeFromShortlist' + establishmentId + prefix).replace('<p id="addToShortlist' + establishmentId + prefix + '" onclick="addToShortlist(' + establishmentId + '); return false;"><img src="/images/sl1.png" alt="Add to Shortlist" /></p>');
		}
	});
	
	if($('placeShortlist' +  establishmentId)) {
	
		$('placeShortlist' +  establishmentId).remove();
		
		if($('placeShortlist') && $('placeShortlist').empty()) {
			$('placeShortlist').innerHTML = '<li id="placeShortlistEmpty"><span class="italic">Shortlist Empty</span></li>';
		}
		
	}
	
	new Ajax.Request('/shortlist.ajax.php', {
		method: 'post',
		parameters: { action: 'removeFromShortlist', establishmentId: establishmentId },
		onSuccess: function(transport) {
		
			Effect.Fade('establishment' + establishmentId + 's', { duration: .7, afterFinish: function() { $('establishment' + establishmentId + 's').remove() } } );

		}

	});

}

/* dom loaded */
Event.observe(window, 'load', function() {


	/* talk to us  */
	if($('topLinksRight')) {
	
		$('topLinksRight').innerHTML = 'Problem, Suggestion or Just Need Help? <img src="/images/icons/talk.png" alt="Talk to Milford about your accommodation requirements"> <a href="#" id="comments" onclick="return false;">Talk To Milford<\/a>';

		new Tip('comments', '<div id="contactPopUp"><p>Having problems? Can\'t find what you are looking for? Got something you want to tell us?<\/p><p class="center"><textarea rows="#" cols="#" id="comment"><\/textarea><\/p><p>Don\'t forget to include your email address if you want a reply!<\/p><p class="right"><input type="submit" value="Send" onclick="sendComment(); return false;" /><\/p><\/div>', {
				title: 'Talk to Milford',
				showOn: 'click',
				hideOn: 'click',
				closeButton: true,
				stem: 'topRight',
				hook: { target: 'bottomMiddle', tip: 'topRight' },
				offset: { x: -20, y: 0 }
		});
		
	}
	
	
	/* change fine size */
	if(fontSizeCookie != null) {
		changetextsize('same');
	}
	
	hide('addressDefault');
	unhide('addressHide');
	
	
	/* wipe alt tags for img and area tags */
	$$('#mapContainer area').each(function(link) {
		link.alt = '';
	});
	$$('#mapContainer img').each(function(link) {
		link.alt = '';
	});
	
	
	/* autocompleter 
	if($('searchBox')) {
		
		new Ajax.Autocompleter('searchBox', 'autocomplete_choices', '/getSearchData.ajax.php', {
		  minChars: 3,
		  frequency: 0.7,
		  autoSelect: false
		});
		
	}
	*/
	
	/* MAPS */
	if(($('mapSwitch')) && ($('mapSwitch').empty())) {
		$('mapSwitch').innerHTML = '<form action="#"><input type="radio" checked="checked" name="map" class="noBorder" />Place view <input type="radio" name="map" class="mapView noBorder" />Map view</form>';
	}
	
	/*
	if($('goToShortlist')) {
		$('goToShortlist').innerHTML = '<a href="?gmap=1&shortlist=1" title="Full Shortlist Details">Full Shortlist Details</a>';
	}
	*/
	
	if($('viewAllHotels')) {
		$('viewAllHotels').toggle();
	}
	
	$$('.mapView').invoke('observe', 'focus', function(event) {
		event.stop();
		window.location = '/hotels-on-map.html?pageId=' + pageid;
	});

	$$('#mapViewFade, #viewAllHotels').invoke('observe', 'click', function(event) {
		event.stop();
		window.location = '/hotels-on-map.html?pageId=' + pageid;
	});

    /* side items */
    if((document.viewport.getWidth() > 958) && ($('mapViewFade'))) {
        Effect.toggle($('mapViewFade'), 'Appear', {duration: 1.5});
    }
    
    if((document.viewport.getWidth() > 958) && ($('adsense-right'))) {
        $('adsense-right').toggle();
    }
	
	/* clear search box */
	if($('searchBox')) {
	
		Event.observe('searchBox', 'focus', function() {

			if(($F('searchBox') == 'Place or Hotel Name') || ($F('searchBox') == 'Place, Hotel Name or Postcode')) {
				$('searchBox').clear();
			}
				
		});
		
	}
    
    /* calendar */
    var cookieDays = 30;
	$$('.month-select').invoke('observe', 'change', function(event) {
        calendar(event.element());
	});
    
    function calendar(monthSelector) {

        /* hide all */
        $$('.calendar-availability').each(function(element) {
            element.hide();
        });

        [monthSelector.selectedIndex, monthSelector.selectedIndex + 1].each(function(index) {

            if(monthSelector[index] == null) return;

            /* show next month*/
            $$('.month-' + monthSelector[index].value).each(function(element) {
                element.show();
            })

        });

        createCookie('calendarDate', monthSelector.getValue(), cookieDays);
        
        $$('.month-select').each(function(element) {
            element.setValue(monthSelector.getValue());
        })
    
    }

    /* set default date */
    if(readCookie('calendarDate') == null) {
        var newdate = new Date();
        createCookie('calendarDate', newdate.getFullYear() + '-' + newdate.getMonth()+1 + '-1', cookieDays);
    }

    if($$('.month-select').size() > 0) {
        $$('.month-select')[0].setValue(readCookie('calendarDate'));
        calendar($$('.month-select')[0]);
    }

});
