var isDebug = false;
var conventionPrice;

var step = new Array();
step[0] = "#CustomerInformation";
step[1] = "#PassengerInformation";
step[2] = "#ItineraryInformation";
step[3] = "#SummaryInformation";

var currentStep = 0;

var regexPatterns = new Object();
regexPatterns["zipcode"] = "^(\\d{5})(-\\d{4})?$";
regexPatterns["phone"] = "^\\(?(\\d{3}).*?(\\d{3}).*?(\\d{4})$";
regexPatterns["email"] = "^([0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$";
regexPatterns["date"] = "^(10|11|12|(0?\\d))/(([012]?\\d)|30|31)/((19|20)\\d\\d)$"

var isValidConCode = false;

Array.prototype.contains=
function(v)
{
	for (i=0;i<this.length;i++)
	{
		if (this[i]==v) return true;
	}
	return false;
}

function displayPanelFromUI(panelIndex)
{
	if(isDebug || panelIndex <= currentStep)
	{
	  currentStep = panelIndex;
		displayPanel(panelIndex);
	}
}

function displayItineraryPanel(menuID,displayClass)
{
	$(menuID + " .itineraryPanel").addClass("displayNone");
	$(menuID + " .itineraryPanel :input").addClass("ignore");
	
	if(displayClass != "")
	{
		$(menuID + " " + displayClass).removeClass("displayNone");
		$(menuID + " " + displayClass + " :input").removeClass("ignore");
	}
}

function displayWayPointPanel(displayID,hide)
{
	if(hide)
	{
		$(displayID).addClass("displayNone");
		$(displayID).removeClass("isActive");
	}
	else
	{
		$(displayID).removeClass("displayNone");
		$(displayID).addClass("isActive");
	}
}

function displayPanel(panelIndex)
{
	$(".panel").css("display","none");
	if(panelIndex == 3) displaySummary();
	
	if(panelIndex == 0)
		$("#BackButton").css("display","none");
	else
		$("#BackButton").css("display","block");
	
	if(panelIndex == step.length-1)
		$("#NextButton").css("display","none");
	else
		$("#NextButton").css("display","block");
		
	$("#Navigation a").each(function(obj){
				$(this).removeClass("isActive");	
		});

	$("#Navigation a").eq(panelIndex).addClass("isActive");
	
	$(step[panelIndex]).css("display","block");
}

function decrement(fieldName)
{
	var field = $("#" + fieldName);
	var val = field.text();
	if(field.attr("minimum"))
	{
		if(field.attr("minimum") < val)
			val--;
	}
	else
		val--;
	field.text(val);
	field.value = val;
}

function increment(fieldName)
{
	var field = $("#" + fieldName);
	var val = field.text();
	if(field.attr("maximum"))
	{
		if(field.attr("maximum") > val)
			val++;
	}
	else
		val++;
	field.text(val);
	field.value = val;
}

function backToPreviousPanel()
{
	if(currentStep > 0)
		currentStep--;
	displayPanel(currentStep);
}

