﻿
//var $ = jQuery.noConflict();

var affiliateDefaultSelectedPickupLocation;

// Initialize Global Vars
var locationType; //international vs. domestic
var datePickerClicked;
var usingVehicleMake = true;
var usingCountryRadioList = false;

var g_urlParams = null;

(function ($, undef) { $.QueryString = function (url) { var pairs, qs = null, index, map = {}; if (url == undef) { qs = window.location.search.substr(1); } else { index = url.indexOf('?'); if (index == -1) return {}; qs = url.substring(index + 1); } pairs = qs.split('&'); if (pairs == "") return {}; for (var i = 0; i < pairs.length; ++i) { var p = pairs[i].split('='); if (p.length != 2) continue; map[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " ")); } return map; }; })(jQuery);


function rePostionDiv()
{
    if (document.location.href.toLowerCase().indexOf('reservationwidget.aspx') >= 0 && isIE)
    {
        var dp = document.getElementById('ui-datepicker-div');
        dp.style.margin = 0;
        dp.style.left = (parseInt(datePickerClicked.offsetLeft) + parseInt(datePickerClicked.parentNode.offsetLeft));
        dp.style.top = (parseInt(datePickerClicked.offsetTop) + parseInt(datePickerClicked.parentNode.offsetTop) + 20);
    }
}

// Run this code after all DOM elements have loaded.
$(document).ready(function () {

    g_urlParams = jQuery.QueryString(theForm.action); 

    // set country type
    if (usingCountryRadioList) {
        locationType = 1;
    }
    else {
        locationType = 0;
    }

    // Initialize the datepicker controls.
    $("#" + pickupDateID).datepicker($.extend({}, $.datepicker.regional[culture], {
        defaultDate: +pickupDays,
        minDate: 0,
        maxDate: 1092,
        showAnim: "slideDown",
        duration: "fast",
        showStatus: true,
        mandatory: true,
        closeAtTop: false,
        showOn: "both",
        buttonImage: imagesDirectory + "Content/calendar.gif",
        buttonImageOnly: true,
        buttonText: "Select Date",
        beforeShow: function () {
            datePickerClicked = this;
            setTimeout(rePostionDiv, 50);
        }

    }));
    $("#" + dropoffDateID).datepicker($.extend({}, $.datepicker.regional[culture], {
        defaultDate: +pickupDays + dropoffDays,
        minDate: 0,
        maxDate: 1092,
        showAnim: "slideDown",
        duration: "fast",
        showStatus: true,
        mandatory: true,
        closeAtTop: false,
        showOn: "both",
        buttonImage: imagesDirectory + "Content/calendar.gif",
        buttonImageOnly: true,
        buttonText: "Select Date",
        beforeShow: function () {
            datePickerClicked = this;
            setTimeout(rePostionDiv, 50);
        }
    }));
    $("#" + rbDomesticLocationID).click(function () { locationType = 1; fillPickupLoc(locationType); fillDropoffLoc(locationType) });
    $("#" + rbInternationalLocationID).click(function () { locationType = 2; fillPickupLoc(locationType); fillDropoffLoc(locationType) });
    cAutocomplete.IE_FIX = isBrowserEarlyIE();
    cAutocomplete.CN_NUMBER_OF_LINES = 8;
    cAutocomplete.CN_HEIGHT_FIX = 15
    cAutocomplete.autoInit();
    // Toggle the promo code box.
    if ($("#" + chkHasPromoCodeID)[0] != null && !$("#" + chkHasPromoCodeID)[0].checked) {
        $("#" + reservationWidgetPromoCodeInputID).hide(); // Start off hidden
        $("#" + reservationWidgetCorporateCodeInputID).hide();
    }
    $("#" + chkHasPromoCodeID).click(function () { moveGuideImage(6); $("#" + reservationWidgetPromoCodeInputID).toggle(); $("#" + reservationWidgetCorporateCodeInputID).toggle(); });
    $("#" + txtCorporateCodeID).change(function () { moveGuideImage(6); clearPromotionCode(); });
    $("#" + txtCorporateCodeID).focus(function () { moveGuideImage(6); });
    $("#" + txtPromoCodeID).change(function () { moveGuideImage(7); clearCorporateCode(); });
    $("#" + txtPromoCodeID).focus(function () { moveGuideImage(7); });
    // Set up control events
    $("#" + pickupDateID).change(function () { fillPickupHoursList(); setDropoffDate(); fillDropoffHoursList(); });
    $("#" + pickupDateID).focus(function () { moveGuideImage(2); });
    $("#" + ddlPickupTimeID).focus(function () { moveGuideImage(3); });
    $("#" + dropoffDateID).change(function () { fillDropoffHoursList(); });
    $("#" + dropoffDateID).focus(function () { moveGuideImage(4); });
    $("#" + ddlDropoffTimeID).focus(function () { moveGuideImage(5); });
    $("#" + lnkEditReservation).click(function () {
        $("#" + guideImage).hide();
        $("#" + showReservationWidgetID).slideToggle("fast");
        $("#" + showViewModifyCancelID).slideToggle("fast");
        $("#" + imgModifyCancelGuide).show();
    });
    $("#lnkMakeReservation").click(function () {
        $("#" + imgModifyCancelGuide).hide();
        $("#" + showReservationWidgetID).slideToggle("fast");
        $("#" + showViewModifyCancelID).slideToggle("fast");
        $("#" + guideImage).show();
    });
    $("#" + txtLastNameID).focus(function () { moveModifyCancelGuideImage(1); });
    $("#" + txtConfirmationNumberID).focus(function () { moveModifyCancelGuideImage(2); });
    // Set dropoff location and dates with Javascript for back button compatibility.
    //setDropoffLocation();
    setDatesWithSessionData();

    //checkBrowser();
    if (usingVehicleMake) {
        initializeMakesList();
    }
    else {
        fillPickupLoc(locationType);
    }

});

