$(function() {
	/* approximate validate routes against this regex
	 */
	var	routeRegex = /^[A-Z]{0,2}\d{1,3}$/ig,
			routePrefix = 'bus-';

	$('#date-button').hide();
	$('#offset').change(function() {
		$('#date-select').submit();
	});

	$('#main-content').addClass("js-version");

	/* don't add the form if there are no results
	 */
	if ($(".disrupted-route").length == 0) return;

	/* add form
	 */
	$(".short-form").prepend("<label for='line'>Bus route <span>e.g. N74</span></label><input name='line' type='text' id='line' title='Enter route number...' class='route-number' size='16' /> <input name='Submit' type='submit' class='button-default-1 check-route-number' value='Check for disruptions' title='Check for disruptions' disabled='disabled' />");

	/* add "no disruptions" hidden message
	 */
	$("<h2 class='no-disruptions'>There are currently no relevant disruptions or this is not a valid route</h2>").hide().insertAfter(".short-form");

	/* add 'show all' link 
	 */
	$(".disrupted-routes-results").after("<p class='clear linklist'><a href='#' class='show-all-routes'>Show all disrupted routes</a></p>");

	/* show route map links and search box since scripts enabled
	 */
	$(".show-route-map, .short-form").show();

	$(".show-all-routes").click(function() {
		$(".no-disruptions").hide();
		$(".disrupted-route").show();
		return false;
	});

	/* create behaviour for button click
	 */
	$(".check-route-number").click(function() {
		var	me = $(this).siblings(".route-number"), val = me.val(),
				cleanedValue = val.toUpperCase().replace(/\s+/g, ""),
				matches = cleanedValue.match(routeRegex);
		if (matches != null) {
			$(".no-disruptions").toggle($(".disrupted-route").hide().find("#" + routePrefix + matches).parent().show().length == 0);
			me.val(cleanedValue);
		} else if (val == "") $(".disrupted-route").hide();
		else $(".no-disruptions").toggle($(".disrupted-route").hide().length > 0);
		me.focus();
		return false;
	}).submit(function() { return false; }).attr("disabled", "");

	/* re-use button click behaviour for maintenance
	 */
	$(".route-number").bind("change keyup paste", function() {
		$(".check-route-number").click();
	});

	/* use behaviours when passed in as a #route-number param
	 */
	var hash = (location.hash || "").replace("#" + routePrefix, "").toUpperCase(), textbox = $(".route-number");
	if (routeRegex.test(hash)) textbox.val(hash);
	textbox.keyup();
});