function validate()
{
	var errorMessage = "";
	var invalidFields = new Array();
	
	// remove validation styling from class
	$(step[currentStep] + " input").each(function(obj){$(this).removeClass("invalid");});
	
	// check to see if items are required
	$(step[currentStep] + " .isActive .required").
		each( 
			function(obj) 
				{
					if(this.value.length == 0 && !invalidFields.contains(this) && !$(this).hasClass(".ignore"))
					{
						invalidFields.push(this);
					}
				}
		);
	
	// check to see if items pass regex
	$(step[currentStep] + " .isActive .regex").
		each( 
			function(obj) 
				{
					var pattern = $(this).attr("regex"); // get the regex key
					pattern = "(" + regexPatterns[pattern] + ")?"; // wrap the regex to make it optional		
					if(this.value.length > 0 && 
						(this.value.match(pattern) == null || this.value.match(pattern)[0].length == 0) && 
						!invalidFields.contains(this)
						 && 	!$(this).hasClass(".ignore"))
					{
						invalidFields.push(this);
					}
				}
		);
		

		var hotel = $(".wayPointPanel.isActive .hotelPanel:not(.displayNone) select option:selected[value='-1']")
		if(hotel.length > 0)
			invalidFields.push(hotel.get(0));
		
	if($(step[currentStep]).attr("maximum"))
	{
		var field = $(step[currentStep]);
		var count = 0;
		var maximum = field.attr("maximum");
		$(step[currentStep] + " .count").
		each( 
			function(obj)
			{
				count += parseInt(this.innerHTML);
			}
		);
		if(count > maximum)
		{
			errorMessage += field.attr("errormessage") + "\n";
		}
	}
		
	$(invalidFields).
	each(
		function (obj)
		{
			$(this).addClass("invalid");
			errorMessage += $(this).attr("errormessage") + "\n";
		}
	);
						
	if(currentStep == 2 && !checkZipCode())
	{
			errorMessage += "\nWe can not automatically generate price for the zip code\n";
			errorMessage += "entered. Please call us at 866-823-4626 for reservations.\n";
	}
						
	if(currentStep == 2 && !checkAirports())
	{
			errorMessage += "\nThis form is for airport shuttles only. Should you want a price for this\n";
			errorMessage += " type of service, please call Customer Service at 866-823-4626.\n";
	}			
						
	if(errorMessage.length > 0)
	{
		alert(errorMessage);
	}
	else
	{
		currentStep++;
		displayPanel(currentStep);
	}
}

var WayPointCount = 0;
function addWayPoint()
{
	WayPointCount++;
	$.get("quote_app/waypoint.php", 
				{ sectionID : "Waypoint_" + WayPointCount, title: "New destination"} ,
				function (obj)
				{
					$("#WayPoints").append(obj);
				},
				"html"
	);
}

function removeWayPoint(waypointID)
{
	WayPointCount--;
	$(waypointID).remove(); 
}

function calculatePriceConventionCode()
{
	var isOneWay = $("#tripTypeRadio_OneWay").get(0).checked;
	var conCode = $("#cust_Convention").val();
	conCode = $.trim(conCode);
	$.get("quote_app/conventioncodes.php",
		{code : conCode},
		function (jsonData)
		{
			isValidConCode = jsonData.result == "SUCCESS";
			if(isValidConCode)
			{
				conventionPrice = jsonData.data;
			}
			
			if(isDebug)
			{
				alert(jsonData.result);
				alert(jsonData.data);
				alert("isValidConCode: " + isValidConCode);
			}
		},
		"json");
}

function calculatePrice()
{		
		var travelPrice = 0;
		var totalPrice = 0;
		var passengerCount = 0;
		var maximum = $(step[1]).attr("maximum");
		
		if(isValidConCode)
		{
			if($(".wayPointPanel.isActive").length == 1)
				travelPrice += conventionPrice[0];
			else
				travelPrice += conventionPrice[1];
				
			if(isDebug)
			{
				alert("active waypoints: " + $(".wayPointPanel.isActive").length);
				alert(travelPrice);
			}
		}
		else
		{
			$(".waypoint").each(function (){ 
				travelPrice += parseFloat(getWayPointPrice(this.id));		
			});
		}
		
		
		$(".wayPointPanel.isActive").each(function (){ 

			var isPrivateCar = $("#" + this.id + "_PrivateCar").get(0).checked;
			if(isPrivateCar)
				travelPrice += 25;	
		});
		
		

		
		//$(step[1] + " .count").
		$(step[1] + " #txt_NumberOfAdults").each( 
			function(obj)
			{
				passengerCount += parseInt(this.innerHTML);
			}
		);
		
		if(isValidConCode)
		{
			totalPrice = travelPrice * passengerCount;
		}
		else
		{
			
			// for every 4 passengers or portion thereof add the travelprice
			totalPrice += Math.ceil(passengerCount / 4) * travelPrice;
			
			// for every 4 passengers add 5 for each passenger after the first
			var passengerModifier = 0;
			var numerOfWayPoints = 1;
			if($("#tripTypeRadio_RoundTrip:checked").length)
					numerOfWayPoints = 2;
			passengerModifier += parseInt(passengerCount) * 5 * numerOfWayPoints;
			passengerModifier -= Math.ceil(passengerCount / 4) * 5 * numerOfWayPoints;
			totalPrice = passengerModifier + travelPrice;
		}
		return totalPrice;
}

