/**
*	Search on 'TODO', to see parts of the form that need
*	updating as part of Jasmine integration
*
*/

/*
	TODO: get this data from somewhere real

	For the form to work without Javascript, all these hotels will be passed in as select options anyway,
	so it may be an idea to parse the select and drop the hotels into this data object
*/
var data = ("London Leicester Cheltenham Cambridge Cantabury Lincoln").split(" ");

var BOOKING_PANEL_HEIGHT = 440;

var regFormErrors = new Array();

/*
	TODO: add further messages
*/
/*
var regFormMessages = [
	"Please indicate which hotel you're interested in", // hotel field error
	"Please check your selected dates, as you can't stay for less than 1 night" //check-in/check-out validity check
]; */

//var viewBtn 		= "#ViewProperty_CheckAvailabilityForm";
var searchBox 		= "#SearchHotelOrLandmark_CheckAvailabilityForm";
var hotelList		= "#SelectHotel_CheckAvailabilityForm";


function matchLayoutWithContent() {

	var crTop = $('#contentRight').css('top');
	var top = parseInt(crTop.substring(0, crTop.length - 2),10);
	top += 20;
	
	if($('#hero img').length > 0)
		$('#layoutRight').height($('#contentRight').height() + top);

	if(isIE6) {
		if(top < -300) {
			var margin = -($('#layoutRight').height() - ($('#contentRight').height() + top));
			$('#layoutRight').css('margin-bottom', margin);
		}
	}
}
	
var hasHeroImage 	= false;
// start it all up here	
$(function() {
	
	if($('#hero img').length > 0) {
		hasHeroImage = true;
	} else {
		$('#bookingPanel').css('margin-bottom', 0);
	}
	setUpForm();
	$("#regForm form").submit(validateBookingForm);
	
	matchLayoutWithContent();
	
	//added script to override GT script - overflowing right column content
	if($('#hero img').length > 0)
	$("#layoutRight").height($("#layoutRight").height() + 46);
	//else
	//$("#layoutRight").css("height", $("#layoutFooter").offset().top - 85);
});

