var showLoadingImage = function() {
	$("#searchErrorMsg").text("").hide();
	$("#availabilitySearchForm .submit_button").hide();
	$("#searchingLoader").show();
}

function getWeekday(strDate) {
	dp = strDate.split("-");
	d = new Date();
	d.setFullYear(dp[0],dp[1]-1,dp[2]);
	wdays=new Array(7);
	wdays[0]="Sun";
	wdays[1]="Mon";
	wdays[2]="Tue";
	wdays[3]="Wed";
	wdays[4]="Thu";
	wdays[5]="Fri";
	wdays[6]="Sat";
	return(wdays[d.getDay()]);
}

var showSearchBoxForm = function() {
	$("#searchBoxForm").fadeIn("slow");
}

function poundAmount(Num) {
dec = Num.indexOf(".");
end = ((dec > -1) ? "" + Num.substring(dec,Num.length) : ".00");
Num = "" + parseInt(Num);
var temp1 = "";
var temp2 = "";
//if (checkNum(Num) == 0) {
//alert("This does not appear to be a valid number.  Please try again.");
//}
//else { 
if (end.length == 2) end += "0";
if (end.length == 1) end += "00";
if (end == "") end += ".00";
var count = 0;
for (var k = Num.length-1; k >= 0; k--) {
var oneChar = Num.charAt(k);
if (count == 3) {
temp1 += ",";
temp1 += oneChar;
count = 1;
continue;
}
else {
temp1 += oneChar;
count ++;
}
}
for (var k = temp1.length-1; k >= 0; k--) {
var oneChar = temp1.charAt(k);
temp2 += oneChar;
}
temp2 = "£" + temp2 + end;
return temp2;
//}
}

function showSearchAlternatives() {
	$("#showSearchAlternativesLink").hide();
	$("#alternativeSearchResultsContainer").show();
	$("#noSearchResultsHeading").html("Alternative Search Results").css("color","#30559C");
}

