var timeOutCall;
$(document).ready(function() {
    //setup the entire page on load
    setupPage();    
    showMore();    
    loginValidate();
    popBubble();
    myAccountSetUp();

    $('.numbersOnly').keyup(function() {
        this.value = this.value.replace(/[^0-9\.]/g, '');
    });
});

function SetupReservationManagement() {
    $('.cancelItinerary').click(function() {
        if (confirm("Are you sure you want to cancel this itinerary?")) {
            return true;
        } else {
            return false;
        }
    });
    $('.editTrip').click(function() {
        if (confirm("Are you sure you want to edit this trip?")) {
            return true;
        } else {
            return false;
        }
    });
}
function setupPage(){
    $('.loginButton').click(function() {
        $('.loginForm').slideToggle();
    });
    $("#Password").keyup(function(event) {
        var buttonId = $('.loginForm a').attr('id');
        if (event.keyCode == 13) {
            javascript: WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(buttonId, "", false, "", "SignIn.aspx?ReturnUrl=/Book.aspx", false, true))
        }
    });
}
function StartSlideShow() {
    //set first image
    $('#slideshow .slide:eq(0)').fadeIn();

    //set slideshow interval
    setInterval("startSliders()", 5000);

    //bind animation button clicks for banner
    $('.button').bind('click', function() {
        $(this).blur();
        if ($(this).hasClass('current')) {
            //do nothing
        }
        else {
            $(this).blur();
            $('.current').removeClass().addClass('button');
            $(this).addClass('current');
            //get current rel value
            var thisRel = $(this).attr('rel');
            //build selector
            var mySelector = "#slideshow .slide[rel='" + thisRel + "']";
            $("#slideshow .slide").fadeOut(1000);
            $(mySelector).fadeIn(1000);
        }
    });
}
function startSliders() {
    if ($("#slideButtons a:last").hasClass("current")) {
        timeOutCall = setTimeout('$("#slideButtons a:first").click()', 5000);
    } else {
        timeOutCall = setTimeout('$("#slideButtons .current").next("a").click()', 5000)
    }
}
function setupBookingWidget() {
    //ResetBookingFields(false);
    //test for page load values.  
    //This is for Trip.aspx to load properly and not show the "going to?" image placeholder when its pre-populated
    var GoingToTest = $('.stationField.destination').val();
    if (GoingToTest.toLowerCase() != "going to?") {
        $('.stationField.destination').show();
        $('.inactiveImage').hide();
    }
    //setup properly for round-trip selected
    var tripType = $('#tripType .radioInput input:checked').val();
    hideShowForTripType(tripType);

    $("#tripType .radioInput input").change(function() {
        var thisValue = $(this).val();
        var thisRel = $(this).attr('rel');
        if (thisRel == "widget") {
            window.location = "/book.aspx?multi=true";
        } else {
            ResetBookingFields(false);
            hideShowForTripType(thisValue);
        }
    });
    var testPrePopulate = $('input.departure').val();
    if (testPrePopulate.toLowerCase() != "leaving from?") {
        var prePopDirection = $('input.departure').next().next().val();
        GetDestinations(prePopDirection);
    }
    

    //setup departure popups
	$('input.departure').click(function(){
	var offset = $(this).offset();
	    //toggle the popup
	    $('.popUp').slideUp();
		$('.popUp.departure').css({top: (offset.top + 22), left: offset.left});		
		$('.popUp.departure').slideDown();
		//this clears the active selected input in case they click from one input directly to another 
		//(without hitting the X button or selecting a city)
		$('.selectedInput').removeClass('selectedInput');
		//then adds the class to the currently selected input.  this is for tracking where the values go.
		$(this).addClass('selectedInput');
    });
    //setup destination popups
    $('input.destination').click(function() {
        var offset = $(this).offset();
        //toggle the popup
        $('.popUp').slideUp();
        $('.popUp.destination').css({ top: (offset.top + 22), left: offset.left });
        $('.popUp.destination').slideDown();
        //this clears the active selected input in case they click from one input directly to another 
        //(without hitting the X button or selecting a city)
        $('.selectedInput').removeClass('selectedInput');
        //then adds the class to the currently selected input.  this is for tracking where the values go.
        $(this).addClass('selectedInput');
    });
    //this is for mult-leg
    $('input.departure2').click(function() {
        var offset = $(this).offset();
        //toggle the popup
        $('.popUp').slideUp();
        $('.popUp.departure2').css({ top: (offset.top + 22), left: offset.left });
        $('.popUp.departure2').slideDown();
        //this clears the active selected input in case they click from one input directly to another 
        //(without hitting the X button or selecting a city)
        $('.selectedInput').removeClass('selectedInput');
        //then adds the class to the currently selected input.  this is for tracking where the values go.
        $(this).addClass('selectedInput');   
    });
    $('input.destination2').click(function() {
        var offset = $(this).offset();
        //toggle the popup
        $('.popUp').slideUp();
        $('.popUp.destination2').css({ top: (offset.top + 22), left: offset.left });
        $('.popUp.destination2').slideDown();
        //this clears the active selected input in case they click from one input directly to another 
        //(without hitting the X button or selecting a city)
        $('.selectedInput').removeClass('selectedInput');
        //then adds the class to the currently selected input.  this is for tracking where the values go.
        $(this).addClass('selectedInput');
    });    
	$('.popUp.departure a:not(.seeAll a)').click(function() {	    
	    var itemCode = $(this).attr('rel');
	    var itemDirection = $(this).attr('direction');
	    var itemReturn = $(this).attr('return');
	    var itemName = $(this).text();
	   
	    $('.selectedInput').val(jQuery.trim(itemName));
	    //write location code into hidden field
	    $('.selectedInput').next().val(itemCode);
	    $('.selectedInput').next().next().val(itemDirection);
	    $('.selectedInput').next().next().next().val(itemReturn);

	    GetDestinations(itemDirection);
	    $('.stationField.destination').val('Going To?');
	    //clear selectedInput
	    $('.selectedInput').removeClass('selectedInput');
	    //toggle the popup
	    $('.popUp').slideUp();
	    $('.inactiveImage').hide();
	    $('input.destination').show();	    
	    return false;
	});
	
	//setup destination popup X buttons
	$(".buttonpane button").click(function(){
		//var options = {direction: 'up'};
		$(this).parents('.popUp').slideUp();		
		//this clears the active selected input
		$('.selectedInput').removeClass('selectedInput');
    });
    $('#findTrips a').click(function() {
        if (validation()) {
            return true;
        } else {
            return false;
        }
    });
}
function fillSecondDateBox(DateText) {
    var tripType = $('#tripType .radioInput input:checked').val();
    
    if (tripType == "2") {
        var secondDatePicker = $('.datepicker:eq(1)').val();
        $('.datepicker:eq(1)').datepicker('option', 'minDate', new Date(DateText)); 
        if (secondDatePicker.length == 0 || secondDatePicker == "Date to return?") {
            $('.datepicker:eq(1)').val(DateText)
        }
    } else if (tripType == "3") {
        var secondDatePicker = $('.datepicker:eq(2)').val();
        $('.datepicker:eq(2)').datepicker('option', 'minDate', new Date(DateText)); 
        if (secondDatePicker.length == 0 || secondDatePicker == "Date to return?") {
            $('.datepicker:eq(2)').val(DateText)
        }
    }
}
function hideShowForTripType(TripType) {    
    switch (TripType) {
        case "1":
            $('#multiLeg, .hiddenTitle').hide();
            $('#stations .hiddenDestination').hide();
            $('#stations .hiddenDate').hide();
            break;

        case "2":
            $('#multiLeg, .hiddenTitle').hide();
            $('#stations .hiddenDestination').hide();

            if ($('.datepicker:eq(0)').val() != "Date to leave?") {
                var dateText = $('.datepicker:eq(0)').val();
                $('.datepicker:eq(1)').datepicker('option', 'minDate', new Date(dateText));
            }

            $('#stations .hiddenDate, .hiddenH').fadeIn('slow');
            break;

        case "3":
            //window.location = "/book.aspx";
            $('#multiLeg, .hiddenTitle').fadeIn('slow');
            $('#stations .hiddenDestination').fadeIn('slow');
            $('#stations .hiddenDate').hide();
            break;
    }
}
function ResetBookingFields(ResetRadioButtons) {
    if (ResetRadioButtons) {
        //$('input[name="ctl00$ContentPlaceHolder1$tripType"]')[0].checked = true;
        $("#tripType .radioInput input:eq(0)").click();
    }
    $('.stationField.departure').val("Leaving from?");
    $('.stationField.destination').val("Going to?");
    $('.stationField.departure2').val("Leaving from?");
    $('.stationField.destination2').val("Going to?");
}
function GetDestinations(direction) {
    var url = "service/getArrivalRoutes.aspx?direction=" + direction;
    var html = "<ul class='templist'>";

    $.ajax({
        type: "GET",
        url: url,
        cache: false,
        dataType: "xml",
        async: true,
        success: function(xml) {
            $(xml).find('Route').each(function() {
                var header = $(this).attr("Header");
                html += "<li>" + header + "<ul>";
                $(this).find('Stop').each(function() {
                    var Line = $(this).find("Line").text();
                    var Abbrev = $(this).find("Abbrev").text();
                    var Name = $(this).find("Name").text();
                    var Direction = $(this).find("Dir").text();
                    var TType = $(this).find("Type").text();
                    var ReturnCode = $(this).find("Return").text();

                    html += "<li><a return='" + ReturnCode + "' direction='" + Direction + "' rel='" + Abbrev + "' href='#'>" + Name + "</a></li>";
                });
                html += "</ul></li>";
            });
        },
        complete: function() {
            $('.popUp.destination .templist').remove();
            $('.popUp.destination .buttonpane').before(html);
            $('.popUp.destination a:not(.seeAll a)').click(function() {
                var itemCode = $(this).attr('rel');
                var itemDirection = $(this).attr('direction');
                var itemReturn = $(this).attr('return');
                var itemName = $(this).text();
                //this is where we use the selected input tracking class
                //validate departure/destination of book travel search   

                $('.selectedInput').val(jQuery.trim(itemName));
                //write location code into hidden field
                $('.selectedInput').next().val(itemCode);
                $('.selectedInput').next().next().val(itemDirection);
                $('.selectedInput').next().next().next().val(itemReturn);
                //if multi-leg, setup the next input
                var tripType = $("#tripType .radioInput input:checked").val();
                if (tripType == "3") {
                    $('.inactiveImage2').hide();
                    $('.hiddenDeparture2 .departure2').show();
                    GetDeparture2(itemDirection)
                }                
                //clear selectedInput
                $('.selectedInput').removeClass('selectedInput');
                //toggle the popup
                $('.popUp').slideUp();
                return false;
            });
        }
    });//END AJAX
}
function GetDeparture2(direction) {
    
    var url = "service/getArrivalRoutes.aspx?direction=" + direction;
    var html = "<ul class='templist'>";

    $.ajax({
        type: "GET",
        url: url,
        cache: false,
        dataType: "xml",
        async: true,
        success: function(xml) {
            $(xml).find('Route').each(function() {
                var header = $(this).attr("Header");
                html += "<li>" + header + "<ul>";
                $(this).find('Stop').each(function() {
                    var Line = $(this).find("Line").text();
                    var Abbrev = $(this).find("Abbrev").text();
                    var Name = $(this).find("Name").text();
                    var Direction = $(this).find("Dir").text();
                    var TType = $(this).find("Type").text();
                    var ReturnCode = $(this).find("Return").text();

                    html += "<li><a return='" + ReturnCode + "' direction='" + Direction + "' rel='" + Abbrev + "' href='#'>" + Name + "</a></li>";
                });
                html += "</ul></li>";
            });
        },
        complete: function() {
            $('.popUp.departure2 .templist').remove();
            $('.popUp.departure2 .buttonpane').before(html);
            $('.popUp.departure2 a:not(.seeAll a)').click(function() {
                var itemCode = $(this).attr('rel');
                var itemDirection = $(this).attr('direction');
                var itemReturn = $(this).attr('return');
                var itemName = $(this).text();
                //this is where we use the selected input tracking class
                //validate departure/destination of book travel search   

                $('.selectedInput').val(jQuery.trim(itemName));
                //write location code into hidden field
                $('.selectedInput').next().val(itemCode);
                $('.selectedInput').next().next().val(itemDirection);
                $('.selectedInput').next().next().next().val(itemReturn);
                $('.inactiveImage3').hide();
                $('.hiddenDestination2 .destination2').show();
                GetDestinations2(itemReturn)
                //clear selectedInput
                $('.selectedInput').removeClass('selectedInput');
                //toggle the popup
                $('.popUp').slideUp();
                return false;
            });
        }
    }); //END AJAX
}
function GetDestinations2(direction) {
    var url = "service/getArrivalRoutes.aspx?direction=" + direction;
    var html = "<ul class='templist'>";

    $.ajax({
        type: "GET",
        url: url,
        cache: false,
        dataType: "xml",
        async: true,
        success: function(xml) {
            $(xml).find('Route').each(function() {
                var header = $(this).attr("Header");
                html += "<li>" + header + "<ul>";
                $(this).find('Stop').each(function() {
                    var Line = $(this).find("Line").text();
                    var Abbrev = $(this).find("Abbrev").text();
                    var Name = $(this).find("Name").text();
                    var Direction = $(this).find("Dir").text();
                    var TType = $(this).find("Type").text();
                    var ReturnCode = $(this).find("Return").text();

                    html += "<li><a return='" + ReturnCode + "' direction='" + Direction + "' rel='" + Abbrev + "' href='#'>" + Name + "</a></li>";
                });
                html += "</ul></li>";
            });
        },
        complete: function() {
            $('.popUp.destination2 .templist').remove();
            $('.popUp.destination2 .buttonpane').before(html);
            $('.popUp.destination2 a:not(.seeAll a)').click(function() {
                var itemCode = $(this).attr('rel');
                var itemDirection = $(this).attr('direction');
                var itemReturn = $(this).attr('return');
                var itemName = $(this).text();
                //this is where we use the selected input tracking class
                //validate departure/destination of book travel search   

                $('.selectedInput').val(jQuery.trim(itemName));
                //write location code into hidden field
                $('.selectedInput').next().val(itemCode);
                $('.selectedInput').next().next().val(itemDirection);
                $('.selectedInput').next().next().next().val(itemReturn);

                //clear selectedInput
                $('.selectedInput').removeClass('selectedInput');
                //toggle the popup
                $('.popUp').slideUp();
                return false;
            });
        }
    }); //END AJAX
}
function validation() {
    var departVal = $("input.departure").val();
    var arriveVal = $("input.destination").val();
    var leaveVal = $(".datepicker.leave").val();
    var returnVal = $(".datepicker.return").val();
    var tripType = $('#tripType .radioInput input:checked').val();
    var isValid = false;

    if (departVal.toLowerCase() == "leaving from?" || arriveVal.toLowerCase() == "going to?") {
        $('.alert[rel=1]').slideDown();
        isValid = false;
    } else {
        $('.alert[rel=1]').slideUp();
        isValid = true;
    }
    if (isValid == true) {
        if (leaveVal.toLowerCase() == "date to leave?" || leaveVal.length < 1) {
            $('.alert[rel=2]').slideDown();
            isValid = false;
        } else {
            $('.alert[rel=2]').slideUp();
            isValid = true;
        }
    }
    if (isValid == true) {
        if (tripType == 2) {
            if (returnVal.toLowerCase() == "date to return?" || returnVal.length < 1) {
                $('.alert[rel=3]').slideDown();
                isValid = false;
            } else {
                $('.alert[rel=3]').slideUp();
                isValid = true;
            }
        }
    }
    if (isValid == true) {
        return true;
    } else {
        return false;
    }
}
function showMore() {
    $('.showAddOptions a').click(function() {
        var thisRel = $(this).attr('rel');
        $(".showAddOptions[rel='" + thisRel + "']").hide();
        $(".hideAddOptions[rel='" + thisRel + "']").show();
        $(".additionalContent[rel='" + thisRel + "']").slideToggle();
        return false;
    });
    $('.hideAddOptions a').click(function() {
        var thisRel = $(this).attr('rel');
            $(".hideAddOptions[rel='" + thisRel + "']").hide();
            $(".showAddOptions[rel='" + thisRel + "']").show();
            $(".additionalContent[rel='" + thisRel + "']").slideToggle();
            return false;
        });
}
function setupTabs() {
        $("#tabs").tabs();
        //Table coloring to various tables throughtout the site
        $("#tabs-1 .tabTable tbody tr:even, #tabs-2 .tabTable tbody tr:even, #tabs-3 .tabTable tbody tr:even, .reviewInfo tbody tr:even, #registrationInfo tbody tr:even").css("background-color", "#f2f2f2");
        $(".reviewInfo.currentReservations tbody:even").css("background-color", "#f2f2f2");
        $(".reviewInfo.currentReservations tbody:odd, .reviewInfo.currentReservations tbody:odd tr").css("background-color", "#ffffff");
        $(".reviewInfo.currentReservations tbody:even .buttonSection").css("background-color", "#dddcdc");
        $(".jitneyTrips:eq(0) tbody tr:last, .jitneyTrips:eq(1) tbody tr:last, .jitneyTrips:eq(2) tbody tr:last").css("border-bottom", "0px");
        $("#tabs-1 .tabTable tbody tr td:last, #tabs-2 .tabTable tbody tr td:last, #tabs-3 .tabTable tbody tr td:last").css("width", "129px");
        //adds blue coloring to selected trip in tabs and replaces dummy continuation buttons at bottom of page
        $(".tabTable input").click(function() {
            var thisRel = $(this).attr('rel');
            $('.tabTable .selected, .jitneyTrips .selected').removeClass('selected');
            $(this).parent("td").parent("tr").addClass('selected');
            $('#continueDummy, #selectreturnDummy').hide();
            $('#continue, #selectreturn').show();
            $(".alert[rel='" + 4 + "']").slideUp();
        });
        //allows user to move forward with trip selection by selecting a Hampton Jitney Trip instead of Ambassador
        $(".jitneyTrips input").click(function() {
            var thisRel = $(this).attr('rel');
            $('.tabTable .selected, .jitneyTrips .selected').removeClass('selected');
            $(this).parent("td").parent("tr").addClass('selected');
            $('#continueDummy, #selectreturnDummy').hide();
            $('#continue, #selectreturn').show();
            $(".alert[rel='" + 2 + "']").slideUp();
        });
        $("#tabs li a").click(function() {
            $(this).blur();
        });
        //shows alert if user has not selected an trip
        $('#continueDummy a, #selectreturnDummy a').click(function() {
            var thisRel = $(this).attr('rel');
            $(".alert[rel='" + thisRel + "']").slideDown();
        });
}
/* function dividerPadding() {
    //Corrects final divider padding for #bookingWrapper
    $("#bookingWrapper .divider:last").css("padding-top", "33px").css("margin-bottom", "0px");
} */
function loginValidate() {
        //Hides dummy email input and displays real one focus
        $("#emailDummy").focus(function() {
        $("#Email").show();
        $("#Email").focus();
        $(this).hide();
    });
        //Hides dummy password input and displays real one on focus
        $("#passwordDummy").focus(function() {
        $("#Password").show();
        $("#Password").focus();
        $(this).hide();
    });
        //Hides real email input if it is left blank and displays dummy
        $("#Email").blur(function() {
        var emailVal = $("#Email").val();
        if (emailVal == "") {
            $("#Email").hide();
            $("#emailDummy").show();
        }
        else {
            // Do Nothing
        }
    });
        //Hides real password input if it is left blank and displays dummy
        $("#Password").blur(function() {
        var passVal = $("#Password").val();
        if (passVal == "") {
            $("#Password").hide();
            $("#passwordDummy").show();
        }
        else {
            // Do Nothing
        }
    });
    //Hides dummy SEmail input and displays real one focus
    $("#SEmailDummy").focus(function() {
        $(this).hide();
        $("#SEmail").show();
        $("#SEmail").focus();
    });
    //Hides dummy SPassword input and displays real one on focus
    $("#SPasswordDummy").focus(function() {
        $(this).hide();
        $("#SPassword").show();
        $("#SPassword").focus();
    });
    //Hides real SEmail input if it is left blank and displays dummy
    $("#SEmail").blur(function() {
        var emailVal = $("#SEmail").val();
        if (emailVal == "") {
            $("#SEmailDummy").show();
            $("#SEmail").hide();
        }
        else {
            // Do Nothing
        }
    });
    //Hides real SPassword input if it is left blank and displays dummy
    $("#SPassword").blur(function() {
        var passVal = $("#SPassword").val();
        if (passVal == "") {
            $("#SPasswordDummy").show();
            $("#SPassword").hide();
        }
        else {
            // Do Nothing
        }
    });
}
function popBubble() {
    $('.showPopBubble').hover(
    function() {
        var thisRel = $(this).attr('rel');
        var offset = $(this).offset();
        $(".popBubble[rel='" + thisRel + "']").css("top", offset.top - 160).show();
    },
    function() {
        $('.popBubble').hide();
    });
    $('.showPopBubbleLarge').hover(
    function() {
        var thisRel = $(this).attr('rel');
        var offset = $(this).offset();
        //console.log(offset.top)
        $("#bubble[rel='" + thisRel + "']").css("top", 24).show();
    },
    function() {
        $('#bubble').hide();
    });
    $('.selectSeat').hover(
    function() {
        var offset = $(this).offset();
        $(this).before('<div class="popBubble" style="top: 401.75px; display: block;"><h3>Select Your Seat</h3><p>The option to select your seat is available on this trip.<br></p></div>');
        $(".popBubble").css("top", offset.top - 160);
        $(".popBubble").css("left", offset.left - 90);
    },
    function() {
        $('.popBubble').remove();
    });
    $('.LMTrip').hover(
    function () {
        var offset = $(this).offset();
        $(this).before('<div class="popBubble" style="top: 401.75px; display: block;"><h3>Lower Manhattan Trip</h3><p>This trip stops in lower Manhattan only.<br></p></div>');
        $(".popBubble").css("top", offset.top - 160);
        $(".popBubble").css("left", offset.left - 90);
    },
    function () {
        $('.popBubble').remove();
    });
}

