function pad(number, length) { var str = '' + number; while (str.length < length) { str = '0' + str; } return str; }
function substr(str, start, len) { str += ''; var end = str.length; if (start < 0) { start += end; } end = typeof len === 'undefined' ? end : (len < 0 ? len + end : len + start); return start >= str.length || start < 0 || start > end ? !1 : str.slice(start, end); }

function hide_estimated_price(){
	$('#availability_footer').css('display', 'none');
	if($('#availability_footer_help').length == 0){
		$('#availability_footer').after('<div id="availability_footer_help"><p>Select a date to see the price estimate.</p></div>');
	}
	$('#bookNowButton').css('display', 'none');
}

function show_estimated_price(prices){
	$('#availability_footer').css('display', 'block');
	$('#availability_footer_help').remove();
	if(prices['qav'] < 2) {
		$('.limited_availability_msg').css('display', 'block');
		$('#bookNowButton').css('display', 'none');
	}
	else {
		$('.limited_availability_msg').css('display', 'none');
                $('#bookNowButton').css('display', 'block');
        }
}

function show_hide_book_button(){
	
	var now = new Date();
	var y = now.getFullYear();
	var m = now.getMonth() + 1;
	m = (m < 10 ? '0' + m : m);
	var d = now.getDate();
	d = (d < 10 ? '0' + d : d);
	
	var sel_date = $('#hiddenStartDate').val();
	var cur_date = y + '-' + m + '-' + d;
	
	console.dir({
		sel_date: sel_date,
		cur_date: cur_date
	});
	
	if(sel_date <= cur_date){
		$('#bookNowButton').css({display: 'none'});
}
	else{
		$('#bookNowButton').css({display: 'block'});
	}
}

function set_estimated_price(prices){
	$("#selectedPrice").html('&pound;' + prices['pay_price']);
	show_estimated_price(prices);
}

function check_next_avail(bui, duration){
	api("john_fowler_availability", "_model", "get_next_available_date_for_unit", [bui, duration], function(response){
		if(response != null){
			$('.next_avail').remove();
			
			var a = $('<input />').attr({
				href: 'javascript:;',
				id: 'bookNowButton',
				rel: bui+'|'+duration+'|'+response,
				type: 'button'
			}).addClass('next_avail').click(function(){
				var t = $(this),
					rel = t.attr('rel').split('|'),
					duration = rel[1],
					bui = rel[0],
					start_date = rel[2];
				api("john_fowler_availability", "_view", "render_availability_calendar", [start_date, duration, bui], function(html){
					$("#availabilityCalendarContainer").html(html).find('span.available:first a').click();
					$('.next_avail').remove();
				});
			}).val('View next holiday');
			
			$('#availability_footer_help').append(a);
		}
		else {
			$('.next_avail').remove();
		}
	})
}

