
var myDomain 	= document.domain.replace(/.*?\.?([^.]+\.(com|co.uk|net|l))/, ".$1");
var fullDomain 	= document.domain.replace(/(.+\.(com|co.uk|net|l)\/).*/, "$1");
var startDay 	= $('.StartDay').html();
var weekDays 	= new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
var reg	= {};


$(document).ready(function () {

	// Initialise front-page inline-datepicker.
   $("#datepicker").datepicker({ 
		minDate: 0,
		maxDate: 500,
		altField: "#start",     
		altFormat: "yy-mm-dd",
		hideIfNoPrevNext: true
	});

	// Date picker for listing pages.
	
	var dpOpts = {
		minDate: 0, 
		maxDate: 500,
		hideIfNoPrevNext: true,
		dateFormat: "M d, yy",
		altField: "#start",     
		altFormat: "yy-mm-dd"
	};
	
	// Filter the available start days for villas.
	if (startDay && startDay != 'Any') dpOpts.beforeShowDay = startDays;
	$('#view_date').datepicker(dpOpts).datepicker('disable');
	$('#view_date').datepicker('enable'); 
	
	// Initialise the cascading menus.
	$('ul.jd_menu').jdMenu();
	$(document).bind('click', function() {
		$('ul.jd_menu ul:visible').jdMenuHide();
	});
	
	// Image cycle plugin on front page.
	if ($('#image_cycle').length > 0) { $('#image_cycle').cycle('fade'); }

	// Lightbox for galleries.
	$('#gallery a').lightBox({
		imageLoading:			'/css/jq/lightbox-ico-loading.gif',
		imageBtnPrev:			'/css/jq/lightbox-btn-prev.gif',
		imageBtnNext:			'/css/jq/lightbox-btn-next.gif',
		imageBtnClose:			'/css/jq/lightbox-btn-close.gif',
		imageBlank:				'/css/jq/lightbox-blank.gif'
	});

	// Bind the search button to the function to update the listing and store the search cookie.
	$('#search_button').bind('click', updateListings);
	$('#reset_button').bind('click', resetListings);
	$('#book_button').bind('click', addReservation);
	
	$('#nights').bind('change', updateRooms);
	$('#view_date').bind('change', updateRooms);
	$('#quantity').bind('change', setGuests);
	$('#room_type').bind('change', setGuests);
	
	// If we are on a listing page and have a search string, then prime the values, if there's no search string but a search cookie then use them instead.
	var theSearch = {};
	if (window.location.href.match(/:.+:.+/)) var searchString = window.location.href.match(/(hotels|villas)\/([^\/]+:[^\/]+)/)[2];
	if (searchString) {
		var allFields = searchString.split('~');
		$.each(allFields, function(n, thisField) {
			var exploded = thisField.split(':');
			theSearch[exploded[0]] = exploded[1];
		});
	} else if ($.cookie('search_params')) {
		theSearch = $.evalJSON($.cookie('search_params'));
	}
	
	$.each(theSearch, function(name, value) {
		if (value) {
			$('#'+name).setValue(value);
			if (name == 'start') {
				var myDate = value.match(/(\d\d\d\d)-(\d\d)-(\d\d)/);
				var arrDate = new Date(myDate[1], myDate[2] -1, myDate[3]);
				if (!startDay || startDay.length < 4 || startDay == weekDays[arrDate.getDay()]) $('#view_date').datepicker('setDate', arrDate);
			}
		}
	});
	
	// Admin stuff.
	

	$('.control_delete').bind('click', confirmDelete);
	$('#edit_tabs').tabs();
	$('.date_input').datepicker({
		minDate: 0, 
		maxDate: 700, 
		hideIfNoPrevNext: true, 
		dateFormat: "yy-mm-dd",
		onSelect: function(dateText) {
			if (this.id.match('From')) {
				var toField = $('#'+this.id.replace(/From/, 'To'));
				if (! toField.getValue()) { toField.setValue(dateText); }
			}
		}});
	
	if (afid = window.location.hash.match(/af(\d+)/)) {
		$.cookie('referrer', afid[1], {domain: myDomain, expires: 30, path: '/'});
		window.location.hash = '';
	}
	
	if ($('#view_date').getValue()) updateRooms();
	
}); // end of all the initialisation stuff that needs to run once the page is loaded.



if (typeof tinyMCE != 'undefined') {
	tinyMCE.init({
		theme : "advanced",
		mode: 				'textareas',
		editor_selector: 	'html_edit',
		convert_urls: false,
		content_css : '/css/tiny.css'
});
}

function setSite() {
	$.cookie('editing', $('#SiteSelector :selected').val(), {domain: myDomain, expires: 300, path: '/'});
}


