var tooptipHints = new Array();
tooptipHints[0] = null;
tooptipHints[1] = "Please enter the postcode, name of the town or name of the city your would like to be collected from.";
tooptipHints[2] = "Please enter the postcode, name of the town or name of the city for your destination.";
tooptipHints[3] = "Please select the date to be picked up and move the sliders on the right to select the time.";
tooptipHints[4] = "Please select the return date to be picked up and move the sliders on the right to select the time.";
tooptipHints[5] = "Please select your return date (if neccessary), and select your vehicle of choice from above.";

function strstr (haystack, needle, bool) {
  var pos = 0;
  haystack += '';
  pos = haystack.indexOf( needle );    if (pos == -1) {
		return false;
	} else{
		if (bool){
	    return haystack.substr( 0, pos );        } else{
	    return haystack.slice( pos );
		}
	}
}

function registerNextStep() {

	$(".next-step").click(function() {
		if($(this).parent().children("input").val().length > 0) {
			$(this).parent().parent().css({"margin-left" : "-9999px"});
			
			var address = null;
			var airportAddress = $(this).parent().children("select").val().split("||");
			
			if ( $(this).parent().children("input").val() == airportAddress[1] ) {
        address = airportAddress[0]+"<br />"+airportAddress[1];
      } else {
        address = $(this).parent().children("input").val();
      }
			$(this).parent().parent().parent().children(".display-text").html("<strong>"+address+"</strong>");
			nextStep( $(this).parent().parent().parent() );
			return false;
		} else {
			alert("Please enter a value.");
			return false;
		}
		return false;
	});	
	
	$(".go").click(function() {
		nextLoad($(this));
		popup = $(this).children(".popup");
		//toolTipPosition(1,popup);
	});	
}

function registerLastStep() {

	$(".last-step").click(function() {

			$(this).parent().parent().css({"margin-left" : "-9999px"});
			
			var address = null;
			var airportAddress = $(this).parent().children("select").val().split("||");
			
			if ( $(this).parent().children("input").val() == airportAddress[1] ) {
        address = airportAddress[0]+"<br />"+airportAddress[1];
      } else {
        address = $(this).parent().children("input").val();
      }
			$(this).parent().parent().parent().children(".display-text").html("<strong>"+address+"</strong>");
      prevStep( $(this).parent().parent().parent() );
			return false;
	});	
	
	$(".go").click(function() {
		nextLoad($(this));
		popup = $(this).children(".popup");
		//toolTipPosition(1,popup);
	});	
}
function calculatePrice() {	
	 var url = "/wp-content/themes/default/calculatePrice.php";
	 $("#cover").css({"height":$(document).height(),"width":$(document).width(),"margin-left":"0px"}).show();
	 $("#loading-popup").css("margin","250px 0 0 50px");

	 var is_multiple_vehicles = 0;
	 if($("#is_multiple_vehicles").length && $("#is_multiple_vehicles").val() == 1) is_multiple_vehicles = 1;

	$.post(url, $("#form-booking-form").serialize(), function(data){	
		var php = data.split("<|>");

		if (php[0] == "E") {
			
			if (php[1] == "") {
				php[1] = "An error has occured.";
			}
			
			$("#loading-popup").find("h4").html("A booking error has occured");
			$("#loading-popup-content").hide();
			if(php[1] == 'Please enter a pickup date.') {
 
			  $("#loading-popup-content").after("<div class='content' id='temporary-div'><br />"+php[1]+"<br /><br /><button id=\"sel_cal\">Select a Pickup date</button><br class='clear' /></div>");
			  $("#sel_cal").click( function () { jQuery("#form_pickup_date").click(); } );
			}
			else {

			  $("#loading-popup-content").after("<div class='content' id='temporary-div'><br />"+php[1]+"<br /><br /><button>Go back</button><br class='clear' /></div>");
			}
			$(document).click(function() {
				$("#cover").hide();
				$("#loading-popup").css("margin-left","-9999px");
				$(document).unbind("click");
				$("#temporary-div").remove();
				$("#loading-popup").find("h4").html("Calculating...");
				$("#loading-popup-content").show();
				return false;
			});

		} else {
			if(is_multiple_vehicles) {
				var nbElem = (php.length)-1;
				$("#form_txid").val(php[nbElem]);
				
				for(i = 0; i < nbElem ; ++i) {
					j = i + 1;
					$("#car_"+j).html("&pound;"+php[i]+".00");
					$("#car_p_"+j).val(php[i]);
					$("#li_car_"+j).removeClass("disabled");
					$("#bookbutt_"+j).removeClass("disabled");
				}
				$("#cover").hide();
				$("#loading-popup").css("margin-left","-9999px");
				$("#temporary-div").remove();
				
			}
			else {
				var miles 			 	= php[0];
				var journey_time 	= php[1];
				var price				 	= php[2];
				var returnjour		= php[3];
				var vehicle				= php[4];
				var txid					= php[5];
				var clean_vehicle = php[6];
						
				$("#quote-price").html("&pound;"+price+".00").show();
				$("#form_price").val(price);
				$("#loading-popup").find("h4").html("Total Fare: &pound;"+price+".00");
				$("#loading-popup-content").hide();
				$("#booking-confirmation").show();
				
				$("#confirm-miles").html(miles+" miles");
				$("#confirm-journeytime").html(journey_time);
				$("#confirm-vehicle").html(clean_vehicle);
				
				$("#continue-booking").click(function() {
					$("#form_txid").val(txid);
					$("#cover").hide();
					$("#booking-confirmation").hide();
					$("#loading-popup-content").show();
					$("#loading-popup").find("h4").html("Calculating...");
					$("#loading-popup").css("margin-left","-9999px");
					loadAddress();
					return false;
				});
				
				$(".cancel-booking").click(function() {
					$("#cover").hide();
					$("#booking-confirmation").hide();
					$("#loading-popup-content").show();
					$("#loading-popup").find("h4").html("Calculating...");
					$("#loading-popup").css("margin-left","-9999px");
					return false;
				});
				
				$("#price-display").animate({
					'height':'43px',
					'margin-top':'92px'
				});
				
				$(".vehicle-price").each(function() {
					var ratemile = $(this).parent().children("input").val();
					$(this).html("&pound;"+price+".00");
				});
			}
			
		}
	
	});	

}

