﻿function getEl(strID)
{
    return document.getElementById(clientPrefix + strID);
}

function select_options(select, value, type) {
  var i = 0;
  
  if (type == 'text') { // moved outside of loop for speed
    for(i = 0; i < select.length; ++i) {
        if(select.options[i].text == value) {
          select.options[i].selected = true;
          return;
        }
    }
  } else {
    for(i = 0; i < select.length; ++i) {
      if(select.options[i].value == value) {
         select.options[i].selected = true;
         return;
      }
    }
  }

  
}


function set_current_date(ed, em, ey, df) {
   var d = new Date();
   var m = d.getMonth() + 1;
   var day = d.getDate();
   var fday = day;
   var y = d.getFullYear();
   
   
  
  if (d.getMonth() + 1 < 10) {
    m = '0' + m;  
  }
  if (fday < 10) {
    fday = '0' + fday;  
  }
  
  select_options(getEl(ed), day, 'text');
  select_options(getEl(em), m, 'value');
  select_options(getEl(ey), y, 'value');

  getEl(df).value = y + '' + m + '' + fday;  
  
}

function set_reservation_dates(ed, em, ey, df) {
  var d = new Date(); 
  d.setDate(d.getDate() + 1); // tomorrow's date
  
  var m = d.getMonth() + 1;
  
  var day = d.getDate();
  var fday = day;
  var y = d.getFullYear();
  
  
  
  if (d.getMonth() + 1 < 10) {
    m = '0' + m;  
  }
  if (fday < 10) {
    fday = '0' + fday;  
  }
  
  
  select_options(getEl(ed), day, 'text');
  select_options(getEl(em), m, 'value');
  select_options(getEl(ey), y, 'value');

  getEl(df).value = y + '' + m + '' + fday;  
  
}

/**
 * Prototype Overrides
 */
// Give string object the trim method.
String.prototype.trim = function(){
  return( this.replace(new RegExp("^([\\s]+)|([\\s]+)$", "gm"), "") );
}
  
 // Give string object the left trim method.
String.prototype.leftTrim = function(){
   return( this.replace(new RegExp("^[\\s]+", "gm"), "") );
}
  
 // Give string object the right trim method.
String.prototype.rightTrim = function(){
  return( this.replace(new RegExp("[\\s]+$", "gm"), "") );
}


/* Reservation.js class */


