$(document).ready(function(){ 
  AvailabilityChecker.initializeDialogues();
  var currentdate = new Date ();
    var year = currentdate.getFullYear () -1;  
    //initialize date drop downs
  if(($('#checkinMonth').val()=='1' && $('#checkinDay').val() == '1'&& $('#checkinYear').val()== year) && 
      ($('#checkoutMonth').val()=='1' && $('#checkoutDay').val() == '1'&& $('#checkoutYear').val()== year)){
    AvailabilityChecker.initCheckinDateCombo();
    AvailabilityChecker.initCheckinDatePicker();
    if($('#displayCheckoutDate').val()=="on"){
      AvailabilityChecker.initCheckoutDateCombo();
      AvailabilityChecker.initCheckoutDatePicker();
    
    }
    AvailabilityChecker.initFlexibleTravelDates();  
  } 
  //don't initailize date drop downs
  else{ 
    AvailabilityChecker.initCheckinDatePicker();
    if($('#displayCheckoutDate').val()=="on"){        
      AvailabilityChecker.initCheckoutDatePicker();
    }
    AvailabilityChecker.initFlexibleTravelDates();
    if($("#numberOfChildren").val()!=0){
      var numChildren = $("#numberOfChildren").val();     
      if(numChildren !=0) {       
        $("#children").show();
         for(var i=0;i<numChildren;i++)
         {
           $("#divChild"+(i+1)).show();
         }
      }
    }
  }
  
  $("#numberOfChildren").bind("change",function () {
     var numChildren = $("#numberOfChildren").find(':selected').val();      
     if(numChildren==0) {
       $("#children").hide();
     }
     else {
       $("#children").show();
       var length = $('#checkinDay')[0].options.length;
       for(var i=0;i<length;i++) {
         $("#divChild"+(i+1)).hide();
       }
       for(var i=0;i<numChildren;i++)
       {
         $("#divChild"+(i+1)).show();
       }
     }     
   });
   $('#checkinDay').bind("change",function(){
     AvailabilityChecker.setCheckinDatepicker();
     if($('#displayCheckoutDate').val()=="on"){
       AvailabilityChecker.updateCheckoutDate(1);
     }
   });
   $('#checkinMonth').bind("change",function(){   
     AvailabilityChecker.validateCheckinDay();
     AvailabilityChecker.setCheckinDatepicker();
     if($('#displayCheckoutDate').val()=="on"){
       AvailabilityChecker.updateCheckoutDate(1);   
     }
   });
   $('#checkinYear').bind("change",function(){  
     AvailabilityChecker.validateCheckinDay();
     AvailabilityChecker.setCheckinDatepicker();
     if($('#displayCheckoutDate').val()=="on"){
       AvailabilityChecker.updateCheckoutDate(1);   
     }    
   });   
   if($('#displayCheckoutDate').val()=="on"){
     $('#checkoutDay').bind("change",function(){  
       AvailabilityChecker.validateCheckoutDay();
       AvailabilityChecker.setCheckoutDatepicker();
       AvailabilityChecker.adjustNumberOfNights();
     });
     $('#checkoutMonth').bind("change",function(){  
       AvailabilityChecker.validateCheckoutDay();
       AvailabilityChecker.setCheckoutDatepicker();
       AvailabilityChecker.adjustNumberOfNights();
     });
     $('#checkoutYear').bind("change",function(){
       AvailabilityChecker.validateCheckoutDay();
       AvailabilityChecker.setCheckoutDatepicker();
       AvailabilityChecker.adjustNumberOfNights();
     });
   }
   $('#numberOfNights').bind("change",function(){
     var nights = $("#numberOfNights").find(':selected').val();
     if($('#displayCheckoutDate').val()=="on"){
       AvailabilityChecker.updateCheckoutDate(nights);
       AvailabilityChecker.setCheckoutDatepicker();
     }
   });

   
   $('#SearchForm').submit(function() {
     var children = $('#numberOfChildren').val();
     var selectChildrenAges = $('#selectChildrenAges').val();
     var childAge = ''; 
     if(selectChildrenAges=="on") {
       for(var i=1; i<=children; i++){
         if(i!=children){       
           childAge = childAge + $("#childAge" + i).find(':selected').val() + ',';
         }
         
         else {
           childAge = childAge + $("#childAge" + i).find(':selected').val();
         }
       }
       $('#childAges').val(childAge);
     }
    });
   // When Show Availability Calendar is clicked, this function is called
   $('.flexible-search span.flex-trig').click(function() {
    DailyRates.init();
    DailyRates.setFlexibleDates();
    
    var checkinYear = parseInt ($("#checkinYear").find(':selected').val(), 10);
    var checkinMonth = parseInt ($("#checkinMonth").find(':selected').val(), 10);
    DailyRates.setDailyRate(checkinYear, checkinMonth);
   });
});

