var g_pMainSearchMap = null;
var g_strMainMapObjId = null;
var g_pZoomSlider = null;
var g_strOnErrorMsg = '';
var g_strFindMsgTxt = 'Could not find address/location. Please try entering a "city, state" or zip code.';
var g_pLocationRefineContainer = null;
var g_bContinuous = false;

SetCookie("WTSC","PSM", "", "/", false);

function ValidateMapSearch(pForm)
{
   //Map searches must have at least a lat/lon selected
   if ( ( pForm.Lat[0].value == '' || pForm.Lat[0].value == '0' ) ||
        ( pForm.Lon[1].value == '' || pForm.Lon[1].value == '0' ) ) {
      alert( "You must first select an area to search by moving the map to view your area." );
      return false;
   }
   return true;
}

function SetMapCntrlImgState(strNameRoot, bState)
{
   var strGraphic = '/eraimages/mapsearch/' + strNameRoot;
   var pImg = document.images[strNameRoot];
   if( bState ) {
      strGraphic += '_on.jpg';
   } else {
      strGraphic += '.jpg';
   }
   if( pImg ) {
      pImg.src = strGraphic;
   }
}

function ResetMap()
{
   g_strOnErrorMsg = 'Could not reset map, please try again.';
   if( g_pMainSearchMap ) {
      g_pMainSearchMap.Clear();
      g_pMainSearchMap.SetZoomLevel(3);
      g_pMainSearchMap.SetCenter( new LatLong( 38.643700, -98.823502 ) );
   }
}

function SetRssStatusMessage( strMessage, bBlink )
{
   if( document.getElementById ) {
      var pRssStatus = document.getElementById("RssStatus");
      if( pRssStatus ) {
         if( strMessage == '' ) pRssStatus.style.backgroundColor='#F0F0E4';
         else pRssStatus.style.backgroundColor='#e4a4a7';
         pRssStatus.innerHTML = strMessage;
      }
   }
   if( bBlink ) {
      setTimeout( function(){ pRssStatus.style.backgroundColor='#ff0000';}, 500 );
      setTimeout( function(){ pRssStatus.style.backgroundColor='#FFF903';}, 750 );
      setTimeout( function(){ pRssStatus.style.backgroundColor='#E4A4A7';}, 1000 );      
   }
}

function NotifyRssComplete( eObj )
{
   RfgHideWaitDialog(g_strMainMapObjId);
   if( eObj.length == 0 ) {
      SetRssStatusMessage('<b>No results found, try expanding your search</b>', true);
   } else {
      var iListing = 0;
      var iOffice = 0;
      var xThisPin = null;
      for(var i=0; i < eObj.length; i++ ) {
         var strIcon = eObj[i].GetCustomIcon();
         if( strIcon == '/images/pushpins/office.gif' ) {
            iOffice++;
         } else {
            iListing++;
         }
      }
      if( iListing == 0 ) SetRssStatusMessage('<b>No results found, try expanding your search</b>', true);
      else SetRssStatusMessage('<b>' + iListing + '<b> listings found, click the Search button to view them all</b>', true);
   }
}

function NotifyRssLoading()
{
   RfgShowWaitDialog(g_strMainMapObjId, true, "Loading properties...");
   SetRssStatusMessage('Loading properties...', false);
}

function NotifyRssNotReady()
{
   if( g_pMainSearchMap && g_pMainSearchMap.GetZoomLevel() > 3 ) {
      SetRssStatusMessage('You can zoom in further to view properties on the map by using the Map Controls to the right of the screen, or use your center mouse button to click and draw a rectangle to zoom in on a specific area. You can also click "Search" to search this entire region.', false);
   } else {
      SetRssStatusMessage('You can zoom in to view properties on the map by using the Map Controls to the right of the screen, or use your center mouse button to click and draw a rectangle to zoom in on a specific area. Once you have zoomed to your desired area, click the "Search" button.', false);
   }         
}

function UpdateRssFeed()
{
   g_strOnErrorMsg = '';

   if( !g_pMainSearchMap ) return;
   var mapView = RfgGetCurrentMapView(g_strMainMapObjId);
   var fTopLeftLat = mapView.TopLeftLatLong.Latitude;
   var fTopLeftLong = mapView.TopLeftLatLong.Longitude;
   var fBottomRightLat = mapView.BottomRightLatLong.Latitude;
   var fBottomRightLong = mapView.BottomRightLatLong.Longitude;
   var pForm = document.mapsearchform;
   pForm.Lat[0].value = fTopLeftLat;
   pForm.Lon[0].value = fTopLeftLong;
   pForm.Lat[1].value = fBottomRightLat;
   pForm.Lon[1].value = fBottomRightLong;

   SynchronizeZoomSlider();

   if( g_pMainSearchMap.GetZoomLevel() > 12 ) {
      //Zoomed in enough to get properties!            
      var strParms = 'Lat=' + fTopLeftLat;
      strParms += '&Lon=' + fTopLeftLong;
      strParms += '&Lat=' + fBottomRightLat;
      strParms += '&Lon=' + fBottomRightLong;
      var strUrl = 'http://' + window.location.hostname  + '/erabin/searchPropertyGeoRss?' + strParms
      g_pMainSearchMap.Clear();
      NotifyRssLoading();
      g_strOnErrorMsg = 'Could not load local properties, please try again.';
      //g_pMainSearchMap.ShowLocations( [ strUrl ], "NotifyRssComplete" );
      RfgAddGeoRssFeed( g_strMainMapObjId, strUrl, NotifyRssComplete );
      SetCookie("lastsearch",strParms,null,'/',null,null);
   } else {
      g_pMainSearchMap.Clear();
      NotifyRssNotReady();
   }
}