function validateVipCode() {

	var vipCode = $("#vipCode").val();

	if(vipCode == '') {
		alert('Please enter a valid code');
	}
	else {
		var subtotal = parseFloat($("#subtotal").html().replace(/,/g,''));
		var online_discount = parseFloat($("#internetdiscountPrice").html());
		var totalPrice = parseFloat($("#totalPrice").html().replace(/,/g,''));
		var vip_discount = ((subtotal+online_discount)*0.11);
		$("#internetdiscountPrice").html(vip_discount.toFixed(2));
		$("#internetdiscountText").html("VIP Discount");
		subtotal = (subtotal+online_discount-vip_discount);
		$("#subtotal").html(subtotal.toFixed(2));
		totalPrice = (totalPrice+online_discount-vip_discount);
		$("#totalPrice").html(totalPrice.toFixed(2));
		$("#balancePrice").html(totalPrice.toFixed(2));
		$("#hiddenBalance").val(totalPrice.toFixed(2));
		$("#availabilitySearch_bookingForm_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.');
	}
}

var varStartTS = 0;
var varEndTS = 0;

function showWeek(startTS,endTS,id,duration,type,accommodation,unit_type,hol_type) {

//	$("#availabilityLoadingOverlay").fadeIn("slow");
//	$("#availabilityLoadingOverlay_iframe").fadeIn("slow");

//	$("#availabilityLoadingOverlay").ajaxSend(function(){
//		$(this).fadeIn("slow");
//	});

	$("#availabilityLoadingOverlay_iframe").ajaxSend(function(){
		$(this).fadeIn("slow");
	});

	if(varEndTS == 0)
		varEndTS = endTS;

	if(varStartTS == 0)
		varStartTS = startTS;

	var results = $.ajax({
					type: "GET",
					url: "/acms/modules/acms_availabilitySearch/client/ajax.php",
					data: "action=showWeek&startTS="+varStartTS+"&endTS="+varEndTS+"&id="+id+"&type="+type+"&duration="+duration+"&accommodation="+accommodation+"&unit_type="+unit_type+"&hol_type="+hol_type,
					async: false
				}).responseText.split("|");

	varStartTS = results[0];
	varEndTS = results[1];

	$("#availabilityBookingTable").html(results[2]);
	
	$(".book_now_button:disabled").css({color:"#909090",cursor:"default"});
	
	$("#availabilityLoadingOverlay").fadeOut("slow");
	$("#availabilityLoadingOverlay_iframe").fadeOut("slow");

}

function oc(a)
{
  var o = {};
  for(var i=0;i<a.length;i++)
  {
    o[a[i]]='';
  }
  return o;
}

$(document).ready(function() {

	$("select[name='availabilitySearch_bookingForm_num_children']").change(function() {

		$num_adults = $("select[name='availabilitySearch_bookingForm_num_adults']").val();
		$num_children = $(this).val();
		$num_unitMaxPer = $("#unitMaxPer").val();
		
		$num_people_total = parseInt($num_adults) + parseInt($num_children);
		
		if($num_people_total > $num_unitMaxPer) {
			$("#availabilitySearch_bookingForm_submit_button").attr("disabled","disabled");
			alert("Please ensure the number of adults and children does not exceed the number of people your chosen accommodation can sleep");
			$("#bookingForm_holidayParty_Error").show();
			$("#availabilitySearch_bookingForm_submit_button").before("<p id=\"bookingForm_submit_Error\" style=\"margin:0 !important;padding-right:5px;text-align:right;color:#C70101;font-weight:bold;background-color:#fff;\">Please correct the errors on your form before continuing</p>");
		}
		else {
			$("#availabilitySearch_bookingForm_submit_button").removeAttr("disabled");
			$("#bookingForm_holidayParty_Error").hide();
			$("#bookingForm_submit_Error").hide();
		}
						   
   });

	$("select[name='availabilitySearch_bookingForm_num_adults']").change(function() {
						   
		$num_adults = $(this).val();
		$num_children = $("select[name='availabilitySearch_bookingForm_num_children']").val();
		$num_unitMaxPer = $("#unitMaxPer").val();
		
		$num_people_total = parseInt($num_adults) + parseInt($num_children);
		
		if($num_people_total > $num_unitMaxPer) {
			$("#availabilitySearch_bookingForm_submit_button").attr("disabled","disabled");
			alert("Please ensure the number of adults and children does not exceed the number of people your chosen accommodation can sleep");
			$("#bookingForm_holidayParty_Error").show();
			$("#availabilitySearch_bookingForm_submit_button").before("<p id=\"bookingForm_submit_Error\" style=\"margin:0 !important;padding-right:5px;text-align:right;color:#C70101;font-weight:bold;background-color:#fff;\">Please correct the errors on your form before continuing</p>");
		}
		else {
			$("#availabilitySearch_bookingForm_submit_button").removeAttr("disabled");
			$("#bookingForm_holidayParty_Error").hide();
			$("#bookingForm_submit_Error").remove();
		}
						   
   });

	$("#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();
		}
	
	});

	$(".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));

	});

	$("#availabilitySearchForm_hol_type").change(function () {

		var holType = $(this).val();

		var results = $.ajax({
						type: "GET",
						url: "/acms/modules/acms_availabilitySearch/client/ajax.php",
						data: "action=updateSearchFields&hol_type="+holType,
						async: false
					}).responseText.split("|");
		
		$("#availabilitySearchForm_park option").each(function(i){
			$(this).removeAttr("disabled");
			$(this).removeAttr("selected");
		});

		$("#availabilitySearchForm_num_people option").each(function(i){
			$(this).removeAttr("disabled");
			$(this).removeAttr("selected");
		});

		if($("#availabilitySearchForm_num_people option:first").val() == "")
			$("#availabilitySearchForm_num_people option:first").remove();
//		$("#availabilitySearchForm_accommodation option").each(function(i){
//			$(this).removeAttr("disabled");
//			$(this).removeAttr("selected");
//		});
		
		$("#availabilitySearchForm_park option").each(function(i){
			var val = $(this).val();
			if(val != '') {
				if(val in oc(results)) {
					$(this).attr("disabled","disabled");
				}
			}
		});

		if(holType == 'TENTS_TOURING') {
//			$("#availabilitySearchForm_accommodation option").each(function(i){
//				$(this).attr("disabled","disabled");
//			});
//			$("#availabilitySearchForm_accommodation").prepend("<option value=\"\">Any</option>");
//			$("#availabilitySearchForm_num_people option").each(function(i){
//				$(this).attr("disabled","disabled");
//			});

			$("#start_date_TENTS_TOURING").show();
			$("#start_date_SELF_CATERING").hide();
			
			var tt_id = $("#start_date_TENTS_TOURING select").attr("id").replace(/_TENTS_TOURING/,'');
			var tt_name = $("#start_date_TENTS_TOURING select").attr("name").replace(/_TENTS_TOURING/,'');
			
			var sc_id = $("#start_date_SELF_CATERING select").attr("id");
			var sc_name = $("#start_date_SELF_CATERING select").attr("name");
			
			$("#start_date_SELF_CATERING select").attr("id",sc_id+"_SELF_CATERING");
			$("#start_date_SELF_CATERING select").attr("name",sc_name+"_SELF_CATERING");
			
			$("#start_date_TENTS_TOURING select").attr("id",tt_id);
			$("#start_date_TENTS_TOURING select").attr("name",tt_name);
			
			$("#availabilitySearchForm_num_nights").empty();
			$("#availabilitySearchForm_num_nights").append("<option value=\"\">- - please select - -</option>");
			for(var x=1; x<22; x++) {
				if(x < 2) { var nightStr = 'night'; }
				else { var nightStr = 'nights'; }
				$("#availabilitySearchForm_num_nights").append("<option value=\""+x+"\">"+x+" "+nightStr+"</option>");
			}
			
			$("#start_date_TENTS_TOURING select").find('option:first').attr('selected', 'selected').parent('select');
		}
		else {
			$("#availabilitySearchForm_num_nights").empty();
			$("#availabilitySearchForm_num_nights").append("<option value=\"\">- - please select - -</option>");
			$("#availabilitySearchForm_num_nights").append("<option value=\"3\">3 nights</option>");
			$("#availabilitySearchForm_num_nights").append("<option value=\"4\">4 nights</option>");
			$("#availabilitySearchForm_num_nights").append("<option value=\"7\">7 nights</option>");
			$("#availabilitySearchForm_num_nights").append("<option value=\"14\">14 nights</option>");
			$("#availabilitySearchForm_num_nights").append("<option value=\"21\">21 nights</option>");

			$("#start_date_TENTS_TOURING").hide();
			$("#start_date_SELF_CATERING").show();

			var sc_id = $("#start_date_SELF_CATERING select").attr("id").replace(/_SELF_CATERING/,'');
			var sc_name = $("#start_date_SELF_CATERING select").attr("name").replace(/_SELF_CATERING/,'');
			
			var tt_id = $("#start_date_TENTS_TOURING select").attr("id");
			var tt_name = $("#start_date_TENTS_TOURING select").attr("name");
			
			$("#start_date_TENTS_TOURING select").attr("id",tt_id+"_TENTS_TOURING");
			$("#start_date_TENTS_TOURING select").attr("name",tt_name+"_TENTS_TOURING");
			
			$("#start_date_SELF_CATERING select").attr("id",sc_id);
			$("#start_date_SELF_CATERING select").attr("name",sc_name);
			
			$("#start_date_SELF_CATERING select").find('option:first').attr('selected', 'selected').parent('select');
		}
		
		$('select').each(function(){
			this.rejectDisabled = function(){
				if (this.options[this.selectedIndex].disabled){
					if (this.lastSelectedIndex) {
						this.selectedIndex = this.lastSelectedIndex;
					} else {
						var first_enabled = $(this).children('option:not(:disabled)').get(0);
						this.selectedIndex = first_enabled ? first_enabled.index : 0;
					}
				} else {
					this.lastSelectedIndex = this.selectedIndex;
				}
			};
			this.rejectDisabled();
			this.lastSelectedIndex = this.selectedIndex;
			$(this).children().each(function(){
				$(this).css('color', '#30559C');
			});
			$(this).children('option[disabled]').each(function(){
				$(this).css('color', '#CCC');
			});
			$(this).change(function() {
				this.rejectDisabled();
			});
		});
		
//		if(jQuery.browser.msie == true && jQuery.browser.version == '6.0') { ativaOptionsDisabled(); }
	});

	$("#availabilitySearchForm_start_date").change(function () {

		var startdate = $(this).val();

		var results = $.ajax({
						type: "GET",
						url: "/acms/modules/acms_availabilitySearch/client/ajax.php",
						data: "action=updateSearchFields&startdate="+startdate,
						async: false
					}).responseText.split("|");
		
		if($("#availabilitySearchForm_hol_type").val() != 'TENTS_TOURING') {
			$("#availabilitySearchForm_num_nights option").each(function(i){
				var val = $(this).val();
				if(val != '') {
					if(val in oc(results)) {
						$(this).removeAttr("disabled");
					}
					else {
						$(this).attr("disabled","disabled");
					}
				}
			});
		}
		
		$('select').each(function(){
			this.rejectDisabled = function(){
				if (this.options[this.selectedIndex].disabled){
					if (this.lastSelectedIndex) {
						this.selectedIndex = this.lastSelectedIndex;
					} else {
						var first_enabled = $(this).children('option:not(:disabled)').get(0);
						this.selectedIndex = first_enabled ? first_enabled.index : 0;
					}
				} else {
					this.lastSelectedIndex = this.selectedIndex;
				}
			};
			this.rejectDisabled();
			this.lastSelectedIndex = this.selectedIndex;
			$(this).children().each(function(){
				$(this).css('color', '#30559C');
			});
			$(this).children('option[disabled]').each(function(){
				$(this).css('color', '#CCC');
			});
			$(this).change(function() {
				this.rejectDisabled();
			});
		});
	
	});

	$("#availabilitySearchForm_park").change(function () {

		var park = $(this).val();

		var results = $.ajax({
						type: "GET",
						url: "/acms/modules/acms_availabilitySearch/client/ajax.php",
						data: "action=updateSearchFields&park="+park,
						async: false
					}).responseText.split("_JF_");
		
//		var accommodation = results[0].split("|");
		var people = results[1].split("|");
		
//		$("#availabilitySearchForm_accommodation option").each(function(i){
//			$(this).removeAttr("disabled");
//			$(this).removeAttr("selected");
//		});
		
		$("#availabilitySearchForm_num_people option").each(function(i){
			$(this).removeAttr("disabled");
			$(this).removeAttr("selected");
		});
		
//		$("#availabilitySearchForm_accommodation option").each(function(i){
//			var val = $(this).val();
//			if(val in oc(accommodation)) {
//				$(this).attr("disabled","disabled");
//			}
//		});

//		if($("#availabilitySearchForm_hol_type").val() != 'TENTS_TOURING') {
//			var selected = false;
//			$("#availabilitySearchForm_num_people option").each(function(i){
//				var val = $(this).val();
//				if(val in oc(people)) {
//					$(this).attr("disabled","disabled");
//				}
//				else {
//					if(selected == false) {
//						$(this).attr("selected","selected");
//						selected = true;
//					}
//				}
//			});
//		}
		
		$('select').each(function(){
			this.rejectDisabled = function(){
				if (this.options[this.selectedIndex].disabled){
					if (this.lastSelectedIndex) {
						this.selectedIndex = this.lastSelectedIndex;
					} else {
						var first_enabled = $(this).children('option:not(:disabled)').get(0);
						this.selectedIndex = first_enabled ? first_enabled.index : 0;
					}
				} else {
					this.lastSelectedIndex = this.selectedIndex;
				}
			};
			this.rejectDisabled();
			this.lastSelectedIndex = this.selectedIndex;
			$(this).children().each(function(){
				$(this).css('color', '#30559C');
			});
			$(this).children('option[disabled]').each(function(){
				$(this).css('color', '#CCC');
			});
			$(this).change(function() {
				this.rejectDisabled();
			});
		});
//		ativaOptionsDisabled();
	});