// encode search values, store them in a cookie, and load the new results.
function updateListings() {
	if ($('input[name=accom]:checked').val()) {
		var thisSection = '/'+$('input[name=accom]:checked').val()+'/';
	} else {
		var thisSection = window.location.href.match(/.+\/(villas|hotels)\//)[0];
	}
	
	var newUrl = '';
	$.cookie('search_params', 
		$.toJSON(
			$.each($('#filter_form').formHash(), function(name, value) {
				if (value) newUrl += name+':'+value+'~'; 
			})), {domain: myDomain, expires: 7, path: '/'});

	window.location.href = thisSection+newUrl.replace(/\~$/, '/');
}


function resetListings() {
	$('#filter_form *').not(':button').setValue('');
	$.cookie('search_params', null);
	updateListings();
	return false;
}

//Fill in the option values for the room select drop down.
function updateRooms() {
	if ((window['rooms'] == undefined) || (rooms[0] == undefined)) return; // No rooms - true for villas and if no availability
	
	$('#room_type option').remove();
	
	var selectedDate = new Date($('#view_date').val());
	var roomOptions	 = '';
	
	$.each(rooms, function (index, room) {
		var inRange 		= false;
		var enoughNights 	= true;
		
		fromDate 			= getDateFromMysql(room.From, 'f'+room.Id);
		toDate 				= getDateFromMysql(room.To,   't'+room.Id);
		
		if ((selectedDate >= fromDate) && (selectedDate <= toDate))             inRange 	 = true;
		if ((room.MinNights > 0) && (room.MinNights > $('#nights').getValue())) enoughNights = false;
		
		if (inRange && enoughNights) {
			roomOptions = roomOptions+"\n"+'<option value="'+room.Id+'">'+room.Room+' '+room.Rate+'</option>';
		}
	});
	
	if (! roomOptions) roomOptions = '<option>No rooms found for selected date and stay length</option>';
	
	$('#room_type').html(roomOptions);
	
	setGuests();
}


function getDateFromMysql(theDate, memoKey) {
	if (reg.storedDates == undefined) reg.storedDates = {};
	
		if (reg.storedDates[memoKey] == undefined) {
		var newDate = new Date();  
		
		var parts = String(theDate).split(/-/);  
		
		newDate.setFullYear(parts[0]);  
		newDate.setMonth(parts[1] - 1);  
		newDate.setDate(parts[2]);  
		
		reg.storedDates[memoKey] = newDate;
	}
	
	return reg.storedDates[memoKey];
}


function setGuests() {
	$('#guests option').remove();
	
	var roomId 	= $('#room_type').val();
	
	if (! roomId) return;
	
	$.each(rooms, function (index, room) {
		if (room.Id == roomId) {
			reg.roomSleeps = room.Persons;
			return false;
		}
	});
	
	var maxG = reg.roomSleeps * $('#quantity').val();
	
	var gOpts = '';
	for (var i = 1 ; i <= maxG ; i++) {
		gOpts += '<option value="'+i+'">'+i+'</option>';
	}
	
	$('#guests').html(gOpts);

}


function addReservation() {
	if ($('#type').val() == 'H' && ! $('#room_type').val()) {
		alert("Please pick a room type to reserve.");
		return false;
	}
	
	if ($('#type').val() == 'T' && ! $('#reservation_form input:radio:checked').val()) {
		alert("Please pick a transfer type to book.");
		return false;
	}
	
	if (! $('#start').val()) {
		alert("Please enter your arrival date.");
		return false;
	}
	
	if ($.cookie('reservations')) var currentReservations = $.evalJSON($.cookie('reservations'));
	else var currentReservations = new Array();
	
	currentReservations.push($('#reservation_form').formHash());
	$.cookie('reservations', $.toJSON(currentReservations), {domain: myDomain, expires: 30, path: '/'});
	$.cookie('previous', '{added: 1, property: '+$('#pid').val()+'}', {domain: myDomain, expires: 30, path: '/'});
	
	window.location.href = 'http://'+fullDomain+'/reservations/';
}

function deleteReservation(resId) {
	if ($.cookie('reservations')) var currentReservations = $.evalJSON($.cookie('reservations'));
	else var currentReservations = new Array();
	
	currentReservations[resId] = 0;
	$.cookie('reservations', $.toJSON(currentReservations), {domain: myDomain, expires: 30, path: '/'});
	
	$('#row'+resId).fadeOut('slow');
}

function startDays(date) {
	if (weekDays[date.getDay()] == startDay) return [true, ''];
	return [false, ''];
}


function confirmDelete() {
	if (! confirm('Really delete this entry?')) return false;
}

// window popup function  -- replace this with an on-page modal box later.
function popup(url, width, height) {
	features = "height=" + height + ",width=" + width + ",directories=0,location=0,menubar=0,resizable=1,scrollbars=1,status=0,toolbar=0";
	open(url, "_blank", features);
}

function toggleEdit(theId) {
	if ($(theId));
}



