function e(i){return document.getElementById(i);}

function getXmlHttpRequestObject()
{
  if(window.XMLHttpRequest) return new XMLHttpRequest();
  if(window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
  return null;
}

var req = getXmlHttpRequestObject();
var ajax_queue = [];

function eval_ajax()
{
  if(req.readyState == 4)
  {
    eval(req.responseText);

    if(ajax_queue.length)
    {
      var q = ajax_queue.pop();

      req.open("GET", '/ajax?cmd=' + escape(q.cmd) + '&arg=' + escape(q.arg), true);
      req.onreadystatechange = eval_ajax;
      req.send(null);
    }
  }
}

function ajax_request(cmd, arg)
{
  if(req.readyState == 0 || req.readyState == 4)
  {
    req.open("GET", '/ajax?cmd=' + escape(cmd) + '&arg=' + escape(arg), true);
    req.onreadystatechange = eval_ajax;
    req.send(null);
  }
  else if(ajax_queue.length < 20)
  {
    var q = new Object();

    q.cmd = cmd;
    q.arg = arg;

    ajax_queue.push(q);
  }
}

var lastSetContinent=-1;
var countryCode='XX';
function setcc(cc){countryCode=cc;}
/* Set Continent */
function sc(i){e('continentimg').src='/static-images/continents_'+i+'_'+countryCode+'.png';lastSetContinent=i;}
function usc(i){if(lastSetContinent==i)e('continentimg').src='/static-images/continents_'+countryCode+'.png';lastSetContinent=-1;}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}


function MM_jumpMenu(targ,selObj,restore){ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}

var calArr = new Object();
var calDep = new Object();
var cals = new Object();

calArr.element = 'arr-calendar';
calArr.offset = 0;
calArr.targetOffset = 0;
calArr.scrolling = false;

calDep.element = 'dep-calendar';
calDep.offset = 0;
calDep.targetOffset = 0;
calDep.scrolling = false;

cals["arr"] = calArr;
cals["dep"] = calDep;

var calDays = 0;

function cal_scroll(cn)
{
  cal = cals[cn];

  if(cal.targetOffset > cal.offset)
  {
    cal.offset += 40;
    if(cal.offset > cal.targetOffset)
      cal.offset = cal.targetOffset;
  }
  else
  {
    cal.offset -= 40;
    if(cal.targetOffset > cal.offset)
      cal.offset = cal.targetOffset;
  }

  e(cal.element).style.marginLeft = (-cal.offset + 1) + 'px';

  if(cal.offset != cal.targetOffset)
  {
    cal.scrolling = true;
    setTimeout("cal_scroll('" + cn + "')", 10);
  }
  else
    cal.scrolling = false;
}

function cal_prev(cn)
{
  cal = cals[cn];

  if(cal.targetOffset > 0)
    cal.targetOffset -= 169;

  if(!cal.scrolling)
    cal_scroll(cn);
}

function cal_next(cn)
{
  cal = cals[cn];

  if(cal.targetOffset < 11 * 169)
    cal.targetOffset += 169;

  if(!cal.scrolling)
    cal_scroll(cn);

  if(cn == "arr" && cal.targetOffset > cals["dep"].targetOffset)
  {
    cals["dep"].targetOffset = cal.targetOffset;

    if(!cals["dep"].scrolling)
      cal_scroll("dep");
  }
}

