var g_pMainSearchMap = null;
var g_strMainMapObjId = null;
var g_strOnErrorMsg = '';
var g_strFindMsgTxt = 'Could not find address/location. Please try entering a "city, state" or zip code.';
var g_strLoadingTxt = 'Please wait for the map to finish loading before searching for a place.';
var g_pLocationRefineContainer = null;
var g_bContinuous = false;
var g_iMaxZoomLevel = 18;
var g_iMinZoomLevel = 8;
var g_iNumAreaResultsPerPage = 20;
var g_aOnChangeComplete = new Array;
var g_iNumAreasSelected = 0;
var g_bMapMovedOffCenter = false;
var g_bIsFirstSearch = true;
var g_bIsInInitialization = true;

var g_bInDragEvent = false;
var g_iLastPosX = -1;
var g_iLastPosY = -1;

g_strErrorLogFunction = 'SearchMapOnError';

function DoAjaxAreaSearch( iOffset )
{
   if( g_bIsInInitialization ) {
      return;
   }
   var iAreaMinPrice = GetHiddenFieldIntValue('areaminprice', 0);
   var iAreaMaxPrice = GetHiddenFieldIntValue('areamaxprice', 20000000);
   var iAreaEduAtm   = GetHiddenFieldIntValue('areaeduatm', 50);
   var iAreaAge      = GetHiddenFieldIntValue('areaage', 50);
   var iAreaIncome   = GetHiddenFieldIntValue('areaincome', 50);
   var iAreaEduLevel = GetHiddenFieldIntValue('areaedulevel', 50);
   var iAreaWKids    = GetHiddenFieldIntValue('areawkids', 50);
   var iAreaDensity  = GetHiddenFieldIntValue('areadensity', 50);

   if( !iOffset ) {
      iOffset = 0;
   }

   var mapView = RfgGetCurrentMapView(g_strMainMapObjId);   
   var strParms = 'limit='+g_iNumAreaResultsPerPage+'&offset='+iOffset;
   strParms += '&north=' + mapView.TopLeftLatLong.Latitude;
   strParms += '&south=' + mapView.BottomRightLatLong.Latitude;
   strParms += '&west=' + mapView.TopLeftLatLong.Longitude;
   strParms += '&east=' + mapView.BottomRightLatLong.Longitude;
   strParms += '&zoom='  + g_pMainSearchMap.GetZoomLevel();

   strParms += '&minprice=' + iAreaMinPrice;
   strParms += '&maxprice=' + iAreaMaxPrice;
   strParms += '&eduatm='   + iAreaEduAtm;
   strParms += '&age='      + iAreaAge;
   strParms += '&income='   + iAreaIncome;
   strParms += '&edulevel=' + iAreaEduLevel;
   strParms += '&wkids='    + iAreaWKids;
   strParms += '&density='  + iAreaDensity;
   
   if( iOffset < 1 && !g_bMapMovedOffCenter ) {
      var strThisWhere = document.getElementById('areawhere_1').value;
      strParms += '&where='  + escape(strThisWhere);
   }
   var strUrl = '/xml-bin/neighborhoodsearch?' + strParms;

   SetCookie('lsn',(strParms+'&where=' + document.getElementById("areawhere_1").value),null,'/',null,null);

   
   var iCurrentZoom = g_pMainSearchMap.GetZoomLevel();
   if( iCurrentZoom >= g_iMinZoomLevel ) {

      var strWaitDlgDefaultHtml = '<div class="calloutblack" style="width:300px;height:110px;margin-right: 20px;color:white;">' +
                                  '   <div class="label"><div class="tl"></div><div class="tr"></div><b>Please Wait...</b>      ' +
                                  '   </div>' +
                                  '   <div class="body" style="color:white">' +
                                  '      <div style="height:90px;padding-left:16px;margin-right:5px;">' +
                                  '         <div style="float:right"><a href="#" onClick="RfgHideWaitDialog(\''+g_strMainMapObjId+'\');"><img src="/images/close.gif" width=20 height=20></a></div>' +
                                  '         Performing area search...' +
                                  '         <br><br>' +
                                  '         <img src="/images/loading.gif">' +
                                  '      </div>' +
                                  '   </div>' +
                                  '   <div class="bl"></div><div class="bm"></div><div class="br"></div>' +
                                  '</div>';
   
      g_strOnErrorMsg = '';
      if( !g_pMainSearchMap ) {
         alert(g_strLoadingTxt);
         return false;
      }
      RfgShowWaitDialog(g_strMainMapObjId, true, "Peforming search", strWaitDlgDefaultHtml);
      g_AjaxQueue.schedule("AreaSearch", strUrl, OnCompleteAreaSearch);      
      if( g_bMapMovedOffCenter ) {
         SetInnerHtml('areasearchdescription', 'Map search');
      } else {
         SetInnerHtml('areasearchdescription', document.getElementById("areawhere_1").value);
      }
   } else {
      SetInnerHtml('areasearchnumresults' , 'n/a');
      SetInnerHtml('areasearchresultstable' , 'You must zoom in further to see results.' );
   }
}