var AvailabilityChecker = {
  //Updates the number of days in the check in day drop down depending on the year and month
  validateCheckinDay: function() {  
    var maxDay = AvailabilityChecker.getDaysInMonth($('#checkinMonth').val(),$('#checkinYear').val());  
    var day =  $('#checkinDay').val();  
    var length = $('#checkinDay')[0].options.length;
    $('#checkinDay')[0].options.length = maxDay;    
    for (var i = length; i < maxDay; i++) {
      $('#checkinDay')[0].options[i] = new Option(i+1,i+1);
    }
    if(day>maxDay) {
     day = maxDay;
    }
    $('#checkinDay').val(day);
  },
  //Updates the number of days in the check out day drop down depending on the year and month
    validateCheckoutDay: function() {   
    var maxDay = AvailabilityChecker.getDaysInMonth($('#checkoutMonth').val(),$('#checkoutYear').val());
    var day =  $('#checkoutDay').val();
    var length = $('#checkoutDay')[0].options.length;
    $('#checkoutDay')[0].options.length = maxDay;
    for (var i = length ; i < maxDay; i++){   
      $('#checkoutDay')[0].options[i] = new Option(i+1,i+1);
    }
    if(day>maxDay){
     day = maxDay;
    }
    $('#checkoutDay').val(day);
  },
  initCheckinDateCombo: function() {
    var currentdate = new Date ();
      var month = currentdate.getMonth () + 1;
      var year = currentdate.getFullYear ();
      var date = currentdate.getDate () + 1;    
      if (date > AvailabilityChecker.getDaysInMonth (month, year))
      {
        date = 1;
          month = month + 1;
        if (month > 12)
        {
           year = year + 1;
           month = 1;
        }     
      }
      var maxDay = AvailabilityChecker.getDaysInMonth (month, year);
      $('#checkinDay')[0].options.length = maxDay;    
      $('#checkinMonth').val(month);
    $('#checkinDay').val(date);   
    $('#checkinYear').val(year);
  },
    initCheckoutDateCombo: function() {
    var currentdate = new Date ();
      var month = currentdate.getMonth () + 1;
      var year = currentdate.getFullYear ();
      var date = currentdate.getDate () + 2;
      var maxDay = AvailabilityChecker.getDaysInMonth (month, year);
      if (date > maxDay){
        date = date - maxDay;
        month = month + 1;
        if (month > 12){
          year = year + 1;
          month = 1;
        }     
      }
      var maxDay = AvailabilityChecker.getDaysInMonth (month, year);
      $('#checkoutDay')[0].options.length = maxDay;
    $('#checkoutMonth').val(month);
    $('#checkoutDay').val(date);  
    $('#checkoutYear').val(year); 
  },
  initFlexibleTravelDates: function() {
    $(".flexible-search input.flex-date").datepick({
      rangeSelect: true,
      monthsToShow: 2,
      showTrigger: '.flexible-search span.flex-trig',
      minDate: 0,
      changeMonth: false,
      onDate: DailyRates.getDailyRate,
      onChangeMonthYear:  DailyRates.setDailyRate,
      onSelect: DailyRates.updateOtherDates,
      renderer: $.datepick.myAvailCalRenderer,
      onShow: $.datepick.hoverCallback(DailyRates.showHover),
      closeText: 'CLOSE WINDOW' /*,  THIS DIDN'T WORK AS I'D HOPED
      prevText: '<span class="ui-icon ui-icon-circle-triangle-w">Prev</span>',
      nextText: '<span class="ui-icon ui-icon-circle-triangle-e">Next</span>'
      */
    });
  },
  initCheckinDatePicker: function() {
    //set selected date in checkin date picker
    AvailabilityChecker.setCheckinDatepicker();
    var y = $('#checkinYear').get(0);   
    var minDate = new Date();
    $("#h_checkinDate").datepicker({ dateFormat: 'mm/dd/yy',
                      showOn: 'button', 
                                  buttonText: 'Calendar', 
                                  buttonImageOnly: true, 
                                  buttonImage: '/assets/webhotel/calendar-icon.png',
                                  minDate: minDate,
                                  selectOtherMonths: false,
                                  showButtonPanel: true,
                                  showOtherMonths: true,
                                  numberOfMonths: 2,
                                  onSelect: AvailabilityChecker.setCheckinDate});
  },
  initCheckoutDatePicker: function() {
    //set selected date in checkout date picker
    AvailabilityChecker.setCheckoutDatepicker();
    var y = $('#checkoutYear').get(0);    
    var minDate = new Date();
    $("#h_checkoutDate").datepicker({ dateFormat: 'mm/dd/yy',
                                   showOn: 'button', 
                                   buttonText: 'Calendar', 
                                   buttonImageOnly: true, 
                                   buttonImage: '/assets/webhotel/calendar-icon.png',
                                   minDate: minDate,
                                 selectOtherMonths: false,
                                   showButtonPanel: true,
                                   showOtherMonths: true,
                                   numberOfMonths: 2,
                                   onSelect: AvailabilityChecker.setCheckoutDate});
  },
  setCheckinDatepicker: function() {
     $('#h_checkinDate').val($("#checkinMonth").find(':selected').val() + '/' +
       $("#checkinDay").find(':selected').val() + '/' +         
       $("#checkinYear").find(':selected').val().substring(2,4));  
  },
  setCheckoutDatepicker: function() {   
    if($('#displayCheckoutDate').val()=="on"){    
       $('#h_checkoutDate').val($("#checkoutMonth").find(':selected').val() + '/' +
         $("#checkoutDay").find(':selected').val() + '/' +          
         $("#checkoutYear").find(':selected').val().substring(2,4));
    }
  },
  //Set the checkin date in the date drop downs from the check in date picker.
  setCheckinDate: function(text, control){  
      var dt = text.split('/');    
      var maxDay = AvailabilityChecker.getDaysInMonth(parseInt(dt[0],10),dt[2]);
      var day =  parseInt(dt[1],10);  
      var length = $('#checkinDay')[0].options.length;  
      $('#checkinDay')[0].options.length = maxDay;    
      for (var i = length ; i < maxDay; i++) {
          $('#checkinDay')[0].options[i] = new Option(i+1,i+1);  
      }   
      if(day>maxDay){
      day = maxDay;
      }
      $('#checkinDay').val(day);
      $("#checkinMonth").val(parseInt(dt[0],10));
      $("#checkinYear").val(dt[2]);  
      $("#h_checkinDate").val(text);    
      if($('#displayCheckoutDate').val()=="on"){
        AvailabilityChecker.updateCheckoutDate(1);
      }
    },
  //Set the checkout date in the date drop downs from the check out date picker.
    setCheckoutDate: function(text, control){
    //
    // Text is the value selected by the user in the form mm/dd/yyyy
    // Control is the checkoutdate input element  
    if($('#displayCheckoutDate').val()=="on"){
        var dt = text.split('/'); 
        var maxDay = AvailabilityChecker.getDaysInMonth(parseInt(dt[0],10),dt[2]);
        var day =  parseInt(dt[1],10);
        
        var length = $('#checkoutDay')[0].options.length;
        $('#checkoutDay')[0].options.length = maxDay;   
        for (var i = length; i <maxDay; i++) {
          $('#checkoutDay')[0].options[i] = new Option(i+1,i+1);
          
        }     
       
        if(day>maxDay){
        day = maxDay;
        }
        $('#checkoutDay').val(day);
        $('#checkoutMonth').val(parseInt(dt[0],10));
        $('#checkoutYear').val(dt[2]);
        $("#h_checkoutDate").val(text);
        
        if($('#displayNumNights').val()=="on"){
          AvailabilityChecker.adjustNumberOfNights();
        }
    }
    },
    updateCheckoutDate: function(days) {  
      AvailabilityChecker.updateDATES(days);
      AvailabilityChecker.setCheckoutDatepicker();
      AvailabilityChecker.validateCheckoutDay();
      AvailabilityChecker.reinitializeDateCombo('checkinYear', 'checkinMonth', 'checkinDay');
      AvailabilityChecker.reinitializeDateCombo('checkoutYear', 'checkoutMonth', 'checkoutDay');
    },
    reinitializeDateCombo : function(yearCombo, monthCombo, dayCombo) {
      var minDate = new Date();
      
      var year = minDate.getFullYear();
      var yrCmbVal = Number($('#' + yearCombo).val());
      
      var month = minDate.getMonth() + 1;
      var moCmbVal = Number($('#' + monthCombo).val());
      
      var day = minDate.getDate();
      var dayCmbVal = Number($('#' + dayCombo).val());
      
      $('#' + monthCombo).children('option').attr('disabled', true);
      $('#' + dayCombo).children('option').attr('disabled', true);
      
      if (yrCmbVal > year) {
        $('#' + monthCombo).children('option').attr('disabled', false);
        $('#' + dayCombo).children('option').attr('disabled', false);
      } else if (yrCmbVal == year) {
        $('#' + monthCombo).children('option').each(
          function (e) {
            var $this = $(this);
            if (Number($this.val()) >= month) {
              $this.attr('disabled', false);
            }
          }
        );
        if (moCmbVal > month) {
          $('#' + dayCombo).children('option').attr('disabled', false);
        } else if (moCmbVal == month) {
          $('#' + dayCombo).children('option').each(
            function (e) {
              var $this = $(this);
              if (Number($this.val()) >= day) {
                $this.attr('disabled', false);
              }
            }
          );
        }
      }
    },
    adjustNumberOfNights: function() {
      AvailabilityChecker.updateDATES(-1);
      AvailabilityChecker.validateCheckoutDay();
    },
    updateDATES: function(days) {
      // Get the current checkin date.
      var checkinYear = parseInt ($("#checkinYear").find(':selected').val(), 10);
      var checkinMonth = parseInt ($("#checkinMonth").find(':selected').val(), 10);
      var checkinDay = parseInt ($("#checkinDay").find(':selected').val(), 10);
    
          // set to 3:00 am to ensure it works with daylight savings time
      var checkinDate = new Date (checkinYear, checkinMonth - 1, checkinDay, 3, 0, 0);
      
      // Get the current checkout date.
      var checkoutYear = parseInt ($("#checkoutYear").find(':selected').val(), 10);
      var checkoutMonth = parseInt ($("#checkoutMonth").find(':selected').val(), 10);
      var checkoutDay = parseInt ($("#checkoutDay").find(':selected').val(), 10);
    
          // Set to 4 am to ensure the number of days will be calculated correctly with daylight savings time (Start + 1 hour)
      var checkoutDate = new Date (checkoutYear, checkoutMonth - 1, checkoutDay, 4, 0, 0);
      //adjust checkout date
      var displayNumNights = $('#displayNumNights').val();
      
      if (days != -1){
         checkoutDate = AvailabilityChecker.addDays(checkinDate,days);
         checkoutYear = checkoutDate.getFullYear() ;
         checkoutMonth = checkoutDate.getMonth() + 1;
         checkoutDay = checkoutDate.getDate() ;
         AvailabilityChecker.updateDateCombos(checkoutYear,checkoutMonth,checkoutDay,'checkoutYear', 'checkoutMonth', 'checkoutDay');
           if(displayNumNights=="on"){
             if(days != document.getElementById('numberOfNights').selectedIndex) {        
               $('#numberOfNights').val(days);
             }  
           }
      }
      //adjust number of nights
      else{
      if(displayNumNights=="on"){
        var daydiff = AvailabilityChecker.DateDiff( checkinDate,checkoutDate);  
        var nights=1;
          if(daydiff > 0){
            nights = daydiff;
          }
          else{
            nights =document.getElementById('numberOfNights').options[document.getElementById('numberOfNights').selectedIndex].value;
          }
          if (document.getElementById('numberOfNights')!=null && nights <=20){
             $('#numberOfNights').val(nights);
          } 
      }
      }   
      DailyRates.setFlexibleDates();
    },
    addDays: function(myDate,days) {
      return new Date(myDate.getTime() + days*24*60*60*1000);
    },
    DateDiff: function(start, end) {
      var daysDiff = 0;  
    
      // Create 2 error messages, 1 for each argument.
      var startMsg = "Check the Start Date and End Date\n";
          startMsg += "must be a valid date format.\n\n";
          startMsg += "Please try again." ;
     
      var stateTime = Date.parse( start ) ;
      var endTime = Date.parse( end ) ;
    
      // check that the start parameter is a valid Date.
      if ( isNaN (stateTime) || isNaN (endTime) ) {
          //alert( startMsg ) ;
          return null ;
      }     
    
      var number = endTime-stateTime ;     
      daysDiff = parseInt(number / 86400000) ;
      return daysDiff ;
    },
    updateDateCombos:function (endYear,endMonth,endDay,yearID,monthID,dayID){ 
      try{
        var objYear = eval("document.getElementById('" + yearID + "')");
        var objMonth = eval("document.getElementById('" + monthID + "')");
        var objDay = eval("document.getElementById('" + dayID + "')");
        // Update checkout year.
        for (index = 0; (index < objYear.length) &&
                        (objYear.options[index].value != endYear);
             index++);
        objYear.options[index].selected = true;
    
        // Update checkout month.
        for (index = 0; (index < objMonth.length) &&
                        (objMonth.options[index].value != endMonth);
             index++);
        objMonth.options[index].selected = true;
    
        // Update checkout day.
        for (index = 0; (index < objDay.length) &&
                        (objDay.options[index].value != endDay);
             index++);
        objDay.options[index].selected = true;        
      }catch(errorObject)
      {
        return false;
      }
      return true;
    },   
    getDaysInMonth: function(mthIdx, YrStr){
     var maxDays = 31;
     if (mthIdx==2){
        if (AvailabilityChecker.isLeapYear(YrStr)){
           maxDays=29;
        }
        else {
           maxDays=28;
        }
     }   
     if (mthIdx==4 || mthIdx==6 || mthIdx==9 || mthIdx==11){
        maxDays=30;
     }
     return maxDays;
    },
    isLeapYear: function(yrStr){
     var leapYear=false;
     if ((parseInt(yrStr, 10)%4) == 0){
        leapYear=true;
     }
     return leapYear;
    },
    localizeCheckinCheckoutMonth: function(language) {
    // TODO: This fails because the language for "regional" is not defined. [BAF 11/1/2010]
    var region = $.datepick.regional[''+language] ? $.datepick.regional[''+language] : $.datepick.regional[''];
      var monthNames = region.monthNamesShort;
    var ci = $('#checkinMonth');
    var co = $('#checkoutMonth');
      for (var i = 0; i < monthNames.length; i++) {
      if (ci.length > 0) {
          ci[0].options[i].text = monthNames[i];
      }
      if (co.length > 0) {
          co[0].options[i].text = monthNames[i];
      }
      }
    },
    initializeDialogues: function(){
       $("#roomPolicyDialog").dialog({
        autoOpen: false,
        draggable: false,
        resizable: false      
      });
     $("#rateTypeDialog").dialog({
        autoOpen: false,
        draggable: false,
        resizable: false
      });
     $("#promoCodeDialog").dialog({
        autoOpen: false,
        draggable: false,
        resizable: false
        
      });
     $("#groupCodeDialog").dialog({
        autoOpen: false,
        draggable: false,
        resizable: false
      });
     $("#corpIdDialog").dialog({
        autoOpen: false,
        draggable: false,
        resizable: false
        
      });
     $("#IATADialog").dialog({
        autoOpen: false,
        draggable: false,
        resizable: false
      });
  
     $('#roomPolicyImg').bind("click",function(){    
       $("#rateTypeDialog").dialog('close');
       $("#promoCodeDialog").dialog('close');
       $("#groupCodeDialog").dialog('close');
       $("#corpIdDialog").dialog('close');
       $("#IATADialog").dialog('close');
       $("#roomTypeDialog").dialog('close');
       var left = $(this).offset().left + 50;    
       var top = $(this).offset().top - 250; 
       $("#roomPolicyDialog").dialog({ position: [left,top] });
       $("#roomPolicyDialog").dialog('open');
     });
     $('#rateTypeImg').bind("click",function(){
       $("#roomPolicyDialog").dialog('close');
       $("#promoCodeDialog").dialog('close');
       $("#groupCodeDialog").dialog('close');
       $("#corpIdDialog").dialog('close');
       $("#IATADialog").dialog('close');
       $("#roomTypeDialog").dialog('close');
       var left = $(this).offset().left + 50;    
       var top = $(this).offset().top - 250; 
       $("#rateTypeDialog").dialog({ position: [left,top] });
       $("#rateTypeDialog").dialog('open');
     });
     $('#promoCodeImg').bind("click",function(){
       $("#roomPolicyDialog").dialog('close');
       $("#rateTypeDialog").dialog('close');
       $("#groupCodeDialog").dialog('close');
       $("#corpIdDialog").dialog('close');
       $("#IATADialog").dialog('close');
       $("#roomTypeDialog").dialog('close');
       var left = $(this).offset().left + 50;    
       var top = $(this).offset().top - 250;
       $("#promoCodeDialog").dialog({ position: [left,top] });  
       $("#promoCodeDialog").dialog('open');
     });
     $('#groupCodeImg').bind("click",function(){
       $("#roomPolicyDialog").dialog('close');
       $("#rateTypeDialog").dialog('close');
       $("#promoCodeDialog").dialog('close');
       $("#corpIdDialog").dialog('close');
       $("#IATADialog").dialog('close');
       $("#roomTypeDialog").dialog('close');
       var left = $(this).offset().left + 50;    
       var top = $(this).offset().top - 250; 
       $("#groupCodeDialog").dialog({ position: [left,top] });
       $("#groupCodeDialog").dialog('open');
     });
     $('#corpIdImg').bind("click",function(){
       $("#roomPolicyDialog").dialog('close');
       $("#rateTypeDialog").dialog('close');
       $("#promoCodeDialog").dialog('close');
       $("#groupCodeDialog").dialog('close');
       $("#IATADialog").dialog('close');
       $("#roomTypeDialog").dialog('close');
       var left = $(this).offset().left + 50;    
       var top = $(this).offset().top - 250; 
       $("#corpIdDialog").dialog({ position: [left,top] });
       $("#corpIdDialog").dialog('open');
     });
     $('#IATAImg').bind("click",function(){
       $("#roomPolicyDialog").dialog('close');
       $("#rateTypeDialog").dialog('close');
       $("#promoCodeDialog").dialog('close');
       $("#groupCodeDialog").dialog('close');
       $("#corpIdDialog").dialog('close');
       $("#roomTypeDialog").dialog('close');
       var left = $(this).offset().left + 50;    
       var top = $(this).offset().top - 250; 
       $("#IATADialog").dialog({ position: [left,top] });
       $("#IATADialog").dialog('open');
     });
     
     $('[id*=srchRoomTypeImg]').bind("click",function(){
    	 $('[id$=Dialog]').dialog('close');
         var left = $(this).offset().left + 50;    
         var top = $(this).offset().top - 250; 
         $("#roomTypeDialog").dialog({ position: [left,top] });
         $("#roomTypeDialog").dialog('open');
       });
    }
}
/*
  Daily rates

  The daily rates for the date picker are diven by a datafile which exists on the server.
  When a daily rate request is made, the entire month of rates is requested from the server
  and any further requests will be blocked until the data is retrieved.  Daily rate data is
  cached on the client for a total of 10 minutes (configurable) for each client request.
  This allows for the rates to adjust.
 */
