function ShowDiv(divid,iframe, state)
{
   var DivRef = document.getElementById(divid);
   var IfrRef = document.getElementById(iframe);
   if(state)
   {
      DivRef.style.display = "block";
      IfrRef.style.width = DivRef.offsetWidth;
      IfrRef.style.height = DivRef.offsetHeight;
      IfrRef.style.top = DivRef.style.top;
      IfrRef.style.left = DivRef.style.left;
      IfrRef.style.zIndex = DivRef.style.zIndex - 1;
      IfrRef.style.display = "block";
   }
   else
   {
      DivRef.style.display = "none";
      IfrRef.style.display = "none";
   }
}
 
// Set the initial date.
var ds_i_date = new Date();
ds_c_month = ds_i_date.getMonth() + 1;
ds_c_year = ds_i_date.getFullYear();
 
// Get Element By Id
function ds_getel(id) {
   return document.getElementById(id);
}
 
// Get the left and the top of the element.
function ds_getleft(el) {
   var tmp = el.offsetLeft;
   el = el.offsetParent
   while(el) {
      tmp += el.offsetLeft;
      el = el.offsetParent;
   }
   return tmp;
}
function ds_gettop(el) {
   var tmp = el.offsetTop;
   el = el.offsetParent
   while(el) {
      tmp += el.offsetTop;
      el = el.offsetParent;
   }
   return tmp;
}
 
// Output Element
var ds_oe = ds_getel('ds_calclass');
// Container
var ds_ce = ds_getel('ds_conclass');
 
// Output Buffering
var ds_ob = '';
function ds_ob_clean() {
   ds_ob = '';
}
function ds_ob_flush() {
   ds_oe.innerHTML = ds_ob;
   ds_ob_clean();
}
function ds_echo(t) {
   ds_ob += t;
}
 
var ds_element; // Text Element...
 
var ds_monthnames = ['January', 'February', 'March', 'April', 'May', 'June','July', 'August', 'September', 'October', 'November', 'December']; // You can translate it for your language.
 
var ds_daynames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; // You can translate it for your language.
 
// Calendar template
function ds_template_main_above(t) {
   return '<table cellpadding="3" cellspacing="1" class="ds_tbl" border="0">'
        + '<tr>'
       + '<td class="ds_head" style="cursor: pointer" onclick="ds_py();">&lt;&lt;</td>'
       + '<td class="ds_head" style="cursor: pointer" onclick="ds_pm();">&lt;</td>'
       + '<td class="ds_head" style="cursor: pointer" onclick="ds_hi();" colspan="3">[Close]</td>'
       + '<td class="ds_head" style="cursor: pointer" onclick="ds_nm();">&gt;</td>'
       + '<td class="ds_head" style="cursor: pointer" onclick="ds_ny();">&gt;&gt;</td>'
       + '</tr>'
        + '<tr>'
       + '<td colspan="7" class="ds_head">' + t + '</td>'
       + '</tr>'
       + '<tr>';
}
 
function ds_template_day_row(t) {
   return '<td class="ds_subhead">' + t + '</td>';
   // Define width in CSS, XHTML 1.0 Strict doesn't have width property for it.
}
 
function ds_template_new_week() {
   return '</tr><tr>';
}
 
function ds_template_blank_cell(colspan) {
   return '<td colspan="' + colspan + '"></td>'
}
 
//intialize current date once
var ds_today = midnight(-1,0,0);
//return true if the date is in past
function ds_pastdate(d, m, y) {
   //create a date from passed parameters and compare to today's date
   var thisdate = midnight(y, m-1, d);
   return (thisdate < ds_today);
}
 
var ds_days_of_month = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
//get the next date
function ds_nextdate(date) {
   var d = date.getDate();
   var m = date.getMonth() + 1;
   var y = date.getFullYear();
 
   d ++;
   //if d is greater than days in the month, advance the month (also check for feb of leap years)
   if( d > ds_days_of_month[m-1] && !(m==2 && isLeapYear(y) && d<30) ) {
      d = 1;
      m ++;
      //if m is greater than 12, advance the year
      if(m > 12) {
         m = 1;
         y++;
      }
   }
   var nextdate = midnight(y, m-1, d);
   return nextdate;
}
 
function ds_template_day(d, m, y) {
   //if it is past date, do not allow to select the cell.
   if(ds_pastdate(d,m,y))
      return '<td class="ds_cell">' + d + '</td>';
   return '<td class="ds_cell ds_cp" onclick="ds_onclick(' + d + ',' + m + ',' + y + ')">' + d + '</td>';
   // Define width the day row.
}
 