function initializeMakesList()
{
    fillMakesList();
}



function getInternetExplorerVersion()
{
    var rv = -1;    // assumes failure
    if (navigator.appName == 'Microsoft Internet Explorer')
    {
        var ua = navigator.userAgent;
        var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
        if (re.exec(ua) != null)
        {
            rv = parseFloat(RegExp.$1);
        }
    }
    return rv;
}   

function moveGuideImage(toPosition)
{   
    switch(toPosition)
    {
        case 1:
            $("#" + guideImage).animate({top: bookingGuideImageTop1}, 1000);
            break;
        case 2:
            $("#" + guideImage).animate({top: bookingGuideImageTop2}, 1000);
            break;
        case 3:
            $("#" + guideImage).animate({top: bookingGuideImageTop3}, 1000);
            break;
        case 4:
            $("#" + guideImage).animate({top: bookingGuideImageTop4}, 1000);
            break;
        case 5:
            $("#" + guideImage).animate({top: bookingGuideImageTop5}, 1000);
            break;
        case 6:
            if($("#" + chkHasPromoCodeID)[0].checked)
                $("#" + guideImage).animate({top: bookingGuideImageTop6}, 1000);
            else
                $("#" + guideImage).animate({top: bookingGuideImageTop5}, 1000); 
            break;
        case 7:
            $("#" + guideImage).animate({top: bookingGuideImageTop7}, 1000);
            break;
    }
} 
function moveModifyCancelGuideImage(toPosition)
{
    switch(toPosition)
    {
        case 1:
            $("#" + imgModifyCancelGuide).animate({top: "20px"}, 1000);
            break;
        case 2:
            $("#" + imgModifyCancelGuide).animate({top: "70px"}, 1000);
            break;
    }
}
function vehicleMakeChange()
{
    fillPickupLoc(locationType);
}
function pickupLocationChange()
{
    fillPickupHoursList();
    fillDropoffLoc(locationType);
    setDropoffDate();
    fillDropoffHoursList();
    moveGuideImage(2);
}
function getSelectedPickupLocationId()
{
    var value = document.getElementById(ddlPickupLocationID).value;
    if(value == undefined)
    {
        return -1;
    }
    
    return value;
}

function setDropDownListLoadingText(objectId)
{
    $('#' + objectId).find('option').remove();
    $('#' + objectId).append("<option value=\"-1\">" + loadingText + "</option>");
}

function setAffiliateDefaultMake()
{
    ETS.UI.Services.VehicleService.GetAffiliateDefaultManufacturer(affiliateID, setAffiliateDefaultMake_CallBack);
}
function setAffiliateDefaultMake_CallBack(response)
{
    //alert(response);
    $('#' + ddlMakeID).val(response);
    fillPickupLoc(locationType);
}

