// --------------------------------------------------------------------------------
/*
   Program: a1villa_checkavailability.js
   
   Author:  James Whitfield
   Date:    23 July 2003
   
   Description:
   
   Checks availability against the bookings file.

   Amendments:

   01/11/03  JJW  Recognize villa.
   03/12/03  JJW  Reworking on booking references
   02/01/04  JJW  Recognize booking status.
   29/02/04  JJW  Increased number of nights available to 28 on drop-down.  Added
                  in 'flexible dates' option.
   06/07/05  JJW  Alternative dates and flexibility added
   18/07/05  JJW  Corrected day of arrival.
   06/10/05  JJW  Amended 'GetVillaName' to reflect passed value from form.
   12/10/05  JJW  Reworked logic for days 1-9.
   15/10/06  JJW  Only return nights when not 0 for FormatStayPeriod.
   07/06/09  JJW  Revamped for new 2009 website.
   13/10/09  JJW  Corrected for FireFox.
   19/10/09  JJW  Corrected issue with no earlier-later dates when provisional
                  booking clashes with dates requested.  Renamed variables.
   22/10/09  JJW  Corrected for Firefox.
   02/01/10  JJW  Ensure provisionally held message is displayed correctly.
   29/07/11  JJW  Re-worked for v10.

*/
// --------------------------------------------------------------------------------

// ====================================================================================================

//------------------------------------------------------------------------------------------------------------------------
// Determine availability of the specific dates.
// 0=Not available
// 1=Is Available
// 2=Provisional Held

function IsVillaAvailable(start_date, end_date, villa_code)
{

 var start_date_dms    = Date.parse(start_date);
 var end_date_dms      = Date.parse(end_date);
 var vm_arrival_date   = new Date();
 var vm_departure_date = new Date();
 var is_available      = 1; 

// Read through current bookings, working on the optimistic approach 
// that there is availability.  That is, until a booking exists that
// clashes with your request.  Compare against dates e.g. CEF20E10

 for (idx = 0; idx < bk.length; idx++) {
    if (bk[idx].charAt(5) == villa_code) {
        vm_booking_status = bk[idx].charAt(0);
        vm_arrival_year   = bk[idx].charCodeAt(1) - 64 +2000;  
        vm_arrival_month  = bk[idx].charCodeAt(2) - 65;

        if ( bk[idx].charAt(3) == "0" ) {
           vm_arrival_day  = parseInt(bk[idx].charAt(4)) }
         else { vm_arrival_day  = parseInt(bk[idx].substring(3,5)) };

        var vm_nights         = parseInt(bk[idx].substring(6,8));
        var vm_arrival_date   = new Date(vm_arrival_day + " " + months[vm_arrival_month] + " " + vm_arrival_year);
        var vm_arrival_dms    = Date.parse(vm_arrival_date);
        var vm_departure_dms  = vm_arrival_dms + (vm_nights * msecsInADay);
        var vm_departure_date = new Date(vm_departure_dms);

        if ((start_date_dms <= vm_departure_dms) && (end_date_dms >= vm_arrival_dms)) {
           is_available = (vm_booking_status == "P") ? 2 : 0;
           break;
        }; 
    }; // if
 }; //for
 return is_available
}

//------------------------------------------------------------------------------------------------------------------------