function cal_highlight_range(begin, end)
{
  now = new Date();
  arrival = dateFromISO(begin);
  departure = dateFromISO(end);

  diff = arrival.getMonth() - now.getMonth();

  if(diff < 0)
    diff += 12;

  if(diff != cals["arr"].targetOffset / 169)
  {
    cals["arr"].offset = diff * 169;
    cals["arr"].targetOffset = cals["arr"].offset;

    cal_scroll("arr");
  }

  diff = departure.getMonth() - now.getMonth();

  if(diff < 0)
    diff += 12;

  if(diff != cals["dep"].targetOffset / 169)
  {
    cals["dep"].offset = diff * 169;
    cals["dep"].targetOffset = cals["dep"].offset;

    cal_scroll("dep");
  }

  var c = e('arr-calendar');

  es = c.getElementsByTagName('td');
  calDays = 0;

  for(i = 0; i != es.length; ++i)
  {
    if(!/^future/.test(es[i].className))
      continue;

    d = es[i].id.split("_");

    if(d[1] == begin)
    {
      es[i].className = 'future endpoint';
      ++calDays;
    }
    else if(d[1] > begin && d[1] <= end)
    {
      es[i].className = 'future selected';
      ++calDays;
    }
    else
      es[i].className = 'future';
  }

  if(calDays > 2)
    e('calendar-caption').innerHTML = (calDays - 1) + nNightsSelected;
  else if(calDays == 2)
    e('calendar-caption').innerHTML = oneNightSelected;
  else
    e('calendar-caption').innerHTML = noNightsSelected;

  c = e('dep-calendar');

  es = c.getElementsByTagName('td');
  calDays = 0;

  for(i = 0; i != es.length; ++i)
  {
    d = es[i].id.split("_");

    if(d[1] == end)
    {
      es[i].className = 'future endpoint';
      ++calDays;
    }
    else if(d[1] > begin)
    {
      es[i].className = 'future';
      ++calDays;
    }
    else
      es[i].className = 'past';
  }
}

function dateFromISO(s)
{
  var re = "([0-9]{4})-([0-9]{2})-([0-9]{2})";
  var d = s.match(new RegExp(re));

  var offset = 0;
  var res = new Date(d[1], 0, 1);

  res.setMonth(d[2] - 1);
  res.setDate(d[3]);

  return res;
}

Date.prototype.toISO = function()
{
  dy = this.getFullYear();
  dm = this.getMonth() + 1;
  dd = this.getDate();
  ys = new String(dy);
  ms = new String(dm);
  ds = new String(dd);
  if(ms.length == 1) ms = "0" + ms;
  if(ds.length == 1) ds = "0" + ds;
  return ys + "-" + ms + "-" + ds;
}

function arr(ev)
{
  if(!ev)
    ev = window.event;

  if (ev.target)
    target = ev.target;
  else if (ev.srcElement)
    target = ev.srcElement;
  if (target.nodeType == 3)
    target = target.parentNode;

  start = target.id.split("_");

  d = dateFromISO(start[1]);

  e('arrivalMonth').selectedIndex = d.getMonth();
  e('arrivalDay').selectedIndex = d.getDate() - 1;

  amadChange(document.hotForm.arrivalMonth, document.hotForm.arrivalDay, document.hotForm.departureMonth, document.hotForm.departureDay);
}

function dep(ev)
{
  if(!ev)
    ev = window.event;

  if (ev.target)
    target = ev.target;
  else if (ev.srcElement)
    target = ev.srcElement;
  if (target.nodeType == 3)
    target = target.parentNode;

  if(!/^future/.test(target.className))
    return;

  start = target.id.split("_");

  d = dateFromISO(start[1]);

  e('departureMonth').selectedIndex = d.getMonth();
  e('departureDay').selectedIndex = d.getDate() - 1;

  dmddChange(document.hotForm.departureMonth, document.hotForm.departureDay);
  cal_update();
}


function loadDates()
{
  var arrival = new Date();
  var departure = new Date();

  var advanceArrival = 14;
  var advanceDeparture = 15;

  arrival.setDate(arrival.getDate() + advanceArrival);
  departure.setDate(departure.getDate() + advanceDeparture);

  var cal;
  var cal2;
  var date;
  var month;
  var year;
  var date2;
  var month2;
  var year2;

  date = arrival.getDate();
  month = arrival.getMonth();

  date2 = departure.getDate();
  month2 = departure.getMonth();

  document.forms['hotForm'].arrivalMonth.value=month;
  document.forms['hotForm'].arrivalDay.value=date;
  document.forms['hotForm'].departureMonth.value=month2;
  document.forms['hotForm'].departureDay.value=date2;
}

//start new script code
// Checks if browser is Netscape 2.0x since the options array properties don't work with Netscape 2.0x
function isBrowserSupp() {
  // Get the version of the browser
  version =  parseFloat( navigator.appVersion );

  if ( ( version >= 2.0 ) && ( version < 2.1 ) && ( navigator.appName.indexOf( "Netscape" ) != -1 ) ) {
    return false;
  } else {
    return true;
  }

  return true;
}

