﻿// On load
$(document).ready(function()
{
    // Itinerary jquery tabs initialize.
    $(".TabControl").tabs();
    $("#ItineraryNestedTabs").tabs({ selected: 1 });    
});

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// Translates a Javascript date to match format .NET code expects.
function formatDateForDotNet(day, month, year)
{
    return (month + 1) + "/" + day + "/" + year;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// Updates the Itinerary Date Range title when switching between multiple itineraries.
function updateItineraryDateRangeTitle(title, subtititle, itineraryId, dvdUrl)
{
    $('#ItineraryTitle').html(title);
    $('#ItinerarySubTitle').html(subtititle);
        
    $('.ItineraryContainer').each(function()
    {
        $(this).css('display', 'none');
    });
    
    // Show the selected itinerary
    $('#Itinerary' + itineraryId).show();
    
    // Update the DVD Share link
    $('#DvdShare').css('display', 'none');
    if (dvdUrl != '')
    {
        $('#DvdShare').attr('href', dvdUrl)
        $('#DvdShare').show();
    }
    
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function loadCalendar()
{
    var tourCode = $('#TourCode').attr('value');
    var tourDuration = $('#TourDuration').attr('value');
    var tourFirstDeparture = $('#TourFirstDeparture').attr('value');
    var departureDateFormat = new Date(tourFirstDeparture);
    var dateList = new Array();
    var unavailableDateList = new Array();
    var minimumDate = new Date();
    var maximumDate = new Date();
    var dateCounter = 0;
    
    $.ajax(
    {
        url: '/Tour/GetTourAvailability/' + tourCode + '/' + tourDuration + '/' + (departureDateFormat.getMonth() + 1) + "-" + departureDateFormat.getDate() + "-" + departureDateFormat.getFullYear(),
        dataType: "json",
        ifModified: true,
        // Code to execute when AJAX returns an error.
        error: function()
        {
            // Display an alert and switch back to first tab.
            alert('Departure dates are currently unavailable.\n\nContact APT directly to make a booking.\n\n');
            $("#Tabs").tabs({ selected: 0 });
        },
        // Code to execute when AJAX returns successfully.
        success: function(data) 
        {
            // Cycle through all dates to find first and last departures.
            $.each(data, function(index, data)
            {
                // Convert AJAX data to JS date format.
                var availableDate = new Date(data.Value);
                // If this is the first iteration, assign minimumDate variable.
                if (dateCounter == 0) { minimumDate = availableDate; }
                dateCounter++;
                // If this date is less than current minimum, replace.
                if (availableDate < minimumDate) { minimumDate = availableDate; }
                // If this date is greater than current maximum, replace.
                if (availableDate > maximumDate) { maximumDate = availableDate; }
            });
            
            // Set minimumDate to first day of month.
            minimumDate.setDate(1);
            
            if (maximumDate.getMonth() in (['1'])) // If month is Feb.
            {
                maximumDate.setDate(28); // Last day of month is 28th (Ignore leap year)
            }
            else if (maximumDate.getMonth() in (['3','5','8','10'])) // If month is Apr, Jun, Sep or Nov.
            {
                maximumDate.setDate(30); // Last day of month is 30th
            }
            else
            {
                maximumDate.setDate(31); // Otherwise, last day of month is 31st
            }
            
            
            // Call back function, once JSON object been returned.                      
            $(function() 
            {
                // Create datepicker widget.
                $('#DatePicker').datepicker(
                {                        
                    numberOfMonths: 2,
                    stepMonths: 2,
                    hideIfNoPrevNext: true,
                    minDate: minimumDate,
                    maxDate: maximumDate,
                    // Function to be run when rendering each day.
                    beforeShowDay: function(date)
                    {
                        // Format current datepicker date
                        var currentDay = new Date(date);
                        var currentDayFormat = formatDateForDotNet(currentDay.getDate(), currentDay.getMonth(), currentDay.getFullYear());
                        // Initialize variables.
                        var availableDateFormat, dateAvailable, dateLimited, dateUnavailable;
                        
                        // Iterate through Json data values and run function.
                        $.each(data, function(index, data)
                        {
                            // Format current Json string to date value.
                            var availableDate = new Date(data.Value);
                            availableDateFormat = formatDateForDotNet(availableDate.getDate(), availableDate.getMonth(), availableDate.getFullYear());
                
                            // Test if current datepicker date matches any Json dates
                            if (currentDayFormat == availableDateFormat)
                            {
                                if (data.Text > 6)
                                {
                                    // Date has availability
                                    dateAvailable = true;
                                }
                                else if (data.Text > 1 && data.Text <= 6)
                                {
                                    // Date has limited availability
                                    dateLimited = true;
                                }
                                else
                                {
                                    // Date has no availability
                                    dateUnavailable = true;
                                }

                                // Breaks out of loop.
                                return false;
                            }
                        });
                        
                        // If current date matches JSON date.
                        if (dateAvailable == true)
                        {
                            // Assign valid date to array.
                            dateList.push(currentDayFormat);
                            // Apply CSS styling to signal date is available.
                            return [true, 'CalendarAvailable'];
                        }
                        
                        // If current date matches JSON date.
                        if (dateLimited == true)
                        {
                            // Assign valid date to array.
                            dateList.push(currentDayFormat);
                            // Apply CSS styling to signal date is available.
                            return [true, 'CalendarLimited'];
                        }
                        
                        // If current date matches JSON date.
                        if (dateUnavailable == true)
                        {
                            // Assign valid date to array.
                            unavailableDateList.push(currentDayFormat);
                            // Apply CSS styling to signal date is available.
                            return [true, 'CalendarUnavailable'];
                        }
                        
                        // Otherwise apply default styling.
                        return [true, 'CalendarDate'];
                    },
                    onSelect: function(dateText, inst) 
                    {
                        // Format selected date value.
                        var currentDay = new Date(dateText);                                                
                        var currentDayFormat = formatDateForDotNet(currentDay.getDate(), currentDay.getMonth(), currentDay.getFullYear());
                        
                        // Check if selected date is contained in valid date array.
                        // The if statement will return -1 if currentDayFormat is not found in array.
                        if ($.inArray(currentDayFormat, dateList) != -1)
                        {
                            // Once datepicker finished loading, hide loading animation and fade in datepicker.
                            $('#DatePickerContainer').fadeOut('normal', function() 
                            {
                                $('#Loading').fadeIn('slow');
                            });
                            
                            // Update field value
                            $('#DepartureDate').val(dateText);                            
                            // Submit form.
                            $('#PackageBookingForm').submit();
                        }
                        else if ($.inArray(currentDayFormat, unavailableDateList) != -1)
                        {
                            // When invalid date clicked, clear hidden input value.
                            $('#DepartureDate').val('');
                            // Reset Departure Date drop down to default.
                            $('#DateSelect option[value=""]').attr('selected', 'selected');
                            alert('Contact us for availability.');
                        }
                    }
                });
            });
            // Once datepicker finished loading, hide loading animation and fade in datepicker.
            $('#Loading').fadeOut('normal', function() 
            {
                $('#DatePickerContainer').fadeIn('slow', function()
                {
                    // Fix IE rendering issues.
                    if (jQuery.browser.msie)
                    {
                        this.style.removeAttribute('filter');
                    }
                });
            });
        }
    });      
}