function ListVillaAvailability(intArrival, intDeparture, no_of_nights, flexibility_days)
{

   var entered_arrival_date   = new Date(intArrival);
   var entered_departure_date = new Date(intDeparture);

   var arrivalDate= document.getElementById("ArrivalDateDisplay");

   // header

   var htmlList= "<table border='0' width='100%' cellspacing='4' cellpadding='2'>" +
                 "<tr><td colspan='2'><h4>Villa Availability from " + arrivalDate.innerHTML + "</h4></td></tr>";


   // --------------------------------------------------------------------------------
   // Check for availability for the requested dates or alternatively the days ahead
   // --------------------------------------------------------------------------------

   var villas_to_book= ["Elegant","Lakeside"];
   for ( villa_idx= 0; villa_idx < 2; villa_idx++ ) {

       var villa_to_check      = villas_to_book[villa_idx].charAt(0);
       var has_earlier_arrival = 0;
       var no_of_days_ahead    = 0;
       var provisional_booking_exists = "N";

       var earlier_arrival_date   = new Date(intArrival);
       var earlier_departure_date = new Date(intDeparture);
       var later_arrival_date     = new Date(intArrival);
       var later_departure_date   = new Date(intDeparture);

       do {  
 
         var has_availability = IsVillaAvailable(later_arrival_date, later_departure_date, villa_to_check);
         if ( has_availability == 2 ) {
            provisional_booking_exists= "Y";
            has_availability= 0;
          }; //provisional

         if ( has_availability == 0 ) {
            later_arrival_date.setDate(later_arrival_date.getDate() +1);
            later_departure_date.setDate(later_departure_date.getDate() +1);
            no_of_days_ahead++;
         };
       } while (( has_availability == 0 ) && ( no_of_days_ahead <= flexibility_days ));

       // --------------------------------------------------------------------------------
       // If the villa is not available, check for availability for earlier dates
       // --------------------------------------------------------------------------------

       var no_of_days_before = 0;
       var today_date        = new Date();

       if ( no_of_days_ahead != 0 ) {

          var no_of_days_before = 1;
          earlier_arrival_date.setDate(entered_arrival_date.getDate() -1);
          earlier_departure_date.setDate(entered_departure_date.getDate() -1);

          do {   
            has_earlier_arrival = IsVillaAvailable(earlier_arrival_date, earlier_departure_date, villa_to_check);
            if ( has_earlier_arrival == 0 ) {
               earlier_arrival_date.setDate(earlier_arrival_date.getDate() -1);
               earlier_departure_date.setDate(earlier_departure_date.getDate() -1);
               no_of_days_before++;
            }; 
          } while (( has_earlier_arrival == 0 ) && ( no_of_days_before <= flexibility_days ) && ( earlier_arrival_date >= today_date ));

       }; 

       // --------------------------------------------------------------------------------
       // Inform requestor
       // --------------------------------------------------------------------------------

       var exact_dates_available   = (no_of_days_ahead == 0)    ? "Y" : "N";
       var earlier_dates_available = (has_earlier_arrival == 1) ? "Y" : "N";
       var later_dates_available   = (has_availability == 1)    ? "Y" : "N";
       var isavailable             = ((later_dates_available == "Y") || (earlier_dates_available == "Y")) ? "available" : "unavailable";

       // villa picture

       var this_villa = GetVillaName(villa_to_check);

       htmlList= htmlList + "<tr><td valign='top' rowspan='3' width='200'>" + 
                            "<img border='0' src='images/" + villas_to_book[villa_idx].toLowerCase() + 
                            "/" + villas_to_book[villa_idx].toLowerCase() + "-" + isavailable + ".jpg' class='bkg_pictureframe' width='180' height='133'></td>" +
                            "<td class='f115bold'><p align='justify'>";

       if ( (later_dates_available == "Y") || (earlier_dates_available == "Y") ) {

          if ( exact_dates_available == "Y" ) 
             html_statusofvilla= "Has availability from " + FormatStayPeriod(entered_arrival_date, no_of_nights) + 
                                 "</p></td></tr><tr><td class='f100' valign='top'><p align='justify'>" + 
                                 "Select " + this_villa + ", then enter your contact details and preferred dates on the form below.  " +
                                 "We shall contact you further with prices and details of what to do next.";
           else {
           if ( provisional_booking_exists == "N" ) {
                html_statusofvilla= "Although " + this_villa + " is unavailable for your selected arrival date, it is available from ";
            } else {
                html_statusofvilla= this_villa + " has a provisionally held booking for your selected arrival date.  Fortunately it is available from ";
           };


           // Check if availability before and potentially after selected dates...

           if ( earlier_dates_available == "Y" ) {
              html_statusofvilla= html_statusofvilla + FormatStayPeriod(earlier_arrival_date, no_of_nights);
              if ( later_dates_available == "Y") { html_statusofvilla= html_statusofvilla + " or later from " + FormatStayPeriod(later_arrival_date, no_of_nights) };

            } else {
              html_statusofvilla= html_statusofvilla + FormatStayPeriod(later_arrival_date, no_of_nights);
           };

           html_statusofvilla= html_statusofvilla + "</p></td></tr><tr><td class='f100' valign='top'><p align='justify'>" +
                                                    "Select " + this_villa + ", then enter your <b>new arrival date</b>, <b>contact details</b> and any " +
                                                    "specific requirements in the form below.  We shall contact you with a confirmed price, along " +
                                                    "with details of how to proceed with renting the property.";
           }
        } 

        else 
        if (( has_availability == 0 ) && (provisional_booking_exists == "N")) {
           html_statusofvilla= "Sorry, " + this_villa + " is unavailable for your selected dates." + 
                               "</p></td></tr><tr><td class='f100' valign='top'><p align='justify'>" + 
                               "Where you are flexible in your dates, please try alternative dates or increase the flexibility of your arrival date.  " +
                               "If you are still having no luck, you may wish to contact us for availability either side of this period";
          }
          else 
          html_statusofvilla=this_villa + " has a provisional option held for your selected dates." + 
                             "</p></td></tr><tr><td class='f100' valign='top'><p align='justify'>" + 
                             "Please try alternative dates, increase the flexibility of your arrival date or contact us for " +
                             "availability should the option expire.";

       htmlList= htmlList + html_statusofvilla + "</p></td></tr><tr><td>";


       // radio check-box - if available

       if ( (later_dates_available == "Y") || (earlier_dates_available == "Y") ) {
          htmlList= htmlList + "<input type='button' class='button40' value='Select " + this_villa + 
                               " &raquo;' name='Villa' onmouseout='HoverOff(this);' onmouseover='HoverOn(this);' " + 
                               "onclick=\"document.getElementById('selected_villa').selectedIndex=" + (villa_idx +1) + "; " +
                               "document.getElementById('actual_arrival_date').focus();\">" };
//                               "'; window.location.hash='details'; document.getElementById('actual_arrival_date').focus();\">" };

       htmlList= htmlList + "</td></tr>";



    } // each villa

    var htmlListRef= document.getElementById("htmlVillaStatusList");
    htmlListRef.innerHTML = htmlList + "</table>";
    window.location.hash='check';

} // fn