function handleAreaDisplay(pAreaNode, iIndex, aoSavedAreas)
{
   var strName       = GetNodeValue(pAreaNode, 'name');
   var strGeoType    = GetNodeValue(pAreaNode, 'geotype');
   var iObId         = GetNodeValue(pAreaNode, 'obid');
   var fLat          = GetNodeValue(pAreaNode, 'lat');
   var fLon          = GetNodeValue(pAreaNode, 'lon');
   var fMedianPrice  = GetNodeValue(pAreaNode, 'medianprice');
   var fMedianIncome = GetNodeValue(pAreaNode, 'medianincome');
   var fMedianAge    = GetNodeValue(pAreaNode, 'medianage');
   var fPctWithKids  = GetNodeValue(pAreaNode, 'pctwithkids');
   var strHtml = '';
   var strMapPreviews = '';

   if( strName == '' ) {
      strName = '&nbsp;';
   }

   var strMedianIncome = '$' + AddCommas(fMedianIncome);
   if( fMedianIncome == '0' ) {
      strMedianIncome = '-';
   }

   var strMedianPrice = '$' + fMedianPrice;
   if( fMedianPrice == '0' ) {
      strMedianPrice = '-';
   }
   var strCheckState = '';

   if(( strGeoType == aoSavedAreas[0].strGeoType && iObId == aoSavedAreas[0].iObId ) ||
      ( strGeoType == aoSavedAreas[1].strGeoType && iObId == aoSavedAreas[1].iObId ) ) {
      strCheckState = ' checked=checked';
   }
   var strTrClass = '';
   if( iIndex < 0 ) {
      strTrClass = ' class="selectedarea"';
   }

   strHtml =  '<tr'+strTrClass+'>' +
              '<td><nobr>' + '<input type="checkbox" id="areacheck_'+strGeoType+iObId+'a" name="acb" onClick="changeAreaSelection(this, \''+strGeoType+'\', \''+iObId+'\', \''+strName+'\', \''+strMedianPrice+'\', \''+strMedianIncome+'\', \''+Math.round(fMedianAge)+'\', \''+Math.round(fPctWithKids)+'%\' );"'+strCheckState+'>' + 
              '    <img src="/images/area/'+(iIndex+1)+'.gif" border="0"></nobr></td>' + 
              '<td><a href="/area/index.jsp?type='+escape(strGeoType)+'&id='+iObId+'">'+strName+'</a></td>' + 
              '<td>'+strMedianPrice+'</td>' + 
              '<td>'+Math.round(fMedianAge)+'</td>' + 
              '<td>'+Math.round(fPctWithKids)+'%</td>' + 
              '</tr>';

   strMapPreviews =  '<div id="areamapviewpreview_'+(iIndex+1)+'" class="hide">' +
                     '  <span id="areamapviewpreviewlat_'+(iIndex+1)+'">' + fLat +'</span>'+
                     '  <span id="areamapviewpreviewlon_'+(iIndex+1)+'">' + fLon +'</span>'+
                     '  <span id="areamapviewpreviewname_'+(iIndex+1)+'">' +
                     '     <img src="/images/area/'+(iIndex+1)+'.gif" border="0">' +
                     '     <a href="/area/index.jsp?type='+escape(strGeoType)+'&id='+iObId+'"><b>'+strName+'</b></a>' +
                     '  </span>' +
                     '  <span id="areamapviewpreviewdetails_'+(iIndex+1)+'">' +
                     '     <label style="color:#EEB31D">' + '<input type="checkbox" name="acb" id="areacheck_'+strGeoType+iObId+'b" onClick="changeAreaSelection(this, \''+strGeoType+'\', \''+iObId+'\', \''+strName+'\', \''+strMedianPrice+'\', \''+strMedianIncome+'\', \''+Math.round(fMedianAge)+'\', \''+Math.round(fPctWithKids)+'%\' );"'+strCheckState+'>' + ' Add to comparison list</label><br>' +
                     '     Median home price: ' +strMedianPrice + '<br>' +
                     '     Median age: ' + Math.round(fMedianAge) + '<br>' +
                     '  </span>' +
                     '</div>';

   if(Math.abs(fLat) > 0.01 || Math.abs(fLon) > 0.01 ){
       RfgQueueCommand(escape("RfgAddPushPin('resultmap', "+ fLat +", "+ fLon +", '"+(iIndex+1)+"', 'empty string', '/images/area/"+(iIndex+1)+".gif')"));
       //g_aVeLatLongPoints.push(new VELatLong(fLat, fLon));
   }

   return new Array( strHtml, strMapPreviews);
}