function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_nbGroup(event, grpName) { //v6.0
  var i,img,nbArr,args=MM_nbGroup.arguments;
  if (event == "init" && args.length > 2) {
    if ((img = MM_findObj(args[2])) != null && !img.MM_init) {
      img.MM_init = true; img.MM_up = args[3]; img.MM_dn = img.src;
      if ((nbArr = document[grpName]) == null) nbArr = document[grpName] = new Array();
      nbArr[nbArr.length] = img;
      for (i=4; i < args.length-1; i+=2) if ((img = MM_findObj(args[i])) != null) {
        if (!img.MM_up) img.MM_up = img.src;
        img.src = img.MM_dn = args[i+1];
        nbArr[nbArr.length] = img;
    } }
  } else if (event == "over") {
    document.MM_nbOver = nbArr = new Array();
    for (i=1; i < args.length-1; i+=3) if ((img = MM_findObj(args[i])) != null) {
      if (!img.MM_up) img.MM_up = img.src;
      img.src = (img.MM_dn && args[i+2]) ? args[i+2] : ((args[i+1])? args[i+1] : img.MM_up);
      nbArr[nbArr.length] = img;
    }
  } else if (event == "out" ) {
    for (i=0; i < document.MM_nbOver.length; i++) {
      img = document.MM_nbOver[i]; img.src = (img.MM_dn) ? img.MM_dn : img.MM_up; }
  } else if (event == "down") {
    nbArr = document[grpName];
    if (nbArr)
      for (i=0; i < nbArr.length; i++) { img=nbArr[i]; img.src = img.MM_up; img.MM_dn = 0; }
    document[grpName] = nbArr = new Array();
    for (i=2; i < args.length-1; i+=2) if ((img = MM_findObj(args[i])) != null) {
      if (!img.MM_up) img.MM_up = img.src;
      img.src = img.MM_dn = (args[i+1])? args[i+1] : img.MM_up;
      nbArr[nbArr.length] = img;
  } }
}

      function toggleReservation(elem) {
        if(elem == 'checkAvailability') {
          document.getElementById('checkAvailability').style.display = 'block';
          document.getElementById('modifyReservation').style.display = 'none';
          document.getElementById('checkTab').src = '/images/glbl_res_chckavail_tab_btn.gif';
          document.getElementById('viewTab').src = '/images/glbl_res_modcanc_tab_bn.gif';
        } else {
          document.getElementById('checkAvailability').style.display = 'none';
          document.getElementById('modifyReservation').style.display = 'block';
          document.getElementById('checkTab').src = '/images/glbl_res_chckavail_off_tab_btn.gif';
          document.getElementById('viewTab').src = '/images/glbl_res_modcanc_on_tab_bn.jpg';          
        }
      }
      
      
      
      
      
      /**
       * These are used for the Meetings and Events search box.
       */
       
       // resets fields to original values
       function _resetCityStateFields(hashHotels, hashCities, resetCity) {
         // re-populate city field
        var i = 0;
        var cities = new Array();
        var hotels = new Array();
          
        if (resetCity == 1) {        
          getEl('selectCity').options.length = 0;
          var opt = new Option('Select a City', '');
          getEl('selectCity').options[i] = opt;
          i++;
          
          $(hashCities.Cities).each(function(city) {
            var hState = new String(city.state);
            
          
            // put these values into the city options
            if (cities.indexOf(city.name) < 0) {
              cities.push(city.name);
              
              var opt = new Option(city.name, city.name);
              getEl('selectCity').options[i] = opt;
              i++;    
            }
          
          });
          
          i = 0;
        }
        
        getEl('selectHotel').options.length = 0;
        
        
        var opt = new Option('Select a Hotel', '');
        getEl('selectHotel').options[i] = opt;
        i++;

        
        $(hashHotels.Hotels).each(function(hotel) {
          var hCity = new String(hotel.city).trim();
          
          if (hotels.indexOf(hotel.name) < 0) {
            hotels.push(hotel.name);
            var opt = new Option(hotel.name, hotel.code);
            getEl('selectHotel').options[i] = opt;
            i++;      
          }
          
          
        });        
        
        
        
         
       }
       
      // executed when province is changed
      function switchCity(hashHotels, hashCities) {
        
        var state = new String(getEl('selectState').value).trim();
        var cities = new Array();
        var i = 0;

        if (getEl('selectState').value == '') {
          _resetCityStateFields(hashHotels, hashCities, 1);
          return;
        }        
        
        getEl('selectCity').options.length = 0;
        
  
        var opt = new Option('Select a City', '');
        getEl('selectCity').options[i] = opt;
        i++;
  
        $(hashCities.Cities).each(function(city) {
          var hState = new String(city.state);
          
          if(state == hState.trim()) {
            // put these values into the city options
            if (cities.indexOf(city.name) < 0) {
              cities.push(city.name);
              
              var opt = new Option(city.name, city.name);
              getEl('selectCity').options[i] = opt;
              i++;    
            }
          }
        });
        
        
        switchHotelByState(hashHotels, hashCities);
      }
      
      
      function switchHotelByState(hashHotels, hashCities) {
        var state = new String(getEl('selectState').value).trim();
        var hotels = new Array();
        var i = 0;
        
      
        
        getEl('selectHotel').options.length = 0;

        var opt = new Option('Select a Hotel', '');
        getEl('selectHotel').options[i] = opt;
        i++;
        
        
        $(hashHotels.Hotels).each(function(hotel) {
          
          
          var hState = new String(hotel.state);
          
          if (state.trim() == hState.trim()) {
            if (hotels.indexOf(hotel.name) < 0) {
              hotels.push(hotel.name);
        
              
              var opt = getEl('reservationBox') || SiteVars.this_url.indexOf('packages') >= 0 || SiteVars.this_url.indexOf('meetings') >= 0 ?  new Option(hotel.name, hotel.code) : new Option(hotel.city + ' - ' + hotel.name, hotel.code);
              
              getEl('selectHotel').options[i] = opt;
              i++;      
            }
            
          }
        });
        
        
        
      }
      
      function switchHotels(hashHotels, hashCities) {
        var city = new String(getEl('selectCity').value).trim();
        var hotels = new Array();
        var i = 0;
        
        
        if (getEl('selectCity').value == '') {
          _resetCityStateFields(hashHotels, hashCities, 1);
          return;
        } 
        
        getEl('selectHotel').options.length = 0;
        
        
        var opt = new Option('Select a Hotel', '');
        getEl('selectHotel').options[i] = opt;
        i++;
        
        
        
        
        $(hashHotels.Hotels).each(function(hotel) {
          var hCity = new String(hotel.city).trim();
          if (city == hCity) {
            if (hotels.indexOf(hotel.name) < 0) {
              hotels.push(hotel.name);
              var opt = new Option(hotel.name, hotel.code);
              getEl('selectHotel').options[i] = opt;
              i++;      
            }
            
          }
        });
      }
      
      // 1. we need to associate hotels with city if they
      //    don't select a hotel
      //
      function searchMeetingsEvents(hashCodes, cityCodes, type) {
        // search for hash code and then redirect
        
        
        
        var hotel = new String(getEl('selectHotel').value).trim();
        
        if (getEl('selectHotel').value == '') {

          // redirect to city page
          if (getEl('selectCity') != '') {
          
            getEl(cityCodes.Codes).each(function(lookup) {
              var id = new String(lookup.city).trim();
              
              if (id == getEl('selectCity').value) {
                if (type == 'event') {
                  window.location = lookup.event_link;
                } else {
                  window.location = lookup.package_link;
                }
              }
            });
            
          } else {
            alert('Please enter a city, or select a hotel.'); 
          }
        
            
        } else {
       
            getEl(hashCodes.Codes).each(function(lookup) {
              var id = new String(lookup.code).trim();
         
              if (id == hotel) {
                if (type == 'event') {
                  window.location = lookup.event_link;
                } else {
                  window.location = lookup.package_link;
                }
              }
         
            });          
        }
        
        
        
  
      }
      
      function checkAvailability(frm, today) {
      

          if (getEl('selectHotel').value == '' && getEl('selectCity').value == '') {
            alert('Please select a city or a hotel.'); 
            return false;
          }
          
          if (getEl('selectHotel').value == '' && getEl('selectCity').value != '') {
            getEl('hdnRedirPage').value = '/rates/resultsByCity';
          } else if (getEl('selectHotel').value != '' && getEl('selectCity').value == '') {
            getEl('hdnRedirPage').value = '/rates/results';
          }
	
	
        var ci_y = getEl('dateFieldN10830').value.substring(0, 4);
        var ci_m = getEl('dateFieldN10830').value.substring(4, 6);
        var ci_d = getEl('dateFieldN10830').value.substring(6, 8);
        if (dayExceedsMonth(ci_y, ci_m, ci_d) == true) {
          alert('Start day exceeds number of days for selected month.\nPlease select a different start day.');
          return false;
        }
        
        var co_y = getEl('dateFieldN10839').value.substring(0, 4);
        var co_m = getEl('dateFieldN10839').value.substring(4, 6);
        var co_d = getEl('dateFieldN10839').value.substring(6, 8);
              
        if (dayExceedsMonth(co_y, co_m, co_d) == true) {
          alert('End day exceeds number of days for selected month.\nPlease select a different end day.');
          return false;
        }
        
        if (getEl('dateFieldN10830').value >= getEl('dateFieldN10839').value) {
          alert('Please select a date greater than the check-in date.');
          return false;
        }
        
       
        if (getEl('dateFieldN10830').value < today) {
          alert('Please select a check-in date after today');
          return false;
        }        
        
        return true;
         
      }
      
      // BUG
      function getMonthLen(theYear, theMonth) {
          return 32 - new Date(theYear, theMonth - 1, 32).getDate();
      }
      
      /**
       * This basically checks to see how many days are in a month.
       * returns false if day exceeds month
       */
      function dayExceedsMonth(year, month, day) {
        var d = parseInt(day, 10);
        var m = parseInt(month, 10);
       
        var c = getMonthLen(year, m);
       
        return (d > c);
        
      }
      
