$(document).ready(function() {

	/**********************************/
	/*      DRAW THE CALENDAR         */
	/*       WHEN PAGE LOADS          */
	/**********************************/
	// setCal();
	if($('#arrival').val() != '' && $('#departure').val() != '') {
		unhide();
	}

	$('#days_apart').html(daysApart());
	/**********************************/
	/*   ADD THE PRICES TO EACH DAY   */
	/*   FOR EACH OF THE CALENDARS    */
	/**********************************/
	$('fieldset.calendar_fieldset').each(function() {
		addPrices(this);
	});

	/**********************************/
	/*  DO WE WANT TO ADD MORE ROOM   */
	/**********************************/
	$('#add-room a.bt-add-room').click(function() {
		
		if($('.calendar_fieldset').length > 5) {
			jAlert('Maximum number of rooms reached');
			return false;
		}
		
		var previousFieldset = $(this).parent().prev().prev();
		var previousSelectedRoom = $(previousFieldset).find('select.room-type-select:eq(0)').val();
		var new_html;
		new_html = '<h4>' + $(this).parent().prev().prev().prev().html() + '</h4>';
		new_html += '<fieldset class="calendar_fieldset">' + $('#calendar_box').html() + '</fieldset>';
		new_html += '<fieldset>' + $(this).parent().prev().html() + '</fieldset>';
		$(this).parent().before(new_html);
		var currentFieldset = $(this).parent().prev().prev();
		$('div.calendar:eq(0)', currentFieldset).data('calendarIndex', $('fieldset.calendar_fieldset').length - 1);

		var selected_box = $(this).parent().prev().prev().find('select.room-type-select:eq(0)');
		var selected_room = $(selected_box).val();
		
		var rooms = new Array();
		$('select.room-type-select').each(function() {
			if(typeof(rooms[$(this).val()]) == 'undefined') {
				rooms[$(this).val()] = new Array();
				rooms[$(this).val()]['value'] = 1;
			} else {
				rooms[$(this).val()]['value'] = rooms[$(this).val()]['value'] + 1;
			}
		});
		var permanent_error = false;
		if(rooms[selected_room]['value'] > Acm[selected_room]['max_rooms']) {
			permanent_error = true;
			for (var room_key in Acm) {
				if(typeof(rooms[room_key]) == 'undefined') {
					rooms[room_key] = new Array();
					rooms[room_key]['value'] = 0;
				}
				if(rooms[room_key]['value'] < Acm[room_key]['max_rooms']) {
					permanent_error = false;
					var searchTerm = eval("/"+ String(Acm[room_key]['name']) + "/i");
					$("option:contains("+Acm[room_key]['name']+")", selected_box).attr("selected", true);
				}
			}
		}

		if(permanent_error == true) {
			jAlert('There are no more rooms available');
			$(this).parent().prev().remove();
		} else {
			// RESET ALL THE VALUES FOR THE AREA HERE
			// $(this).parent().prev().find('.room-type-select').change();

			updateUnavailableDates(previousSelectedRoom, previousFieldset);
			

			var max_people_allowed = Acm[$(this).parent().prev().prev().find('.room-type-select').val()]['max_people'];

//			$(this).parent().prev().prev().find('.no-of-adults').removeOption(/./);
//			$(this).parent().prev().prev().find('.no-of-children').removeOption(/./);
			$(currentFieldset).find('select.no-of-adults').removeOption(/./);
			$(currentFieldset).find('select.no-of-children').removeOption(/./);

			for (i = 1; i <= max_people_allowed; i++) {
				$(currentFieldset).find('select.no-of-adults').addOption(i,i, false);
			}
			for (i = 0; i < max_people_allowed; i++) {
				$(currentFieldset).find('select.no-of-children').addOption(i,i, false);
			}

			$('a.bt-delete', currentFieldset).css('display', 'block');

			var currency = $('div.running-total select.currency-select').val();
			$(currentFieldset).find("option:contains("+currency+")", '.currency-select').attr("selected", true);
			addPrices($(currentFieldset));
		}
		return true;
	});

	/**********************************/
	/*  DO WE WANT TO REMOVE A ROOM   */
	/**********************************/
	$('fieldset.calendar_fieldset a.bt-delete').live('click', function() {
		btn = this;
		var removable_element1 = $(this).parent().parent().prev();
		var removable_element2 = $(this).parent().parent();
		var removable_element3 = $(this).parent().parent().next();
		jConfirm("Are you sure ? It's such a lovely room", 'Confirmation Required', function(r) {
			if(r == true) {
				$(removable_element1).remove();
				$(removable_element2).remove();
				$(removable_element3).remove();
				addSummary();
				if($('.calendar_fieldset').length < 2) {
					$(btn).css('display', 'none');
//					$('.bt-delete').css('display', 'none');
				}
			}
		});
	});

	/**********************************/
	/*  IF ANY DROP DOWN IS CHANGES   */
	/* UPDATE THE PRICES FOR EACH DAY */
	/**********************************/
	var previous_room_option = false;
	$('fieldset.calendar_fieldset select.room-type-select').live('mouseover', function(event) {
		previous_room_option = $(this).val();
	});

	$('fieldset.calendar_fieldset .no-of-rooms, fieldset.calendar_fieldset .no-of-children, fieldset.calendar_fieldset .no-of-adults, fieldset.calendar_fieldset .room-type-select').livequery('change', function(event) {
		var target = $(event.target);
		if ($(target).parent().attr('tagName').toLowerCase() == 'div') {
			var parent_fieldset = $(target).parent().parent();
		} else {
			var parent_fieldset = $(target).parent();
		}
		var Acm_id = $('select.room-type-select:eq(0)', parent_fieldset).val();

		if($(target).hasClass('.room-type-select')) {
			updateUnavailableDates();
			
			// CHECK HOW MANY ROOM ARE ALLOWED FOR THIS OPTION
			var selected_room = Acm_id;
			var rooms = new Array();
//			$('.room-type-select').each(function() {
			$(target).each(function() {
				if(typeof(rooms[$(this).val()]) == 'undefined') {
					rooms[$(this).val()] = new Array();
					rooms[$(this).val()]['value'] = 1;
				} else {
					rooms[$(this).val()]['value'] = rooms[$(this).val()]['value'] + 1;
				}
			});
			var permanent_error = false;
			if(rooms[selected_room]['value'] > Acm[selected_room]['max_rooms']) {
				jAlert('There are no more rooms of this type available');
				$("option:contains("+Acm[previous_room_option]['name']+")", target).attr("selected", true);
				return false;
			}

			var max_people_allowed = Acm[Acm_id]['max_people'];
			var max_rooms_allowed = Acm[Acm_id]['max_rooms'];

			var max_people_selected = (parseFloat($(parent_fieldset).find('.no-of-adults').val())+parseFloat($(parent_fieldset).find('.no-of-children').val()));

			if(max_people_selected > max_people_allowed) {

				jAlert('The room you selected does not support the number of people you have in your company. Your options has been reset.');

				$(parent_fieldset).find('select.no-of-adults:eq(0)').removeOption(/./);
				$(parent_fieldset).find('select.no-of-children:eq(0)').removeOption(/./);

				for (i = 1; i <= max_people_allowed; i++) {
					$(parent_fieldset).find('select.no-of-adults:eq(0)').addOption(i,i, false);
				}
				for (i = 0; i < max_people_allowed; i++) {
					$(parent_fieldset).find('select.no-of-children:eq(0)').addOption(i,i, false);
				}

			} else {

				var adults_current = $(parent_fieldset).find('select.no-of-adults:eq(0)').val();
				var children_current = $(parent_fieldset).find('select.no-of-children:eq(0)').val();
				$(parent_fieldset).find('select.no-of-adults:eq(0)').removeOption(/./);
				$(parent_fieldset).find('select.no-of-children:eq(0)').removeOption(/./);

				for (i = 1; i <= max_people_allowed-children_current; i++) {
					if(adults_current == i) {
						$(parent_fieldset).find('select.no-of-adults:eq(0)').addOption(i,i, true);
					} else {
						$(parent_fieldset).find('select.no-of-adults:eq(0)').addOption(i,i, false);
					}
				}

				for (i = 0; i <= max_people_allowed-adults_current; i++) {
					if(children_current == i) {
						$(parent_fieldset).find('select.no-of-children:eq(0)').addOption(i,i, true);
					} else {
						$(parent_fieldset).find('select.no-of-children:eq(0)').addOption(i,i, false);
					}
				}

			}
		}

		// UPDATE THE PRICES
		addPrices(parent_fieldset);

		if($(target).hasClass('.no-of-adults')) {

			var number_of_adults = $(target).val();
			var remaining_people = (Acm[Acm_id]['max_people']-number_of_adults);

			// CHECK WHAT OPTION IS SELECTED FOR CHILDREN
			var children_current = $(parent_fieldset).find('select.no-of-children:eq(0)').val();
			$(parent_fieldset).find('select.no-of-children:eq(0)').removeOption(/./);
			for (i = 0; i <= remaining_people; i++) {
				if(children_current == i) {
					$(parent_fieldset).find('select.no-of-children:eq(0)').addOption(i,i, true);
				} else {
					$(parent_fieldset).find('select.no-of-children:eq(0)').addOption(i,i, false);
				}
			}
		}
		if($(target).hasClass('.no-of-children')) {
			var number_of_children = $(parent_fieldset).find('.no-of-children').val();
			var remaining_people = (Acm[Acm_id]['max_people']-number_of_children);
			// CHECK WHAT OPTION IS SELECTED FOR ADULTS
			var adults_current = $(parent_fieldset).find('.no-of-adults').val();
			$(parent_fieldset).find('.no-of-adults').removeOption(/./);
			for (i = 1; i <= remaining_people; i++) {
				if(adults_current == i) {
					$(parent_fieldset).find('.no-of-adults').addOption(i,i, true);
				} else {
					$(parent_fieldset).find('.no-of-adults').addOption(i,i, false);
				}
			}
		}

		return true;
	});

	/**********************************/
	/*  DATE FUNCTIONALITY GOES HERE  */
	/**********************************/
	$(function() {
		Date.format = 'yyyy-mm-dd';
		$(".dateISO").datePicker({
			clickInput:true
		});
		// $('#arrival').dpSetEndDate($('#departure').val());
		// $('#departure').dpSetStartDate($('#arrival').val());
		$('#arrival:visible, #arrivalS:visible').bind('dpClosed',
			function(e, selectedDates) {
				var d = selectedDates[0];
				if (d) {
					d = new Date(d);
					// $('#departure').dpSetStartDate(d.addDays(1).asString());

					if(startDateBigger() == false) {
						//var days_apart = Math.round($('#days_apart').text());  //Functionality confuses client
						var days_apart = 1;
						$('#departure:visible, #departureS:visible').attr('value', d.addDays(days_apart).asString());
						$('#departure:visible, #departureS:visible').dpSetSelected($('#departure:visible, #departureS:visible').val());
					} else if(daysApart() > 30) {
						$('#departure:visible, #departureS:visible').attr('value', d.addDays(29).asString());
						$('#departure:visible, #departureS:visible').dpSetSelected($('#departure:visible, #departureS:visible').val());
						jAlert('You have selected a period which is more that 30 days apart. Your dates have been auto corrected.');
					}
					$('#days_apart').html(daysApart());
					setCal();
					$('.calendar_fieldset').each(function() {
						addPrices(this);
					});
				}
				if($('#arrival:visible, #arrivalS:visible').val() != '' && $('#departure:visible, #departureS:visible').val() != '') {
					unhide();
				}
			}
		);
		$('#departure:visible, #departureS:visible').bind('dpClosed',
			function(e, selectedDates) {
				var d = selectedDates[0];
				if (d) {
					d = new Date(d);
					// $('#arrival').dpSetEndDate(d.addDays(-1).asString());

					if(startDateBigger() == false) {
						//var days_apart = Math.round($('#days_apart').text()*-1); //Functionality confuses client
						var days_apart = -1;
						$('#arrival:visible, #arrivalS:visible').attr('value', d.addDays(days_apart).asString());
						$('#arrival:visible, #arrivalS:visible').dpSetSelected($('#arrival:visible, #arrivalS:visible').val());
					} else if(daysApart() > 30) {
						$('#arrival:visible, #arrivalS:visible').attr('value', d.addDays(-29).asString());
						$('#arrival:visible, #arrivalS:visible').dpSetSelected($('#arrival:visible, #arrivalS:visible').val());
						jAlert('You have selected a period which is more that 30 days apart. Your dates have been auto corrected.');
					}
					$('#days_apart').html(daysApart());

					setCal();
					$('.calendar_fieldset').each(function() {
						addPrices(this);
					});
					if($('#arrival:visible, #arrivalS:visible').val() != '' && $('#departure:visible, #departureS:visible').val() != '') {
						unhide();
					}

				}
			}
		);
	});
});

