$(function() {
	$('#contentMain #oneCol.home #search_submit').addClass('enabled');
	
	// Initialize the date picker
	// Date.firstDayOfWeek = 7; // Sets sunday as first day
	// 	var dtm=(new Date()).zeroTime().addYears(2).asString();
	// 	if (!($.browser.safari && $.browser.version < 500))
	// 	  $('#search_ride_date').datePicker({clickInput:true,createButton:false,endDate:dtm});
	$('#search_ride_date').datepicker({minDate:'0d',maxDate:'+1y',numberOfMonths:2});
	
	// Wire up more / less search results links
	$('#more_search_options_link').click(function(){
		// shows the more options div and turns on virt attr form_div
		// uncheck everything on the extended menu
		$('#search_more_options').toggle(true);
		$('#search_less_options').toggle(false);
		
		// $(":checkbox[id *= 'types_']").attr("checked", false);
		// for all checked boxes on short menu, check those boxes on the other menu
		$(":checkbox[id *= 'type_'][checked]").each(function(){
		  var values = $(this).attr('value').split(',');
		  jQuery.each(values , function(){
		    $(":checkbox[id *= 'types_'][value = "+this+"]").attr("checked", true);
		  });
		});
		
		$('#search_form_div').val('selected');
	});
	
	$('#less_search_options_link').click(function(){
		// shows the less options div and clears the virt attr form_div
		$('#search_less_options').toggle(true);
		$('#search_more_options').toggle(false);
		
		// for all checked boxes on short menu, check those boxes on the other menu
		$(":checkbox[id *= 'type_']").attr("checked", false);
		$(":checkbox[id *= 'types_'][checked]").each(function(){
		  $(":checkbox[id *= 'type_'][value *= "+$(this).attr('value')+"]").attr("checked", true);
		});
		
		$('#search_form_div').val('');
	});
	
	// Disable drop off times and locations for air/cruiseports, enable only for hourly
	$('#service_type').change(function(){
		// rules to set certain vehicle types on certain service types
		if ($(this).val()=='4' || $(this).val() == '8') {
			$('#search_vehicle_type_antique').attr("checked", true);
			$(":checkbox[id*='types_'][value='8']").attr("checked", true);
			$(":checkbox[id*='types_'][value='9']").attr("checked", true);
			$(":checkbox[id*='types_'][value='10']").attr("checked", true);
		} else if ($(this).val()=='16'||$(this).val()=='32'||$(this).val()=='8192') {
			$(":checkbox[id*='types_'][value='9']").attr("checked", true);
		} else {
		  $('#search_vehicle_type_antique').attr("checked", false);
			$(":checkbox[id*='types_'][value='8']").attr("checked", false);
			$(":checkbox[id*='types_'][value='9']").attr("checked", false);
			$(":checkbox[id*='types_'][value='10']").attr("checked", false);
		}
		show_hide_drop_offs(); show_hide_drop_location(); change_labels();
	});
	show_hide_drop_offs();
	show_hide_drop_location();
	change_labels();
	
	// Search submit needs to clear off various checkboxes on the hidden vehicles div
	$('#search_submit').click( function(){
		// If search form div field has a value, then clear the less options form
		if($('#search_form_div').val() == "selected"){
			$('#search_less_options :checkbox').each(function(){
				$(this).removeAttr('checked');
				$(this).checked=undefined;
			});
		}else{
			// Otherwise clear the more options form
			$('#search_more_options :checkbox').each(function(){
				$(this).removeAttr('checked');
				$(this).checked=undefined;
			});
		}
	});
	
	$('#new_search').submit(function(){
		if(ucsv==true || ucsv > 0 ) {
			formvalid = validate_form();
			if (formvalid==true) shield('search_submit', 'cancelsearch', 'Searching    ', 'Searching ');
			return formvalid;
		}
		else {
			shield('search_submit', 'cancelsearch', 'Searching    ', 'Searching ');
		}
	});
	
	$('#search_user_tz').val((new Date()).getTimezoneOffset()/60);   // submit user's time zone
	
	var checked = false;
	// clicking on car image is same as clicking on checkbox
	$('.cartype').click(function(){
		if (checked) {checked=false; return true;}
		cartype = $(this).attr('cartype');
		chkd = $('#search_vehicle_type_'+cartype).attr('checked');
		if (chkd) $('#search_vehicle_type_'+cartype).removeAttr('checked').checked=undefined;
		else $('#search_vehicle_type_'+cartype).attr('checked', 'checked');
		return false;
	});
	// this needed to avoid interference between the checkbox click and div click
	$(':checkbox[cartype]').click(function() { checked = true; });
	$('#search_pickup_time').change(function() {changeTimeSlot();});
	
	$("input, select").blur(function(){$(this).removeClass('highlighted');});
	$("#contentMain input[type!=submit], #contentMain select").bind('focus', function(){$(this).addClass('highlighted');});	
	$('#service_type').focus();
	$('select').bind('change', function(){ 
	  $(this).removeClass('highlighted'); 
	  $(":input[type!=hidden]:eq("+ ($(":input[type!=hidden]").index(this)+1) +")").focus();
	});
	$('#search_ride_date').bind('change', function(){ 
	  if($(this).val().length==10){
	    $(this).removeClass('highlighted'); 
  	  $(":input[type!=hidden]:eq("+ ($(":input[type!=hidden]").index(this)+1) +")").focus();
  	}
	});
});

