// JavaScript Document
$(function(){
	//change days when month dropdown is changed
	$(".datePicker .dpMonth").change(function(){
		var y = $(this).next().val();
		var m = $(this).val();
		var d = $(this).prev().val();
		$(this).prev().replaceWith(populateDays(m,y,d));
	});	
	//change days when year dropdown is changed (check for leap years)
	$(".datePicker .dpYear").change(function(){
		var y = $(this).val();
		var m = $(this).prev().val();
		var d = $(this).prev().prev().val();
		$(this).prev().prev().replaceWith(populateDays(m,y,d));
	});	
	//respond to button click
	$(".avForm input:button").click(function(){
		var url = "http://www.globalavailability.com/art/guests/";
		var str = "?";
		var id = $(this).attr("id");
		var dd = padTo2($(this).parent().find(".dpDay").val());
		var mm = padTo2($(this).parent().find(".dpMonth").val());
		var yyyy = $(this).parent().find(".dpYear").val();
		var rn = $(this).parent().find(".noNights").val();
		//check that date selected is later than today's date
		var today = new Date();
		var early = false;
		if(today.getFullYear() == $(this).parent().find(".dpYear").val()){
			if(today.getMonth() + 1 > $(this).parent().find(".dpMonth").val()){
				early = true;
			}else if(today.getMonth() + 1 == $(this).parent().find(".dpMonth").val()){
				if(today.getDate() > $(this).parent().find(".dpDay").val()){
					early = true;	
				}
			}
		}
		//alert if date is before today, or build url string and redirect to availability page
		if(early){
			alert("Sorry, you cannot check for a vacancy before today. Please try again.");
		}else{
			prop_id = id.split("_");
			str += "pid="+prop_id[1];
			str += "&referrer=38";
			str += "&iframe=1";
			str += "&availability=show";
			str += "&dd="+dd;
			str += "&mm="+mm;
			str += "&yyyy="+yyyy;
			str += "&requirednights="+rn;
			str += "#";
			url += str;
			window.location.href = url;
		}
	});
});
function padTo2(number){
	var no = number.toString();
	if(no.length < 2){
		no = "0"+no;	
	}
	return no;
}
function monthDays(month, year){
	//determines days in month
	var d;
	switch(month){
		case "Jan":
		case "Mar":
		case "May":
		case "Jul":
		case "Aug":
		case "Oct":
		case "Dec":
		d = 31;
		break;
		
		case "Apr":
		case "Jun":
		case "Sep":
		case "Nov":
		d = 30;
		break;
		
		case "Feb":
		year%4 == 0?d = 29: d = 28;
		break;
		
		default:
		d = 31;
	}
	return d;
}
function populateDays(month, year, day){
	//refresh day list
	var d, s;
	var md = monthDays(month, year);
	var dh = "<select class='dpDay'>\n";
	for(d=1;d<=md;d++){
		d == day?s="selected='selected'":s="";
		dh += "<option value='"+padTo2(d)+"' "+s+">"+d+"</option>\n";
	}
	dh += "</select>";
	return dh;
}
