var isDebug = false;
var conventionPrice;

var step = new Array();
step[0] = "#CustomerInformation";
step[1] = "#PassengerInformation";
step[2] = "#ItineraryInformation";
step[3] = "#PaymentDetails";
step[4] = "#SummaryInformation";
step[5] = "#Confirmation";

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)$"

// Visa, MasterCard, Discover, American Express
//regexPatterns["cardnumber"] = "^4[0-9]{12}(?:[0-9]{3})?|^5[1-5][0-9]{14}|^6(?:011|5[0-9]{2})[0-9]{12}|^3[47][0-9]{13}$";

// Visa, MasterCard, American Express
regexPatterns["cardnumber"] = "^4[0-9]{12}(?:[0-9]{3})?|^5[1-5][0-9]{14}|^3[47][0-9]{13}$";
regexPatterns["cardvercode"] = "(^[0-9]{3}$)|(^[0-9]{4}$)";


var isValidConCode = false;


Array.prototype.contains =
function(v) {
    for (i = 0; i < this.length; i++) {
        if (this[i] == v) return true;
    }
    return false;
}


function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
}

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) displayTotalPrice();
    if (panelIndex == 4) displaySummary();

    // NOTE: #BackButton will be hidden for the first and last step

    if ((panelIndex == 0) || (panelIndex == step.length - 1))
        $("#BackButton").css("display", "none");
    else
        $("#BackButton").css("display", "block");

    // NOTE: #NextButton will be hidden for the Summary and last step

    if ((panelIndex == step.length - 1) || (panelIndex == 4))
        $("#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);
}

// FIELD VALIDATION ------------------------------------------------------------------------------- 

function validate() {
    var errorMessage = "";
    var invalidFields = new Array();

    // used in Payment Details
    var cardtype = document.DoDirectPaymentForm.payCreditCardType.value;
    var cardnumber = document.DoDirectPaymentForm.payCreditCardNumber.value;

    // 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";
        errorMessage += " type of service, please call Customer Service at 866-823-4626.\n";
    }
    

    // check if credit card number matches pattern	
    var cardpattern = "(" + regexPatterns["cardnumber"] + ")?";

    if (cardnumber.length > 0 && !invalidFields.contains(cardnumber) && !$(cardnumber).hasClass(".ignore") &&
        (cardnumber.match(cardpattern) == null || cardnumber.match(cardpattern)[0].length == 0)) {
        errorMessage += "You have entered an invalid credit card number.\n";
    }
	
    // checks if credit card number matches credit card type
    if (cardnumber.length > 0 && cardtype.length > 0 && !invalidFields.contains(cardnumber) && !$(cardnumber).hasClass(".ignore") &&
    cardtype != "Visa" && cardnumber.match(/^4[0-9]{12}(?:[0-9]{3})$/)) {
        errorMessage += "You have entered a Visa card number. The credit card number must match the credit card type.\n";
    }

    else if (cardnumber.length > 0 && cardtype.length > 0 && !invalidFields.contains(cardnumber) && !$(cardnumber).hasClass(".ignore") &&
    cardtype != "MasterCard" && cardnumber.match(/^5[1-5][0-9]{14}$/)) {
    errorMessage += "You have entered a Mastercard number. The credit card number must match the credit card type.\n";
    }

