function submit(theform) {
if (document.getElementById) {
  window.external.AutoCompleteSaveForm(theform);
}
theform.submit();
}

function initfocus()
{
  var elements = DOM.getElementsByClassName('initfocus');
  var focuselement;
  if (elements.length > 0)
  {
    focuselement = elements[0];
    focuselement.focus();
  }
}

function DaysInMonth(Mon, Year)
{
  var DaysInMonth;
  switch (Mon)
  {
    case 'Apr':
    case 'Jun':
    case 'Sep':
    case 'Nov':
      DaysInMonth = 30;
      break;
    case 'Feb':
      if (Year % 4 != 0)
      {
        DaysInMonth = 28;
      } else {
        if (Year % 400 == 0 || Year % 100 != 0)  // evenly divisible by 400 or not evenly divisible by 100, IS leap year
        {
          DaysInMonth = 29;
        } else {
          DaysInMonth = 28;  // is not leap year
        }
      }
      break;
    default:
      DaysInMonth = 31;
      break;
  }
  return DaysInMonth;
}

function ChangeOptionDays(dd,mm,yy)
{
  Day   = dd[dd.selectedIndex].text;
  Month = mm[mm.selectedIndex].text;
  Year  = yy[yy.selectedIndex].text;
  DaysForThisSelection   = DaysInMonth(Month, Year);
  CurrentDaysInSelection = dd.length;
  if (CurrentDaysInSelection > DaysForThisSelection)
  {
    for (var i=0, limit=(CurrentDaysInSelection - DaysForThisSelection); i < limit; i++)
    {
      dd.options[dd.options.length - 1] = null;
    }

  }
  if (DaysForThisSelection > CurrentDaysInSelection)
  {
    for (var i=0, limit=(DaysForThisSelection - CurrentDaysInSelection); i < limit; i++)
    {
      NewOption = new Option(dd.options.length + 1);
      dd.options[dd.options.length] = NewOption;
//      dd.add(NewOption, null);
    }
  }
  if (Day > DaysForThisSelection)
  {
    dd[(dd.options.length)-1].selected=true;
  } else {
    dd[Day-1].selected=true;
  }
}

function SetToToday(dd,mm,yy)
{
 Now = new Date();
 NowDay = Now.getDate();
 NowMonth = Now.getMonth();
 NowYear = Now.getYear();
 if (NowYear < 2000) NowYear += 1900;
 yy[0].selected = true;
 mm[NowMonth].selected = true;
 ChangeOptionDays(dd,mm,yy);
 dd[NowDay-1].selected = true;
}

function WriteYearOptions(YearsAhead,selyear)
{
 Now = new Date();
 NowDay = Now.getDate();
 NowMonth = Now.getMonth();
 NowYear = Now.getYear();
 if (NowYear<2000) NowYear+=1900;
  line = "";
  for (i=0; i<YearsAhead; i++)
  {
    if (selyear==(NowYear+i))
    {
    line += "<OPTION SELECTED>";
    }
    else
     {
    line += "<OPTION>";
    }
    line += NowYear + i;
  }
  return line;
}


function textCount(field,limit)
{
  var counterElm=document.getElementById('counter'+field.id);
  if (field.value.length > limit)
  {
    field.value = field.value.substring(0,limit);
    alert(field.id+' value can only be '+limit+' characters in length.' );
    return false;
  }  else {
    counterElm.textContent = ', '+(limit - field.value.length)+' remaining';
  }
}

/**
 * sprintf() for JavaScript v.0.4
 *
 * Copyright (c) 2007 Alexandru Marasteanu <http://alexei.417.ro/>
 * Thanks to David Baird (unit test and patch).
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 2 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 * Place, Suite 330, Boston, MA 02111-1307 USA
 */

function str_repeat(i, m) { for (var o = []; m > 0; o[--m] = i); return(o.join('')); }

function sprintf () {
  var i = 0, a, f = arguments[i++], o = [], m, p, c, x;
  while (f) {
    if (m = /^[^\x25]+/.exec(f)) o.push(m[0]);
    else if (m = /^\x25{2}/.exec(f)) o.push('%');
    else if (m = /^\x25(?:(\d+)\$)?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(f)) {
      if (((a = arguments[m[1] || i++]) == null) || (a == undefined)) throw("Too few arguments.");
      if (/[^s]/.test(m[7]) && (typeof(a) != 'number'))
        throw("Expecting number but found " + typeof(a));
      switch (m[7]) {
        case 'b': a = a.toString(2); break;
        case 'c': a = String.fromCharCode(a); break;
        case 'd': a = parseInt(a); break;
        case 'e': a = m[6] ? a.toExponential(m[6]) : a.toExponential(); break;
        case 'f': a = m[6] ? parseFloat(a).toFixed(m[6]) : parseFloat(a); break;
        case 'o': a = a.toString(8); break;
        case 's': a = ((a = String(a)) && m[6] ? a.substring(0, m[6]) : a); break;
        case 'u': a = Math.abs(a); break;
        case 'x': a = a.toString(16); break;
        case 'X': a = a.toString(16).toUpperCase(); break;
      }
      a = (/[def]/.test(m[7]) && m[2] && a > 0 ? '+' + a : a);
      c = m[3] ? m[3] == '0' ? '0' : m[3].charAt(1) : ' ';
      x = m[5] - String(a).length;
      p = m[5] ? str_repeat(c, x) : '';
      o.push(m[4] ? a + p : p + a);
    }
    else throw ("Huh ?!");
    f = f.substring(m[0].length);
  }
  return o.join('');
}