/**
 * Receives a date string acceptable to Date(), and returns the supplied date
 * converted into the YYYY-MM-DD format.
 */
function formatDate(dateString) {
	var current_date_obj = new Date(dateString)
	var month, year, day;

	year = current_date_obj.getFullYear().toString();
	if(current_date_obj.getMonth() < 9) { // months start at 0
		month = '0' + (parseInt(current_date_obj.getMonth()) + 1);
	} else {
		month = (parseInt(current_date_obj.getMonth()) + 1);
	}

	if(current_date_obj.getDate().toString().length == 1) {
		day = '0' + current_date_obj.getDate().toString();
	} else {
		day = current_date_obj.getDate().toString();
	}

	return year + '-' + month + '-' + day;
}

/**
 * Cycles through all the calendars on the page, and completely re-builds the
 * calendar subset of the unavailable dates for rooms.
 */
function updateUnavailableDates() {
	// run through all the calendars, and build up dates
	var calendars = $('div.calendar');
	var added;
	var roomType;
	var maxInstance = $(calendars).length - 1;
	
	Acm['unavailabilities']['calendar'] = [];

//	console.clear();
//	console.log('re-building calendar unavailabilities...');
//	console.log('using maximum instance count of ' + maxInstance);
//	console.log('-----------------------------------------------------');

	$(calendars).each(function() {
		var calendar = this;
		var i = $(calendar).data('calendarIndex');
		var nextInstance = 0;
		roomType = $(calendar).parent().find('select.room-type-select:eq(0)').val();
		
		while(i < maxInstance) {
			nextInstance = i + 1;
			added = 0;

//			console.log('cycling through calendar ' + $(calendar).data('calendarIndex') + '[nextInstance='+ nextInstance +']');

			if(typeof Acm['unavailabilities']['calendar'][nextInstance] == 'undefined') {
				Acm['unavailabilities']['calendar'][nextInstance] = [];
			}

			if(typeof Acm['unavailabilities']['calendar'][nextInstance][roomType] == 'undefined') {
				Acm['unavailabilities']['calendar'][nextInstance][roomType] = [];
			}

			$('table tr td.selected', calendar).each(function() {
				var date = formatDate($('span.date', this).html());

				if(!Acm['unavailabilities']['calendar'][nextInstance][roomType].has(date)) {
//					console.log('adding unique date ' + date + ' to "Acm[unavailabilities][calendar][' + nextInstance + ']['+ roomType +']"');
//					added++;
					Acm['unavailabilities']['calendar'][nextInstance][roomType].push(date);
				}
			});

//			console.log('added ' + added + ' unavailable dates to calendar with instance ' + nextInstance + ' and room id of ' + roomType);
			i++;
		}
	});

//	console.log(' ');
//	console.log('processing fully-booked sashes');
//	console.log('-----------------------------------------------------');
	$(calendars).each(function() {
//		console.log('processing sashes for calendar indexed ' + $(this).data('calendarIndex') + '. processing ' + $(this).find('table tr td').length + ' table cells');
		var roomType = $(this).parent().find('select.room-type-select:eq(0)').val();
		flagFullyBookedBulk($(this).find('table tr td'), roomType);
	});
}