function OnCompleteAreaSearch(pThisAjaxReq)
{
   if(pThisAjaxReq.readyState != 4) {
      return;
   }
   g_bIsFirstSearch = false;
   RfgHideWaitDialog(g_strMainMapObjId);

   //alert( pThisAjaxReq.responseText );
   /*
   /areas/numresults
   /areas/limit
   /areas/offset
   /areas/area
   /areas/area/index
   /areas/area/meddist
   /areas/area/name
   /areas/area/geotype
   /areas/area/obid
   /areas/area/lat
   /areas/area/lon
   /areas/area/zip
   /areas/area/medianprice
   /areas/area/medianage
   /areas/area/pctwithkids
   /areas/area/medianincome
   /areas/area/educationclimate
   /areas/area/medianeducation
   /areas/area/populationdensity
   */
   RfgClearMap('resultmap');

   var strPackedArea1 = GetCookie('ar1');
   var strPackedArea2 = GetCookie('ar2');
   var aoSavedAreas = new Array;
   aoSavedAreas[0] = new Object();
   aoSavedAreas[1] = new Object();
   if( strPackedArea1 && strPackedArea1 != ''  ) {
      var aFields = strPackedArea1.split('|');
      if( aFields && aFields[0].length > 0 ) {
         aoSavedAreas[0].strGeoType = aFields[0];
         aoSavedAreas[0].iObId = aFields[1];
      }
   }
   if( strPackedArea2 && strPackedArea2 != ''  ) {
      var aFields = strPackedArea2.split('|');
      if( aFields && aFields[0].length > 0 ) {
         aoSavedAreas[1].strGeoType = aFields[0];
         aoSavedAreas[1].iObId = aFields[1];
      }
   }


   var pAreasNode = pThisAjaxReq.responseXML.getElementsByTagName('areas');
   if( !pAreasNode.length || pAreasNode.length == 0 ) {
      alert("Could not perform area search.");
      return;
   }

   var iNumResults = parseInt(GetNodeValue(pAreasNode[0], 'numresults'));
   var iLimit = parseInt(GetNodeValue(pAreasNode[0], 'limit'));
   var iOffset = parseInt(GetNodeValue(pAreasNode[0], 'offset'));

   SetInnerHtml('areasearchnumresults' , AddCommas(iNumResults));


   var iNumPages = parseInt(iNumResults / g_iNumAreaResultsPerPage);
   if((iNumResults % g_iNumAreaResultsPerPage) > 0) iNumPages++;
   var iCurrentPage = parseInt(iOffset / g_iNumAreaResultsPerPage);
   if((iCurrentPage % g_iNumAreaResultsPerPage) > 0) iCurrentPage++;
   
   var pAreaNodes = pThisAjaxReq.responseXML.getElementsByTagName('area');
   var strMapPreviews = '';
   var strBottomPagination = '';
   var strHtml = '<div id="searchpaginationcontainer">' +
                 '   <div class="left">' +
                 '   </div>' +
                 '   <div class="right">';
   if( iOffset > 0 ) {
      strHtml += '      <a href="javascript:DoAjaxAreaSearch(0);">first</a> | ' +
                 '      <a href="javascript:DoAjaxAreaSearch('+Math.max((iOffset-g_iNumAreaResultsPerPage), 0)+');">previous</a> ' +
                 '      <a href="javascript:DoAjaxAreaSearch('+Math.max((iOffset-g_iNumAreaResultsPerPage), 0)+');"><img src="/images/search/previous.gif" width="15" height="15" border="0" class="inlinesphere"></a>';
   }

   strHtml += '      page ' + Math.max(iCurrentPage, 1) +' of ' + Math.max(iNumPages, 1);
   if( iNumResults > (iOffset + g_iNumAreaResultsPerPage) ) {
      strBottomPagination = '<div class="searchbottompagination">' + 
                            '<a href="javascript:DoAjaxAreaSearch('+(g_iNumAreaResultsPerPage + iOffset)+');">next page of results <img src="/images/search/next.gif" width="15" height="15" border="0" class="inlinesphere"></a>' + 
                            '</div>';
      strHtml += '      <a href="javascript:DoAjaxAreaSearch('+(g_iNumAreaResultsPerPage + iOffset)+');"><img src="/images/search/next.gif" width="15" height="15" border="0" class="inlinesphere"></a>' +
                 '      <a href="javascript:DoAjaxAreaSearch('+(g_iNumAreaResultsPerPage + iOffset)+');">next</a> | ' +
                 '      <a href="javascript:DoAjaxAreaSearch('+(g_iNumAreaResultsPerPage * (iNumPages-1))+');">last</a>';
   }
   strHtml += '   </div>' +
              '</div>';   
   strHtml += '<table width="100%" border="0" cellpadding="3" cellspacing="0" class="searchresultstable"><tbody>';
   strHtml += '<tr><th>&nbsp;</th><th>NAME</th><th width="84">MEDIAN HOME PRICE</th><th width="50">MEDIAN AGE</th><th width="62">%&nbsp;HOUSES<br>w/ KIDS</th></tr>';


   var pSearchAreaNode = pThisAjaxReq.responseXML.getElementsByTagName('searchstartarea');
   if( pSearchAreaNode && pSearchAreaNode.length && pSearchAreaNode.length > 0 ) {
      //This exact area...
      var aRes = handleAreaDisplay(pSearchAreaNode[0], -1, aoSavedAreas);
      strHtml += aRes[0];
      strMapPreviews += aRes[1];
   }
   
   for (var i=0; i<pAreaNodes.length;i++) {     
      var aRes = handleAreaDisplay(pAreaNodes[i], i, aoSavedAreas);
      strHtml += aRes[0];
      strMapPreviews += aRes[1];
   }
   strHtml += '</tbody></table>';
   strHtml += strBottomPagination;

   var pDiv = document.getElementById('areasearchresultstable');
   if( pDiv ) {
      pDiv.innerHTML = strHtml + strMapPreviews;
   }
}