function fillMakesList()
{
    setDropDownListLoadingText($('#' + ddlMakeID).attr('id'));
    ETS.UI.Services.VehicleService.GetMakeListItems(fillMakesList_CallBack);
}
function fillMakesList_CallBack(response)
{
    var makes = document.getElementById(ddlMakeID);
    fillDropDownList(response, $('#' + ddlMakeID).attr('id'));
    setAffiliateDefaultMake();
}

function pickupCountryChange()
{
    locationType = document.getElementById(ddlCountryID).value * 1;
    
    fillPickupLoc(locationType);
}

function fillPickupLoc(countryGrouping)
{
    affiliateDefaultSelectedPickupLocation = $('#' + ddlPickupLocationID).val();
    setDropDownListLoadingText($('#' + ddlPickupLocationID).attr('id'));
    
    if (usingVehicleMake)
    {
        manufacturerSelectedValue = 0;
        manufacturerSelectedValue = document.getElementById(ddlMakeID).value * 1;        
        
        ETS.UI.Services.LocationService.GetPickupLocationsListItemsFromVehicleManufacturer(countryGrouping, bookingVehicleID, manufacturerSelectedValue, fillPickupLoc_CallBack);
    }
    else
    {
        ETS.UI.Services.LocationService.GetPickupLocationsListItems(countryGrouping, bookingVehicleID, affiliateID, fillPickupLoc_CallBack);
    }
}
function fillPickupLoc_CallBack(response)
{
    var pickupLocations = document.getElementById(ddlPickupLocationID);
    fillLocationDropDownList(response, $('#' + ddlPickupLocationID).attr('id'), defaultPickupLocationValue);
    $('#' + ddlPickupLocationID).val(affiliateDefaultSelectedPickupLocation);

    fillDropoffLoc(locationType);

  if( g_urlParams.ReferralCode == '045CBF3A-F3D1-44BE-8FE7-A2AE55F1EF1C' )
    {
      custCode001( response );
    }
}

function getSelectedDropoffLocationId()
{
    var value = document.getElementById(ddlDropoffLocationID).value;
    if(value == undefined)
    {
        return -1;
    }
    
    return value;
}

function dropoffLocationChange()
{
    setDropoffDate();
    fillDropoffHoursList();
}        
function resetDropOffList()
{
    fillLocationDropDownList("", $('#' + ddlDropoffLocationID).attr('id'), defaultDropoffLocationValue);
}
function fillDropoffLoc(locationType)
{
    var pickupLocationID = getSelectedPickupLocationId();
    
    if (pickupLocationID > 0)
    {
        setDropDownListLoadingText($('#' + ddlDropoffLocationID).attr('id'));
        ETS.UI.Services.LocationService.GetValidDropoffLocationsListItems(pickupLocationID, $("#" + pickupDateID).val(), locationType, cultureName, fillDropoffLoc_CallBack);
    }
    else
    {
        resetDropOffList();
    }
}
function fillDropoffLoc_CallBack(response)
{
    var dropoffLocations = document.getElementById(ddlDropoffLocationID);
    fillLocationDropDownList(response, $('#' + ddlDropoffLocationID).attr('id'), defaultDropoffLocationValue);
}

function fillDropDownList(response, ddlID)
{
    $('#' + ddlID).find('option').remove();
    var options = "";
    
    $.each(response, function(key, value)
    {
        var optionValue = value.Text;
        var optionKey = value.Value;
        
        options += "<option value=\"" + optionKey + "\">" + optionValue + "</option>";
   })
   $('#' + ddlID).append(options);
}

function fillLocationDropDownList(response, ddlID, defaultValue)
{
    $('#' + ddlID).find('option').remove();
    $('#' + ddlID).find('optgroup').remove();
    var options;
    options = "<optgroup>" + "<option value=\"-1\">" + defaultValue + "</option>";
    
    $.each(response, function(key, value)
    {
        var optionValue = value.Text;
        var optionKey = value.Value;
            
        if (optionKey < 0)
        {
            var optgroupText = "</optgroup><optgroup label=\"" + optionValue + "\">";
            options += optgroupText;
	    }
        else
        {
            options += "<option value=\"" + optionKey + "\">" + optionValue + "</option>";
        }
    })
    options += "<optgroup>";
    $('#' + ddlID).append(options);
}