$(function(){
	var durations = new Array();
	
	// Postcode stuff... 
	if($('#bookingFormStep1').length){
		var t = $(this),
			country = t.find('select.country'),
			postcode = t.find('input.postcode'),
			postcode_label = t.find('label.postcode_label');
			
		if(country.val() != 'GB'){
			postcode_label.find('span').hide();
		}
		else {
			postcode_label.find('span').show();
		}
		
		country.change(function(){
			country = $(this);
			
			if(country.val() != '' && country.val() != 'GB'){
				postcode_label.find('span').hide();
			}
			else {
				postcode_label.find('span').show();
			}
		})
	}
	
	// Booking form brochure stuff.. 
	if($('#bookingFormStep2').length){
		$('#bookingFormStep2').submit(function(){
			var t = $(this),
				sel = t.find('select[name="source_code_general"]');
				
			if(sel.is(':visible') && sel.val() == ''){
				if($('#booking_tc').is(":checked")){
					alert('Please let us know how you found us');
				}
				
				$('#sourceSelector').find('p').css('color', 'red');
				
				return false;
			}
			else {
				$('#sourceSelector').find('p').css('color', '#325690');
			}
		})
	}

	$('#selectedDuration option').each(function(){
		if($(this).val().length){
			durations[durations.length] = $(this).val();
		}
	})
	
	if(durations.length){
		var bui = $('#hiddenBui').val();
		api("john_fowler_availability", "_model", "get_next_available_dates_for_unit_by_duration", [bui, durations], function(response){
			var len = durations.length;
			
			for (var i=0; i<len; ++i){
				if(!(durations[i] in response)){
					$('#selectedDuration option[value="'+durations[i]+'"]').remove();
				}
			}
		})
	}
	
	if($("#hiddenStartDate").length > 0 && $("#hiddenStartDate").val() != '') {
		var start_date_split = $("#hiddenStartDate").val().split("-");
		var current_date = parseInt(start_date_split[2]);
		current_month = parseInt(start_date_split[1].replace(/^0+/,''));
		current_year = parseInt(start_date_split[0]);
		
		var duration = parseInt($('#selectedDuration').val());
		
		var start_date_obj = new Date();
		start_date_obj.setUTCFullYear(current_year);
		start_date_obj.setUTCMonth(current_month - 1);
		start_date_obj.setUTCDate(current_date);
		
		var start_ts = start_date_obj.getTime();
		
		for(var i = start_ts; i <= start_ts + (duration * 86400000); i += 86400000){
			
			var i_date = new Date();
			i_date.setTime(i);
			
			var i_year = i_date.getFullYear();
			var i_month = (i_date.getMonth() + 1); i_month = (i_month < 10 ? '0' + i_month : i_month);
			var i_date = i_date.getDate(); i_date = (i_date < 10 ? '0' + i_date : i_date);
			
			var selector_date =  i_year + '-' + i_month + '-' + i_date;
			
			if(i == start_ts && $('#' + selector_date).hasClass('unavailable')){
				break;
			}
			
			$('#' + selector_date).addClass('selected');
		}
	}
	
	$("#monthAfterLink").live("click",function(){
		var start_date = $(this).parent().parent().find("div.right").find("table.calendar").attr("id")+'-01';
		var duration = $("#selectedDuration").val();
		var bui = $("#hiddenBui").val();
		api("john_fowler_availability", "_view", "render_availability_calendar", [start_date, duration, bui], function(html){
			$("#availabilityCalendarContainer").html(html);
		});
	});
	
	$("#monthBeforeLink").live("click",function(){
		year_month = $(this).parent().parent().find("div.left").find("table.calendar").attr("id").split("-");
		year = parseInt(year_month[0]);
		month = parseInt(year_month[1].replace(/^0+/,''))-1;
		var start_date = year+'-'+pad(month,2)+'-01';
		var duration = $("#selectedDuration").val();
		var bui = $("#hiddenBui").val();
		api("john_fowler_availability", "_view", "render_availability_calendar", [start_date, duration, bui], function(html){
			$("#availabilityCalendarContainer").html(html);
		});
	});
	
	$("#selectedDuration").change(function(){
		hide_estimated_price();
		
		var start_date = current_year+'-'+pad(current_month,2)+'-01';
		var duration = $(this).val();
		var bui = $("#hiddenBui").val();
		api("john_fowler_availability", "_view", "render_availability_calendar", [start_date, duration, bui], function(html){
			$("#availabilityCalendarContainer").html(html);
			check_next_avail(bui, duration);
		});
	});

	if($("#selectedPrice").length < 1) { $("#selectedDuration").change(); }

	$("#selectedNumPeople").change(function(){
		var start_date = current_year+'-'+pad(current_month,2)+'-'+pad(current_date,2);
		var duration = $("#selectedDuration").val();
		var bui = $("#hiddenBui").val();
		var num_people = $(this).val();
		var unit_type_id = $("#hiddenUnitTypeId").val();
		
		api("john_fowler_availability", "_model", "get_availability_price", [unit_type_id, start_date, duration, num_people], function(prices){
			if(prices['pay_price'] != '0.00'){
				set_estimated_price(prices);
			}
		});
	});
	
	$(".availabilityCalendarDate").live("click",function(){

		console.log('.availabilityCalendarDate click');
		
		var selected_date = $(this).parent().attr("id").split("-");
		var year = parseInt(selected_date[0],10);
		var month = parseInt(selected_date[1],10);
		var date = parseInt(selected_date[2],10);
		var num_people = $("#selectedNumPeople").val();		
		var duration =  $("#selectedDuration").val();
		var unit_type_id =  $("#hiddenUnitTypeId").val();
		var start_date = year + "-" + pad(month,2) + "-" + pad(date,2);
		
		$("table.calendar").find(".selected").removeClass('selected');

		$(this).parent().attr("class","selected");
		
		for(var i=0; i<duration; i++) {
			date += 1;
			var month_str = pad(month,2);
			var date_str = pad(date,2);
			id = year+"-"+month_str+"-"+date_str;
			if($("#"+id).length > 0) {
				$("#"+id).addClass('selected');
			}
			else {
				month += 1;
				if(month == 13) {
					month = 1;
					year += 1;
				}
				date = 1;
				var month_str = pad(month,2);
				var date_str = pad(date,2);
				id = year+"-"+month_str+"-"+date_str;
				$("#"+id).addClass('selected');
			}
		}
		
		$('#hiddenStartDate').val(start_date);
		$("#selectedStartDate").html(duration+" nights from "+selected_date[2]+"/"+selected_date[1]+"/"+substr(selected_date[0],2,2)+" for "+num_people+" "+(num_people == 1 ? 'person' : 'people'));
		
		show_hide_book_button();
		
		api("john_fowler_availability", "_model", "get_availability_price", [unit_type_id, start_date, duration, num_people], function(prices){
			set_estimated_price(prices);
		});

	});
	
	$("#disabledInfoBox").hide();

	$("#bookingPartyDisabledAccessCheckbox").click(function() {
		$("#disabledInfoBox").toggle();
		$("#fieldset_YourDetails").toggle();
		$("#proceedWithBookingButton").toggle();
	});

	$("#searchForm select[name='type']").change(function() {
		var search_type = $(this).val();
		api("john_fowler_availability", "_model", "get_start_dates", [], function(dates){
			var valid_dates = dates[search_type];
			$("#searchForm select[name='start_date']").empty();
			$("#searchForm select[name='start_date']").append('<option value="">Loading dates...</option>');
			$.each(valid_dates, function(key, value) {
				$("#searchForm select[name='start_date']").append('<option value="'+key+'">'+value+'</option>');
			});
			$("#searchForm select[name='start_date'] option:first").text('Select a Start Date...');
		});
		api("john_fowler_availability", "_model", "get_parks", [], function(parks){
			var valid_parks = parks[search_type];
			$("#searchForm select[name='park']").empty();
			$("#searchForm select[name='park']").append('<option value="">Loading dates...</option>');
			$.each(valid_parks, function(key, value) {
				$("#searchForm select[name='park']").append('<option value="'+key+'">'+value+'</option>');
			});
			$("#searchForm select[name='park'] option:first").text('Select a Park...');
		});
		$("#searchForm select[name='duration']").empty();
		$("#searchForm select[name='duration']").append('<option value="">Select a Duration...</option>');
		$("#searchForm select[name='duration']").append('<option value="">- select start date first -</option>');
	});
	
	$("#searchForm select[name='start_date']").change(function() {
		var search_type = $("#searchForm select[name='type']").val();
		var start_date = $(this).val();
		var start_date_str = start_date.replace(/-/g,'/');
		var dayOfWeek = new Array();
		dayOfWeek[0] = "Sun";
		dayOfWeek[1] = "Mon";
		dayOfWeek[2] = "Tue";
		dayOfWeek[3] = "Wed";
		dayOfWeek[4] = "Thu";
		dayOfWeek[5] = "Fri";
		dayOfWeek[6] = "Sat";
		var myDate = new Date(start_date_str);
		var day = dayOfWeek[myDate.getDay()];
		
		var y = myDate.getFullYear();
		var m = (myDate.getMonth() + 1);
		m = (m < 10 ? '0' + m : m);
		var d = myDate.getDate();
		d = (d < 10 ? '0' + d : d);
		var ymd = y + '-' + m + '-' + d;
		
		api("john_fowler_availability", "_model", "get_durations", [], function(durations){
			var valid_durations = durations[search_type];
			var src_date_durations = valid_durations[day];
			var date_durations = [];
			
			// Temp fix for dates/durations at the end of 2012
			for(var i in src_date_durations){
				var duration = src_date_durations[i];
				
//				if(ymd == '2012-10-27' && duration > 7) continue; 
//				if(ymd == '2012-10-29' && duration >= 7) continue; 
				
				date_durations.push(duration);
			}
			
			$("#searchForm select[name='duration']").empty();
			$("#searchForm select[name='duration']").append('<option value="">Loading durations...</option>');
			$.each(date_durations, function(key, value) {
				$("#searchForm select[name='duration']").append('<option value="'+value+'">'+value+' nights</option>');										 
			});
			$("#searchForm select[name='duration'] option:first").text('Select a Duration...');
		});														 
	});
	
	$("#searchForm").submit(function(){
		var start_date = $("#searchForm select[name='start_date']").val();
		var duration = $("#searchForm select[name='duration']").val();
		if(start_date == '') {
			if($("#searchStartDateError").length == 0){
				$("#searchForm select[name='start_date']").after("<div id=\"searchStartDateError\">Please select a start date</div>");
			}
			return false;
		}
		else {
			$("#searchStartDateError").remove();
		}
		if(duration == '') {
			if($('#searchDurationError').length == 0){
				$("#searchForm select[name='duration']").after("<div id=\"searchDurationError\">Please select a duration</div>");
			}
			return false;
		}
		else {
			$("#searchDurationError").remove();
		}
	});
	
	$(".optionalExtras").change(function () {
		var x = $(this).attr("id").split("_");
		var id = x[1];
		var amt = x[2];
		var val = parseFloat($("#optionalExtraPrice_"+id).html());
		var num = parseFloat($("#optionalExtraSelector_"+id+"_"+amt).val());
		var extraPrice = num*parseFloat(amt);
		var totalPrice = parseFloat($("#totalPrice").html().replace(/,/g,''));
		$("#optionalExtraPrice_"+id).html(extraPrice.toFixed(2));
		totalPrice = (totalPrice+extraPrice-val);
		$("#totalPrice").html(totalPrice.toFixed(2));
		$("#balancePrice").html(totalPrice.toFixed(2));
		$("#hiddenBalance").val(totalPrice.toFixed(2));
	});
	
	$("#editionCode").change(function () {
		var val = $(this).val();
		if(val == 'VX' || val == '2' || val == '3') {
			$("#sourceSelector").hide();
			$("#vipCodeInput").show();
		}
		else if(val != '') {
			$("#sourceSelector").hide();
			$("#vipCodeInput").hide();
		}
		else {
			$("#sourceSelector").show();
			$("#vipCodeInput").hide();
		}
	});
	
	$("#editionCode").change(function () {
		var val = $(this).val();
		if(val == 'VX' || val == '2' || val == '3') {
			$("#sourceSelector").hide();
			$("#vipCodeInput").show();
		}
		else if(val != '') {
			$("#sourceSelector").hide();
			$("#vipCodeInput").hide();
		}
		else {
			$("#sourceSelector").show();
			$("#vipCodeInput").hide();
		}
	});
	
	$("select[name='num_children']").change(function() {
		var num_adults = $("select[name='num_adults']").val();
		var num_children = $(this).val();
		var num_unitMaxPer = $("#unitMaxPer").val();
		var num_people_total = parseInt(num_adults) + parseInt(num_children);
		if(num_people_total > num_unitMaxPer) {
			alert("Please ensure the number of adults and children does not exceed the number of people your chosen accommodation can sleep");
		}
   });

	$("select[name='num_adults']").change(function() {
		var num_adults = $(this).val();
		var num_children = $("select[name='num_children']").val();
		var num_unitMaxPer = $("#unitMaxPer").val();
		var num_people_total = parseInt(num_adults) + parseInt(num_children);
		if(num_people_total > num_unitMaxPer) {
			alert("Please ensure the number of adults and children does not exceed the number of people your chosen accommodation can sleep");
		}
   });
	
	$("#bookingFormStep1").submit(function(){
		var num_adults = $("select[name='num_adults']").val();
		var num_children = $("select[name='num_children']").val();
		var num_unitMaxPer = $("#unitMaxPer").val();
		var num_people_total = parseInt(num_adults) + parseInt(num_children);
		if(num_people_total > num_unitMaxPer) {
			alert("Please ensure the number of adults and children does not exceed the number of people your chosen accommodation can sleep");
			return false;
		}
   });

});