function loadAddress() {
	$("#booking-data").animate({"height":"670px"});
	//$("#booking-position").html("Step 6 of 6");
	$("#booking-tooltip").hide();
}

function nextStep(obj) {
	$(obj).removeClass("active").next().removeClass("disabled");
	nextLoad(obj.next());
}

function prevStep(obj) {
	$(obj).addClass("disabled").removeClass("active").prev().removeClass("disabled");
	prevLoad(obj.prev());
}

function finalTooltip() {
	$('html,body').animate({scrollTop: "160px"}, 1000);	
	
	$("#booking-tooltip").show();
	$(".up-arrow").show();
	
	$("#booking-tooltip").css({
		'margin':"220px 0 0 270px",
		'top':"auto",
		'left':"auto",
		'z-index':1
		});
		
	$("#booking-tooltip-text").html(tooptipHints[5]);	
}

function toolTipPosition(pos,popup) {
	if (pos != 1 && pos != 2) {
		//$("#booking-tooltip").show();
	  if(popup.offset()) {
		$("#booking-tooltip").css({
			'margin':0,
			'top':popup.offset().top+(popup.height()/2)+"px",
			'left':popup.width()+popup.offset().left+5+"px",
			'z-index':999
			});
	  } 
		if (pos < 4) {
			$(".up-arrow").hide();
		}
			
		if (tooptipHints[pos] != null) {
			$("#booking-tooltip-text").html(tooptipHints[pos]);
		}	
	}

}

function nextLoad(obj) {
		hideForm();
		var pos = strstr($(obj).attr("id"),"-").substr(1);
		var newHeight = (parseInt(pos)*72) + 60;
		//$("#booking-data").animate({"height":newHeight+"px"});
		//$("#booking-position").html("Step "+pos+" of 6");

		$(".active").removeClass("active").children(".popup").css({"margin-left" : "-9999px"});		
		$(obj).addClass("active").children(".popup").css({"margin-left" : "-150px"});
		
		popup = $(".active").children(".popup");
		
		if($(obj).hasClass("date")) {
			nextDateLoad($(obj));
			popup = $("#ui-timepicker-div");
		}
		
		toolTipPosition(pos,popup);
		
		//alert($(".active").height());
		if (pos == 3) {
			//$("#booking-5").css("display","block");
			//$("#vehicles-more").show();
		}
		
		return false;

}

function prevLoad(obj) {

		hideForm();
		var pos = strstr($(obj).attr("id"),"-").substr(1);
		var newHeight = (parseInt(pos)*72) + 60;
		//$("#booking-data").animate({"height":newHeight+"px"});
		//$("#booking-position").html("Step "+pos+" of 6");

		$(".active").removeClass("active").children(".popup").css({"margin-left" : "-9999px"});		
		$(obj).addClass("active").children(".popup").css({"margin-left" : "-150px"});
		
		popup = $(".active").children(".popup");
		
		if($(obj).hasClass("date")) {
			nextDateLoad($(obj));
			popup = $("#ui-timepicker-div");
		}
		
		if($(obj).hasClass("information")) {
       $(".next-step-info").show(); 
		}
				
		toolTipPosition(pos,popup);
		
		//alert($(".active").height());
		if (pos == 3) {
			//$("#booking-5").css("display","block");
			//$("#vehicles-more").show();
		}
		
		return false;

}