function ds_template_main_below() {
   return '</tr>'
        + '</table>';
}
 
// This one draws calendar...
function ds_draw_calendar(m, y) {
 
   // First clean the output buffer.
   ds_ob_clean();
   // Here we go, do the header
   ds_echo (ds_template_main_above(ds_monthnames[m - 1] + ' ' + y));
   for (i = 0; i < 7; i ++) {
      ds_echo (ds_template_day_row(ds_daynames[i]));
   }
   // Make a date object.
   var ds_dc_date = midnight(y, m-1, 1);
   if (m == 1 || m == 3 || m == 5 || m == 7 || m == 8 || m == 10 || m == 12) {
      days = 31;
   } else if (m == 4 || m == 6 || m == 9 || m == 11) {
      days = 30;
   } else {
      days = isLeapYear(y) ? 29 : 28;
   }
   var first_day = ds_dc_date.getDay();
   var first_loop = 1;
   // Start the first week
   ds_echo (ds_template_new_week());
   // If sunday is not the first day of the month, make a blank cell...
   if (first_day != 0) {
      ds_echo (ds_template_blank_cell(first_day));
   }
   var j = first_day;
   for (i = 0; i < days; i ++) {
      // Today is sunday, make a new week.
      // If this sunday is the first day of the month,
      // we've made a new row for you already.
      if (j == 0 && !first_loop) {
         // New week!!
         ds_echo (ds_template_new_week());
      }
      // Make a row of that day!
      ds_echo (ds_template_day(i + 1, m, y));
      // This is not first loop anymore...
      first_loop = 0;
      // What is the next day?
      j ++;
      j %= 7;
   }
   // Do the footer
   ds_echo (ds_template_main_below());
   // And let's display..
   ds_ob_flush();
   // Scroll it into view.
   ds_ce.scrollIntoView();
}
 
// A function to show the calendar.
// When user click on the date, it will set the content of t.
function ds_sh(t) {
   // Set the element to set...
   ds_element = document.getElementById(t);
   // Pick element's value, if null, Make a new date, and set the current month and year.
   if(ds_element.value == '')
   {
      var ds_sh_date = new Date();
      ds_c_month = ds_sh_date.getMonth() + 1;
      ds_c_year = ds_sh_date.getFullYear();
   }
   else
   {
      var dateArray = ds_element.value.split('-');
      ds_c_month = parseInt(dateArray[1], 10);
      ds_c_year = parseInt(dateArray[0], 10);
   }
   // Draw the calendar
   ds_draw_calendar(ds_c_month, ds_c_year);
   // To change the position properly, we must show it first.
   ds_ce.style.display = '';
   // Move the calendar container!
   the_left = ds_getleft(ds_element);
   the_top = ds_gettop(ds_element) + ds_element.offsetHeight;
   ds_ce.style.left = the_left + 'px';
   ds_ce.style.top = the_top + 'px';
   // Scroll it into view.
   ds_ce.scrollIntoView();
   ShowDiv(ds_ce.id,'ds_iframe', true);
}
 
// Hide the calendar.
function ds_hi() {
   ShowDiv(ds_ce.id,'ds_iframe', false);
// ds_ce.style.display = 'none';
}
 
// Moves to the next month...
function ds_nm() {
   // Increase the current month.
   ds_c_month ++;
   // We have passed December, let's go to the next year.
   // Increase the current year, and set the current month to January.
   if (ds_c_month > 12) {
      ds_c_month = 1;
      ds_c_year++;
   }
   // Redraw the calendar.
   ds_draw_calendar(ds_c_month, ds_c_year);
}
 
// Moves to the previous month...
function ds_pm() {
   ds_c_month = ds_c_month - 1; // Can't use dash-dash here, it will make the page invalid.
   // We have passed January, let's go back to the previous year.
   // Decrease the current year, and set the current month to December.
   if (ds_c_month < 1) {
      ds_c_month = 12;
      ds_c_year = ds_c_year - 1; // Can't use dash-dash here, it will make the page invalid.
   }
   // Redraw the calendar.
   ds_draw_calendar(ds_c_month, ds_c_year);
}
 
// Moves to the next year...
function ds_ny() {
   // Increase the current year.
   ds_c_year++;
   // Redraw the calendar.
   ds_draw_calendar(ds_c_month, ds_c_year);
}
 