var Holidays = new Array();
Holidays[0] = new Array();
Holidays[0]['date'] = '2009-11-21';
Holidays[0]['name'] = 'Liam\'s Birthday';
Holidays[1] = new Array();
Holidays[1]['date'] = '2009-11-25';
Holidays[1]['name'] = 'Shantal\'s Birthday';
Holidays[2] = new Array();
Holidays[2]['date'] = '2009-12-16';
Holidays[2]['name'] = 'Day of Reconciliation';
Holidays[3] = new Array();
Holidays[3]['date'] = '2009-12-25';
Holidays[3]['name'] = 'Christmas Day';
Holidays[4] = new Array();
Holidays[4]['date'] = '2009-12-26';
Holidays[4]['name'] = 'Day of Goodwill';
Holidays[5] = new Array();
Holidays[5]['date'] = '2010-1-1';
Holidays[5]['name'] = 'New Year\'s Day';
Holidays[6] = new Array();
Holidays[6]['date'] = '2010-3-21';
Holidays[6]['name'] = 'Human Rights Day';
Holidays[7] = new Array();
Holidays[7]['date'] = '2010-3-22';
Holidays[7]['name'] = 'Public holiday';
Holidays[8] = new Array();
Holidays[8]['date'] = '2010-4-2';
Holidays[8]['name'] = 'Good Friday';
Holidays[9] = new Array();
Holidays[9]['date'] = '2010-4-5';
Holidays[9]['name'] = 'Family Day';
Holidays[10] = new Array();
Holidays[10]['date'] = '2010-4-27';
Holidays[10]['name'] = 'Freedom Day';
Holidays[11] = new Array();
Holidays[11]['date'] = '2010-5-01';
Holidays[11]['name'] = 'Workers Day';
Holidays[12] = new Array();
Holidays[12]['date'] = '2010-6-16';
Holidays[12]['name'] = ' 	Youth Day';
Holidays[13] = new Array();
Holidays[13]['date'] = '2010-8-9';
Holidays[13]['name'] = 'National Women\'s Day';
Holidays[14] = new Array();
Holidays[14]['date'] = '2010-9-24';
Holidays[14]['name'] = 'Heritage Day';
Holidays[15] = new Array();
Holidays[15]['date'] = '2010-12-16';
Holidays[15]['name'] = 'Day of Reconciliation';
Holidays[16] = new Array();
Holidays[16]['date'] = '2010-12-25';
Holidays[16]['name'] = 'Christmas Day';
Holidays[17] = new Array();
Holidays[17]['date'] = '2010-12-26';
Holidays[17]['name'] = 'Day of Goodwill';
Holidays[18] = new Array();
Holidays[18]['date'] = '2010-12-27';
Holidays[18]['name'] = 'Public holiday';