function showSearchAlternatives() {
	$("#showSearchAlternativesLink").hide();
	$("#alternativeSearchResultsContainer").show();
	$("#noSearchResultsHeading").html("Alternative Search Results").css("color","#30559C");
	$("#noSearchResultsHeading").show();
	$("#noSearchResultsMsg").html("Apologies but an alternative search did not return available dates for this criteria within one week of search");
}

function validateVipCode() {
	var vipCode = $("#vipCode").val();
	if(vipCode == '') {
		alert('Please enter a valid code');
	}
	else {
		var subtotal_wrapper = $('#subtotal');
		
		var online_discount_label;
		if($('#online_discount_label').length){
			online_discount_label = $('#online_discount_label');
		}
		else{
			online_discount_label = $('th.costs_header:contains("Internet discount")');
			online_discount_label.attr('id', 'online_discount_label');
		}
		
		var online_discount_wrapper = online_discount_label.next();
		var totalPrice_wrapper = $('#totalPrice');
		
		var subtotal = subtotal_wrapper.html();
		subtotal = parseFloat( subtotal.replace(/[^0-9\.]/g,'') );
		
		var online_discount = online_discount_wrapper.html();
		online_discount = parseFloat( online_discount.replace(/[^0-9\.]/g,'') );
		
		var totalPrice = totalPrice_wrapper.html();
		totalPrice = parseFloat( totalPrice.replace(/[^0-9\.]/g,'') );
		
		var vip_discount = ((subtotal+online_discount)*0.11);
		
		online_discount_wrapper.html('&pound;' + vip_discount.toFixed(2));
		online_discount_label.html("VIP Discount");
		
		subtotal = (subtotal + online_discount - vip_discount);
		subtotal_wrapper.html('&pound;' + subtotal.toFixed(2));
		
		totalPrice = (totalPrice+online_discount-vip_discount);
		
		totalPrice_wrapper.html(totalPrice.toFixed(2));
		
		$("#balancePrice").html(totalPrice.toFixed(2));
		$("#hiddenBalance").val(totalPrice.toFixed(2));
		$("#scode").val("VX");
		var hiddenExtras = $("#hiddenExtras").val();
		$("#hiddenExtras").val(hiddenExtras+'|168/1/-'+(vip_discount-online_discount).toFixed(2));
		alert('Your VIP discount has been applied.');
	}
}