var LAST_UPDATED_FIELD = "CheckInDate"; // CheckOut or CheckIn


function isdate(d, m, y) {
 var dt = new Date(y, m, d);
 return ((d == dt.getDate()) && (m == dt.getMonth()) && (y == dt.getFullYear())); 
}

function lastDayOfMonth(m, y) {
  var dt = new Date(y, m, 0);
  return dt.getDate();
}

/** extra calendar stuff **/
function updateDateField(dt, field) {
  
  
  
  var y = getEl('dateFieldYear' + dt).value;
  var m = getEl('dateFieldMonth' + dt).value;
  var d = parseInt(getEl('dateFieldDay' + dt).value, 10);
  var invalid_range = false;
  
  

  
  
  
  
  if (d < 10) {
    d = '0' + d; 
  }
  
  
  
  getEl('dateField' + dt).value = y + m + d;
  
  // update associated field
  
  /*
  if (document.getElementsByName('CheckInDate')[0].value >= document.getElementsByName('CheckOutDate')[0].value) {
    invalid_range = true;
  } else {
     invalid_range = false;
  }
  */
  
  if (getEl('dateFieldN10830').value >= getEl('dateFieldN10839').value) {
    invalid_range = true;
  } else {
     invalid_range = false;
  }
  

  if(field == "CheckInDate" && LAST_UPDATED_FIELD != "CheckOutDate" || invalid_range == true) {
    
    //cin_date = document.getElementsByName('CheckInDate')[0].value;
    cin_date = getEl('dateFieldN10830').value;
    updateCheckOut(cin_date.substring(0, 4),parseFloat(cin_date.substring(4, 6)), parseFloat(cin_date.substring(6, 8)));
  } 
  
  
  LAST_UPDATED_FIELD = field;  
    

}