function isLeapYear( yrStr ) {
  var year = parseInt( yrStr, 10 );
  if(year % 400 == 0)
    return true;
  if(year % 100 == 0)
    return false;
  return (year % 4) == 0;
}

function getDaysInMonth( mthIdx, YrStr ) {
  // all the rest have 31
  var maxDays = 31
    // expect Feb. (of course)
    if( mthIdx == 1 ) {
      if( isLeapYear( YrStr ) ) {
        maxDays=29;
      } else {
        maxDays=28;
      }
    }

  // thirty days hath...
  if( mthIdx == 3 || mthIdx == 5 || mthIdx == 8 || mthIdx == 10 ) {
    maxDays=30;
  }
  return maxDays;
}

//the function which does some magic to the date fields
// return non-zero if it is the last day of the month
function adjustDate( mthIdx, Dt ) {
  var value = 0;

  var today = new Date()
    var theYear = parseInt( today.getYear(), 10 )

    if( mthIdx < today.getMonth() ) {
      theYear = ( parseInt( today.getYear(), 10 ) + 1 )
    }
  if( theYear < 100 ) {
    theYear = "19" + theYear
  } else {
    if( ( theYear - 100 ) < 10 ) {
      theYear = "0" + ( theYear - 100 )
    } else {
      theYear = ( theYear - 100 ) + ""
    }
    theYear = "20" + theYear
  }


  var numDays = getDaysInMonth( mthIdx, theYear );

  if( mthIdx == 1 ) {
    if( Dt.options.selectedIndex + 2 < numDays ) {
      return 0;
    } else {
      if( Dt.options.selectedIndex + 1 > numDays) {
        Dt.options.selectedIndex=numDays - 1;
      }
      //check for leap year
      if( (Dt.options.selectedIndex + 1) == numDays ) {
        return 1;
      } else {
        return 4;
      }
    }
  }

  if( Dt.options.selectedIndex + 2 < numDays ) {
    value = 0;
  } else {
    if ( Dt.options.selectedIndex + 1 > numDays ) {
      Dt.options.selectedIndex--;
      value = 3;
    } else if ( Dt.options.selectedIndex + 1 == numDays ) {
      //index is 31 or 30
      value = 2;
    } else {
      value = 4;
    }
  }
  return value;
}

/* Changes departure month when arrival month is changed */
function amadChange()
{
  if(!isBrowserSupp())
    return;

  var arrival = new Date();
  var departure = new Date();

  month = e('arrivalMonth').value;
  day = e('arrivalDay').value;
  year = arrival.getFullYear();
  if(month < arrival.getMonth())
    ++year;
  arrival.setMonth(0); /* Month 0 has 31 (max) days, so next line won't fail */
  arrival.setDate(day);
  arrival.setMonth(month);
  arrival.setYear(year);

  month = e('departureMonth').value;
  day = e('departureDay').value;
  year = departure.getFullYear();
  if(month < departure.getMonth())
    ++year;
  departure.setMonth(0); /* Month 0 has 31 (max) days, so next line won't fail */
  departure.setDate(day);
  departure.setMonth(month);
  departure.setYear(year);

  if(departure.toISO() <= arrival.toISO())
  {
    departure = arrival;
    departure.setDate(departure.getDate() + 1);

    e('departureMonth').selectedIndex = departure.getMonth();
    e('departureDay').selectedIndex = departure.getDate() - 1;
  }

  cal_update();
}


function dmddChange()
{
  if(!isBrowserSupp())
    return;

  var arrival = new Date();
  var departure = new Date();

  month = e('arrivalMonth').value;
  day = e('arrivalDay').value;
  year = arrival.getFullYear();
  if(month < arrival.getMonth())
    ++year;
  arrival.setMonth(0); /* Month 0 has 31 (max) days, so next line won't fail */
  arrival.setDate(day);
  arrival.setMonth(month);
  arrival.setYear(year);

  month = e('departureMonth').value;
  day = e('departureDay').value;
  year = departure.getFullYear();
  if(month < departure.getMonth())
    ++year;
  departure.setMonth(0); /* Month 0 has 31 (max) days, so next line won't fail */
  departure.setDate(day);
  departure.setMonth(month);
  departure.setYear(year);

  if(departure.toISO() <= arrival.toISO())
  {
    var now = new Date();

    arrival = departure;
    arrival.setDate(arrival.getDate() - 2);

    if(arrival.toISO() <= now.toISO())
      arrival = now;

    e('arrivalMonth').selectedIndex = arrival.getMonth();
    e('arrivalDay').selectedIndex = arrival.getDate() - 1;
  }

  cal_update();
}