function myAccountSetUp() {
    $(".myAccount #currentReservations table:odd").css("background-color", "#f2f2f2");
}
function serviceAnnounce() {
    var myUrl = "/announce/announce.xml";
    var AnnounceCounter = 0;
    $.ajax({
        type: "GET",
        url: myUrl,
        cache: false,
        dataType: "xml",
        async: true,
        success: function(xml) {
            $(xml).find('announcement').each(function() {
                AnnounceCounter++;
            });
        },
        complete: function() {
            if (AnnounceCounter > 0) {
                $('.announcement .number').text(AnnounceCounter);
                $('.announcement').slideDown();
                ActivateAnnounceLink();
            }
        }
    }); //END AJAX
    $('#modal').dialog({ autoOpen: false, modal: true });
}
function ActivateAnnounceLink() {
    $('.announcement a').click(function() {
        var myUrl = "/announce/announce.xml";
        var newHTML = "";
        $.ajax({
            type: "GET",
            url: myUrl,
            cache: false,
            dataType: "xml",
            async: true,
            success: function(xml) {
                $(xml).find('announcement').each(function() {
                    newHTML += "<div>";
                    newHTML += "<h2>" + $(this).attr('title') + "</h2>";
                    newHTML += $(this).text();
                    newHTML += "</div>";
                });
            },
            complete: function() {
                $('#modal').html(newHTML);
                $('#modal').dialog('open');
            }
        }); //END AJAX
    });
}