// set to next day
function updateCheckOut(y,m,d) {
  // get tomorrow
  var dt = new Date(); 
  dt.setYear(y);
  dt.setMonth(m - 1);
  dt.setDate(d + 1);
  
  var fday = dt.getDate();
  
  
  
  if (fday < 10) {
    fday = '0' + fday;  
  }
  
  dm = dt.getMonth() + 1;
  if (dm < 10) {
    dm = '0' + dm;  
  }
  
  
  // now set the other date combo
  if (document.getElementsByClassName('cin_day').length > 0) {
    select_options(document.getElementsByClassName('cin_day')[1], dt.getDate(), 'text');
    select_options(document.getElementsByClassName('cin_month')[1], dm, 'value');
    select_options(document.getElementsByClassName('cin_year')[1], dt.getFullYear(), 'value');
    // update checkout

  } else {
    select_options(document.getElementsByClassName('dateFieldDay')[1], dt.getDate(), 'text');
    select_options(document.getElementsByClassName('dateFieldMonth')[1], dm, 'value');
    select_options(document.getElementsByClassName('dateFieldYear')[1], dt.getFullYear(), 'value');
  }
  
  //var el = document.getElementsByName('CheckOutDate');  
  //el[0].value = dt.getFullYear() + '' + dm + '' + fday;  
  getEl('dateFieldN10839').value = dt.getFullYear() + '' + dm + '' + fday;
  
  
}

function popup_window(url, name, opts) {
  win = window.open(url, name, opts);
} 

// ****** opens link in popup window
 function openWin(url) { 
    topL=130;
    leftL=40;
    width=540;
    height=410;    
    bar=1;      
    wName='popUp';
    width = (arguments.length>1)?arguments[1]:width; // option to pass in width
    bar = (arguments.length>2)?arguments[2]:bar; // option to turn scrollbar on
    wName = (arguments.length>3)?arguments[3]:wName; // option to pass in window name 
    height = (arguments.length>4)?arguments[4]:height; // option to pass in height       
    
    var str="toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars="+ bar +",width="+ width +",height="+ height +",screenX="+ leftL +",screenY="+ topL +",left="+ leftL +",top="+ topL +",resizable=1";
    var Pwin = window.open(url,wName,str,true)
    Pwin.focus();

}

function showElement(elmnt)

{

  document.getElementById(elmnt).style.visibility="visible";

  document.getElementById(elmnt).style.display="";

}

function hideElement(elmnt)

{

  document.getElementById(elmnt).style.visibility="hidden";

  document.getElementById(elmnt).style.display="none";

}


function validateRetrieveReservation() {
   if (getEl('FirstName').value == '' ||
       getEl('LastName').value == '' ||
       getEl('ConfirmationNumber').value == '') {
       alert('Please enter a confirmation #, first name, and last name.');
       return false;
   }
   return true;
}

/* rewards */
function change_reward_product() {
   var idx = getEl('rewards_product_selector').selectedIndex;
   var item = getEl('rewards_product_selector')[idx].value
   var sku = item.substring(0, item.indexOf('|'));
   //var url = SiteVars.this_url.substring(0, SiteVars.this_url.indexOf('/product/'))

   document.location.replace(SiteVars.this_url + '?sku=' + sku.trim());
}

function search_rewards() {
  if (getEl('rewards_search_box').value != '') {
    return true; 
  } else {
    alert('Please enter a search term');
    return false;
  }
}