function setUpForm() {
	$('#layoutRight').css("position","relative"); //for z-index issue on google location map
	if(hasHeroImage) {$('#bookingPanel').css('height', BOOKING_PANEL_HEIGHT);}
	if(!bookingPanelIsFixed) {
		$('#regForm-header').click(
			
			
			function() {
			
				if(formIsOpen) {
					formIsOpen = false;
					if(hasHeroImage) {$('#bookingPanel').css('height', BOOKING_PANEL_HEIGHT);}
					$('#regForm-bottom').hide();
					$('#regForm').slideUp("normal", toggleRegFormTabs);
					$('#bookingPanel').css('z-index', '1');
					$('#layoutRight').css("z-index","1"); //for z-index issue on google location map

				} else {
					$('#bookingPanel').css('z-index', '999');
					formIsOpen = true;
					$('#regForm-tabs').slideDown("fast", toggleRegForm);
					$('#regForm-reset').slideUp("fast");
					$('#layoutRight').css("z-index","200"); //for z-index issue on google location map
				}			
				if($(this).css('background-position') == '-1px 0px') {
					$(this).css('background-position', '-1px -56px');
				} else {
					$(this).css('background-position', '-1px 0px');
				}
			}
		);
		$('#regForm-header').mouseover(
			function() {
				if(formIsOpen) {
					$(this).css('background-position', '-1px -168px');
				} else {
					$(this).css('background-position', '-1px -112px');
				}
			}
		);
		$('#regForm-header').mouseout(
			function() {
				if(formIsOpen) {
					$(this).css('background-position', '-1px -56px');
				} else {
					$(this).css('background-position', '-1px 0px');
				}
			}
		);
		$('#regForm-header').css('cursor', 'pointer');
	}	
	// capture reset button click and reset number of rooms 
	// displayed in order to hide extra room fields
	$('#regForm-reset input').click(
		function() {
			//$('#roomsfield select').val(1); // tanto
			//$('#roomsfield select').change(); // tanto
			$("#noOfNights").text("");
			panelNumRooms = 1;
			return true;
		}
	);
	
	//hide 'update' button for rooms and put click onto select
	$('#updatefield input').hide();
	//anthony $('#roomsfield select').change(addRemoveRooms);
	
	if(!isIE6) {
		// only show this line if Javascript is enabled to update it
		
        try {
		$("'<p class='small' style='margin-bottom:6px;'>"+jasmineTranslate("HBS/NoOfNights","No. of nights")+": <span id='noOfNights'></span></p>").insertAfter(".roomReq ol");
        }
        catch(e) {  
        }
		//$("'<p class='small' style='margin-bottom:6px;'>No. of nights: <span id='noOfNights'></span></p>").insertAfter(".dates ol");
		// replace dropdowns with text inputs
		//$('#checkinol').html('<label for="CheckInDate_CheckAvailabilityForm">Check-in: </label><input type="text" class="ghostcontent" id="CheckInDate_CheckAvailabilityForm" />');
		//$('#checkoutol').html('<label for="CheckOutDate_CheckAvailabilityForm">Check-out:</label><input type="text" class="ghostcontent" id="CheckOutDate_CheckAvailabilityForm" />');

		// add datepickers
		var props = {
			showOn: 'both',
			buttonImage: '/media/images/themes/forms/date_picker_logo.gif',
			buttonImageOnly: true,
			dateFormat:'dd/mm/yy',
			onSelect:updateNumberOfNights,
			minDate:0,
			changeFirstDay:false,
			firstDay:1,			
			hideIfNoPrevNext:true
		};
		//$(".dates input").datepicker(props); //should point to specific to avoid conflict
		try {
			$("#CheckInDate_CheckAvailabilityForm").datepicker(props);
			$("#CheckOutDate_CheckAvailabilityForm").datepicker(props);
		}
		catch(e) {  }
	}
	
	// add form tabs
	$('#regForm-header').after('<div id="regForm-tabs"><span>Search</span><a href="">Hotel list</a></div>');
	
	// set first click up to change to autoComplete
	$('#regForm-tabs a').click(showAutoComplete);
	
	showAutoComplete();
	
	// a few form fields have guide content ('type here...') which should be a lighter shade
	// when the fields receive focus, though, the content should be removed, and the text color darkened
	//class changed from ghostcontent to SearchHotelOrLandmark
	$('.ghostcontent').css('color', '#B3B4B4');
	$('.ghostcontent').focus(
		function() {
			$(this).css('color', '#000000');
			
			if($(this).attr('id') != 'SearchHotelOrLandmark_CheckAvailabilityForm') {
				$(this).val('');
				return;
			}
			//N.B if the input field's default value changes, the next line needs to change too!
			if($(this).val() == "e.g. London") {
				$(this).val('');
			}
		}
	);
	
	if(bookingPanelIsClosed != undefined) {
		if(bookingPanelIsClosed) {
			$('#regForm-header').css('background-position', '-1px 0px');
			$('#regForm').hide();
			$('#regForm-tabs').hide();
		} else {
			$('#regForm-reset').hide();
			$('#regForm-bottom').show();
		}
	} else {
		$('#regForm-reset').hide();
	}
}

// fired by changing the value of the rooms dropdown
function addRemoveRooms() {
	var ROOM_FIELDSET_HEIGHT = 57;
	var newNumRooms = $('#roomsfield select').val();
	var currentNumRooms = $('.roomdetailsgroup').length;
	var snippet = $('#room1').clone();
	
	
	if(currentNumRooms > newNumRooms) {
		for(var i=currentNumRooms; i>newNumRooms; i--) {
			$('#room' + i).remove();
			$('#layoutRight').height($('#layoutRight').height() - ROOM_FIELDSET_HEIGHT);
		}
	} else {
		for(var i=currentNumRooms + 1; i<=newNumRooms; i++) {
			var node = snippet.clone();
			$(node).attr('id', 'room' + i);
			$('legend', node).text('Room ' + i);
			$('ol li.left label', node).attr('for', 'adults' + i);
			$('ol li.left select', node).attr('id', 'adults' + i);
			$('.childrenfield label', node).attr('for', 'children' + i);
			$('.childrenfield select', node).attr('id', 'children' + i);
			$('.infantfield label', node).attr('for', 'infants' + i);
			$('.infantfield select', node).attr('id', 'infants' + i);
			$('.cotfield label', node).attr('for', 'cot' + i);
			//$('.cotfield input', node).attr('id', 'cot' + i);
			$(node).insertAfter($('#room' + (i-1)));
		}
	}
	if(newNumRooms > 1) {
		$('fieldset.roomdetailsgroup').css('border-top', 'solid #757575 1px');
		$('legend.room').css('display', 'block');
		$('#bookingPanel').css('height', 'auto');
	} else {
		$('fieldset.roomdetailsgroup').css('border-top', 'none');
		$('legend.room').css('display', 'none');
		if(hasHeroImage) {$('#bookingPanel').css('height', BOOKING_PANEL_HEIGHT);}
	}
	matchLayoutWithContent();
}