var menubrowserUpdateCounts = function(cart,compares,searches)
{
	if(cart)
	{
	  var d = document.getElementById('menubrowser_cart_count');
	  if(d) d.innerHTML = cart;
	}

	if(compares)
	{
	  var d = document.getElementById('menubrowser_compare_count');
		if(d) d.innerHTML = compares;
	}

	if(searches)
	{
		var d = document.getElementById('menubrowser_search_count');
		if(d) d.innerHTML = searches;
	}
}

var getElementsByClassname = function(classname, tagname)
{
  var els = null;
  var ret = [];
  var j = 0;
  if(tagname)
  {
    els = document.getElementsByTagName(tagname);
  } else {
    els = document.getElementsByTagName('*');
  }

  for(var i = 0; i < els.length; i++)
  {
    if(els[i].className == classname)
    {
      ret[j] = els[i];
      j++;
    }
  }

  return ret;
}


var toggleSearchlistContent = function(objname)
{
  var most_recent = document.getElementById("searchlist_container_most_recent");
  var classname = "searchlist_content_container";
  var els = getElementsByClassname(classname, 'div');

  if(most_recent) els[ els.length+1 ] = most_recent;

  //get them all and make sure they are closed (display:none or blind up?) then open the one passed
  for( var i = 0; i < els.length; i++)
  {
    if( els[i] != undefined )
    {
      if( els[i].id != objname )
      {
        var el = document.getElementById(els[i].id);
        if(el)
        {
          if(el.style.display != 'none')
          {
            Effect.BlindUp(els[i]);
          }
        }
      }
    }
  }
  toggleFaqContent(objname); //in the /js/faq.js file. loaded from default_header
};

var clearSearchlist = function()
{
  //call the php ajax page to clear the cookies or just clear them here?
	var urlstring='/widgets/searchlist/searchlist_ajax.php?action=clear';

	new Ajax.Request(urlstring,
	{
		method:'get',
		onSuccess: function(o)
		{
      window.location.reload();
		},
		onFailure: function()
		{
			alert('Request error...')
		}
	});
};

var getSearchlistCountJS = function()
{
	var urlstring='/widgets/searchlist/searchlist_ajax.php?action=count';
	new Ajax.Request(urlstring,
	{
		method:'get',
		onSuccess: function(o)
		{
      menubrowserUpdateCounts(null,null,o.responseText); //located here in common.js
		},
		onFailure: function()
		{
			alert('Request error...')
		}
	});
};


//http://www.devarticles.com/c/a/DHTML/Dynamically-Positioned-Layers-by-Mouse-Position/2/
function getObject( obj ) {

  // step 1
  if ( document.getElementById ) {
    obj = document.getElementById( obj );

  // step 2
  } else if ( document.all ) {
    obj = document.all.item( obj );

  //step 3
  } else {
    obj = null;
  }

  //step 4
  return obj;
  }

//http://www.devarticles.com/c/a/DHTML/Dynamically-Positioned-Layers-by-Mouse-Position/2/
function moveObject( obj, e )
{
  // step 1
  var tempX = 0;
  var tempY = 0;
  var offset = 5;
  var objHolder = obj;

  // step 2
  obj = getObject( obj );
  if (obj==null) return;

  // step 3
  if (document.all) {
    tempX = event.clientX + document.body.scrollLeft;
    tempY = event.clientY + document.body.scrollTop;
  } else {
    tempX = e.pageX;
    tempY = e.pageY;
  }

  // step 4
  if (tempX < 0){tempX = 0}
  if (tempY < 0){tempY = 0}

  // step 5
  obj.style.top  = (tempY + offset) + 'px';
  obj.style.left = (tempX + offset) + 'px';

  // step 6
  displayObject( objHolder, true );
}