//    else if (cardnumber.length > 0 && cardtype.length > 0 && !invalidFields.contains(cardnumber) && !$(cardnumber).hasClass(".ignore") &&
//    cardtype != "Discover" && cardnumber.match(/^6(?:011|5[0-9]{2})[0-9]{12}$/)) {
//    errorMessage += "You have entered a Discover card number. The credit card number must match the credit card type.\n";
//    }

    else if (cardnumber.length > 0 && cardtype.length > 0 && !invalidFields.contains(cardnumber) && !$(cardnumber).hasClass(".ignore") &&
    cardtype != "Amex" && cardnumber.match(/^3[47][0-9]{13}$/)) {
    errorMessage += "You have entered an American Express card number. The credit card number must match the credit card type.\n";
    }
    
    // variables used for credit card expiration date check
    var month = document.DoDirectPaymentForm.payExpDateMonth.value;
    var year = document.DoDirectPaymentForm.payExpDateYear.value;

    var d = new Date();
    var curr_month = d.getMonth() + 1;
    var curr_year = d.getFullYear();

    //if credit card expiration year = current year (the expiration month < current month)
    if (month.length > 0 && year.length > 0 && !invalidFields.contains(month) && !$(month).hasClass(".ignore") &&
        parseInt(year, 10) == curr_year && parseInt(month, 10) < curr_month) {
        errorMessage += "You have entered an invalid expiration date.\n";
    }

    // if credit card expiration year < current year (the expiration month doesn't matter)
    if (month.length > 0 && year.length > 0 && !invalidFields.contains(year) && !$(year).hasClass(".ignore") &&
        parseInt(year, 10) < curr_year) {
        errorMessage += "You have entered an invalid expiration date.\n";
    }

    //checks if credit card verification number matches the pattern
    var vercode = document.DoDirectPaymentForm.payCardVerificationNum.value;
    var vercodepattern = "(" + regexPatterns["cardvercode"] + ")?";

    if (vercode.length > 0 && !invalidFields.contains(vercode) && !$(vercode).hasClass(".ignore") &&
        (vercode.match(vercodepattern) == null || vercode.match(vercodepattern)[0].length == 0)) {
        errorMessage += "You have entered an invalid card verification number. Only digits are allowed.\n";
    }

    //checks if credit card verification number is corresponding to the credit card number
    // card number is American Express (digits must be 4)
    if (vercode.length > 0 && cardnumber.length > 0 && !invalidFields.contains(vercode) && !$(vercode).hasClass(".ignore") &&
        vercode.match(vercodepattern) && vercode.match(/^[0-9]{4}$/) == null && cardnumber.match(/^3[47][0-9]{13}$/)) {
        errorMessage += "You have entered an invalid card verification number. American Express card verification number must be four digits.\n";
    }
		
	// card number is Visa
    if (vercode.length > 0 && cardnumber.length > 0 && !invalidFields.contains(vercode) && !$(vercode).hasClass(".ignore") &&
        vercode.match(vercodepattern) && vercode.match(/^[0-9]{3}$/) == null && cardnumber.match(/^4[0-9]{12}(?:[0-9]{3})$/)) {
        errorMessage += "You have entered an invalid card verification number. Visa card verification number must be three digits.\n";
    }
    // card number is MasterCard
    if (vercode.length > 0 && cardnumber.length > 0 && !invalidFields.contains(vercode) && !$(vercode).hasClass(".ignore") &&
        vercode.match(vercodepattern) && vercode.match(/^[0-9]{3}$/) == null && cardnumber.match(/^5[1-5][0-9]{14}$/)) {
        errorMessage += "You have entered an invalid card verification number. Mastercard verification number must be three digits.\n";
    }

    // card number is Discover
//    if (vercode.length > 0 && cardnumber.length > 0 && !invalidFields.contains(vercode) && !$(vercode).hasClass(".ignore") &&
//        vercode.match(vercodepattern) && vercode.match(/^[0-9]{3}$/) == null && cardnumber.match(/^6(?:011|5[0-9]{2})[0-9]{12}$/)) {
//        errorMessage += "You have entered an invalid card verification number. Discover card verification number must be three digits.\n";
//    }

    		
    // shows the whole error message    
    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;
    }

    // format price as 0.00    

    return totalPrice.toFixed(2);
}

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>";
}


// displays the total price on the Payment Details step

function displayTotalPrice() {
    $("#PriceTotalPayment").text(calculatePrice());
}

function maskCC(cardnumber) {
    var length = cardnumber.length;
    var result = "";
    for (var i = 0; i < length - 4; i = i + 1) {
        result = result + "*";
    }
    result = result + cardnumber.substr(length - 4, 4)

    return result;
}

// function to generate REFERENCE NUMBER
function refnumber() {

    var rfnum = "";

    // generate the string
    var chars = "ABCDEFGHIJKLMNOPQRSTUVWXTZ";
    var string_length = 5;
    var randomReference = "";
    for (var i = 0; i < string_length; i++) {
        var rnum = Math.floor(Math.random() * chars.length);
        randomReference += chars.substring(rnum, rnum + 1);
    }

    // generate the date
    var d = new Date();

    var curr_date = d.getDate();

    var curr_month = d.getMonth() + 1;
    if (curr_month < 10) {
        curr_month = "0" + curr_month;
    }

    if (curr_date < 10) {
        curr_date = "0" + curr_date;
    }

    var curr_year = d.getFullYear();

    // make the whole number
    rfnum = curr_year + "" + curr_month + "" + curr_date + "." + randomReference;

    return rfnum;
}

function displaySummary() {

    // fill Mail hidden fields

    var hiddenmail = "";

    // set the total price that is used for the PayPal transaction & Mail
    hiddenmail += "<input type='hidden' name='hiddenPriceTotal' id='hiddenPriceTotal' value='" + calculatePrice() + "'/>";


    // set the reference number for the PayPal transaction & Mail
    var referenceNumber = refnumber();

    hiddenmail += "<input type='hidden' name='hiddenReferenceNumber' id='hiddenReferenceNumber' value='" + referenceNumber + "'/>";
    hiddenmail += "<input type='hidden' name='hiddenItemName' id='hiddenItemName' value='James River Transportation (Norfolk)'/>";


    // APPLY HIDDEN FIELDS 

    document.getElementById("hiddenMail").innerHTML = hiddenmail;

    // fill Payment Summary fields (used for PayPal transaction as well)

    document.getElementById("psFirstName").innerHTML = $("#payFirstName").get(0).value;
    document.getElementById("psLastName").innerHTML = $("#payLastName").get(0).value;
    document.getElementById("psCardType").innerHTML = $("#payCreditCardType").get(0).value;
    document.getElementById("psCardNumber").innerHTML = maskCC($("#payCreditCardNumber").get(0).value);
    document.getElementById("psExpDateMonth").innerHTML = $("#payExpDateMonth").get(0).value;
    document.getElementById("psExpDateYear").innerHTML = $("#payExpDateYear").get(0).value;
    document.getElementById("psAddress1").innerHTML = $("#payBillingAddress1").get(0).value;
    document.getElementById("psCity").innerHTML = $("#payBillingCity").get(0).value;
    document.getElementById("psState").innerHTML = $("#payBillingState").get(0).value;
    document.getElementById("psZip").innerHTML = $("#payBillingZip").get(0).value;
    $("#PriceTotal").text(calculatePrice());


    // fill Customer Information fields

    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("Company", $("#cust_Company").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);

    // fill Travel Information fields

    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 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;
}