function getWayPointPrice(waypointID)
{
	var locationSelection = $("#" + waypointID + " .locationSelect").get(0).value;
	if (locationSelection == ".hotelPanel")
	{
		return parseFloat($("#" + waypointID + " .hotelList").get(0).value);
	}
	else if (locationSelection == ".addressPanel")
	{
		var z = $("#" + waypointID + "_ZipCode").get(0).value;
		return parseFloat(FindPriceByZip(z));
	}
	else
	{
		return parseFloat(0);
	}
}

function createRow(cellTitle,cellData)
{
	return "<tr><td valign=\"center\">" + cellTitle + ": &nbsp; &nbsp; </td><td>" + cellData + "</td></tr>";
}

function displaySummary()
{
		var isOneWay = $("#tripTypeRadio_OneWay").get(0).checked;
		
		$("#SummaryTable").empty();
		$("#SummaryPassengerInfo").empty();
		var summaryPassengerInfo = "<table cellspacing=5 border=0 cellpadding=0>";
		summaryPassengerInfo += createRow("Name",$("#cust_FirstName").get(0).value + " " + $("#cust_LastName").get(0).value);
		summaryPassengerInfo += createRow("Address",
			$("#cust_Address").get(0).value + "<br/>" + 
			$("#cust_City").get(0).value + ", " +
			$("#cust_State").get(0).value + " " +
			$("#cust_ZipCode").get(0).value);
		summaryPassengerInfo += createRow("Phone",$("#cust_PhoneNumber").get(0).value);
		summaryPassengerInfo += createRow("Cell",$("#cust_CellPhone").get(0).value);
		summaryPassengerInfo += createRow("Email",$("#cust_EmailAddress").get(0).value);
		summaryPassengerInfo += "</table>";
		
		$("#SummaryPassengerInfo").append(summaryPassengerInfo);
		
		$("#PriceTotal").text(calculatePrice());
		var adultCount = parseInt($("#txt_NumberOfAdults").text());
		if(adultCount > 1)
			$("#adultsCount").text( adultCount + " passengers" );
		else
			$("#adultsCount").text( "1 passenger" );
			
		var babyCount = parseInt($("#txt_NumberOfBabies").text());
		if(babyCount > 1)
		{
			$("#babyCount").css("display","inline");
			$("#babyCount").text( ", " + babyCount + " infants" );
		}
		else if(babyCount == 1)
		{
			$("#babyCount").css("display","inline");
			$("#babyCount").text( ", 1 infant" );
		}
		else	
		{			
			$("#babyCount").css("display","none");
		}
		
		
		var tripNum = 1;
		$(".isActive.wayPointPanel").each(function (){
			
			// init variables
			var otherText = "";
			var destinationText = "";
			
			
			// start fieldset
			var contents = "";
			
			if(!isOneWay)
				contents += "<fieldset><legend>Segment " + tripNum + "</legend>";
			
			contents += "<table>";
			contents += "<tr><td width='140'> Pick up date and time</td>";
			contents += "<td>" +  getTripDate("#" + this.id) + " &nbsp; - &nbsp; " + getTripTime("#" + this.id) + "</td></tr>";	
			contents += "<tr><td width='140'> Private Car?</td>";
			contents += "<td>" + getPrivateCar(this.id) + "</td></tr>";	

			var waypointCount = 0;
			
			$("#" + this.id + " .waypoint").each(function (){

				// get location text
				var locationSelection = $("#" + this.id + " .locationSelect").get(0).value;

				if (locationSelection == ".flightPanel")
				{
					destinationText = "Norfolk International Airport";
				}
				else if (locationSelection == ".hotelPanel")
				{
					var thisSelect = $("#" + this.id + " .hotelList").get(0);
					destinationText = thisSelect.options[thisSelect.selectedIndex].text;
					destinationText += "<br/>";
					destinationText += getHotelAddress("#" + this.id + " .hotelList");
				}
				else if (locationSelection == ".addressPanel")
				{
					var street = $("#" + this.id + "_Address").get(0).value;
					var city = $("#" + this.id + "_City").get(0).value;
					var z = $("#" + this.id + "_ZipCode").get(0).value;
					destinationText = street + ", " + city + ", VA " + z;
				}
				else
				{
					destinationText = "Way point price not calculated";
				}
				
				var niatext = "Pick up location";
				if(waypointCount % 2 == 1)
					niatext = "Drop off destination";
				
				contents += "<tr class=\"destinationRow\"><td valign='top'>" + niatext +"</td><td>" + destinationText + "</td></tr>";				
				waypointCount++;
			});
			
						
			// close it off and append to div
			contents += "</table>";
			
			if(!isOneWay) contents += "</fieldset>";
			
			$("#SummaryTable").append(contents);
			
			tripNum++;
		});
}