function SearchMapOnError( strService, exception )
{
   //Return true from this function ONLY if this message is
   //handled, and should not be further reported.
   RfgHideWaitDialog(g_strMainMapObjId);
   if( g_strOnErrorMsg != '' ) {
      alert( g_strOnErrorMsg );
      return true;
   }   
   return false;
}


//On change view function stack
function OnMapChangeView() {
   if( !g_bIsFirstSearch ) {
      g_bMapMovedOffCenter = true;
   }
   DoAjaxAreaSearch();
}

function SetMapLocation(strName, fLat, fLon)
{
   var pPlace = document.getElementById("placename");
   if( pPlace && strName ) {
      pPlace.value = unescape( strName );
   }
   if( g_pLocationRefineContainer ) {
      g_pLocationRefineContainer.style.visibility = 'hidden';
      g_pLocationRefineContainer.innerHTML = '';
   }      

   g_pMainSearchMap.Clear();
   g_pMainSearchMap.SetCenter( new VELatLong( fLat, fLon ) );
   g_pMainSearchMap.SetZoomLevel(12);
   g_pMainSearchMap.SetCenter( new VELatLong( fLat, fLon ) );
}

function HandleMultipleLocationMatches( results )
{
   if( results.numberFound > 1 ) {
      try {
         //Are there results that really are different?

         if( !g_pLocationRefineContainer ) {
            //Create a control if there is not one already
            var pMapContainerDiv = document.getElementById(g_strMainMapObjId);
            var iMapWidth = parseInt(pMapContainerDiv.offsetWidth);
            var iMapHeight = parseInt(pMapContainerDiv.offsetHeight);
            var iChildWidth = parseInt(iMapWidth - (iMapWidth * 0.2));   //Leave a 20% margin
            var iChildHeight = parseInt(iMapHeight - (iMapHeight * 0.15)); //Leave a 15% margin
            var iChildLeft = parseInt((iMapWidth-iChildWidth) / 2.0);
            var iChildTop = parseInt((iMapHeight-iChildHeight) / 2.0);
   
            g_pLocationRefineContainer = document.createElement('div');
            g_pLocationRefineContainer.id = 'locrefine_' + g_strMainMapObjId;
            g_pLocationRefineContainer.style.top = iChildTop + 'px';
            g_pLocationRefineContainer.style.left = iChildLeft + 'px';
            //g_pLocationRefineContainer.style.width = iChildWidth + 'px';
            g_pLocationRefineContainer.style.width = '580px';
            //g_pLocationRefineContainer.style.height = iChildHeight + 'px';
            g_pLocationRefineContainer.style.height = '360px';
            g_pLocationRefineContainer.style.background = '#F0F0E4';
            g_pLocationRefineContainer.style.border = '1px solid #F0F0E4';
            g_pLocationRefineContainer.innerHTML = '';
            g_pMainSearchMap.AddControl(g_pLocationRefineContainer, null);
         }

         var strLocationOptions = '<ul>';
         var iShowResults = 0;
         var strSetCmd = '';
         for( var i=0; i < results.numberFound; i++ ) {
            if( iShowResults < 18 ) {
               if( results.results[i].entity.name.indexOf("United States") >= 0 ) {
                  iShowResults++;
                  strSetCmd = 'SetMapLocation(\''+escape(results.results[i].entity.name)+'\', '+results.results[i].latlong.Latitude+', '+results.results[i].latlong.Longitude+');';
                  strLocationOptions += '<li><a href="Javascript:' + strSetCmd + '">' +
                                        results.results[i].entity.name +
                                        '</a>';
               }
            }
         }
         strLocationOptions += '</ul>';
         g_pLocationRefineContainer.innerHTML = '<div class="calloutblack" style="width:580px;height:380px;margin-right: 20px;color:white;">' +
                                     '   <div class="label"><div class="tl"></div><div class="tr"></div><b>More than one location matched your search, please select one<b> ' +
                                     '   </div>' +
                                     '   <div class="body" style="color:white">' +
                                     '      <div style="height:90px;padding-left:16px;margin-right:5px;">' +
                                     '         <div style="float:right"><a href="#" onClick=\"g_pLocationRefineContainer.style.visibility = \'hidden\';\"><img src="/images/close.gif" width=20 height=20></a></div>' +
                                     '         '+ strLocationOptions + 
                                     '      </div>' +
                                     '   </div>' +
                                     '   <div class="bl"></div><div class="bm"></div><div class="br"></div>' +
                                     '</div>';
         if( iShowResults > 1 ) g_pLocationRefineContainer.style.visibility = 'visible';
         else g_pLocationRefineContainer.style.visibility = 'hidden';

         if( iShowResults == 1 ) {
            //Only 1 result in USA, warp there...
            eval( strSetCmd );
         }
         return (iShowResults > 0 );
      } catch ( e ) {
         //Fall through to first location
      }
   }

   return false;
}