function StartPanMap( strDirection )
{
   g_strOnErrorMsg = 'Could not navigate map, please check your direction and try again.';
   switch( strDirection )
   {   
      case 'north':      
          g_pMainSearchMap.StartContinuousPan(0, -20);
			 g_bContinuous = true;
         break;
      case 'south':
          g_pMainSearchMap.StartContinuousPan(0, 20);
          g_bContinuous = true;
         break;
      case 'east':
          g_pMainSearchMap.StartContinuousPan(20, 0);
          g_bContinuous = true;
         break;
      case 'west':
         g_pMainSearchMap.StartContinuousPan(-20, 0);
         g_bContinuous = true;
         break;
   }
}

function StopPanMap()
{
	 if( g_bContinuous ){
        g_pMainSearchMap.EndContinuousPan();
		  g_bContinuous = false;
    }
}

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.SetZoomLevel(13);
   g_pMainSearchMap.SetCenter( new VELatLong( fLat, fLon ) );
}

function FindLocationCallback(layer, aResults, pPlaces, bHasMore, veErrorMessage)
{   
   RfgHideWaitDialog(g_strMainMapObjId);
   g_strOnErrorMsg = '';

   if( pPlaces == null || pPlaces.length < 1 ) {
      alert( g_strFindMsgTxt );
      return;
   }
//alert( pPlaces.length );
//Name
//LatLong
//MatchConfidence
//MatchCode
//Locations

   if( pPlaces.length > 1 ) { 
      if( HandleMultipleLocationMatches( pPlaces ) ) {
         return;
      }
   }
   var result = pPlaces[0];
   g_pMainSearchMap.Clear();
   g_pMainSearchMap.SetZoomLevel(13);
   g_pMainSearchMap.SetCenter( result.LatLong  );

/*
   if( results != null && results.numberFound > 1 ) {
      RfgHideWaitDialog(g_strMainMapObjId);
      if( HandleMultipleLocationMatches( results ) ) {
         return;
      }
   }

   if( results != null && results.numberFound > 0){
      RfgHideWaitDialog(g_strMainMapObjId);
      var result = results.results[0];
      g_pMainSearchMap.Clear();
      g_pMainSearchMap.SetZoomLevel(13);
      g_pMainSearchMap.SetCenter( result.latlong  );
   } else {
      var pPlace = document.getElementById("placename");
      if( pPlace && pPlace.value != '' ) {
         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" );
      } else {
      }
   }
*/
}

function ResetMapToPlace()
{
   g_strOnErrorMsg = '';
   if( !g_pMainSearchMap ) {
      alert('Please wait for the map to finish loading before searching for a place.');
      return false;
   }
   var pPlace = document.getElementById("placename");
   if( pPlace && pPlace.value != '' ) {
      RfgShowWaitDialog(g_strMainMapObjId, true, "Locating place");
      g_strOnErrorMsg = g_strFindMsgTxt;
      //RfgFindLocation( g_strMainMapObjId, pPlace.value, false, false, 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 SynchronizeZoomSlider()
{
   if( g_pMainSearchMap ) {
      if( g_pZoomSlider ) {
         g_pZoomSlider.SetValue(g_pMainSearchMap.GetZoomLevel());
      }
   }
}

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;
}

function HandleMultipleLocationMatches( results )
{
   if( results.length > 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.height = iChildHeight + 'px';
            g_pLocationRefineContainer.style.background = '#F0F0E4';
            g_pLocationRefineContainer.style.border = '1px solid #989890';
            g_pLocationRefineContainer.innerHTML = '';
            g_pMainSearchMap.AddControl(g_pLocationRefineContainer, null);
         }

         var strLocationOptions = '<ul>';
         var iShowResults = 0;
         var strSetCmd = '';
         for( var i=0; i < results.length; i++ ) {
            if( iShowResults < 18 ) {
               iShowResults++;
               strSetCmd = 'SetMapLocation(\''+escape(results[i].Name)+'\', '+results[i].LatLong.Latitude+', '+results[i].LatLong.Longitude+');';
               strLocationOptions += '<li><a href="Javascript:' + strSetCmd + '">' +
                                     results[i].Name +
                                     '</a>';
            }
         }
         strLocationOptions += '</ul>';
         g_pLocationRefineContainer.innerHTML = "<table cellpadding=2 cellspacing=0 width=\"100%\" height=\"100%\">" +
                                                "<tr><td align=center style=\"background-color: #B8B898; height: 19px;color:#ffffff;\">" +
                                                "<img src=\""+g_strRfgClientSupportUrl+"/close.gif\" alt=\"X\" border=0 align=right onClick=\"g_pLocationRefineContainer.style.visibility = 'hidden';\">" +
                                                "<b>More than one location matched your search, please select one<b></td></tr>" + 
                                                "<tr><td bgcolor=white><br>" + strLocationOptions + "</td></tr>" + 
                                                "</table>";
         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;
}