function validate(form) {
  if (form.numberOfRooms.value == "9") {
    window.location = "/support.php";
    return false;
  }

  if (document.forms["hotForm"].cityText.value != "") {
    document.forms["hotForm"].stateProvince.value = "";
    document.forms["hotForm"].country.value = "";
    document.forms["hotForm"].city.value = document.forms["hotForm"].cityText.value;
  }

  return submitGuestInfoForm(form);
}

function formAlert(text)
{
  e('formError').innerHTML = text;
  e('formError').style.display = 'block';
}

function validateAndSubmit()
{
  var arrival = new Date();
  var departure = new Date();

  e('formError').style.display = 'none';

  month = e('arrivalMonth').value;
  day = e('arrivalDay').value;
  year = arrival.getFullYear();
  if(month < arrival.getMonth())
    ++year;
  arrival.setMonth(0); /* Month 0 has 31 (max) days, so next line won't fail */
  arrival.setDate(day);
  arrival.setMonth(month);
  arrival.setYear(year);

  month = e('departureMonth').value;
  day = e('departureDay').value;
  year = departure.getFullYear();
  if(month < departure.getMonth())
    ++year;
  departure.setMonth(0); /* Month 0 has 31 (max) days, so next line won't fail */
  departure.setDate(day);
  departure.setMonth(month);
  departure.setYear(year);

  var ndays = (departure.getTime() - arrival.getTime()) / (1000 * 60 * 60 * 24);

  if(ndays >= maxDayCount)
  {
    formAlert(tooLongInterval);

    return false;
  }

  e("hotForm").submit();
}

function chooseCountry(idx)
{
  menu = e("c"+idx);
  country = menu.options[menu.selectedIndex].value;

  document.location = '/?country=' + country;
}

var arrivalCal = null;
var departureCal = null;

function cal_update()
{
  var arrival = new Date();
  var departure = new Date();

  month = document.forms['hotForm'].arrivalMonth.value;
  day = document.forms['hotForm'].arrivalDay.value;
  year = arrival.getFullYear();
  if(month < arrival.getMonth())
    ++year;
  arrival.setMonth(0); /* Month 0 has 31 (max) days, so next line won't fail */
  arrival.setDate(day);
  arrival.setMonth(month);
  arrival.setYear(year);

  month = document.forms['hotForm'].departureMonth.value;
  day = document.forms['hotForm'].departureDay.value;
  year = departure.getFullYear();
  if(month < departure.getMonth())
    ++year;
  departure.setMonth(0); /* Month 0 has 31 (max) days, so next line won't fail */
  departure.setDate(day);
  departure.setMonth(month);
  departure.setYear(year);

  cal_highlight_range(arrival.toISO(), departure.toISO());
}

function showAmenities()
{
  e('amenities').style.display = 'inline';
}

function hideAmenities()
{
  e('amenities').style.display = 'none';
}

function showHotelSearch()
{
  e('city-search-table').style.display = 'none';
  e('hotel-search-table').style.display = 'table';
  e('amenities').style.display = 'none';
}

function showNormalSearch()
{
  e('city-search-table').style.display = 'table';
  e('hotel-search-table').style.display = 'none';
  e('amenities').style.display = 'none';
}

function validateAmenities(idx)
{
  count = 0;

  for(i = 1; 9 >= i; ++i)
  {
    if(e('am'+i).checked)
      ++count;
  }

  if(count > 3)
  {
    e('amenityWarning').style.display = 'block';
    e('am'+idx).checked = 0;
  }
  else
    e('amenityWarning').style.display = 'none';
}

function openMapWindow(url)
{
  window.open(url, 'map', 'width=860,height=700,toolbar=no,location=no,directories=no,status=no,menubar=no,dependent=yes,resizable=no,status=no,scrollbars=yes');
}

