var IE=GECKO=MAC=OPERA=KHTML=NS=false;
var ua=navigator.userAgent;
IE=(ua.indexOf('MSIE')!=-1) ? parseFloat(ua.substring(ua.indexOf('MSIE')+5,ua.indexOf('MSIE')+8)) : false;
if (ua.indexOf('Gecko')!=-1) GECKO=true;
if (ua.indexOf('Mac')!=-1) MAC=true;
if (ua.indexOf('Opera')!=-1) {IE=GECKO=false;OPERA=true;}
if (ua.indexOf('KHTML')!=-1) {IE=GECKO=false;KHTML=true;}
if (ua.indexOf('Netscape')!=-1&&GECKO) NS=true;
var default_miles='50';
var default_where = 'USA';
var marketWhereTerm=(marketWhereTerm||default_where);
var marketProp = marketProp || '';
var marketLon = marketLon || '';
var marketLat = marketLat || '';
var marketRadius = marketRadius || '50';
var prefix=(prefix||'http://'+document.domain);
var ref_uri=(ref_uri||'');
var goToOmissions='lat|long|savedLocs|street|recLocs|link|cmode|where|c_zip|market_id|sorted|start|alpha|ref_uri|orig_where';
var mostRecLocIndex = 0;
var valuesObj=getValues();
var searchForm = 'anythingTop'; // set as string because form not written to DOM yet, Use eval.
if(typeof(addToOnLoad) != 'undefined') addToOnLoad("searchFormOnLoad()");

searchFormOnLoad = function(){
  searchForm = document.forms['anythingTop'];
  if(typeof(searchForm) != 'object') return;
  hotelsChangeMe('h_address'); // changes topbar to address lookup
  popForm();
  storeComparisonWhere();
}

function addPrefix(url) { return (!url.search('^/')) ? prefix+url : url; }