function fillPickupHoursList()
{
    var pickupLocationID = getSelectedPickupLocationId();
    if(pickupLocationID > 0) 
    {
        setDropDownListLoadingText($('#' + ddlPickupTimeID).attr('id'));
        ETS.UI.Services.LocationService.GetLocationTimes(pickupLocationID,$("#" + pickupDateID).val(), cultureName, fillPickupHoursList_CallBack);
    }
}
function fillPickupHoursList_CallBack(response) 
{
    /* 2000 Charge related changes by Henrik - Starts */
    //var selectedTime = $("#" + ddlPickupTimeID).val();
    //fillListItems(ddlPickupTimeID, response);
    //selectFromList($("#" + ddlPickupTimeID)[0], selectedTime);
    var eList = getObject(ddlPickupTimeID);
    var selectedTime = $("#" + ddlPickupTimeID).val();
    if (response.length == 48) {
        fillListItems(ddlPickupTimeID, [{ Name: '  CLOSED', Value: '-1'}]);
        if (eList) {
            eList.style.backgroundColor = "yellow";
        }
    }
    else {
        fillListItems(ddlPickupTimeID, response);
        if (eList) {
            eList.style.backgroundColor = "white";
        }
    }
    /* 2000 Charge related changes by Henrik - Ends */
}
function fillDropoffHoursList()
{
    var dropoffLocationID = (getSelectedDropoffLocationId() == -1) ?  getSelectedPickupLocationId() : getSelectedDropoffLocationId();
    if(dropoffLocationID > 0)
    {
        setDropDownListLoadingText($('#' + ddlDropoffTimeID).attr('id'));
        ETS.UI.Services.LocationService.GetLocationTimes(dropoffLocationID, $("#" + dropoffDateID).val(), cultureName, fillDropoffHoursList_CallBack);
    }
}
function fillDropoffHoursList_CallBack(response) 
{
    /* 2000 Charge related changes by Henrik - Starts */
    //var selectedTime = $("#" + ddlDropoffTimeID).val();
    //fillListItems(ddlDropoffTimeID, response);
    var eList = getObject(ddlDropoffTimeID);
    var selectedTime = $("#" + ddlDropoffTimeID).val();
    if (response.length == 48) {
        fillListItems(ddlDropoffTimeID, [{ Name: '  CLOSED', Value: '-1'}]);
        if (eList) {
            eList.style.backgroundColor = "yellow";
        }
    }
    else {
        fillListItems(ddlDropoffTimeID, response);
        if (eList) {
            eList.style.backgroundColor = "white";
        }
    }
    /* 2000 Charge related changes by Henrik - Ends */
    //selectFromList($("#" + ddlDropoffTimeID)[0], selectedTime);
}

function setDatesWithSessionData()
{
    ETS.UI.Services.ReservationService.GetDatesFromSession(cultureName, setDatesWithSessionData_CallBack);
}
function setDatesWithSessionData_CallBack(response)
{
    $("#" + pickupDateID).val(response[0]);
    $("#" + dropoffDateID).val(response[1]);
}

// Sets the drop off date based on drop-off location and pick-up date.
function setDropoffDate() 
{
    var dropoffLocationID = getSelectedDropoffLocationId();
    var daysToAdd = (dropoffLocationID == -1) ? dropoffDays : onewayDropOffDays;

    var pickupDate = new Date($("#" + pickupDateID).val());
    pickupDate = $.datepicker.parseDate($.datepicker.regional[culture].dateFormat, $("#" + pickupDateID).val());

    var dropoffDate = new Date($("#" + dropoffDateID).val());
    dropoffDate = $.datepicker.parseDate($.datepicker.regional[culture].dateFormat, $("#" + dropoffDateID).val());

	var daysCount = daysInMonth(pickupDate.getMonth(), pickupDate.getFullYear());

	if(Date.parse(dropoffDate.toDateString()) <= Date.parse(pickupDate.toDateString()))
	{
	    if((pickupDate.getDate() + daysToAdd) > daysCount) 
	    {   // Roll over to next month.
	        if (pickupDate.getMonth() >= 11) {
	            //alert((pickupDate.getDate() + daysToAdd - daysCount));
	            $("#" + dropoffDateID).val($.datepicker.formatDate($.datepicker.regional[culture].dateFormat, new Date((pickupDate.getFullYear() + 1), 0, (pickupDate.getDate() + daysToAdd - daysCount))));
	            //$("#" + dropoffDateID).val(1 + "/" + (pickupDate.getDate() + daysToAdd - daysCount) + "/" + (pickupDate.getFullYear() + 1));
	            //$("#" + dropoffDateID).val(1 + "/" + (pickupDate.getDate() + daysToAdd - daysCount) + "/" + (pickupDate.getFullYear() + 1));
	        }
	        else {
	            $("#" + dropoffDateID).val($.datepicker.formatDate($.datepicker.regional[culture].dateFormat, new Date(pickupDate.getFullYear(), (pickupDate.getMonth() + 1), (pickupDate.getDate() + daysToAdd - daysCount))));
                //$("#" + dropoffDateID).val((pickupDate.getMonth() + 2) + "/" + (pickupDate.getDate() + daysToAdd - daysCount) + "/" + pickupDate.getFullYear());
	        }
        }
        else 
        {
            $("#" + dropoffDateID).val($.datepicker.formatDate($.datepicker.regional[culture].dateFormat, new Date(pickupDate.getFullYear(), pickupDate.getMonth(), pickupDate.getDate() + daysToAdd)));
            //$("#" + dropoffDateID).val(new Date(pickupDate.getFullYear(), pickupDate.getMonth(), pickupDate.getDate() + daysToAdd));
            //$("#" + dropoffDateID).val(pickupDate.getMonth() + 1 + "/" + (pickupDate.getDate() + daysToAdd) + "/" + pickupDate.getFullYear());
        }
	} 
}