/*
	$("#availabilitySearchForm_accommodation").change(function () {

		var accommodation = $(this).val();
		var park = $("#availabilitySearchForm_park").val();
		
		var results = $.ajax({
						type: "GET",
						url: "/acms/modules/acms_availabilitySearch/client/ajax.php",
						data: "action=updateSearchFields&loc="+park+"&accommodation="+accommodation,
						async: false
					}).responseText.split("|");

		$("#availabilitySearchForm_num_people option").each(function(i){
			$(this).removeAttr("disabled");
			$(this).removeAttr("selected");
		});

		var selected = false;
		$("#availabilitySearchForm_num_people option").each(function(i){
			var val = $(this).val();
			if(val in oc(results)) {
				$(this).attr("disabled","disabled");
			}
			else {
				if(selected == false) {
					$(this).attr("selected","selected");
					selected = true;
				}
			}
		});
//		ativaOptionsDisabled();
	});
*/
	$("#availabilitySearchForm").submit(function() {

		if($("#availabilitySearchForm_start_date").val() == "") {

			$("#searchErrorMsg").text("Please select start date").fadeIn("slow");
			return false;

		}
		else if($("#availabilitySearchForm_num_nights").val() == "") {

			$("#searchErrorMsg").text("Please select duration").fadeIn("slow");
			return false;

		}
		else if($("#availabilitySearchForm_num_nights").val() == "3") {

			weekday = getWeekday($("#availabilitySearchForm_start_date").val());
			
			if($("#availabilitySearchForm_hol_type").val() == 'SELF_CATERING') {
				if(weekday != 'Fri') {
					$("#searchErrorMsg").text("Please select a Friday start date for a 3 night short break").fadeIn("slow");
					return false;
				}
				else {
					setTimeout(showLoadingImage, 250);
					return true;
				}
			}
			else {
				setTimeout(showLoadingImage, 250);
				return true;
			}
		}
		else if($("#availabilitySearchForm_num_nights").val() == "4") {
			
			weekday = getWeekday($("#availabilitySearchForm_start_date").val());
			
			if($("#availabilitySearchForm_hol_type").val() == 'SELF_CATERING') {
				if(weekday != 'Mon') {
					$("#searchErrorMsg").html("Please select a Monday start date for a 4 night short break").fadeIn("slow");
					return false;
				}
				else {
					setTimeout(showLoadingImage, 250);
					return true;
				}
			}
			else {
				setTimeout(showLoadingImage, 250);
				return true;
			}
		}
		else {

			setTimeout(showLoadingImage, 250);
			return true;

		}
		
	});

	$("#availabilitySearch_bookingForm_fieldset_DisabledAccess").hide();

	$("#bookingPartyDisabledAccessCheckbox").click(function () {
		$("#availabilitySearch_bookingForm_fieldset_DisabledAccess").toggle();
		$("#availabilitySearch_bookingForm_fieldset_YourDetails").toggle();
		$("input[value='Next']").toggle();
	});

	$(".book_now_button:disabled").css({color:"#909090",cursor:"default"});