function cleanUp(field) {
  field.value=field.value.replace(/[\`\~\!\@\#\$\%\^\&\*\(\)\+\{\}\"\<\>\/\_\=\?\:\;]|\s\s/g,' ');
  field.value=field.value.replace(/^\s+/g,'');
  field.value=field.value.replace(/\s+/g,' ');
}

function getCookie(cookieName) {
  var start=document.cookie.indexOf(cookieName);
  if (start !=-1) start+=(cookieName.length+1);
  var end=document.cookie.indexOf(";",start);
  if (end==-1) end=document.cookie.length;
  var cookie=unescape(document.cookie.substring(start,end));
  if (start !=-1) return cookie;
}

function getRefUri() {
  var newUrl=document.URL.replace('http://','');
  newUrl=newUrl.replace(document.domain,'');
  ref_uri=(ref_uri||newUrl.replace(location.search,''));
  return (ref_uri.match('change')) ? ref_uri.replace('/change','') : ref_uri;
}

function getValues() {
  var queryObj=new Object;
  var temp=new Array();
  var qs=new String(location.search);
  qs=qs.substr(1,qs.length);
  qs=qs.replace(/\;/g,'&');
  var queryArray=new Array();
  queryArray=qs.split('&');
  for (i=0; i<queryArray.length; i++) {
    temp=queryArray[i];
    temp=temp.split('=');
    if (temp[0]&&temp[1]&&temp[0]!='init_change') {
      queryObj[temp[0]]=unescape(temp[1]);
      queryObj[temp[0]]=queryObj[temp[0]].replace(/\+/g,' ');
    }
  }
  ref_uri=(ref_uri||queryObj['ref_uri']);
  queryObj['recLocs']=parseCookie('recent_locs');
  queryObj['savedLocs']=parseCookie('saved_location');
  queryObj['city_state']=(queryObj['city_state']||marketWhereTerm);
  queryObj['where']=(queryObj['where']||marketWhereTerm);
 

  if(typeof(queryObj['recLocs']) != 'undefined'){
    if(typeof(queryObj['store_where_for_comparison']) != 'undefined'){
      for(var i = 0; i < queryObj['recLocs'].length; i++){
        if((typeof(queryObj['recLocs'][i]['where']) != 'undefined' && queryObj['store_where_for_comparison'] == queryObj['recLocs'][i]['where']) ||
         (typeof(queryObj['recLocs'][i]['geo_id']) != 'undefined' && queryObj['store_where_for_comparison'] == queryObj['recLocs'][i]['geo_id'])){
          mostRecLocIndex = i;
          break;
        }
      }
    }
    for (x in queryObj['recLocs'][mostRecLocIndex]) queryObj[x]=queryObj['recLocs'][mostRecLocIndex][x];
  }

  return queryObj;
}

function goToChange(prevUrl,other_attributes) {
  prevUrl=(prevUrl||getRefUri());
  var queryString ='';
  var change=new Object();
  for (var i in valuesObj) if (i.search(goToOmissions)) change[i]=valuesObj[i];
  var others=new Array;
  if (other_attributes) others=other_attributes.split('|');
  if (others.length) {
    for (i=0; i<others.length; i++) {
      temp=others[i].split('=');
      change[temp[0]]=temp[1];
    }
  }
  var count=0;
  var nextChar='?';
  for (var i in change) {
    queryString+=nextChar+i+'='+escape(change[i]);
    nextChar='&';
  }
  location=addPrefix("/change/"+queryString+nextChar+"ref_uri="+prevUrl+"&orig_where="+escape(valuesObj['city_state']));
}

function parseCookie(cookieName) {
  var cookie=getCookie(cookieName);
  if (cookie==-1||!cookie) return;
  var cslinkName=(cookieName=='recent_locs') ? 'recent' : 'saved';
  var temp=new Array();
  var col1=new Array();
  col1=cookie.split('^|');
  for (var x=0; x<col1.length; x++) {
    var col2=col1[x].split('~|');
    temp[x]=new Object();
    temp[x]['where']=(col2[2]||default_where);
    temp[x]['lat']=col2[3];
    temp[x]['long']=col2[4];
    temp[x]['miles']=(col2[5]||default_miles);
    temp[x]['market_id']=col2[6];
    temp[x]['c_zip']=col2[7];
    if (cookieName=='recent_locs') {
      temp[x]['city_state']=(col2[0]||default_where);
      temp[x]['street']=(col2[8])? col2[8].substring(0,22) : "";
      temp[x]['city_state_zip']=(col2[9]||temp[x]['city_state']);
      if (col2[10]&&col2[9]) temp[x]['city_state_zip']+=","+col2[10];
      if (col2[11]&&col2[9]) temp[x]['city_state_zip']+=" "+col2[11];
      if(col2[12] != 'undefined' && col2[12] != '') temp[x]['geo_id'] = col2[12];
    }
    if (cookieName=='saved_location') temp[x]['default']=col2[8];
    if (cookieName=='saved_location'&&col2[1]) {
      temp[x]['nameD']=col2[1];
      var cszArray=col2[2].split('::');
      temp[x]['street']=cszArray[0];
      temp[x]['city']=cszArray[1];
      temp[x]['state']=cszArray[2];
      temp[x]['zip']=cszArray[3];
      if (temp[x]['city']) temp[x]['city_state_zip']=temp[x]['city'];
      else if (temp[x]['zip']) temp[x]['city_state_zip']=temp[x]['zip'];
      if (temp[x]['city']&&temp[x]['state']) temp[x]['city_state_zip']+=','+temp[x]['state'];
      if (temp[x]['city']&&temp[x]['zip']) temp[x]['city_state_zip']+=' '+temp[x]['zip'];
    }
    temp[x]['link']='parent.goToChange(\''+getRefUri()+'\',\'street='+temp[x]['street']+'|city_state_zip='+temp[x]['city_state_zip']+'|lat='+temp[x]['lat']+'|long='+temp[x]['long']+'|miles='+temp[x]['miles']+'|cslink=change_'+cslinkName+'\')';
  }
  return temp;
}

function popForm() {
  var fields=new Array('where','lat','long','miles','market_id','query','name','c_zip','type');
  for (var count=0; count<document.forms.length; count++) {
    for (var field_count=0; field_count<fields.length; field_count++) {
      if (document.URL.match(/change\/*\?|user_location/)&&valuesObj['cmode']!='add_edit') continue;
      if (document.forms[count][fields[field_count]]&&valuesObj[fields[field_count]])
        document.forms[count][fields[field_count]].value=valuesObj[fields[field_count]];
    } 
  }
}   

function togglePseudo() {
  if(typeof(searchForm) != 'object') return;
  if(searchForm.gcats && searchForm.gcats.checked == false){
    searchForm.pseudo_constrain.value = '';
  }
}

var iframeMenu=(IE>=5) ? true : false;
var divMenu=(GECKO||OPERA||KHTML) ? true : false;
if (valuesObj['menu'] == 'iframe') {iframeMenu=true;divMenu=false;}
if (valuesObj['menu'] == 'div' ) {divMenu=true;iframeMenu=false;}
var subMenus=new Object();
var flavorMenus=new Object();
var menuStates=new Object();
var menuParent=new Object();
var menuChild=new Object();
var timeout;
var nhoods=(nhoods||false);
var locationMenu=new Object();

locationMenu['changeNeighborhood']=true;
locationMenu['newLocation']=new Array("Enter&nbsp;New&nbsp;Location...","parent.goToChange('"+getRefUri()+"','init_change=1|cslink=change_enter_location')");
locationMenu['metro']=new Array("Greater&nbsp;"+marketProp,'parent.goToChange(\''+getRefUri()+
                                   '\',\'city_state_zip='+marketWhereTerm+
                                   '|long='+marketLon+'|lat='+marketLat+
                                   '|miles='+marketRadius+
                                   '|cslink=change_greater_market\')');
setParent('newLocation','changeNeighborhood');
setParent('metro','changeNeighborhood');
locationMenu['savedLocs']=new Array("Saved&nbsp;Locations");
locationMenu['recLocs']=new Array("Recent&nbsp;Locations");
subMenus['savedLocs']=getLocations('savedLocs');
subMenus['recLocs']=getLocations('recLocs');

function addMenu(id) {
  menuStates[id]=new Object();
  menuStates[id]['on']=true;
  if (iframeMenu) newIframe(id);
  if (divMenu) newDiv(id);
  if (!wrapper(id)) return;
  if (subMenus[id]) insertHTML(wrapper(id),insertLinks(id,subMenus));
  else if (nhoods[id]) insertHTML(wrapper(id),insertNeighborhoodMenu(id));
  else if (locationMenu[id]) insertHTML(wrapper(id),insertLocationMenu(id));
  else if (flavorMenus[id]) insertHTML(wrapper(id),insertFlavorMenu(id));
  if (MAC&&IE) {
    thisMenu(id).style.visibility="visible";
    resizeMenu(id);
    moveMenu(id);
    thisMenu(id).style.visibility="hidden";
  }
}

switchSearchArea = function(newArea){
  var newArea = newArea || 'h_address';
  if(CS_DHTML){
    // switchDisplay on all off
    CS_DHTML.switchDisplay("addressSearchText","none");
    CS_DHTML.switchDisplay("h_address_block","none");
    CS_DHTML.switchDisplay("neighborhoodSearchText","none");
    CS_DHTML.switchDisplay("h_neighborhood_block","none");
    CS_DHTML.switchDisplay("airportSearchText","none");
    CS_DHTML.switchDisplay("h_airport_block","none");
    CS_DHTML.switchDisplay("attractionSearchText","none");
    CS_DHTML.switchDisplay("h_attraction_block","none");
  
    // switchDisplay on newArea on.
    CS_DHTML.switchDisplay(newArea.substring(2) + 'SearchText','block')
    CS_DHTML.switchDisplay(newArea+ '_block','block');
  }
}

function fadeMenu(id) { stopFade(); if (menuParent[id]) return; timeout=setTimeout("hideAll()",500); }

function getLocations(id) {
  var locsArray=new Array();
  var place=0;
  setParent(id,'changeNeighborhood');
  var start=(id=="recLocs") ? 1 : 0;
  if (valuesObj[id]) {
    var limit=(valuesObj[id].length>4&&id=='recLocs') ? 4 : valuesObj[id].length;
    for (var x=start; x<limit; x++) {
      if (!valuesObj[id][x]['lat']) continue;
      locsArray[place++]=(valuesObj[id][x]['nameD']||valuesObj[id][x]['city_state_zip']);
      locsArray[place++]=valuesObj[id][x]['link'];
    }
    if (id=='savedLocs') {
      locsArray[place++]=grayBar('#000');
      locsArray[place++]='graybar';
    }
  }
  if (id=='savedLocs') {
    locsArray[place++]='<b>Add/Edit&nbsp;Locations</b>';
    locsArray[place++]='/change?cmode=add_edit';
  }
  return locsArray;
}

function grayBar(color) {
  return '<div id="graybar" style="background: '+color+';" height="1"><img src="'+t_gif.src+'" height="1" width="10"></div>';
}

function hideAll(oId) {
  stopFade();
  for (var id in menuStates) {
    if (thisMenu(id)&&oId!=id&&id!=menuParent[oId]&&(menuStates[id]['on']||!oId)) {
      thisMenu(id).style.visibility="hidden";
      if (iframeMenu&&menuParent[id]&&thisOpener(id+'Open',menuParent[id]))
        thisOpener(id+'Open',menuParent[id]).className="top_sub";
      if (divMenu&&menuParent[id]&&thisMenu(id+'Open'))
        thisMenu(id+'Open').className="top_sub";
      menuStates[id]['on']=false;
      if (thisMenu(id+'Open')) thisMenu(id+'Open').src = flavor_images[id].src;

    }
  }
}

function insertHTML(menu,html) { menu.innerHTML=html; }

function insertMenu(mId,t,r,b,l) {
  if (divMenu) {
    var html='<div valign="bottom" style="position: absolute; visibility: hidden;';
    if (t !=-1&&r !=-1&&b !=-1&&l !=-1) html+=' margin: '+t+'px '+r+'px '+b+'px '+l+'px;';
    return html+='" id="'+mId+'"></div>';
  } else {
    var html='<iframe style="position: absolute; visibility: hidden;';
    if (t !=-1&&r !=-1&&b !=-1&&l !=-1) html+=' margin: '+t+'px '+r+'px '+b+'px '+l+'px;';
    return html+='" id="'+mId+'" frameborder="0" scrolling="no"></iframe>';
  }
}

function insertLink(id,list,nId,subList) {
  var aId=(nId||id);
  var oId=thisMenu(id+"_Cell");
  nId=(subList)? nId+"Open" : nId;
  var offWidth=(oId) ? oId.offsetWidth-7 : 1;
  if (id=='changeNeighborhood') offWidth++;
  if (list[aId][1]&&list[aId][1].match('graybar')) return list[aId][0];
  var link=(list[aId].length>1) ? (list[aId][1].match('parent')) ? list[aId][1] : 'parent.window.location=(\''+addPrefix(list[aId][1])+'\');' : '';
  var html='<div id="'+nId+'" class="top_sub" style="padding: 0px 0px 0px 4px; line-height: 18px; font-family: verdana,arial,sans-serif; font-size: 11px; cursor: ';
  html+=(link) ? pointerType()+'" onclick="'+link+'"' : 'default"';
  html+=' onmouseover="parent.linkOn(this)';
  if (id=='changeNeighborhood') html+=';parent.hideAll(\''+id+'\')';
  html+=(subList) ? ';parent.showMenu(\''+aId+'\');" onmouseout="parent.linkOff(this);" style="cursor:default;" nowrap><img align="right" width="8" height="7" src="'+rightArrow.src+'" border="0" style="margin: 6px 0px 0px 0px">'+list[aId][0].replace(/\s/,'&nbsp;')+'<br /><img src="'+t_gif.src+'" border="0" width="'+offWidth+'" height="1"></div>' : '" onmouseout="parent.linkOff(this);parent.fadeMenu(\''+aId+'\')" nowrap>'+list[aId][0].replace(/\s/,'&nbsp;')+'&nbsp<br /><img name="'+aId+'Arrow" src="'+t_gif.src+'" border="0" width="'+offWidth+'" height="1"></div>';
  return html;
}

function insertLinks(id,list) {
  var html='';
  for (var i=0; i<list[id].length; i++) {
    var singleList=new Object();
    singleList[id]=new Array(list[id][i],list[id][i+1]);
    html+=insertLink(id,singleList);
    i++;
  }
  return html;
}

function insertLocationMenu(id) {
  var html=insertLink(id,locationMenu,'newLocation');
  html+=insertLink(id,locationMenu,'savedLocs',subMenus['savedLocs']);
  if (subMenus['recLocs'].length)
    html+=insertLink(id,locationMenu,'recLocs',subMenus['recLocs']);
  if (nhoods) {
    html+=grayBar('#000');
    var areas=new Array('area1','A-F','area2','G-L','area3','M-R','area4','S-Z');
    for (var x=0; x<areas.length; x++) {
      if (nhoods[areas[x]]) {
        setParent(areas[x],'changeNeighborhood');
        locationMenu[areas[x]]=new Array("Neighborhoods&nbsp;"+areas[x+1]);
        html+=insertLink(id,locationMenu,areas[x],nhoods[areas[x]]);
      }
      x++;
    }
    html+=insertLink(id,locationMenu,'metro');
  }
  return html;
}

function insertFlavorMenu(id) {
  var html='<table cellpadding="10" cellspacing="0" border="0" onmouseout="parent.fadeMenu(\''+id+'\')" onmouseover="parent.stopFade();"><tr><td><div class="droptext" nowrap>All available '+flavor_text[id]+' around <b>'+valuesObj['city_state']+'</b>.</div><br /><div><img src='+t_gif.src+' width=1 height=7></div><div style="background:#CECFCE"><img src='+t_gif.src+' width=1 height=1></div><div><img src='+t_gif.src+' width=1 height=7></div><table border="0" cellpadding="2" cellspacing="2"><tr><td class="droplink" nowrap valign=top>';
  for (var x=0; x<flavorMenus[id].length; x++) {
    var text=flavorMenus[id][x];
    x++;
    var url=flavorMenus[id][x];
    html+='<a href='+url+' target=_parent>'+text+'</a><br />';
    if ( flavorMenus[id].length > 20 && x >= flavor_menu_break_count ) {
      var divider = Math.round(flavorMenus[id].length/flavor_menu_break_count);
      if (divider > flavor_menu_max_cols) divider = flavor_menu_max_cols;
      if ( x%Math.floor(flavorMenus[id].length/divider)==0||(x-1)%Math.floor(flavorMenus[id].length/divider)==0 ) {
        html += '</td><td>&nbsp;&nbsp;</td><td class="droplink" nowrap valign=top>';
      }
    }
  }
  return html + '</td></tr></table></td></tr></table>';
}

function insertNeighborhoodMenu(id) {
  for (var x=0; x<nhoods[id].length; x++) {
    nhoods[id][++x]='parent.goToChange(\''+getRefUri()+'\',\'geo_id='+nhoods[id][x]+'|cslink=change_neighborhood\')';
  }
  setParent(id,'changeNeighborhood');
  return insertLinks(id,nhoods);
}

function linkOff(item) {
  var id=item['id'].replace(/Open/,'');
  if (menuStates[id]) if (menuStates[id]['on']) return;
  item.className='top_sub';
}

function linkOn(item) { stopFade(); item.className='top_sub_hover'; }

function moveMenu(id) {
  if (!menuParent[id]) return;
  var mParent=thisMenu(menuParent[id]);
  var doc=(divMenu) ? thisDoc(id+"Open") : thisOpener(id+"Open",menuParent[id]);
  var ie_gecko_left=(IE>=5.5) ? -3 : (OPERA) ? 3 : -1;
  var ie_top=(IE>=5.5) ? -7 : (GECKO) ? -1 : (OPERA) ? 3 : -6;
  if (MAC&&IE) { ie_top=3; ie_gecko_left=3; }
  var winHeight=document.body.clientHeight+document.body.scrollTop;
  var top=(KHTML||OPERA||GECKO||IE>=5.5||(MAC&&IE>=5)) ?
        mParent.offsetTop+doc.offsetTop+ie_top :
        mParent.top+ie_top+doc.offsetTop+document.body.scrollTop+1;
  var fromBottom=(top+thisMenu(id).offsetHeight>winHeight) ?
        winHeight-thisMenu(id).offsetHeight-1 : top;
  thisMenu(id).style.top=(fromBottom<1+document.body.scrollTop) ?
    1+document.body.scrollTop : fromBottom;
  thisMenu(id).style.left=(KHTML||OPERA||GECKO||IE>=5.5||(MAC&&IE>=5)) ?
    mParent.offsetLeft+ie_gecko_left+mParent.offsetWidth :
    mParent.left-1+mParent.offsetWidth;
}

function newDiv(id) {
  insertHTML(thisMenu(id),'<table border="0" cellpadding="0" cellspacing="0"><tr><td><div id="menuWrapper'+id+'" style="border-style:solid; border-color:#8c8773; background: #FFF; border-width:1px;"></div></td></tr></table>');
}

function newIframe(id) {
  if (IE) thisDoc(id).createStyleSheet(mainStyleSheet.src);
  var ss=(!IE) ? '<link rel="stylesheet" href="'+mainStyleSheet.src+'" type="text/css">' : '';
  var mMar=(MAC&&IE==5) ? ' margin:-4px 0px 0px-4px;' : '';
  thisDoc(id).body.text="#000000";
  insertHTML(thisDoc(id).body,ss+'<table border="0" cellpadding="0" cellspacing="0" style="position: absolute; left: 0; top: 0;"><tr><td><div id="menuWrapper" style="border-style:solid; border-color:#000; background: #FFF; border-width:1px;'+mMar+'">Menu Loading...</div></td></tr></table>');
}

function pointerType() { return (GECKO) ? 'pointer' : 'hand'; }

function resizeMenu(id) {
  var oId=(thisMenu(id+"_Cell")||false);
  if (oId&&IE) if (oId.offsetWidth>thisMenu(id).width+3) addMenu(id);
  thisMenu(id).width=wrapper(id).offsetWidth;
  thisMenu(id).height=wrapper(id).offsetHeight;
  thisMenu(id).style.zIndex=(menuParent[id]) ? 1001 : 1000;
  thisMenu(id).style.filter="progid:DXImageTransform.Microsoft.Shadow(color='#999999',Direction=135,Strength=2)";
}

function setParent(id,pId) {
  if (!id||!pId) return;
  menuParent[id]=pId;
  if (!menuChild[pId]) menuChild[pId]=new Object();
  menuChild[pId][id]=id;
}

function showMenu(id) {
  if (!menuStates[id]) addMenu(id);
  menuStates[id]['on']=true;
  stopFade();
  hideAll(id);
  resizeMenu(id);
  moveMenu(id);
  if (menuParent[id]&&menuStates[id]['on']) {
    if (iframeMenu) thisOpener(id+'Open',menuParent[id]).className="top_sub_hover";
    if (divMenu) thisMenu(id+'Open').className="top_sub_hover";
  }
  if (thisMenu(id+'Open') && flavor_images[id+'_on']) thisMenu(id+'Open').src = flavor_images[id+'_on'].src;
  thisMenu(id).style.visibility='visible';
}

function stopFade() { clearTimeout(timeout); }

function thisDoc(id) { return (IE&&iframeMenu&&document.frames(id)) ? document.frames(id).document :
         (iframeMenu&&GECKO) ? thisMenu(id).contentDocument : thisMenu(id);}

function thisMenu(id) { return document.getElementById(id); }

function thisOpener(id,parent) { return (thisDoc(parent)) ? thisDoc(parent).getElementById(id) : thisDoc(id); }

function wrapper(id) { return (iframeMenu) ? thisOpener('menuWrapper',id) : thisMenu('menuWrapper'+id); }

document.onmouseup=hideAll;
