$(document).ready(function(){
	
	// var validateForm = validate;
	
	// Main Nav Design stuff.
	$('#main_nav').prepend("<li id='left_cap'></li>");
	$('#main_nav').append("<li id='right_cap'></li>");	
	// $('#main_nav li:last').css('border-right', 'none');
	
	// Datepicker and timepickr setup
	$('#dep_date, #arv_date').datepicker({minDate: 0, maxDate: '+6M +0D'});
	// $('#dep_time').timepickr({convention:12, updateLive:true, resetOnBlur:false});
	// $('#arv_time').timepickr({convention:12});
	
	$('#dep_time, #arv_time, #pickup_flight_time, #droppff_flight_time, #call_from, #call_to').ptTimeSelect();
	
	// 
	// Airport Autocomplete setup
	var data = "Aer Lingus,Air Canada,Air France,AirTran,Alaska Airlines,Alitalia,American Airlines,American Eagle,British Airways,Cape Air,Continental Airlines,Delta Air Lines,Finnair,Iberia,Icelandair,JetBlue,KLM,Lufthansa,Midwest Airlines,Northwest Airlines,SATA,Southwest,Spirit Airlines,Swiss,TACV,United Airlines,United Express,US Airways,Virgin America,Virgin Atlantic".split(",");
	$("#pickup_airline, #dropoff_airline").autocomplete(data);
	
	// $("form").validate({
	// 		rules:{
	// 			dep_date: {
	// 				required: {
	// 					function(element) {
	// 						return $("#age").val() != "Date";
	// 					}
	// 				}
	// 			}
	// 		}
	// 	});
	// $("#inputForm").validate();
	
	// if coming from another page with a form...
	if(window.location.search) handleQueryString(window.location.search);
	
	// roundtrip, hourly, and driver wait setup
	handleRoundTrip($('#round_trip').click(handleRoundTrip).attr('checked'));
	handleRentHourly($('#rent_hourly').click(handleRentHourly).attr('checked'));
	handleDriverWait($('#driver_wait').click(handleDriverWait).attr('checked'));
	
	// For toggling the text inputs default values
	$('input[type="text"]').click(handleFieldFocus).focus(handleFieldFocus).blur(handleFieldBlur).each(handleFieldBlur);
	handleVehicleChange($('#vehicle_form input:radio').click(handleVehicleChange));
	$('input#use_contact').click(function(){
		if($(this).attr("checked"))
			$('#passenger_name').val($('#contact_name').val()).blur();
		else
			$('#passenger_name').val("").blur();
	})
	
	$('#locations_form input:radio').click(handleLocationsType).each(function(index) {
		if($(this).attr("checked")) $(this).click();
	});
	
	$('#continue, #enter_contact, #book_trip').click(function(){
		// console.log("validating form...");
		var rtrip = $('#round_trip').attr('checked');
		var dwait = $('#driver_wait').attr('checked');
		
		validateForm('form');
		// $('form').submit();
		return false;
	});
	$("form#contact").submit(function() {
		//validating
		if ($('#contact_name').val() == 'Contact Name' || $('#contact_name').val() == '') {
		   alert('Please enter your Contact Name')
		   return false;
		} else { if ($('#contact_email').val() == 'Email Address' || $('#contact_email').val() == '') {
		   alert('Please enter your Email Address')
		   return false;
		} else { if ($('#message').val() == '' || $('#message').val() == '') {
		   alert('Please enter your Message')
		   return false;
		}}}
	});
	$("#send_btn").click(function(){
		$("form#contact").submit();
		return false;
	});
      setInterval ( "settime()", 1000 );
      slideSwitch();
});

// Event Handlers
function handleRoundTrip(val)
{
	if($(this).attr('checked') || val==true){
		$('.arrive').fadeIn();
		
	}else{
		$('.arrive').fadeOut();
	}
}

function handleRentHourly(val)
{
	if($(this).attr('checked') || val==true){
		$('#rent_hours').fadeIn(); //.addClass('required');
	}else{
		$('#rent_hours').fadeOut(); //.removeClass('required');
	}
}

function handleDriverWait(val)
{
	if($(this).attr('checked') || val==true){
		$('.arrive *:not(#driver_wait, #driver_wait_label)').animate({opacity:0.4}, 500);
		$('.arrive input[type="text"]').attr('disabled', 'disabled'); //.removeClass('required');
	}else{
		$('.arrive *').animate({opacity:1}, 500);
		$('.arrive input').removeAttr('disabled'); //.addClass('required');
	}
}

function handleFieldFocus() {
	$(this).css('color', 'black');
	if($(this).val() == $(this).attr("title")) $(this).val('');
}

function handleFieldBlur() {
	if($(this).val() == "" || $(this).val() == $(this).attr("title")) $(this).val($(this).attr("title")).css('color', 'gray');
	else $(this).css('color', 'black');
}