// listens to changes in check-in/check-out pair
var NumberOfNightsHolder_CheckAvailabilityForm=1;
function updateNumberOfNights(dateText, datePicker) {
    var isStartDate=false;
    if(dateText==$('#CheckInDate_CheckAvailabilityForm').val())
        isStartDate=true;

	var checkin = new Date();
	var checkinStrArr = $('#CheckInDate_CheckAvailabilityForm').val().split("/");

    checkin.setDate("1");
    checkin.setYear(checkinStrArr[2]);	
    checkin.setMonth(parseInt(checkinStrArr[1],10)-1); // Force Decimal
	checkin.setDate(checkinStrArr[0]);

var checkout = new Date();
	var checkoutStrArr = $('#CheckOutDate_CheckAvailabilityForm').val().split("/");

    checkout.setDate("1");
    checkout.setYear(checkoutStrArr[2]);
    checkout.setMonth(parseInt(checkoutStrArr[1],10)-1);
    checkout.setDate(checkoutStrArr[0]);

	var result = Math.floor(((checkout - checkin) + (1000*60*60*12)) / (1000*60*60*24));
	if(isNaN(result)) {
		result = 0;
	} else if(result < 1) {
		showErrors(1, regFormMessages[1]);
		result = 0;
	}

    if(result > 0)
        {
        NumberOfNightsHolder_CheckAvailabilityForm=result;
        }
    else
        {
        var checkout = new Date(checkinStrArr[2],parseInt(checkinStrArr[1],10)-1,(parseInt(checkinStrArr[0],10)+NumberOfNightsHolder_CheckAvailabilityForm));
        result=NumberOfNightsHolder_CheckAvailabilityForm;
        var day = checkout.getDate();
        var month = checkout.getMonth()+1;
        var year = checkout.getFullYear();
        if(day < 10)
            day ="0"+day;
        if(month < 10)
            month ="0"+month;
        $('#CheckOutDate_CheckAvailabilityForm').val(day+"/"+month+"/"+year);            
        }

	$("#noOfNights").text(result);
}

// called by clicking on 'hotel list' tab
function showDropdown() {
	//TODO: add in all options for these 3 selects
	
	//Enable/Disable View Hotel button If a hotel is selected

	var str= $("#SelectHotel_CheckAvailabilityForm").val();
	str = str.substr(0,3);
	/*
	if($("#SelectHotel_CheckAvailabilityForm option:selected").val() == "" || str == "ALL") { 
		$(viewBtn).attr("disabled","disabled");
		$(viewBtn).css("background","url(/media/images/themes/forms/btn_check_availability_disabled.png) no-repeat");
		$(viewBtn).css("color","#d8d2ca");

	}
	else { 
		$(viewBtn).removeAttr("disabled"); 
		$(viewBtn).css("background","url(/media/images/themes/forms/btn_check_availability.png) no-repeat");
		$(viewBtn).css("color","#ffffff");
	}
	*/
	
	$("#searchfield_CheckAvailabilityForm").hide();
    $("#threeDDLfields_CheckAvailabilityForm").show();
    $("#SearchOrList_CheckAvailabilityForm").val("List");
   
	$('#regForm-tabs').css('background-position', '-2px -24px');
	var txt = $('#regForm-tabs span').text();
	$('#regForm-tabs span').replaceWith('<a href="#">' + txt + '</a>');
	txt = $('#regForm-tabs a:last').text();
	$('#regForm-tabs a:last').replaceWith('<span>' + txt + '</span>');
	$('#regForm-tabs a').click(showAutoComplete);
	
	$('#bookingPanel').css('height', 'auto');// Bring back when multi-room function is enabled
	
	if(hasHeroImage)
	$('#bookingPanel').css('height',BOOKING_PANEL_HEIGHT);
	
	matchLayoutWithContent();
	return false;
}