function show_hide_drop_offs() {
	var val=$('#service_type :selected').val();
	if(val == 99 || val == 100 || val == 101 || val == 102 || val==''){
	  $('#search_between_time_div').hide();
		$('#search_dropoff_time_div').hide();
	}else{
	  $('#search_between_time_div').show();
		$('#search_dropoff_time_div').show();
	}
}

function show_hide_drop_location() {
	var val=$('#service_type :selected').val();
	if(val == 99 || val == 100 || val == 101 || val == 102 || val == 131072){
		$('#search_pickup_location_div').removeClass('wide');
		$('#search_dropoff_location_div').show();
	}else{	
		$('#search_dropoff_location_div').hide();
		$('#search_pickup_location_div').addClass('wide');
	}
}

function change_labels(only_labels) {
	// Any of the direct clearing of the value attributed on the drop off and pickup places 
	// will erase anything the user has added.
	var val=$('#service_type :selected').val();
	var pval=$('#search_pickup_place').val(); //attr('refid');
	var dval=$('#search_drop_off_place').val(); //attr('refid');
	var csz='Address, City, or Zip';
	var anc='Airport Name, Code or City';
	var cnc='Cruiseport Name or City';
	// All the undefined checks allow us to segment off the onload vs a event call. When onload
	// happens (form submit or page load), we only want to change the text labels - this will 
	// allow and Airport To to have the labels updated correctly. Direct calls do not pass in 
	// the only_labels flag and therefore, blow away the values in the text field(s) directly.
	// Note: Don't forget that this works in conjunction with forms:update_fields
	if(val == 100) {
		// to airport
		$('#pickup_location_label').text('Pick-up address');
		$('#drop_off_location_label').text('Airport');
		if(only_labels == undefined){
			updatable_fields('#search_pickup_place',csz);
			updatable_fields('#search_drop_off_place',anc);
		}
	} else if ( val == 99 ) {
		// from airport
		$('#pickup_location_label').text('Airport');
		$('#drop_off_location_label').text('Drop-off Address');
		if(only_labels == undefined){		
			updatable_fields('#search_pickup_place',anc);
			updatable_fields('#search_drop_off_place',csz);
		}
	} else if (val == 102) {
		// to cruise port
		$('#pickup_location_label').text('Pick-up address');
		$('#drop_off_location_label').text('Cruiseport');
		if(only_labels == undefined){		
			updatable_fields('#search_pickup_place',csz);
			updatable_fields('#search_drop_off_place',cnc);
		}
	} else if (val == 101) {
		// from cruise port
		$('#pickup_location_label').text('Cruiseport');
		$('#drop_off_location_label').text('Drop-off Address');
		if(only_labels == undefined){
			updatable_fields('#search_pickup_place',cnc);
			updatable_fields('#search_drop_off_place',csz);
		}
	} else {
		$('#pickup_location_label').text('Pick-up address');
		$('#drop_off_location_label').text('Drop-off Address');
		if(only_labels == undefined){
			updatable_fields('#search_pickup_place',csz);
			updatable_fields('#search_drop_off_place',csz);
		}
	}
}