function getData()
{
	var result = false;
	var mailerData = new Object();
	mailerData.FirstName = $("#cust_FirstName").get(0).value;
	mailerData.LastName = $("#cust_LastName").get(0).value;
	mailerData.Address = $("#cust_Address").get(0).value;
	mailerData.City = $("#cust_City").get(0).value;
	mailerData.State = $("#cust_State").get(0).value;
	mailerData.ZipCode = $("#cust_ZipCode").get(0).value;
	mailerData.Phone = $("#cust_PhoneNumber").get(0).value;
	mailerData.Cell = $("#cust_CellPhone").get(0).value;
	mailerData.Email = $("#cust_EmailAddress").get(0).value;
	mailerData.Adults = $("#txt_NumberOfAdults").eq(0).text();
	mailerData.Babies = $("#txt_NumberOfBabies").eq(0).text();
	mailerData.ConventionCode = $("#cust_Convention").val();
	mailerData.TotalPrice = calculatePrice();
	
	
	if( $("#tripTypeRadio_OneWay").get(0).checked )
		mailerData.TripType = "One Way";
	else
		mailerData.TripType = "Round Trip";
	
	var tripNum = 1;
	$(".isActive.wayPointPanel").each(function (){
		
		
		// get time
		mailerData["Segment_" + tripNum] = tripNum;
		mailerData["Segment_Date_" + tripNum] = getTripDate("#" + this.id);
		mailerData["Segment_Time_" + tripNum] = getTripTime("#" + this.id);
		
			
		mailerData["Segment_Private_Car_" + tripNum] = getPrivateCar(this.id);
		
		var tripCount = 0;
		$("#" + this.id + " .waypoint").each(function (){
				
			var locationSelection = $("#" + this.id + " .locationSelect").get(0).value;
			var destinationText = "";
			var waypointType = "";
			
			if (locationSelection == ".flightPanel")
			{
				waypointType = "NIA"
				mailerData["Segment_" + tripNum + "_Airline_" + tripCount] = $("#" + this.id + "_AirlineName").get(0).value;
				mailerData["Segment_" + tripNum + "_Flight_" + tripCount] = $("#" + this.id + "_FlightNumber").get(0).value;
				
				var luggage = $("#" + this.id + "_Luggage").get(0);
				mailerData["Segment_" + tripNum + "_Luggage_" + tripCount] = luggage.options[luggage.selectedIndex].value;
				mailerData["Segment_" + tripNum + "_GolfBags_" + tripCount] = $("#" + this.id + "_NumberOfGolfBags").eq(0).text();
			}
			if (locationSelection == ".hotelPanel")
			{
				waypointType = "HOTEL";
				var thisSelect = $("#" + this.id + " .hotelList").get(0);
				destinationText = thisSelect.options[thisSelect.selectedIndex].text + "<br/>";
				destinationText += getHotelAddress("#" + this.id + " .hotelList");
			}
			else if (locationSelection == ".addressPanel")
			{
				waypointType = "ADDRESS";
				var street = $("#" + this.id + "_Address").get(0).value;
				var city = $("#" + this.id + "_City").get(0).value;
				var z = $("#" + this.id + "_ZipCode").get(0).value;
				destinationText = street + ", " + city + ", VA " + z;
			}
			else
			{
				destinationText = "Segment not set";
			}
		
			mailerData["Segment_" + tripNum + "_WaypointType_" + tripCount] = waypointType;
			mailerData["Segment_" + tripNum + "_Location_" + tripCount] = destinationText;

			tripCount++;
		});
			
		tripNum++;
	});
	
	return mailerData;
}