// called by clicking on 'search'
function showAutoComplete(){
	//will trigger View Hotel Button Logic
	//$(searchBox).trigger("blur");
							
    $("#searchfield_CheckAvailabilityForm").show();
    $("#threeDDLfields_CheckAvailabilityForm").hide();
    $("#SearchOrList_CheckAvailabilityForm").val("Search");
   
	//try {
	//$('#SearchHotelOrLandmark_CheckAvailabilityForm').autocomplete(data);	
	//}
	//catch(e) {}
	
	$('#regForm-tabs').css('background-position', '-2px 0px');
	var txt = $('#regForm-tabs span').text();
	$('#regForm-tabs span').replaceWith('<a href="#">' + txt + '</a>');
	txt = $('#regForm-tabs a:first').text();
	$('#regForm-tabs a:first').replaceWith('<span>' + txt + '</span>');
	$('#regForm-tabs a').click(showDropdown);
	
	
	if($('#roomsfield select').val() == 1 && hasHeroImage) {
		$('#bookingPanel').css('height', BOOKING_PANEL_HEIGHT);
	} 
	matchLayoutWithContent();
	return false;
	
	
}

// called by clicking on form header
function toggleRegForm() {
	toggleRightHeight();	
	$('#regForm').slideToggle("normal", 
		function() {
			$('#regForm-bottom').show();
			matchLayoutWithContent();
		}
	);			
}

// called by clicking on form header
function toggleRegFormTabs() {
	$('#regForm-tabs').slideToggle("fast", 
		function() {
			toggleRightHeight();
		}
	);
	$('#regForm-reset').slideToggle("fast");			
}


/*
	If a user selects 9 rooms, the right-hand column should expand to hold the expanded form.
	If the user closes the form panel, the column should reduce back down.
	If the user reopens the panel, it should show the 9 rooms again, and expand the right-hand
	column to facilitate that.

		  * * * * * * * * * * * *
	Enter * toggleRightHeight() *
		  * * * * * * * * * * * *
*/
var panelNumRooms = 1;
function toggleRightHeight() {
	if(!formIsOpen) {
		panelNumRooms = $('#roomsfield select').val();
		//$('#roomsfield select').val(1); // tanto
	} else {
		//$('#roomsfield select').val(panelNumRooms);
	}
	//anthony addRemoveRooms();
}

function showErrors(section, message) {
	var error;
	for(var i=0; i<regFormErrors.length; i++) {
		error = regFormErrors[i];
		$('#regForm fieldset').eq(error.section).prepend('<li class="error">' + error.message + '</li>');
		$('#regForm fieldset.submit').prepend('<li class="error">' + error.message + '</li>');
	}
	if(regFormErrors.length > 0 ) {
		$('li.error').css('display', 'block');
	}
}

/*
	TODO: add further validation checks, if you need them
*/
function validateBookingForm() {
	regFormErrors = new Array();
	
	//clear previous error messages
	$('li.error').css('display', 'none');
	$('li.error').remove();
	
	//mandatory fields that require values: SearchHotelOrLandmark_CheckAvailabilityForm, checkin, checkout
	if($('#SearchHotelOrLandmark_CheckAvailabilityForm').val() == "" || $('#SearchHotelOrLandmark_CheckAvailabilityForm').val() == "e.g. London" || $('#SearchHotelOrLandmark_CheckAvailabilityForm').val() == "Select a hotel") {
		//N.B. 'section' refers to the fieldset that the error's in, as the message will be displayed at the top of that fieldset
		// it's a zero-based array, section:0 refers to the first fieldset, which holds the SearchHotelOrLandmark_CheckAvailabilityForm input
		regFormErrors.push({section:0, message:regFormMessages[0]});
	}
	testDates();	
	
	showErrors();
	
	// return true/false to allow/prevent form submission
	if(regFormErrors.length > 0 ) {
		return false;
	}
	return true;
	
}




function testDates() {
	var checkin = new Date();
	var checkinStrArr = $('#CheckInDate_CheckAvailabilityForm').val().split("/");
    checkin.setDate("1");	
    checkin.setYear(checkinStrArr[2]);
    checkin.setMonth(checkinStrArr[1]);
    checkin.setDate(checkinStrArr[0]);
	var checkout = new Date();
	var checkoutStrArr = $('#CheckOutDate_CheckAvailabilityForm').val().split("/");

    checkout.setDate("1");
	checkout.setYear(checkoutStrArr[2]);
    checkout.setMonth(checkoutStrArr[1]);
    checkout.setDate(checkoutStrArr[0]);

	var result = Math.floor((checkout - checkin) / (1000*60*60*24));
	if(isNaN(result) || (result < 1)) {
		regFormErrors.push({section:1, message:"Please check your selected dates, as you can't stay for less than 1 night"});
	}
}
