var d;
var ds;
var PROTECT_CLASS = "protected";
var PROTECT_TIMEOUT = 100;

$(document).ready(function() {
	
	$('#step-nav li:has(a)').hover(
		function(){ $(this).addClass('hover') },
		function(){ $(this).removeClass('hover') }
	);
	
	$('#cheaper_price, #change_booking').click(function(){
		alert('Coming soon');
	});
	
	if (typeof(pickupTime) != 'undefined') {
		if (pickupTime != "") {
			$("#pick-up-time").val(pickupTime);
		} else {
			$("#pick-up-time").val("10:00AM");
		}
	}
	if (typeof(dropoffTime) != 'undefined') {
		if (dropoffTime != "") {
			$("#drop-off-time").val(dropoffTime);
		} else {
			$("#drop-off-time").val("10:00AM");
		}
	}
	
	/* autocomplete */
	var cache = {},lastXhr;
	
	$("#pick_up_location").click(function(){
		$(this).autocomplete('search','');
	});
	
	$("#pick_up_location").autocomplete({
		selectFirst: true,
		source: function( request, response ) {
			var term = request.term;
			if ( term in cache ) {
				response( cache[ term ] );
				return;
			}
			lastXhr = $.getJSON("/autocomplete/master_locations/"+request.term, {}, function( data, status, xhr ) {
				cache[ term ] = data;
				if ( xhr === lastXhr ) {
					response( data );
				}
			});
		},
		minLength: 0,
		select: function( event, ui ) {
			this.value = ui.item.label;
			$("#pickup_code").val(ui.item.value);
			
			if ( $("#dropoff_code").val().length == 0 )
			{
				$("#drop_off_location").val(ui.item.label);
				$("#dropoff_code").val(ui.item.value);
			}
			$("#drop_off_location").effect('highlight', 500);
			$("#drop_off_location").trigger('change');
			
			$("#pick_up_location").siblings('.popup').remove();
			return false;
		}
	});
	
	$("#pickup_location_id").change(function(){
		$("#dropoff_location_id").val($("#pickup_location_id").val());
	});
	
	$("#pick-up-time").change(function(){
		$("#drop-off-time").val($("#pick-up-time").val());
		$("#drop-off-time").effect('highlight', 500);
		$("#drop-off-time").change();
	});
	
	$("#drop-off-time").change(function(){
		$(".faq-container .popup, .step-container .popup").hide();
		if ($("#pick-up-date").val() == '' || $("#drop-off-date").val() == '') return false;
		if ($("#pick-up-time").val() == '' || $("#drop-off-time").val() == '') return false;
		
		var dod = $("#drop-off-date").val().split('-');
		var pud = $("#pick-up-date").val().split('-');
		dod[0] = parseInt(dod[0],10);
		dod[1] = parseInt(dod[1],10);
		pud[0] = parseInt(pud[0],10);
		pud[1] = parseInt(pud[1],10);
		var dot = $('#drop-off-time').val().split(':');
		var put = $('#pick-up-time').val().split(':');
		  
		if (dot[1].substr(2,2)=='PM' && dot[0] != "12") dot[0] = parseInt(dot[0],10)+12;
		else if (dot[1].substr(2,2)=='AM' && dot[0] == "12") dot[0] = 0;
		else dot[0] = parseInt(dot[0],10);
		dot[1] = parseInt(dot[1].substr(0,2),10);
		  
		if (put[1].substr(2,2)=='PM' && put[0] != "12") put[0] = parseInt(put[0],10)+12;
		else if (put[1].substr(2,2)=='AM' && put[0] == "12") put[0] = 0;
		else put[0] = parseInt(put[0],10);
		
		put[1] = parseInt(put[1].substr(0,2),10);
		
		pickup = new Date();
		pickup.setYear(parseInt(pud[2],10));
		pickup.setDate(parseInt(pud[0],10));
		pickup.setMonth(parseInt(pud[1],10) - 1);
		pickup.setHours(put[0]);
		pickup.setMinutes(put[1]);
		// console.log(pickup);
		
		dropoff = new Date();
		dropoff.setYear(parseInt(dod[2],10));
		dropoff.setDate(parseInt(dod[0],10));
		dropoff.setMonth(parseInt(dod[1],10) - 1);
		dropoff.setHours(dot[0]);
		dropoff.setMinutes(dot[1]);
		// console.log(dropoff);		
		
	});
	
	
	$("#drop_off_location").click(function(){
		$(this).autocomplete('search','');
	});
	
	$("#drop_off_location").autocomplete({
		selectFirst: true,
		source: function( request, response ) {
			var term = request.term;
			if ( term in cache ) {
				response( cache[ term ] );
				return;
			}
			lastXhr = $.getJSON("/autocomplete/master_locations/"+request.term, {}, function( data, status, xhr ) {
				cache[ term ] = data;
				if ( xhr === lastXhr ) {
					response( data );
				}
			});
		},
		minLength: 0,
		select: function( event, ui ) {
			this.value = ui.item.label;
			
			$("#drop_off_location").val(ui.item.label);
			$("#dropoff_code").val(ui.item.value);
			
			$("#drop_off_location").effect('highlight', 500);
			$("#drop_off_location").trigger('change');
			
			$("#drop_off_location").siblings('.popup').remove();
			return false;
		}
	});
	
	
	$.datepicker.setDefaults( $.datepicker.regional[ "" ] );
	$('#pick-up-date, #drop-off-date').datepicker({
		dateFormat: 'yy-mm-dd',
		minDate: '+1d',
		maxDate: '+1y',
		numberOfMonths: 2,
		showAnim: 'fadeIn',
		onSelect:function(){
			this.fireEvent && this.fireEvent('onchange') || $(this).change();
		}
	});
	
	
	$('#pick-up-date').datepicker('option', 'onSelect', function() {

		// dropoff date must be after pickup
		var pickup_date = $(this).datepicker('getDate');
		$('#drop-off-date').datepicker('option', 'minDate', pickup_date );

		var date = $('#pick-up-date').val();
		if ( date.length > 0)
		{
			// default dropoff date is +1w from pickup
			//alert(pickup_date);
			var dropoff_date = new Date;
			dropoff_date.setFullYear( pickup_date.getFullYear() );
			dropoff_date.setMonth( pickup_date.getMonth() );
			dropoff_date.setDate( pickup_date.getDate() + 7 );
			//alert(dropoff_date);
			$("#drop-off-date").datepicker("setDate", dropoff_date );
		}

		$("#pick-up-date").effect('highlight', 500);
		//$("#pick-up-time").focus();
		$("#drop-off-date").effect('highlight', 500);
	});

	$('.pick-up-date, #pick-up-date-icon').click(function() {
		$('#pick-up-date').datepicker('show');
	});

	$('#drop-off-date').datepicker('option', 'onSelect', function() {
		$("#drop-off-date").effect('highlight', 500);
		//$("#drop-off-time").focus();
	});
	$('.drop-off-date, #drop-off-date-icon').click(function() {
		$('#drop-off-date').datepicker('show');
	});
	
	/*
	$("#live-in").click(function(){
		if ($("#live-in").val() == '') {
			$("#live-in").val('New Zealand');
			//$("#live-in").focus();
			$("#live-in").select();
		}
	});
	
	if(typeof(countryNames) != 'undefined') {
		$("#live-in").autocomplete({
			source: countryNames,
			selectFirst: true,
			minLength: 0
		});
	}
	*/
	
	$("#compare").click(function() {
		
		$.getJSON("/autocomplete/master_locations", {}, function(locationNames) {
			
			locationLabels = [];
			locationIDs = [];
			$.each(locationNames, function(){
				locationLabels.push(this['label']);
				locationIDs.push(this['value']);
			});

			if (jQuery.inArray($('#pick_up_location').val(), locationLabels) == -1) {
				$('#pick_up_location').val("");
			}
			if (jQuery.inArray($('#drop_off_location').val(), locationLabels) == -1) {
				$('#drop_off_location').val("");
			}
			if (jQuery.inArray($('#pickup_code').val(), locationIDs) == -1) {
				$('#pick_up_location, #pickup_code').val("");
			}
			if (jQuery.inArray($('#dropoff_code').val(), locationIDs) == -1) {
				$('#drop_off_location, #dropoff_code').val("");
			}
			/*
			if (jQuery.inArray($('#live-in').val(), countryNames) == -1) {
				$('#live-in').val("");
			}
			*/
			if (
				error_field('#pick_up_location', 'Please enter a pickup location')
				&& error_field('#drop_off_location', 'Please enter a dropoff location')
				&& error_field('#pick-up-date', 'Please enter a pickup date')
				&& error_field('#pick-up-time', 'Please enter a pickup time')
				&& error_field('#drop-off-date', 'Please enter a dropoff date')
				&& error_field('#drop-off-time', 'Please enter a dropoff time')
				&& error_field('#no_of_sleeping_passengers', 'Please select no of sleeping passengers')
				&& error_field('#live-in', 'Please enter your country')
				&& validate_pickup_dropoff_time()
			) {
				$("#resform").submit();  
			}
		});
		
		return false;
	});
	
	function error_field(selector, tip) {
		
		// iframe widget only
		if (selector == '#pick_up_location' && $('#pickup_location_id').val() != undefined )
		{
			selector = '#pickup_location_id';
		}
		if (selector == '#drop_off_location' && $('#dropoff_location_id').val() != undefined )
		{
			selector = '#dropoff_location_id';
		}
		
		
		if ($(selector).val() == '') {
			$(selector).addClass('error_border').effect("pulsate", { times:2 }, 1000);
			if (selector == '#no_of_sleeping_passengers') {
				$('#no_of_sleeping_passengers').after('<span class="error_message">'+tip+'</span>');
			} else {
				$(selector).after('<span class="error_message">'+tip+'</span>');
			}
			$(selector).focus();
			
			return false;
		}
		else
		{
			$(selector).removeClass('error_border');
			$(selector).siblings('.error_message').remove();
		}
		
		return true;
	}
	
	function validate_pickup_dropoff_time() {
		if ($('#drop-off-time').val() == $('#pick-up-time').val() && $('#drop-off-date').val() == $('#pick-up-date').val()) {
			$('#drop-off-time').effect('highlight', {}, 1500);
			$('#drop-off-time').after('<span class="popup">You have selected the same pickup date and time for drop off. Please enter a valid pick up and drop off time.</span>');
			$('#drop-off-time').focus();
			// $('#std').addClass(PROTECT_CLASS).hide().css({
			// 	top: $('#drop-off-time').offset().top + 5,
			// 	left: $('#drop-off-time').offset().left + $('#drop-off-time').width(),
			// 	position: 'absolute',
			// 	display: 'block'
			// }).show('fadeIn');
			// setTimeout(function(){
			// 	$("#std").removeClass(PROTECT_CLASS);
			// },PROTECT_TIMEOUT);
			return false;
		} 
		return true;
	}
	
	$('#age_group_toggle').click(function(){
		$('#age_group').show();
		$('#o25').hide();
		return false;
	});
	
	//$('#pick_up_location').focus();
	
	function navigate(e) {  
		if(e && e.keyCode && e.keyCode == 13) $("#compare").click();
	}
	document.onkeypress=navigate;
	
});

function pop_up_window(page_url,w,h) {
	var left = (screen.width/2)-(w/2);
	var top = (screen.height/2)-(h/2);
	window.open(page_url,'','toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width='+w+', height='+h+', top='+top+', left='+left);
}