function changeSortMethod()
{
  if(e('landmarkSel'))
    e('landmarkSel').selectedIndex = 0;
  e('sortForm').submit();
}

function setHotelView(url, width, height)
{
  e('hotelView').src = '/static-images/pixel.gif';

  if(width > 350)
  {
    var calc_width = 310;
    var calc_height = height * calc_width / width;

    e('hotelView').style.width = calc_width + 'px';
    e('hotelView').style.height = calc_height + 'px';
  }
  else
  {
    if(width != -1)
      e('hotelView').style.width = width + 'px';
    else
      e('hotelView').style.width = null;

    if(height != -1)
      e('hotelView').style.height = height + 'px';
    else
      e('hotelView').style.height = null;
  }

  e('hotelView').src = url;
}

// *** Mailing list stuff ***

// check multi checkboxes based on the name passed in.
function CheckMultiple(name) 
{
  theFrm = document.frmSS;
  for (var i=0; i < theFrm.length; i++) 
  {
    fldObj = theFrm.elements[i];
    var fieldnamecheck=fldObj.name.indexOf(name);
    if (fieldnamecheck != -1) {
      if (fldObj.checked) {
        return true;
      }
    }
  }
  return false;
}


function CheckSS()
{
  theFrm = document.frmSS;

  hasDot = theFrm.Email.value.indexOf(".");
  hasAt = theFrm.Email.value.indexOf("@");

  if (hasDot == -1 || hasAt == -1)
  {
    alert("Please enter a valid email address.");
    theFrm.Email.focus();
    theFrm.Email.select();
    return false;
  }

  return true;
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function element_x(el)
{
  var result = 0;

  while(el)
  {
    result += el.offsetLeft;
    el = el.offsetParent;
  }

  return result;
}

function element_y(el)
{
  var result = 0;

  while(el)
  {
    result += el.offsetTop;
    el = el.offsetParent;
  }

  return result;
}

var mouse_x = 0;
var mouse_y = 0;

function mouse_move(ev)
{
  if(!ev)
    ev = window.event;

  if(ev.pageX)
  {
    mouse_x = ev.pageX;
    mouse_y = ev.pageY;
  }
  else
  {
    mouse_x = ev.clientX + document.body.scrollLeft;
    mouse_y = ev.clientY + document.body.scrollTop;
  }
}

var rating_track = null;
var rating_track_width = 0;

function rating_hover_update()
{
  if(!rating_track)
    return;

  var x = mouse_x - element_x(e(rating_track));
  var y = mouse_y - element_y(e(rating_track));

  if(x < 0 || x > rating_track_width || y < 0 || y > 17)
    e(rating_track + '-overlay').style.width = '0';
  else
    e(rating_track + '-overlay').style.width = x + 'px';

  setTimeout("rating_hover_update()", 20);
}

function rating_hover(width, id)
{
  if(rating_track)
  {
    if(rating_track == id)
      return;

    e(rating_track + '-overlay').style.width = '0';
  }

  rating_track_width = width;
  rating_track = id;

  rating_hover_update();
}

function rating_leave(id)
{
}

function rating_set(width, ev, id)
{
  if(!ev)
    ev = window.event;

  var x;

  if(ev.pageX)
    x = ev.pageX - element_x(e(id));
  else
    x = ev.clientX + document.body.scrollLeft - element_x(e(id));

  rating = x * 5 / (width - 1);
  if(rating > 5) rating = 5;
  else if(rating < 0) rating = 0;
  rating = rating.toFixed(1);

  e(id + '-bar').style.width = x + 'px';
  e(id + '-legend').innerHTML = rating;
  e(id + '-legend').className = 'ok';
  e(id + '-value').value = rating;
}

function geo_search_done(point)
{
  if(!point)
  {
    parent.not_found();

    return;
  }

  parent.e('latitude').value = point.lat();
  parent.e('longitude').value = point.lng();
  parent.e('address-search-form').submit();
}

function geo_search()
{
  var geocoder = new GClientGeocoder();

  geocoder.getLatLng(e('search-address').value + ", " + e('search-address-append').value,
                     geo_search_done);
}

document.onmousemove = mouse_move;