//	$(".availability_people_select").attr("disabled","disabled").css({color:"#909090"});

	$(".availability_people_select").each(function() {
		if($(this).val() == "") {
			$(this).attr("disabled","disabled").css({color:"#909090"});
		}
	});

	$(".availability_people_select").livequery('change', function(event) {

		var people = $(this).val();
		var start_date = $(this).parent().parent().parent().parent().parent().children("input[name='availabilitySearch_bookingForm_arrival_date']").val();
		var unit_id = $(this).parent().parent().parent().parent().parent().children("input[name='unit_type']").val();
		if(!unit_id)
			unit_id = $(this).parent().parent().parent().parent().parent().children("input[name='availabilitySearchForm_unit_type']").val();
		var duration = $(this).parent().parent().parent().parent().parent().children("input[name='temp_duration']").val();
		var locno = $(this).parent().parent().parent().parent().parent().children("input[name='availabilitySearchForm_park']").val();
		
		$(this).parent().parent().children("td:nth-child(4)").children("span[class='book_now_price']").html("");
		
		if(people != "") {
			$(this).parent().parent().children("td:nth-child(4)").children("span[class='book_now_price']").html("Finding<br />price...");

			var price = $.ajax({
							type: "GET",
							url: "/acms/modules/acms_availabilitySearch/client/ajax.php",
							data: "action=getAvailabilitySelectPrice&start_date="+start_date+"&duration="+duration+"&unit_id="+unit_id+"&people="+people,
							async: false
						}).responseText;
			
			$(this).parent().parent().children("td:nth-child(4)").children("span[class='book_now_price']").html(price);
			$(this).parent().parent().children("td:last").children("input[class='book_now_button']").removeAttr("disabled");
			$(this).parent().parent().children("td:last").children("input[class='book_now_button']").css({color:"#CC3300",cursor:"pointer"});
		}
	});

	$(".availability_search_select").livequery('change', function(event) {

		var duration = $(this).val();
		var people = $(this).parent().parent().children("td").children("select[name='availabilitySearch_bookingForm_num_people']").val();

		$(this).parent().parent().parent().parent().parent().children("input[name='temp_duration']").val(duration);

		$(".availability_search_select").each(function() {
			$(this).attr("selectedIndex","0");
			$(this).parent().parent().children("td:nth-child(4)").children("span[class='book_now_price']").html("");
			$(this).parent().parent().children("td:last").children("input[class='book_now_button']").attr("disabled","disabled");
		});

		if(people != "") {
			if(duration != "") {
				$(this).parent().parent().children("td:nth-child(4)").children("span[class='book_now_price']").html("Finding<br />price...");
			}
		}

		$(".book_now_button").attr("disabled","disabled").css({color:"#909090",cursor:"default"});

		$(".availability_people_select").each(function() {
			$(this).attr("selectedIndex","0");
		});

		$(".availability_people_select").attr("disabled","disabled").css({color:"#909090"});

		$(".availability_search_select").parent().parent().parent().each(function() {
			$(this).children("tr").removeClass("selected");
		});

		$(this).parent().parent().addClass("selected");

		$(this).children("option[value='"+duration+"']").attr("selected","selected");
		
		$(this).parent().parent().children("td").children("select[name='availabilitySearch_bookingForm_num_people']").children("option[value='"+people+"']").attr("selected","selected");
		
		$(this).parent().parent().children("td").children("select[name='availabilitySearch_bookingForm_num_people']").removeAttr("disabled").css({color:"#393B94"});
		
		if(people != "") {
			if(duration != "") {
				var start_date = $(this).parent().parent().parent().parent().parent().children("input[name='availabilitySearch_bookingForm_arrival_date']").val();
				var unit_id = $(this).parent().parent().parent().parent().parent().children("input[name='unit_type']").val();
				if(!unit_id)
					unit_id = $(this).parent().parent().parent().parent().parent().children("input[name='availabilitySearchForm_unit_type']").val();
				var locno = $(this).parent().parent().parent().parent().parent().children("input[name='availabilitySearchForm_park']").val();
		
				var price = $.ajax({
								type: "GET",
								url: "/acms/modules/acms_availabilitySearch/client/ajax.php",
								data: "action=getAvailabilitySelectPrice&start_date="+start_date+"&duration="+duration+"&unit_id="+unit_id+"&people="+people,
								async: false
							}).responseText;
				
				$(this).parent().parent().children("td:nth-child(4)").children("span[class='book_now_price']").html(price);
				$(this).parent().parent().children("td:last").children("input[class='book_now_button']").removeAttr("disabled");
				$(this).parent().parent().children("td:last").children("input[class='book_now_button']").css({color:"#CC3300",cursor:"pointer"});
			}
		}

	});

});
