var startDate;

$(document).ready(onLoad);

// once the document is loaded
function onLoad() {

	// default the date to today
	var now = new Date();

	var year = now.getYear();
	if (year < 2000) { 
		year = year + 1900; 
	}

	document.getElementById('year').value = year;
	document.getElementById('month').selectedIndex = now.getMonth();
	document.getElementById('day').selectedIndex = now.getDate() - 1;

	// hide the results for now
	$("#results").hide();
	
	// when the detect button is clicked or return is hit on any of the fields do stuff
	$("#calculate").click(calculateClicked);
	$("#month").keyup(function(e) { if (e.keyCode == 13) calculateClicked() });
	$("#day").keyup(function(e) { if (e.keyCode == 13) calculateClicked() });
	$("#year").keyup(function(e) { if (e.keyCode == 13) calculateClicked() });
	$("#days").keyup(function(e) { if (e.keyCode == 13) calculateClicked() });

}

// detect has been clicked
function calculateClicked() {

	// query the detector
	$.get("date-fu.php", { 
		year: $("#year").attr("value"), 
		month: $("#month").attr("value"), 
		day: $("#day").attr("value"),
		days: $("#days").attr("value")
	}, function(xml) { resultsRetrieved(xml) }, "xml");
}

// the requested detection XML has been received
function resultsRetrieved(xml) {

	// get the data from the XML
	root = $("date-fu", xml);
	inputDate = root.find("input-date").text();
	inputDays = root.find("input-days").text();
	outputDate = root.find("output-date").text();

	// set context of various nodes in the HTML
	$("#input-date").html(parseDate(inputDate).toDateString());
	$("#input-days").html(inputDays);
	$("#output-date").html(parseDate(outputDate).toDateString());

	// show the results div
	$("#results").show();
	$("#results-bottom").show();
}

function parseDate(date) {

	dateParts = date.split("-");
	year = dateParts[0];
	month = dateParts[1] - 1;
	day = dateParts[2];

	returnDate = new Date();
	returnDate.setFullYear(year, month, day);

	return returnDate;
}