//http://www.devarticles.com/c/a/DHTML/Dynamically-Positioned-Layers-by-Mouse-Position/2/
function displayObject( obj, show )
{
  // step 1
  obj = getObject( obj );
  if (obj==null) return;

  // step 2
  obj.style.display = show ? 'block' : 'none';
  obj.style.visibility = show ? 'visible' : 'hidden';
}


  var doSearchResultsSort = function (value)
  {
//    document.getElementById("avSort").value = document.getElementById("avSortSearchResults").options[document.getElementById("avSortSearchResults").selectedIndex].value;
    document.getElementById("avSort").value = value;

//if the sort gets added to the avail search can use this instead. right now the field is hidden on the avail search
//  document.getElementById("avSort").selectedIndex = document.getElementById("avSortSearchResults").selectedIndex;
    if(document.fmsearch) document.fmsearch.submit(); else alert("cant find the availability form...");
  }

  /**
   * show the avail search in the main YUI popup
   * or, if we are on a page where the availsearch
   * is already on the page we need to scroll to it
   * and highlight it to bring attention to it.
   * this is accomplished with scriptaculous
   */
  var popupSearch = function(e)
  {
    //check to see if we are on a page with the search widget
    var el = document.getElementById('availsearchbox');
    var theBrowser= new browser;
    var thePopup = document.getElementById("availsearch_popup_bd");
    var is_popup = DOM.get("availsearch_is_popup");

    if( ! is_popup)
    {
      if( el )
      {
        //see which div is showing so we flash the right one
        var elsearch = document.getElementById('avail_search_div');
        var elhomes = document.getElementById('avail_search_homes_div');
        if( elsearch ) //which panel are we looking at, so which to highlight
        {
          if( theBrowser.isIE() )
          {
            Effect.ScrollTo('availsearchbox', { duration:'0.2', offset:-20 });
            new Effect.Highlight('avail_search_div', { startcolor:'#FF0000', duration:3 });
          } else {
            Effect.ScrollTo('availsearchbox', { duration:'0.2', offset:-20 });
            new Effect.Highlight('avail-yui-content', { startcolor:'#FF0000', duration:1.5 });
            Effect.Pulsate('avail-yui-content', { pulses: 5, duration: 1.5 });
          }
        }
      }
    } else {
      //no widget on page so load it into the popup
      var cRegion = DOM.getClientRegion();
      var elmwidth  = 310;
      var elmheight = 350;
      var x_coord = (cRegion.right  - elmwidth)/2;
      var y_coord = cRegion.top + ((cRegion.bottom - cRegion.top - elmheight) / 2);
      toggle_availsearch_popup();
      new Effect.Move("availsearch_popup", {x:x_coord,y:y_coord,duration:.5,mode:'absolute'});
    }
  }

  var toggle_availsearch_popup = function()
  {
    //if visible then hide-if hidden then show
    var theEl = document.getElementById("availsearch_popup");
    if(theEl)
    {
      if(theEl.style.display == "block") theEl.style.display = "none";
      else theEl.style.display = "block";
    }
  }


/***********************************************
* Bookmark site script- � Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/

/* Modified to support Opera */
function bookmarksite(title,url){
if (window.sidebar) // firefox
	window.sidebar.addPanel(title, url, "");
else if(window.opera && window.print){ // opera
	var elem = document.createElement('a');
	elem.setAttribute('href',url);
	elem.setAttribute('title',title);
	elem.setAttribute('rel','sidebar');
	elem.click();
}
else if(document.all)// ie
	window.external.AddFavorite(url, title);
}


function csValidateQuoteform()
{
  var ardate = document.forms.quoteform.arDate;
  var ardate_array = ardate.value.split('-');
  var yy = parseInt(ardate_array[0]);
  var mo = parseInt(ardate_array[1], 10) - 1;  // number is base10 (LZ interpreted as octal), month is 0-11
  var dd = parseInt(ardate_array[2], 10);
  var arrival = new Date(yy, mo, dd);
  var today   = new Date();
  var days_out = parseInt((arrival.getTime() - today.getTime()) / 86400000); // 1000 * 60 * 60 * 24 (milliseconds)
  // if the arrival date is less than 30 days out, turn off VCP
  var qtVCP_Y = document.getElementById('qtVCP_Y');
  var qtVCP_N = document.getElementById('qtVCP_N');
  if (days_out < 30 && qtVCP_Y.checked)
  {
    qtVCP_Y.checked = false;
    qtVCP_N.checked = true;
    alert('Cancellation Protection is not available when your arrival is less than 30 days from today.  It will not be included in your quote.');
  }
  return true;
}

  //http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric
  isNumber = function(n)
  {
//    return !isNaN(parseFloat(n)) && isFinite(n);
    var number = /^-?\d*\.?\d+([eE]\d*.\d+)?$/i;
    var regex = RegExp(number);

    return regex.test(n) && n.length>0;
  }


  /**
   * <textarea name="limitedtextarea" onKeyDown="limitText(this.form.limitedtextarea,this.form.countdown,100);" onKeyUp="limitText(this.form.limitedtextarea,this.form.countdown,100);">
   *
   * <input name="limitedtextfield" type="text" onKeyDown="limitText(this.form.limitedtextfield,this.form.countdown,15);" onKeyUp="limitText(this.form.limitedtextfield,this.form.countdown,15);" maxlength="15">
   *
   */
  limitText = function (limitField, limitCount, limitNum)
  {
    if (limitField.value.length > limitNum) {
      limitField.value = limitField.value.substring(0, limitNum);
    } else {
      limitCount.value = limitNum - limitField.value.length;
    }
  }