function finalizeReservation()
{		
	var mailerData = getData();
	var mailerUrl = "quote_app/mailer.php?unique=" + new Date();
	
	if(!isDebug)
	{
		$("#FinalizeButton").get(0).value = "Please Wait";
		$("#FinalizeButton").get(0).disabled = true;
	}
	
	$.post(mailerUrl,
		mailerData,
		function (objData)
		{
			if(isDebug)
				alert(objData);
			else
			{
				if(objData.match(/^\d{8}\.[A-Z]{5}$/))
				{
					$("#PaypalReferenceNumber").attr("value",objData);
					$("#PaypalAmount").attr("value",calculatePrice());
					$("#PaypalForm").get(0).submit();		
				}
				else
				{
					alert("Delivery Error - " + objData);
					$("#FinalizeButton").get(0).value = "Delivery Error";
					$("#FinalizeButton").get(0).disabled = false;
				}
		}
		},
		"text");
}

function getTripDate(wayPointPanelID)
{
	return $(wayPointPanelID + " .datePicker").get(0).value; 
}

function getTripTime(wayPointPanelID)
{
	return $(wayPointPanelID + " .hours").get(0).value + ":" +
	$(wayPointPanelID + " .minutes").get(0).value + " " +
	$(wayPointPanelID + " .ampm").get(0).value; 
}

function checkZipCode()
{
	var result = true;
	$(".wayPointPanel.isActive .zipcode:not(.ignore)").each( function (){
		result = false;
		var thisZip = $(this).val();
		for(i = 0; i < zipcodes.length;i++)
		{
			if(zipcodes[i].zipcode == thisZip)
			{
				result = true;
				break;
			}
		}
	});
	
	return result;
}

function checkAirports()
{
	var result = true;
	$(".wayPointPanel.isActive").each( function (){
		
		var fpCount = 0;
		var noneCount = 0;
		
		$("#" + this.id + " select.locationSelect").each( function (){
	
		
			if(this.options[this.selectedIndex].value == ".flightPanel")
				fpCount++;
			else if(this.options[this.selectedIndex].value == "")
				noneCount++;
				
		});
		
		if(fpCount != 1)
			result = false;
			
		if(noneCount == 2)
			result = true;
	});
		
	return result;
}


jQuery(document).ready(function() {
		
	jQuery(".datePicker").dynDateTime({				
		button: ".next()", //next sibling
		ifFormat : "%m/%d/%Y",
		align : "Bl"
	}); 
	
	$(".datePicker").each( function() {
		
		var nextClick = $(this).next().get(0).onclick;
		$(this).mousedown(nextClick);
		
	});
	
	$("#FinalizeButton").get(0).disabled = false;
	$("select").each(function (){ this.options.selectedIndex = 0; });
	$("input:radio").eq(0).each(function (){ this.checked = true; });
	
	$("#cust_Convention").change(calculatePrice);
});

function displayHotel(obj,sectionID)
{
	$("#" + sectionID + " td.hotelAddress").html(getHotelAddress(obj));
}

function getHotelAddress(obj)
{
	var i = $(obj).get(0).options.selectedIndex;
	i--;
	var addressText = "No hotel selected<br/><br/>";
	if(i != -1)
	{
		addressText = hotelArray[i].street +
		"<br/>" + hotelArray[i].city +
		", " + hotelArray[i].state +
		" " + hotelArray[i].zipcode; 
	}
	return addressText;
}

function getPrivateCar(thidId)
{
		var privateCar = "NO";
		if($("#" + thidId + "_PrivateCar").get(0).checked)
			privateCar = "YES";
		return privateCar;
}