//gets the data for the mail
function getMailerData()
{
	var mailerData = new Object();
	mailerData.FirstName = $("#cust_FirstName").get(0).value;
	mailerData.LastName = $("#cust_LastName").get(0).value;
	mailerData.Company = $("#cust_Company").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.Zip = $("#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.Convention = $("#cust_Convention").val();
	mailerData.hiddenPriceTotal = $("#hiddenPriceTotal").get(0).value;
	mailerData.hiddenReferenceNumber = $("#hiddenReferenceNumber").get(0).value;
	
	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;
}

// shows the last "Confirmation" step
function completeReservation() {

    // we want to store the values from the form input box, then send via ajax below
    var payFirstName = $('#payFirstName').attr('value');
    var payLastName = $('#payLastName').attr('value');
    var payCreditCardType = $('#payCreditCardType').attr('value');
    var payCreditCardNumber = $('#payCreditCardNumber').attr('value');
    var payExpDateMonth = $('#payExpDateMonth').attr('value');
    var payExpDateYear = $('#payExpDateYear').attr('value');
    var payCardVerificationNum = $('#payCardVerificationNum').attr('value');
    var payBillingAddress1 = $('#payBillingAddress1').attr('value');
    var payBillingCity = $('#payBillingCity').attr('value');
    var payBillingState = $('#payBillingState').attr('value');
    var payBillingZip = $('#payBillingZip').attr('value');
    var hiddenPriceTotal = $('#hiddenPriceTotal').attr('value');
    var hiddenReferenceNumber = $('#hiddenReferenceNumber').attr('value');
    var hiddenItemName = $('#hiddenItemName').attr('value');
    var requestData = "payFirstName=" + payFirstName + "& payLastName=" + payLastName +
                "& payCreditCardType=" + payCreditCardType + "& payCreditCardNumber=" + payCreditCardNumber +
                "& payExpDateMonth=" + payExpDateMonth + "& payExpDateYear=" + payExpDateYear +
                "& payCardVerificationNum=" + payCardVerificationNum + "& payBillingAddress1=" + payBillingAddress1 +
                "& payBillingCity=" + payBillingCity + "& payBillingState=" + payBillingState +
                "& payBillingZip=" + payBillingZip + "& hiddenPriceTotal=" + hiddenPriceTotal +
                "& hiddenReferenceNumber=" + hiddenReferenceNumber + "& hiddenItemName=" + hiddenItemName;


    $("#FinalizeButton").css("display", "none");
    $("#BackButton").css("display", "none");

    $("#PleaseWait").jqmShow();

    $.ajax(
            {
                type: "POST",
                url: "quote_app/web-payments-pro/DoDirectPaymentReceipt.php",
                data: requestData,
                success: function(result) {
                    var arr = result.toString().split(String.fromCharCode(94));
                    if (arr[0] == "SUCCESS") {
                        $.ajax(
                            {
                                type: "POST",
                                url: "mailer.php",
                                data: getMailerData(),
                                success: function(mailerResult) {
                                    var arr = mailerResult.toString().split(String.fromCharCode(94));

                                    if (arr[0] == "ERROR") {
                                        $("#PleaseWait").jqmHide();
                                        currentStep = 5;
                                        displayPanel(currentStep);
                                        $("#ErrorText").html(arr[1] + arr[2] + arr[3] + arr[4]);
                                    }
                                    else {
                                        $("#PleaseWait").jqmHide();
                                        currentStep = 5;
                                        displayPanel(currentStep);
                                        $("#ConfirmationText").css("display", "block");

                                    }

                                    //disables the tabs once the last step is shown
                                    $("#Navigation a").attr("href", "javascript:disablePanelFromUI()");

                                }
                            });
                    }
                    else {
                        $("#PleaseWait").jqmHide();
                        $("#FinalizeButton").get(0).value = "Complete Reservation";
                        alert("An error occured.\n" + arr[1]);
                        $("#FinalizeButton").css("display", "block");
                        $("#BackButton").css("display", "block");
                        currentStep = 3;
                        displayPanel(currentStep);
                        $("#hiddenPayPalMessage").html(arr[1]);
                    }
                }
            });
    return false;
}

// enables the processing screen
$(document).ready(function() {
    $("#PleaseWait").jqm({ modal: true });
});

//added to the anchors href for the tabs (at the last confirmation step, in case the user clicks on 
//any of the other tabs
function disablePanelFromUI() {
        //shows only last step panel
        displayPanel(5);    
}