var DailyRates = {};  // Namespace for daily rates methods
(function() {
  // ** Privately scoped **

  // Constants
  var DAILY_RATES_URL = "/bp/get_availability_calendar_data.cmd",
      CACHE_TIMEOUT = 0;  // seconds

  // Storage of daily rates (stored by month and year: MM/YYYY)
  var dailyRatesTable = {};
  
  //To track the date selected. 
  var _selectedDate = null;
  
  //To make sure the selection is due to user click
  var _userClickedSelection = false;
  
  //These variables are to make sure we do not query the data more than once.
  var _prevMonth = "";
  var _prevYear = "";
  
  // Private method to get data from the cache or server
  var _lookupRates = function (year, month) {   
    $('.datepick-popup').block({ message: "<span class='waitingMsg'>Loading ...</span>" });
    // See if the key exists in the table
    var key = month + "/" + year,
    daily = dailyRatesTable[key],
    cacheTimer = new Date().getTime();
    if (daily == null || daily.timeout < cacheTimer) {      
      var formInput = $("#SearchForm").serialize();
      formInput += "&reqMonth="+ month;
      formInput += "&reqYear=" + year;
      
      // There is no data yet, or it is stale.
      // Request data from the server
      $.ajax({
        url: DAILY_RATES_URL,
        async: true,            // Blocking request
        dataType: 'text',         // We'll perform the JSON parsing ourselves
        cache: false,
        data: formInput,
        success: function(data) {_parseDailyRateData(year, month, data); },
        error: function(xhr, status, err) {
          throw new Error(status);
        }
      });
    }
  };

  // Private method to parse the data into the rates table
  var _parseDailyRateData = function(year, month, data) {   
    
    var bError = false;
    
    if (data != null) {
      // This should be an array, at this point, of daily rates organized by month
      data = $.parseJSON(data);     
    }   
    
    if (!data || !data.rateData) {
      // No date for the requested month came back. Put an entry in the
      // table so we don't keep requesting remote data
      var key = (month + 1) + "/" + year;
      dailyRatesTable[key] = {
        timeout: (new Date()).getTime() + CACHE_TIMEOUT * 1000,
        rates: {}
      };
    
      bError = true;
      $.datepick.replaceWithError();
    }
    else {
      var showPrice = data.showPrice;
        for (var e in data.rateData) {
        // Create an entity to store in the rates table
        var entity = {
          timeout: (new Date()).getTime() + CACHE_TIMEOUT * 1000,
          rates: data.rateData[e].rateStructure,
          showPrice : showPrice
          
        };
        var key = data.rateData[e].responseMonth + "/" + data.rateData[e].responseYear;
        dailyRatesTable[key] = entity;                
      }
      var rateText = '';
      if (data.currencyCode != null) //get rate text if we have currency code
        rateText = 'All Rates shown in '+data.currencyCode;
      
      //add color legend and rate text - color legend should only be shown if site param is on
      if (data.bShowColorLegend == "true") {
        $.datepick.addColorLegendAndRateText($(".flexible-search input.flex-date"), true, rateText);      
      }
      else {
        $.datepick.addColorLegendAndRateText($(".flexible-search input.flex-date"), false, rateText);
      }
      
      $.datepick._update($(".flexible-search input.flex-date")); //update the date picker
    }
    
    $('.datepick-popup').unblock() ;
  };

  // Private method to format the rate info for the date
  var _formatDate = function(date, rateInfo, sameMonthFlag, showPrice) {
    // Force empty rateInfo to be null
    rateInfo = (typeof rateInfo === "undefined" || rateInfo.replace(/^\s*|\s*$/g,"") === "") ? null : rateInfo;
    //Display price based on configuration setting 
    if(showPrice) {
      var c = date.getDate() + "<br/>" + (rateInfo ? rateInfo : "--");      
    }
    else {
      var c = date.getDate() + "<br/>";
    }   
    var cssClass = "ratedDate" + (sameMonthFlag && rateInfo ? "" : " ui-state-unavailable");
    return { content: c, dateClass: cssClass};
  };

  DailyRates.init = function() {
    _selectedDate = null;
    _userClickedSelection = false;
    _prevMonth = "";
  };
  
  DailyRates.setDailyRate = function(year, month) {
    if(year != _prevYear || month != _prevMonth) 
      _lookupRates(year, month);
    _prevYear = year;
    _prevMonth = month;
  };
  
  // Export the method to get the daily rate to populate the date picker
  DailyRates.getDailyRate = function(date, sameMonthFlag) {
    var key = (date.getMonth() + 1) + "/" + date.getFullYear();
    var daily = dailyRatesTable[key];   
    return daily && daily.rates ? _formatDate.call(this, date, daily.rates[date.getDate()], sameMonthFlag, daily.showPrice) : "";
  };

  DailyRates.updateOtherDates = function(dates) {
    var oneday = 86400000; // In milliseconds
    if (_userClickedSelection) {
      // "dates" will be an array with two entries in it.  The first
      // is the start date, the second is the end date.  If the start
      // and end date are the same, don't do anything
      var st = dates[0];
      var en = dates[1];
      if(!(typeof st === "undefined") &&  !(typeof en === "undefined")){
        if (st.getTime() != en.getTime()) {
          // They differ.  Update the two date pickers above
          AvailabilityChecker.setCheckinDate((st.getMonth() + 1) + "/" + st.getDate() + "/" + st.getFullYear());
          var nightsDropdown = $('#numberOfNights');
          if (nightsDropdown.length == 0) {
            AvailabilityChecker.setCheckoutDate((en.getMonth() + 1) + "/" + en.getDate() + "/" + en.getFullYear());
          } else {
            nightsDropdown.val(Math.ceil((en.getTime() - st.getTime()) / oneday));
          }
        }
      }
      _selectedDate = new Date(st);
    }
    
    _userClickedSelection = true;
  };

  DailyRates.setFlexibleDates = function() {
    // Get the current checkin date.
    var checkinYear = parseInt ($("#checkinYear").find(':selected').val(), 10);
    var checkinMonth = parseInt ($("#checkinMonth").find(':selected').val(), 10);
    var checkinDay = parseInt ($("#checkinDay").find(':selected').val(), 10);
    var checkinDate = new Date (checkinYear, checkinMonth - 1, checkinDay, 3, 0, 0);

    // Get the current checkout date.
    var nightsDropdown = $('#numberOfNights');
    var checkoutDate;
    if (nightsDropdown.length == 0) {
      var checkoutYear = parseInt ($("#checkoutYear").find(':selected').val(), 10);
      var checkoutMonth = parseInt ($("#checkoutMonth").find(':selected').val(), 10);
      var checkoutDay = parseInt ($("#checkoutDay").find(':selected').val(), 10);
      checkoutDate = new Date (checkoutYear, checkoutMonth - 1, checkoutDay, 4, 0, 0);
    } else {
      checkoutDate = new Date(checkinDate.getTime());
      checkoutDate.setDate(checkoutDate.getDate() + parseInt(nightsDropdown.val()));
    }

    var dates = [checkinDate];
    if (checkoutDate.getTime() > checkinDate.getTime()) {
      dates.push(checkoutDate);
    }
    
    $(".flexible-search input.flex-date").datepick('setDate', dates);
  };

  DailyRates.showHover = function(date, selectable) {
    
    if (selectable && _selectedDate != null && date >= _selectedDate ) {
      $(".datepick-popup .selected-date-background").removeClass("selected-date-background");
      var curDate = new Date(_selectedDate);
      while (curDate <= date) {
        var rateDateClass = ".datepick-popup .dp" + curDate.getTime();
        $(rateDateClass).each(function() {
          var d = $(this);
          if (!d.hasClass("ui-datepicker-other-month")) {
            d.addClass("selected-date-background");
            d.parent().addClass("selected-date-background");
          }
        });
        
        curDate.setDate(curDate.getDate() + 1);
      }
    }
  };
  
})();

/**
 * This method handles rate change events on /bp/room_type_details.cmd page
 * @param roomTypeCode room type code
 * @param roomPlanRateCode room plan rate
 * @param numOfUnits number of units
 */
function selectRate(roomTypeCode, roomPlanRateCode, numOfUnits) {
  jQuery(document).ready(function() {
    jQuery("#roomTypeCode").val(roomTypeCode);
    jQuery("#ratePlanCode").val(roomPlanRateCode);
    jQuery("#numOfUnits").val(numOfUnits);

    var form = jQuery("#searchRoomForm");
    form.attr("action", "/bp/room_type_details.cmd");
    form.submit();
  });
}