function nextDateLoad(obj) {
	$(obj).children(".datepicker").datepicker('show');
}

function showForm () {
	theCar = $("#form_vehicle").val();
	thePrice = $("#form_price").val();
	$("#selected_vehicle_content").html("<img src=\"/wp-content/themes/default/images/vehicles/"+theCar+"\" alt=\""+theCar+"\" />");
	$("#selected_vehicle_price").html("&pound;"+thePrice+".00");
	$("#cars-browse").hide("slow");
	$("#booking-form-det").show("slow");
	
}
function hideForm () { 
	$("#booking-form-det").hide("slow");
	$("#cars-browse").show("slow");
}

$(document).ready(function() {
  
	$('#rpickupday').html("?");
  $('#rpickuptime').html("");
  $('#rpickuptime').html("");
  
	$('#is_multiple_vehicles').val(1);

	$(".disabled").click(function() {
		return false;
	})
	
	$(".next-step-info").click(function() { 
	  if($("#form_customer_name").val().length == 0 || $("#form_customer_email").val().length == 0 || $("#form_customer_telephone").val().length == 0) {
	    alert('Please fill all the mandatory fields');
	  }
	  else { 
	  nextStep($("#booking-f")); 
	  $(".next-step-info").hide(); 
	  }
	  return false; 
	} );
	
	$("#form_return_date").val("");
	$("#form_txid").val("");

	registerNextStep();
	registerLastStep();
		
	$("#booking-5 img").click(function() {
		
		if(jQuery("#form_pickupdate").val().length > 0) {		
			theLi = $(this).parent().parent();
		
			if(!theLi.hasClass("end")) {
				$(".active-vehicle").removeClass("active-vehicle").addClass("notop");
				theLi.removeClass("notop").addClass("active-vehicle");
				theLi.parent().prepend(theLi);
				$("#form_vehicle").val($(this).attr("alt"));
				
				//$("#booking-position").html("Step 5 of 6");
				
				
			}
			
		} else {
			
			alert("Please select a valid date");
			
		}
	});
	
	$("#booking-1").click(function() {
		if (!$(this).hasClass("disabled")) {
		  hideForm();
		  nextLoad($(this));
		}
		
	});
		
	$("#booking-2").click(function() {
		if (!$(this).hasClass("disabled")) {
		  hideForm();
		  nextLoad($(this));
		}
		
	});
	
	$("#booking-3").click(function() {
		if (!$(this).hasClass("disabled")) {
			hideForm();
			$("#form_pickup_date").datepicker("show");
		}
	});
	
	$("#booking-4").click(function() {
		if (!$(this).hasClass("disabled")) {
			hideForm();
			$("#form_return_date").datepicker("show");
    	popup = $("#ui-timepicker-div");
    	toolTipPosition(4,popup);			
		}
	});	
	
	$(".airport-select").change(function() {
		var address = $(this).val().split("||");
		$(this).parent().children("input").val(address[1]);
	});
	
	$("#booking-form-second").validate();
	$("#form-booking-form").bind("keypress", function(e) {
	  	if (e.keyCode == 13 || e.keyCode == 9) return false;
	});
	
	$(".book_button").click(function() {
		if (!$(this).hasClass("disabled")) {
			if(jQuery("#form_pickupdate").val().length > 0) {		
					theLi = $(this).parent();

					theImg = theLi.find("img");
					theInp = theLi.find("input");
					$("#form_vehicle").val(theImg.attr("alt"));
					
					$("#form_price").val(theInp.val());
					//$("#booking-position").html("Step 5 of 6");
			}
    	showForm();			
		}
	});	

	/*if($("#booking-form-det-f").length) {
		$("#booking-form-second").submit( function() {
				$('#is_multiple_vehicles').val(0);
				$('#booking-form-second :input[isacopy]').remove();
				$('#form-booking-form :input').not(':submit').clone().hide().attr('isacopy','y').appendTo('#booking-form-second');
				return true;
		});
		
		$("#form_submit").click( function () { $('#is_multiple_vehicles').val(0); $("#form-booking-form").submit(); return false; } );
	}	*/
	$("#form_submit").click( function () { $('#is_multiple_vehicles').val(0); $("#form-booking-form").submit();  } );
  // Departure Date
  jQuery("#form_pickup_date").datepicker({
    	duration: '',
      showTime: true,
      constrainInput: false,
      beforeShow: function(input, inst) { $("#ui-datepicker-div").addClass("pickupdatePick"); $("#ui-timepicker-div").addClass("pickuptimePick"); },
      stepMinutes: 5,  
      stepHours: 1,  
      altField: '#form_pickupdate',
      altTimeField: '#form_pickuptime',
      altFormat: 'd M yy',
      defaultDate: +1,
      minDate: +1,
      yearRange: +1, 
      time24h: true,
      onClose: function() {
      	
   			// Update calendar
				dateText = jQuery("#form_pickupdate").val();
		    timeText = jQuery("#form_pickuptime").val();
		    
		    jQuery("#confirm-destination").html($("#form_destination").val());
		    jQuery("#confirm-pickuppoint").html($("#form_pickup_point").val());
		    
		    jQuery("#confirm-pickupdate").html(dateText+" "+timeText);
		    jQuery("#confirm-returndate").html("Not applicable");
		
				var arr_dateText = dateText.split(" ");
				jQuery("#pickupday").html(arr_dateText[0]);
		    jQuery("#pickupmonth").html(arr_dateText[1]);
		    jQuery("#pickuptime").html(timeText);
		    jQuery("#departure_time").html(dateText);
		    jQuery("#departure_time2").html(timeText);
		    
		  	jQuery("#form_pickupdate").val(dateText);
		    jQuery("#form_pickuptime").val(timeText);
		      
		    $("#ui-datepicker-div").removeClass("pickupdatePick"); $("#ui-timepicker-div").removeClass("pickuptimePick");
		    
		    $(this).parent().next().removeClass("disabled");
		    $(this).parent().children(".display-text").html("<strong>"+$("#form_pickupdate").val()+" "+$("#form_pickuptime").val()+"</strong>");
		    //finalTooltip();
		    calculatePrice();
	    
		    
		   // $("#booking-data").animate({"height":"276px"}); 
		    
      }
		});
		
	// Hack for Webkit bug http://code.google.com/p/chromium/issues/detail?id=1701
	$("#booking-data").scroll(function() {
		$(this).scrollTop("0px");
	});		

		
  // Return Date
  jQuery("#form_return_date").datepicker({
    	duration: '',
      showTime: true,
      constrainInput: false,
      stepMinutes: 5,  
      beforeShow: function(input, inst) { $("#ui-datepicker-div").addClass("returndatePick"); $("#ui-timepicker-div").addClass("returntimePick"); },
      stepHours: 1,  
      altField: '#form_returndate',
      altTimeField: '#form_returntime',
      altFormat: 'd M yy',
      defaultDate: +7,
      minDate: +1, 
      yearRange: +1,
      time24h: true,
      onClose: function() {

   			// Update calendar
				dateText = jQuery("#form_returndate").val();
		    timeText = jQuery("#form_returntime").val()
		    
		    jQuery("#confirm-returndate").html(dateText+" "+timeText);		   

		    //$("#booking-data").animate({"height":"276px"}); 
		
				var arr_dateText = dateText.split(" ");
				jQuery("#rpickupday").html(arr_dateText[0]);
		    jQuery("#rpickupmonth").html(arr_dateText[1]);
		    jQuery("#rpickuptime").html(timeText);
		    jQuery("#rdeparture_time").html(dateText);
		    jQuery("#rdeparture_time2").html(timeText);
		    
		    jQuery("#form_returndate").val(dateText);
		    jQuery("#form_returntime").val(timeText);
		    
		   $("#ui-datepicker-div").removeClass("returndatePick"); $("#ui-timepicker-div").removeClass("returntimePick");
		    //$("#booking-position").html("Step 4 of 6");
		    $(this).parent().children(".display-text").html("<strong>"+$("#form_returndate").val()+" "+$("#form_returntime").val()+"</strong>");
		    //finalTooltip();
		    calculatePrice();

      }
	});
	
	// Automatically show pickup point box
	//setTimeout( function() { $(".go").click(); }, 1000 );      	
	
	
	$('a[href*=#]').click(function() {
		if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
			var target = $(this.hash);
			target = target.length && target || $('[name=' + this.hash.slice(1) +']');
			if (target.length) {
				var targetOffset = (parseInt(target.offset().top)-40)+"px";
				$('html,body').animate({scrollTop: targetOffset}, 1000);
				return false;
			}
		}
	});	

	$("#topnav li").prepend("<span></span>"); //Throws an empty span tag right before the a tag

	$("#topnav li").each(function() { //For each list item...
		var linkText = $(this).find("a").html(); //Find the text inside of the <a> tag
		$(this).find("span").show().html(linkText); //Add the text in the <span> tag
	}); 

	$("#topnav li").hover(function() {	//On hover...
		$(this).find("span").stop().animate({
			marginTop: "-40" //Find the <span> tag and move it up 40 pixels
		}, 250);
	} , function() { //On hover out...
		$(this).find("span").stop().animate({
			marginTop: "0"  //Move the <span> back to its original state (0px)
		}, 250);
	});

});