// Moves to the previous year...
function ds_py() {
   // Decrease the current year.
   ds_c_year = ds_c_year - 1; // Can't use dash-dash here, it will make the page invalid.
   // Redraw the calendar.
   ds_draw_calendar(ds_c_month, ds_c_year);
}
 
// Format the date to output.
function ds_format_date(d, m, y) {
   // 2 digits month.
   m2 = '00' + m;
   m2 = m2.substr(m2.length - 2);
   // 2 digits day.
   d2 = '00' + d;
   d2 = d2.substr(d2.length - 2);
   // YYYY-MM-DD
   return y + '-' + m2 + '-' + d2;
}
 
// When the user clicks the day.
function ds_onclick(d, m, y) {
   // Hide the calendar.
   ds_hi();
   // Set the value of it, if we can.
   if (typeof(ds_element.value) != 'undefined') {
      ds_element.value = ds_format_date(d, m, y);
      if( ds_element.id == checkinElementId || ds_element.id == checkoutElementId ) {
         validatecontext(ds_element);
      }
   // Maybe we want to set the HTML in it.
   } else if (typeof(ds_element.innerHTML) != 'undefined') {
      ds_element.innerHTML = ds_format_date(d, m, y);
      // I don't know how should we display it, just alert it to user.
   } else {
      alert (ds_format_date(d, m, y));
   }
}
 
var selectedElement = '';
function focusSelected()
{
   //if(selectedElement)
      //selectedElement.focus();
}
 
var millis_in_day = 24*60*60*1000;
 
function midnight(y, m, d)
{
   var date1 = new Date();
   //enter y = -1 for todays date
   if(y!=-1)
      date1.setFullYear(y, m, d);
   date1.setHours(0);
   date1.setMinutes(0);
   date1.setSeconds(0);
   date1.setMilliseconds(0);
   return date1;
}
 
function validatecontext(ele)
{
   selectedElement = ele;
   if(ele.id == checkinElementId)
   {
      var date = validatedate(ele);
      if( date ) {
         checkinDate = date;
      }
      if( (date) && ( (checkoutDateChanged == false) || (date > checkoutDate) ) )
      {
         var n = Math.round(parseFloat(document.getElementById(nnightsId).value));
         if( n <= 0 || isNaN(n) )
            n = 2;
         var nextdate = checkinDate;
         for(var i=0;i<n;i++)
            nextdate = ds_nextdate(nextdate);
         var y = nextdate.getFullYear();
         var m = nextdate.getMonth() + 1;
         var d = nextdate.getDate();
         document.getElementById(checkoutElementId).value = ds_format_date(d, m, y);
         checkoutDateChanged = false;
         checkoutDate = nextdate;
      }
      else
      {
          var n = parseFloat((checkoutDate.getTime() - checkinDate.getTime())/millis_in_day);
         document.getElementById(nnightsId).value = Math.round(n);
      }
   }
   else if(ele.id == checkoutElementId)
   {
      var date = validatedate(ele);
      if( date ) {
         checkoutDateChanged = true;
         checkoutDate = date;
         if(checkoutDate<checkinDate || (checkoutDate.getDate() == checkinDate.getDate() && checkoutDate.getMonth() == checkinDate.getMonth() && checkoutDate.getFullYear() == checkinDate.getFullYear())) {
            alert('Check-out date selected is on or before check-in date.\nPlease correct the date.');
            setTimeout(focusSelected, 100);
         }
         else
         {
           var n = parseFloat((checkoutDate.getTime() - checkinDate.getTime())/millis_in_day);
           document.getElementById(nnightsId).value = Math.round(n);
         }
      }
      else
         checkoutDateChanged = false;
   }
   else if(ele.id == nnightsId)
   {
      var n = parseInt(ele.value);
      var nextdate = checkinDate;
      for(var i=0;i<n;i++)
         nextdate = ds_nextdate(nextdate);
      var y = nextdate.getFullYear();
      var m = nextdate.getMonth() + 1;
      var d = nextdate.getDate();
      document.getElementById(checkoutElementId).value = ds_format_date(d, m, y);
      checkoutDateChanged = false;
      checkoutDate = nextdate;
   }
   else if(ele.id == nadultsId)
   {
      var adults = parseInt(document.getElementById(nadultsId).value);
      var nchilds = document.getElementById(nchildsId);
      if(adults == 1)
      {
         removeOption(nchilds, 1);
         removeOption(nchilds, 2);
      }
      else if(adults == 2)
      {
         addOption(nchilds, '1 child', 1);
         removeOption(nchilds, 2);
      }
      else if(adults == 3)
      {
         addOption(nchilds, '1 child', 1);
         addOption(nchilds, '2 children', 2);
      }
      showAgeDrops(nchilds);
   }
}
 