function handleVehicleChange()
{
	var speed = 500;
	var fade = 0.3;
	$('#vehicle_form input:radio').prev().prev('label').children('img').stop().animate({opacity:fade}, speed);
	$('#vehicle_form input:radio:checked').prev().prev('label').children('img').stop().animate({opacity:1}, speed);
}

function handleLocationsType() {
	// console.log($(this).val());
	if($(this).val() == "airport"){
		$(this).parent().children('.airport_form').fadeIn();
		$(this).parent().children('.address_form').hide();
	}else{
		$(this).parent().children('.airport_form').hide();
		$(this).parent().children('.address_form').fadeIn();
	}
}

function handleQueryString(qString)
{
	qString = qString.substr(1, qString.length);
	var qArr = qString.split("&");
	var qOutput = "";
	for(var i=0; i < qArr.length; i++)
	{
		var qItem = qArr[i].split("=");
		var item = $('input[name="' + qItem[0] + '"]');
		// console.log(item.attr("type") + ": " + qItem[0] +" = " + decodeURIComponent(qItem[1]));
		if( item.attr("type") == "checkbox"){
			item.attr("checked", decodeURIComponent(qItem[1]));
		}else{
			item.val(decodeURIComponent(qItem[1]).replace("+", " "));
		}
	}
}

// For validating the homepage form
function validateForm(targetForm)
{
	var valid = true;
	if($(targetForm).attr("name") == "contact_form")
	{
		$('#contact_details input:text').each(function(){
			if(!$(this).hasClass("optional"))
			{
				if($(this).val() == $(this).attr("title") || $(this).val() == ""){
					alert("Please enter a valid " + $(this).attr("title") + " to continue.");
					valid = false; // hacky because we're in a temporary function here.
					return false;
				}
			}
		});
		
		if(!valid) return false;
	}else{
		var dDate = [ $(targetForm +' input#dep_date'), $(targetForm + ' input#dep_time') ];
		var rTrip = $(targetForm +	' input#round_trip').attr("checked");
		var aDate = [ $(targetForm +' input#arv_date'), $(targetForm + ' input#arv_time') ];
		var dWait = $(targetForm +	' input#driver_wait').attr("checked");
		var hourly= $(targetForm +	' input#rent_hourly').attr("checked");
		var hours = $(targetForm +' input#rent_hours');

		for(var i=0; i < dDate.length; i++){
			// console.log(dDate[i].val() + ", " + dDate[i].attr("title"));
			if(dDate[i].val() == "" || dDate[i].val() == dDate[i].attr("title")){
				alert("Please enter a valid Departure " + dDate[i].attr("title") + " to continue.");
				return false;
			}else{
				// all ok so far
				if(rTrip && !dWait){
					for(var k=0; k < aDate.length; k++){
						if(aDate[k].val() == "" || aDate[k].val() == aDate[k].attr("title")){
							alert("Please enter a valid Arrival " + aDate[k].attr("title") + ". If you need the driver to wait, please check \"Driver Will Wait.\"");
							return false;
						}
					}
				}
			}

			if(hourly){
				if(hours.val() == "" || hours.val() == hours.attr("title")){
					alert("Please enter a valid number of hours");
					return false;
				}
			}
		}
		
		if($(targetForm).attr("name") == "booking_form")
		{
			// valid pickup location needed
			$('#locations_form div.half:first input:text:visible').each(function(){

					if($(this).val() == $(this).attr("title") || $(this).val() == ""){
						alert("Please enter a valid Pickup " + $(this).attr("title") + " to continue.");
						valid = false; // hacky because we're in a temporary function here.
						return false;
					}
				
			});

			if(!valid) return false;
		}
	}
	$(targetForm).submit();
	return false;
}

//Set Time/Date
function settime () {
  var curtime = new Date();
  var curhour = curtime.getHours();
  var curmin = curtime.getMinutes();
  var cursec = curtime.getSeconds();
  var time = "";
 
  if(curhour == 0) curhour = 12;
  time = (curhour > 12 ? curhour - 12 : curhour) + ":" +
         (curmin < 10 ? "0" : "") + curmin + ":" +
         (cursec < 10 ? "0" : "") + cursec + " " +
         (curhour > 12 ? "PM" : "AM");
 
  $("#current_time").text("Current Time: "+time);
}



function slideSwitch() {
    var $active = $('#vehicle_slideshow IMG.active');

    if ( $active.length == 0 ) $active = $('#vehicle_slideshow IMG:last');

    var $next =  $active.next().length ? $active.next()
        : $('#vehicle_slideshow IMG:first');

    $active.addClass('last-active');

    $next.css({opacity: 0.0})
        .addClass('active')
        .animate({opacity: 1.0}, 1000, function() {
            $active.removeClass('active last-active');
        });
}

$(function() {
    setInterval( "slideSwitch()", 5000 );
});