//function FindLocationCallback( results )
function FindLocationCallback(layer, aResults, pPlaces, bHasMore, veErrorMessage)
{   
   g_strOnErrorMsg = '';

   if( pPlaces == null || pPlaces.length < 1 ) {
         g_strOnErrorMsg = g_strFindMsgTxt;
         g_strOnErrorMsg = 'Could not understand address format. Please try using the "city name, state" format, or a zip code -- make sure to use commas to separate your city and state.';
         //g_FindService.ParseAddress( pPlace.value, null, "ParseAddressCallback" );
         alert( g_strOnErrorMsg );
         RfgHideWaitDialog(g_strMainMapObjId);
         g_strOnErrorMsg = '';
         return;
   }

   if( pPlaces.length > 1 ) {
      RfgHideWaitDialog(g_strMainMapObjId);
      if( HandleMultipleLocationMatches( pPlaces ) ) {
         return;
      }
   }

   var result = pPlaces[0];
   g_pMainSearchMap.Clear();
   g_pMainSearchMap.SetZoomLevel(13);   
   g_pMainSearchMap.SetCenter( result.LatLong  );
   RfgHideWaitDialog(g_strMainMapObjId);
}

function GoDirectlyTo(strWhere)
{
   var strWaitDlgDefaultHtml = '<div class="calloutblack" style="width:300px;height:110px;margin-right: 20px;color:white;">' +
                               '   <div class="label"><div class="tl"></div><div class="tr"></div><b>Please Wait...</b>      ' +
                               '   </div>' +
                               '   <div class="body" style="color:white">' +
                               '      <div style="height:90px;padding-left:16px;margin-right:5px;">' +
                               '         <div style="float:right"><a href="#" onClick="RfgHideWaitDialog(\''+g_strMainMapObjId+'\');"><img src="/images/close.gif" width=20 height=20></a></div>' +
                               '         Locating '+strWhere+'' +
                               '         <br><br>' +
                               '         <img src="/images/loading.gif">' +
                               '      </div>' +
                               '   </div>' +
                               '   <div class="bl"></div><div class="bm"></div><div class="br"></div>' +
                               '</div>';

   g_strOnErrorMsg = '';
   if( !g_pMainSearchMap ) {
      alert(g_strLoadingTxt);
      return false;
   }
   var pPlace = document.getElementById("areawhere_1");
   if( !pPlace ) {
      alert('I\'m sorry, we could not initialize the map search.  Please try pressing "refresh" on your browser.');
      return false;
   }
   pPlace.value = strWhere;

   if( pPlace && pPlace.value != '' ) {
      RfgShowWaitDialog(g_strMainMapObjId, true, "Locating place", strWaitDlgDefaultHtml);
      g_strOnErrorMsg = g_strFindMsgTxt;
      //g_FindService.Find( pPlace.value, "FindLocationCallback" );
      RfgFindLocation( g_strMainMapObjId, pPlace.value, false, false, FindLocationCallback );
   } else {
      alert('Please enter a city & state, zip code or major landmark to start your search.');
   }
   return false;
}