//------------------------------------------------------------------------------------------------------------------------
// Ensure a valid arrival date has been specified and depending on specific
// periods of rental, determine availability.
//------------------------------------------------------------------------------------------------------------------------

function ShowVillaAvailability() {
 
  var idarrivaldate        = document.getElementById("ArrivalDate");
  var idflexibility        = document.getElementById("ArrivalDateFlexibility");
  var entered_arrival_date = parseInt(idarrivaldate.value);
  var flexibility_days     = parseInt(idflexibility.value);
  var id_arrival_date      = document.getElementById("ArrivalDateDisplay");
  var id_no_of_nights      = document.getElementById("Nights");
  var today_date           = new Date();

  if (( entered_arrival_date == "0" ) || ( id_arrival_date.value == "" )) { 
     window.alert('Please select an arrival date to check availability of the villas') }
   else 
   if ( idarrivaldate.value < today_date ) {
     window.alert('You have selected a date that has already passed.  Please select a future date for arriving.') }
    else {
    var no_of_nights   = parseInt(id_no_of_nights.options[id_no_of_nights.selectedIndex].value);
    var departure_date = parseInt(entered_arrival_date) + (no_of_nights * msecsInADay);
    ListVillaAvailability(entered_arrival_date, departure_date, no_of_nights, flexibility_days);
  };

};

// --------------------------------------------------------------------------------