function addOption(selectbox, text, val )
{
   for(var i=0;i<selectbox.options.length;i++)
   {
      if(selectbox.options[i].value == val )
         return;
   }
   var optn = document.createElement("OPTION");
   optn.text = text;
   optn.value = val;
   selectbox.options.add(optn);
}
 
function removeOption(selectbox, val)
{
   for(var i=0;i<selectbox.options.length;i++)
   {
      if(selectbox.options[i].value == val )
         selectbox.remove(i);
   }
}
 
function validateForm()
{
   if(checkoutDate<checkinDate || (checkoutDate.getDate() == checkinDate.getDate() && checkoutDate.getMonth() == checkinDate.getMonth() && checkoutDate.getFullYear() == checkinDate.getFullYear()))
   {
	  alert('Check-out date selected is on or before check-in date.\nPlease correct the date.');
  }
   else
      document.getElementById('bookerform').submit();
}
 
//validate the textual date
function validatedate(ele)
{
   var valid = true;
   var year, month, day;
   //split the date.
   var dateArray = ele.value.split("-");
   if(dateArray.length == 3) {
      year = parseInt(dateArray[0], 10);
      month = parseInt(dateArray[1], 10);
      day = parseInt(dateArray[2], 10);
      //alert(year + ' ' + month + ' ' + day);
      if(year > 0)
      {
         if(month > 0 && month <= 12)
         {
            if( month==2 && isLeapYear(year) && day > 0 && day <= 29) {
               valid = true;
            }
            else if(day > 0 && day <= ds_days_of_month[month-1]) {
               valid = true;
            }
            else {
               //alert('days out of range');
               valid = false;
            }
         }
         else {
            //alert('months out of range');
            valid = false;
         }
      }
      else {
         //alert('year out of range');
         valid = false;
      }
   }
   else {
      //alert('lenght is not 3');
      valid = false;
   }
   //remove the invalid date
   if(valid == true ) {
      valid = midnight(year, month-1, day);
      if(ds_pastdate(day, month, year)) {
         alert('Date entered is in past.\nPlease correct the date.');
         setTimeout(focusSelected, 100);
         valid = false;
      }
      else {
         ele.value = ds_format_date(day, month, year);
      }
   }
   else {
      alert('Format of the date is not correct.\nPlease correct the date.');
      setTimeout(focusSelected, 100);
   }
   return valid;
}
 
function isLeapYear(y) {
   return (y%4==0 && (y%100!=0 || y%400==0) );
}
 
function showAgeDrops(ele)
{
   var nchild = ele.value;
   switch(nchild)
   {
      case '0':
         document.getElementById('tr_childage1').style.display="none";
         document.getElementById('tr_childage2').style.display="none";
         break;
      case '1':
         document.getElementById('tr_childage1').style.display="";
         document.getElementById('tr_childage2').style.display="none";
         break;
      case '2':
         document.getElementById('tr_childage1').style.display="";
         document.getElementById('tr_childage2').style.display="";
         break;
   }
}
 
// calculate the ASCII code of the given character
function CalcKeyCode(aChar) {
  var character = aChar.substring(0,1);
  var code = aChar.charCodeAt(0);
  return code;
}
 
function checkNumber(val) {
  var strPass = val.value;
  var strLength = strPass.length;
  var lchar = val.value.charAt((strLength) - 1);
  var cCode = CalcKeyCode(lchar);
 
  /* Check if the keyed in character is a number
     do you want alphabetic UPPERCASE only ?
     or lower case only just check their respective
     codes and replace the 48 and 57 */
 
  if (cCode < 48 || cCode > 57 ) {
    var myNumber = val.value.substring(0, (strLength) - 1);
    val.value = myNumber;
  }
  return false;
}
 
//checkin & checkout element ID
var checkinElementId = 'dateA';
var checkoutElementId = 'date2';
var nnightsId = 'nnights';
var nchildsId = 'nchilds';
var nadultsId = 'nadults';
var checkoutDateChanged = false;
var checkoutDate = midnight(-1,0,0);
var checkinDate = midnight(-1,0,0);
// And here is the end.