function ZoomIn()
{
   if( g_pMainSearchMap ) {
      var iCurrentZoom = g_pMainSearchMap.GetZoomLevel();
      if( iCurrentZoom < g_iMaxZoomLevel) {
         g_pMainSearchMap.SetZoomLevel(iCurrentZoom+1);
      } else {
         alert( 'You can not zoom-in any further' );
      }
   } else {
      alert(g_strLoadingTxt);
   }
}

function ZoomOut()
{
   if( g_pMainSearchMap ) {
      var iCurrentZoom = g_pMainSearchMap.GetZoomLevel();
      if( iCurrentZoom > g_iMinZoomLevel ) {
         g_pMainSearchMap.SetZoomLevel(iCurrentZoom-1);
      } else {
         alert( 'You can not zoom-out any further' );
      }
   } else {
      alert(g_strLoadingTxt);
   }
}

function ShowSelectedNeighborhoods()
{
   var strPackedArea1 = GetCookie('ar1');
   var strPackedArea2 = GetCookie('ar2');
   var oSavedArea1 = new Object();
   var oSavedArea2 = new Object();
   if( strPackedArea1 && strPackedArea1 != ''  ) {
      var aFields = strPackedArea1.split('|');
      if( aFields && aFields[0].length > 0 ) {
         oSavedArea1.strGeoType = aFields[0];
         oSavedArea1.iObId = aFields[1];
      }
   }
   if( strPackedArea2 && strPackedArea2 != ''  ) {
      var aFields = strPackedArea2.split('|');
      if( aFields && aFields[0].length > 0 ) {
         oSavedArea2.strGeoType = aFields[0];
         oSavedArea2.iObId = aFields[1];
      }
   }

   if( oSavedArea1.strGeoType && oSavedArea1.iObId && oSavedArea2.strGeoType && oSavedArea2.iObId ) {
      document.location.href = '/area/compare.jsp?type1='+escape(oSavedArea1.strGeoType)+'&id1='+oSavedArea1.iObId+'&type2='+escape(oSavedArea2.strGeoType)+'&id2='+oSavedArea2.iObId;
   } else if( oSavedArea1.strGeoType && oSavedArea1.iObId ) {
      document.location.href = '/area/index.jsp?type='+escape(oSavedArea1.strGeoType)+'&id='+oSavedArea1.iObId;
   } else if( oSavedArea2.strGeoType && oSavedArea2.iObId ) {
      document.location.href = '/area/index.jsp?type='+escape(oSavedArea2.strGeoType)+'&id='+oSavedArea2.iObId;
   } else {
      alert("Please select at least one area first");
   }
}

function checkSelectedAreas(strCheckmarkId)
{
   var aChildren = document.getElementById(strCheckmarkId);
   if( aChildren ) {
      if( aChildren.length && aChildren.length > 1 ) {
         for( var i=0; i < aChildren.length; i++) {
            aChildren[i].checked = true;
         }               
      } else {
         aChildren.checked = true;
      }
   }
}