// Updates a field(s) refid and value attributes to val param based on id param.
function updatable_fields(id,val){
	var oldRefid = $(id).attr('refid');
	$(id).attr('refid',val);
	if( $(id).val() == '' || $(id).val() == oldRefid ){$(id).val(val);}
}

//If first time is set, change second time to an hour later
function changeTimeSlot() {
	var hs = $('#search_pickup_time').attr('selectedIndex');
	var et = $('#search_drop_off_time').attr('selectedIndex');
	if (hs <= 48) {
		var do_time_idx = hs+6;
		if (do_time_idx>48) {do_time_idx=48;}
		$('#search_drop_off_time').attr('selectedIndex', do_time_idx);
	} else {
		$('#search_drop_off_time').attr('selectedIndex', hs-48);
	}
}


function validate_form() {

	var alertmsg = '';
	var errfields = new Array();
	var extraerr = '';
	
	svctype = $('#service_type').val();
	sdop = $('#search_drop_off_place').val();
	spup = $('#search_pickup_place').val();
	if (svctype=='')
	{ 
		alertmsg += " 'Type of Service'\n";
		errfields.push('#service_type');
    }
	if ($('#search_pax').val()=='')
	{
	    alertmsg += " 'Passengers'\n";
		errfields.push('#search_pax');
	}
	if ($('#search_ride_date').val()=='' || $('#search_ride_date').val()=='Select Date')
	{
		alertmsg += " 'Date of service'\n";
		errfields.push('#search_ride_date');
	}
	if ($('#search_pickup_time').val()=='')
	{
		alertmsg += " 'Time of Pickup'\n";
		errfields.push('#search_pickup_time');
	}
	if ( $('#search_drop_off_time').val()=='' && (svctype!="99" && svctype!="100" && svctype!="101" && svctype!="102") )
	{
		alertmsg += " 'Expected drop-off Time'\n";
		errfields.push('#search_drop_off_time');
		
	}

	if (spup==''||spup=='Address, City, or Zip'||spup=='Airport Name, Code or City')
	{
		alertmsg += " 'Pick-up address'\n";
		errfields.push('#search_pickup_place');
	}
	if ((svctype=="99"||svctype=="100"||svctype=="101"||svctype=="102"||svctype=="131072") && (sdop==''||sdop=='Address, City, or Zip'||sdop=='Airport Name, Code or City')) 
	{
		alertmsg += " 'Drop-off address'\n";
		errfields.push('#search_drop_off_place');
	}

	if ( alertmsg=='' && svctype!="99" && svctype!="100" && svctype!="101" && svctype!="102" ) 
	{
		var drophour = parseInt($('#search_drop_off_time').val().substring(0,2),10);
		if( $('#search_drop_off_time').val().substring(3)=="30" ) drophour += 0.5;
		var pickhour = parseInt($('#search_pickup_time').val().substring(0,2),10);
		if( $('#search_pickup_time').val().substring(3)=="30" ) pickhour += 0.5;
		var timediff = drophour - pickhour;
		if( timediff < 0 ){ timediff += 24; /* account for times spanning midnight */ }
		if( timediff >= 12 && !confirm( 'You have selected a ride duration of '+timediff+' hours. Is this correct?\n\nClick OK to continue.' ) )
		{
	 	   alertmsg += " 'Time of Pickup'\n";
		   errfields.push('#search_pickup_time');
		   extraerr = "<br/>Please select a valid time span."
		}
	}
   
	if (alertmsg!='' && ucsv == 2 ) {
		$('.formError').remove(); /* clear out old errors */
		$('.errorRed').removeClass('errorRed');
		
		msg = "<div class='formError'><strong>Please provide all information below for accurate results.</strong>"+extraerr+"</div>";
		$(msg).prependTo('#homeFormTop');
		$(errfields.toString()).each( function(){ 
			$(this).parent().addClass('errorRed'); 
			$(this).change(function(){
				$(this).parent().removeClass('errorRed');
			});
		});
		return false;
	}
	else if (alertmsg!='') {
		alert('Please complete all of the following fields:\n\n'+alertmsg);
		return false;
	}
	return true;
}

$(window).unload(function() {
	$('#search_submit').removeAttr('disabled');
	$('#search_submit').attr('value','Find a limo');
});
