/*jslint browser: true */
/*global $, jQuery, window, google, alert, console, unescape*/

// this is loaded after the form HTML is written


// G uses document.write to load scripts, which makes the page go white
// if the DOM is already loaded. Also doesn't work in XHTML
// lets hop this doesn't break anything
/*document.write = function(str) {
	jQuery('head').append(str);
	//(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild($(str)[0]);
};*/


var autocomplete_locations = [],
	jp_active = false,
	bad_form_fields = 0,
	towns = ['Bournemouth', 'Poole', 'Christchurch', 'Dorset'];



function show_loading_screen() {
	setTimeout(function() {

		$('body').prepend(
			'<div class="overlay">'
			+ '<div id="loading-screen"><img src="/wp-content/themes/yellowbuses-child/images/clock-load.gif" alt="Please Wait..." /></div>'
			+ '</div>'
		);
		/*
		if ($.browser.webkit) {
			// no idea why chrome needs this to load the image

			setTimeout(function() {
				$('#loading-screen img')
					.attr('src', $('#loading-screen img').attr('src'));

				$('#loading-screen').css({background: 'url(/wp-content/themes/yellowbuses-child/images/loading-screen-bg-2.jpg)'})
					.height(304)
					.width(615);
			}, 100);

			// this still doesn't work
		}
		*/
	}, 0);
}


$(function() {

//google.load("jqueryui", "1.8.7");

(function($) {

	$('.page-template-template-journeyplanner #access .current_page_parent').removeClass('current_page_parent');
	$('.page-template-template-journeyplanner #menu-item-3680').addClass('current-menu-item');

	var $jp_form = $('#journey-planner-full-form');

	if ($().datepicker) {
		$('.datepicker', $jp_form).datepicker({
			//dateFormat: 'yy-mm-dd'
			dateFormat: 'dd/mm/yy',
			minDate: 0,
			maxDate: 30
		});
	}

}(jQuery));


if ($.browser.webkit) {
	window.preload_i = new Image(); window.preload_i.src = '/wp-content/themes/yellowbuses-child/images/clock-load.gif';
	window.preload_j = new Image(); window.preload_j.src = '/wp-content/themes/yellowbuses-child/images/loading-screen-bg.jpg';
}



jQuery.getScript('/foundation/autocomplete_locations');

//#journey-planner-form,

(function() {

	// if the previous search was a geosearch, use the same lat/lng as before

	var parts = location.search.replace('?', '').split('&'),
		lls = {},
		latlng_re = /^([+\-]?\d*\.\d+)(?![\-+0-9\.]), ?([+\-]?\d*\.\d+)(?![\-+0-9\.])$/;

	function get_ll(str) {
		return latlng_re.test(str) ? str : null;
	}

	parts = $.map(parts, function(p) {
		return p.split('=');
	});

	for (var i in parts) {

		if (typeof lls.to !== 'undefined' && typeof lls.from !== 'undefined') {
			break;
		}

		if (parts[i] === 'from' || parts[i] === 'to') {
			lls[parts[i]] = get_ll(unescape(parts[parseInt(i, 10) + 1]));
		}
	}

	if (lls.from) {
		$('#from').data('latlng', lls.from);
	}

	if (lls.to) {
		$('#to').data('latlng', lls.to);
	}

})();


jQuery('#journey-planner-full-form').powerGeoSearch({
	//activate: function() {
	//	$.getScript(site_root + '/ajax/all-stop-names');
	//},
	autocomplete: {
		delay: 0,
		source: function(request, response) {
			var matcher_start = new RegExp('(^)' + jQuery.ui.autocomplete.escapeRegex(request.term) + '.*', 'i'),
				matcher_word = new RegExp('([^a-zA-Z])' + jQuery.ui.autocomplete.escapeRegex(request.term) + '.*', 'i'),
				sort_by_length = function(a, b) {
					return a.length - b.length;
				},
				matches_start = jQuery.map(autocomplete_locations, function(value ) {
					return matcher_start.test(value) ? value.replace('&amp;', '&') : null;
				}).sort(sort_by_length),
				matches_word = jQuery.map(autocomplete_locations, function(value ) {
					return matcher_word.test(value) ? value.replace('&amp;', '&') : null;
				}).sort(sort_by_length);

			response(matches_start.concat(matches_word).slice(0, 20));
		}
	},
	appendQuery: ['Bournemouth', 'Poole', 'Christchurch', 'Dorset'],
	bounds: [[50.633348784855336, -2.1196746826171875], [50.85147463352982, -1.6033172607421875]],
	logError: function(msg) {
		if (window.console && console.log) {
			console.log(msg);
		}
	},


	getOutput: function() {
		// called in context of input field
		var msg = 'Please choose a matching location from the list below:';

		if (jQuery(this).parent().next().is('.suggestion-container')) {
			return jQuery(this).parent().next();
		}

		return jQuery(
			'<div style="display:none" class="suggestion-container">'
				+ '<em>' + msg + '</em>'
				+ '<div class="additional-options">'
					+ '<div class="additional-options-top"></div>'
					+ '<div class="fieldContainer">'
						+ '<select></select>'
					+ '</div>'
					+ '<div class="additional-options-bottom"></div>'
				+ '</div>'
			+ '</div>'
		).insertAfter(jQuery(this).parent());

	},
	preTestValues: function(val) {
		// guess which browser *still* doesn't have an Array.indexOf method...
		var i;

		if (val.match(/^[A-Z][A-Z]?[0-9][0-9]?[A-Z]? [0-9]?[A-Z]?[A-Z]?$/i)) {
			// post code
			return true;
		}

		//if(!Array.prototype.indexOf){
		for (i = 0; i < autocomplete_locations.length; i++) {
			if (autocomplete_locations[i].toLowerCase() === val.toLowerCase()) {
				return true;
			}
		}
		return false;
		//}

		//return autocomplete_locations.indexOf(val) !== -1;
	},
	submit: function() {
		show_loading_screen();
			/*$('#journey-planner-full-form').after(
				'<div class="jp-load">Please wait while we process your request</div>'
				'<div class="jp-load">Please wait while we process your request</div>'
			);*/
	},
	resultsComplete: function(config) {
		var options = $('option', config.getOutput.call(this));

		$(this).next('.message-error').remove();

		if ($(this).val() === '') {
			config.hideOutput.call(this);
			$('<div class="message-error">Please enter a search term.</a>').insertAfter(this).show();
			return;
		}

		if (options.length === 0) {
			config.hideOutput.call(this);
			$('<div class="message-error">Your search term was not found.</a>').insertAfter(this).show();
		} else {
			// populate the input field
			$(options).parent().trigger('change');

			if (options.length === 1) {
				// only 1 googl result so we assume google is right
				config.bad_fields--;
				if (config.bad_fields === 0) {
					// the other field is "ok" so submit the form
					$('#journey-planner-full-form').submit();
				}
			}
		}

	}
});


});



$(function() {
	$('.different-times a').click(function() {
		show_loading_screen();
	});
});