function updateAreaSelectionBeacon()
{
   var strPackedArea1 = GetCookie('ar1');
   var strPackedArea2 = GetCookie('ar2');

   g_iNumAreasSelected = 0;
   //Uncheck them all..
   var aChildren = document.getElementsByName('acb');
   if( aChildren && aChildren.length > 0 ) {
      for( var i=0; i < aChildren.length; i++ ) {
         aChildren[i].checked = false;
      }
   }

   if( strPackedArea1 && strPackedArea1.length > 0  ) {
      var aFields = strPackedArea1.split('|');
      if( aFields && aFields[0].length > 0 ) {
         SetInnerHtml('areasearchSave1Name', aFields[2]);
         SetInnerHtml('areasearchSave1Price', aFields[3]);
         SetInnerHtml('areasearchSave1Income', aFields[4]);
         SetInnerHtml('areasearchSave1Age', aFields[5]);
         SetInnerHtml('areasearchSave1Kids', aFields[6]);
         SetInnerHtml('areasearchSave1Remove', '<a href="javascript:removeFromList(\''+aFields[0]+'\', \''+aFields[1]+'\');" style="text-decoration:underline;">remove from list</a>');

         //Now check selected..
         checkSelectedAreas('areacheck_'+aFields[0]+aFields[1]+'a');
         checkSelectedAreas('areacheck_'+aFields[0]+aFields[1]+'b');

         g_iNumAreasSelected++;
      }
   } else {
      SetInnerHtml('areasearchSave1Name', '<span style="color:#444444">- none -</span>');
      SetInnerHtml('areasearchSave1Price', '');
      SetInnerHtml('areasearchSave1Income', '');
      SetInnerHtml('areasearchSave1Age', '');
      SetInnerHtml('areasearchSave1Kids', '');
      SetInnerHtml('areasearchSave1Remove', '');
   }
   if( strPackedArea2 && strPackedArea2 != ''  ) {
      var aFields = strPackedArea2.split('|');
      if( aFields && aFields[0].length > 0 ) {
         SetInnerHtml('areasearchSave2Name', aFields[2]);
         SetInnerHtml('areasearchSave2Price', aFields[3]);
         SetInnerHtml('areasearchSave2Income', aFields[4]);
         SetInnerHtml('areasearchSave2Age', aFields[5]);
         SetInnerHtml('areasearchSave2Kids', aFields[6]);
         SetInnerHtml('areasearchSave2Remove', '<a href="javascript:removeFromList(\''+aFields[0]+'\', \''+aFields[1]+'\');" style="text-decoration:underline;">remove from list</a>');

         //Now check selected..
         checkSelectedAreas('areacheck_'+aFields[0]+aFields[1]+'a');
         checkSelectedAreas('areacheck_'+aFields[0]+aFields[1]+'b');

         g_iNumAreasSelected++;
      }
   } else {
      SetInnerHtml('areasearchSave2Name', '<span style="color:#444444">- none -</span>');
      SetInnerHtml('areasearchSave2Price', '');
      SetInnerHtml('areasearchSave2Income', '');
      SetInnerHtml('areasearchSave2Age', '');
      SetInnerHtml('areasearchSave2Kids', '');
      SetInnerHtml('areasearchSave2Remove', '');
   }

}

//
// Removes saved areas, repacking the list to the top if needed.
//
function removeFromList(strGeoType, iObId)
{
   var strPackedArea1 = GetCookie('ar1');
   var strPackedArea2 = GetCookie('ar2');   
   if( strPackedArea1 && strPackedArea1 != ''  ) {
      var aFields = strPackedArea1.split('|');
      if( aFields[0] == strGeoType && aFields[1] == iObId ) {
         if( strPackedArea2 ) {
            SetCookie('ar1',strPackedArea2,null,'/',null,null);
         } else {
            SetCookie('ar1','',null,'/',null,null);
         }
         SetCookie('ar2','',null,'/',null,null);
      }
   }
   if( strPackedArea2 && strPackedArea2 != ''  ) {
      var aFields = strPackedArea2.split('|');
      if( aFields[0] == strGeoType && aFields[1] == iObId ) {
         SetCookie('ar2','',null,'/',null,null);
      }
   }
   updateAreaSelectionBeacon();
}


function changeAreaSelection(pCheckbox, strGeoType, iObId, strName, strMedianPrice, strMedianIncome, strMedianAge, strPctWithKids)
{
   var bChecked = pCheckbox.checked;
   if( bChecked ) {
      //Add this property to list
      if( g_iNumAreasSelected >= 2 ) {
         alert("Please remove an area before attempting to add another.  You may compare up to 2 neighborhoods at once.");
         pCheckbox.checked = false;
         return;
      }
      
      var strCookieValue = strGeoType + "|" + iObId + "|" + (strName.replace(/\|/g,"")) + "|" + strMedianPrice + "|" + strMedianIncome + "|" + strMedianAge + "|" +strPctWithKids;      
      SetCookie('ar'+(g_iNumAreasSelected+1),strCookieValue,null,'/',null,null);
   } else {
      removeFromList(strGeoType, iObId);
   }
   updateAreaSelectionBeacon();
}