// Sets the drop off date based on drop-off location and pick-up date.
function setDropoffDateOld()
{
    var dropoffLocationID = getSelectedDropoffLocationId();
    var daysToAdd = (dropoffLocationID == -1) ? dropoffDays : onewayDropOffDays;
    var pickupDate = new Date($("#" + pickupDateID).val());
	var dropoffDate = new Date($("#" + dropoffDateID).val());
	
	var daysCount = daysInMonth(pickupDate.getMonth(), pickupDate.getFullYear());
	if(Date.parse(dropoffDate.toDateString()) <= Date.parse(pickupDate.toDateString()))
	{
	    if((pickupDate.getDate() + daysToAdd) > daysCount) 
	    {   // Roll over to next month.
            if(pickupDate.getMonth() >= 11) 
            {
                $("#" + dropoffDateID).val(1 + "/" + (pickupDate.getDate() + daysToAdd - daysCount) + "/" + (pickupDate.getFullYear() + 1));
            }
            else 
                $("#" + dropoffDateID).val((pickupDate.getMonth() + 2) + "/" + (pickupDate.getDate() + daysToAdd - daysCount) + "/" + pickupDate.getFullYear());
        }
        else 
        {
            $("#" + dropoffDateID).val(pickupDate.getMonth() + 1 + "/" + (pickupDate.getDate() + daysToAdd) + "/" + pickupDate.getFullYear());
        }
	} 
}

/*
 iMonth is zero based - January is 0
 */
function daysInMonth(iMonth, iYear)
{
    return 32 - new Date(iYear, iMonth, 32).getDate();
}


function clearPromotionCode()
{
    var corporateCode = $("#" + txtCorporateCodeID).val();
    if(corporateCode.length > 0)
    {
        $("#" + txtPromoCodeID).val("");
    }
}
function clearCorporateCode()
{
    var corporateCode = $("#" + txtPromoCodeID).val();
    if(corporateCode.length > 0)
    {
        $("#" + txtCorporateCodeID).val("");
    }
}




// EagleRider Booking Widget v02 for Wild Fire - Harley Davidson 
function custCode001( response )
{
  // Vehicle Type
    $('#' + ddlMakeID).val('1');
    $('#' + ddlMakeID).attr("disabled", "disabled");

  // Pickup Country
    $('#' + ddlCountryID).val('1');
    $('#' + ddlCountryID).attr("disabled", "disabled");

  // Pickup City
    var _ID = $('#' + ddlPickupLocationID).attr('id')
      $('#' + _ID).find('option').remove();
      $('#' + _ID).find('optgroup').remove();

    var options;
      options = "<optgroup>" + "<option value=\"-1\">" + "Choose One..." + "</option>";

      $.each( response , function( key , value ) {
          var optionValue = value.Text;
          var optionKey = value.Value;

          if (optionKey < 0 && optionValue == 'Illinois' )
            {
              var optgroupText = "</optgroup><optgroup label=\"" + optionValue + "\">";
                options += optgroupText;
            }
          else if( optionKey == '218' || optionKey == '23954' || optionKey == '23949' )
            {
              options += "<option value=\"" + optionKey + "\">" + optionValue + "</option>";
            }
      })
      options += "<optgroup>";
      $('#' + _ID).append( options );

}