function recenterAreaMapToNSEW( fNorth, fSouth, fEast, fWest, iZoom )
{
   //This function accepts the exact n/s/e/w bounding box we want, but VE will size it
   //wider than that, so we need to actually size to center, and re-zoom.
   /*
   var aVeLatLongPoints = new Array();
   aVeLatLongPoints.push( new VELatLong((fNorth+0.2 ), (fWest-0.2)) );   
   aVeLatLongPoints.push( new VELatLong((fSouth-0.2), (fEast+0.2)) );   
   RfgResizeMapToPoints('resultmap', aVeLatLongPoints);
   */

   var fLat = (fNorth + fSouth) / 2;
   var fLon = (fWest + fEast) / 2;

   //Rfg Map Appliance loses command some times... let's force this one through...
   g_pMainSearchMap.SetCenter( new VELatLong( fLat, fLon) );
   g_pMainSearchMap.SetZoomLevel( iZoom );
   g_pMainSearchMap.SetCenter( new VELatLong( fLat, fLon) );
   g_pMainSearchMap.SetZoomLevel( iZoom );
   g_pMainSearchMap.SetCenter( new VELatLong( fLat, fLon) );
   

   RfgQueueCommand(escape("RfgAddPushPin('resultmap', "+ (fNorth) +", "+ (fWest) +", '1', 'empty string', '/images/area/1.gif')"));
   RfgQueueCommand(escape("RfgAddPushPin('resultmap', "+ (fSouth) +", "+ (fEast) +", '2', 'empty string', '/images/area/2.gif')"));  
}

function InitializeAreaSearch()
{
   /*if( navigator && navigator.vendor ){
     var strVendor = new String(navigator.vendor);
     if( strVendor.indexOf('Apple') == 0 ) {
        document.location.href = '/error/limitedbrowser.jsp';
        return;
     }
   }*/
   //RfgQueueCommand(escape("document.getElementById('maplegallinks').innerHTML = document.getElementById('page_legallinks').innerHTML;"));
   //RfgQueueCommand(escape("document.getElementById('page_legallinks').innerHTML = '';"));
   RfgQueueCommand(escape("updateAreaSelectionBeacon();"));

   RfgCreateMap('resultmap', 'RoadVE', false, 38.6437, -98.8235, 4, false, false );
   RfgShowMapDashboard('resultmap', false);
   g_pMainSearchMap = RfgGetMapById('resultmap');
   RfgAttachMapEvent( 'resultmap', Events.ONCHANGEVIEW, OnMapChangeView );

   var fNorth = parseFloat( document.getElementById('areanorth').value );
   var fSouth = parseFloat( document.getElementById('areasouth').value );
   var fEast = parseFloat( document.getElementById('areaeast').value );
   var fWest = parseFloat( document.getElementById('areawest').value );
   var iZoom = parseInt( document.getElementById('areazoom').value );
   var strThisWhere = trim(document.getElementById('areawhere_1').value);

   var strIsOp = document.getElementById('areaop').value;
   
   if( strIsOp == 'Y' ) {
      //Recenter map to area
      RfgQueueCommand(escape("GoDirectlyTo(document.getElementById('areawhere_1').value);"));
   } else if( Math.abs(fNorth) > 0 && Math.abs(fSouth) > 0 && Math.abs(fEast) > 0 && Math.abs(fWest) > 0 ) {
      //Recenter map to viewport
      RfgQueueCommand(escape("recenterAreaMapToNSEW("+fNorth+", "+fSouth+", "+fEast+", "+fWest+", "+iZoom+");"));
      g_bMapMovedOffCenter = true;
   } else {
      //Recenter map to area
      RfgQueueCommand(escape("GoDirectlyTo(document.getElementById('areawhere_1').value);"));
   }

   RfgShowDetailOnMouseOver( false );
   RfgAddVEPushpinOnMouseOver( ShowSearchResultMapMouseOver );

   g_objMapPreview.popupname = 'areamapviewpreview';   

   RfgQueueCommand(escape("g_bIsInInitialization = false;"));
   RfgQueueCommand(escape("DoAjaxAreaSearch(0);"));

   //http://c21.smoore.cyberitas.com/search/area.jsp?svf=lsn&rw=85205&north=34.31394984163214&south=32.54912838093525&east=-109.99786376953126&west=-113.43933105468751&zoom=8&op=y&where=90210&x=11&y=4&minprice=&maxprice=&eduatm=&age=&income=&edulevel=&wkids=&density=
}



