// setup dropdown variables for convenience
var prefix = "ctl00_cphMain_";
var ddPropertyType = prefix + "ddPropertyType";
var ddMinPrice = prefix + "ddMinPrice";
var ddMaxPrice = prefix + "ddMaxPrice";
var ddBeds = prefix + "ddBeds";
var ddBaths = prefix + "ddBaths";
var ddUnits = prefix + "ddUnits";
var ddCounty = prefix + "ddCounty";
var ddCity = prefix + "ddCity";
var MoreOptionsDiv = prefix + "MoreOptions";
var txtZip = prefix + "txtZip";
var txtStreet = prefix + "txtStreet";
var txtSubdivision = prefix + "txtSubdivision";
var txtCondominium = prefix + "txtCondominium";
var txtMLS = prefix + "txtMLS";
var ddSchoolDistrict = prefix + "ddSchoolDistrict";
var ddResultsPerPage = prefix + "ddResultsPerPage";
var priceVal = ["25000","50000","100000","150000","200000","250000","300000","400000","500000","1000000"];
var priceTxt = ["$25,000","$50,000","$100,000","$150,000","$200,000","$250,000","$300,000","$400,000","$500,000","$1,000,000"];
var hidNWLat = prefix + "hidNWLat";
var hidNWLng = prefix + "hidNWLng";
var hidSELat = prefix + "hidSELat";
var hidSELng = prefix + "hidSELng";
var map = null;
var q = 1;
var lastID;
var lastQuery = 0;
var pageIndex = 0;
var totalPages = 0;
var resultsPerPage = 10;
var maxResults = 250;
var SortOrder = "Price";
var SortDir = "asc";
var SortImg = "arrowup";
var options = "less";
var view = "map";

var lastSearch = 0;
var newSearch = 0;

// map bounds
var nwLat = 0, nwLng = 0, seLat = 0, seLng  = 0;
// set search parameters to default
var _zip = "", _street = "", _subdiv = "", _condo = "", _category = 1, _priceMin = 0, _priceMax = 999999999, _beds = 0, _baths = 0, _county = 0, _city = 0, _school = "", _units = 0;
var _firstName = "", _lastName = "", _email = "", _listingStatus = "2", _listingCompany = "", _description = "", _mls = "";
// page dimensions
var PageHeight = 0;
var PageWidth = 0;

// call load function
if( typeof window.onload != 'function')
{
  window.onload = Load;
}
else
{
  window.onload = function(){ Load(); };
}

//set page event handlers
if (window.attachEvent) {
	window.attachEvent("onunload", Page_Unload);	
} else {
	window.addEventListener("unload", Page_Unload, false);
}


//Clean up all objects
function Page_Unload() {
    if (map!=null) {
        map.Dispose();
        map = null;
    }
}

SetOnResize();
document.onkeypress = keyPress;

function UpdatePageDimensions()
{
    PageHeight = document.documentElement.clientHeight;
    PageWidth = document.documentElement.clientWidth;
}
//
// load function
//
function Load()
{
    LoadMap();
    LoadMapHandlers();
    onCategoryChange();
    ResizeMap();
    SetupLoadingMessage();
    SetOptions();
    PageMode();
    EliteProp.MapService.LoggedIn(CheckLoggedIn);
    setTimeout("btnSearch_Click();",350);
}
// set up for loading message
function SetupLoadingMessage()
{
    var _loading = document.getElementById("loading");
    var _error = document.getElementById("error");
    var _map = document.getElementById("map");
    var topOffset = 359;
    var leftOffset = 179 + ((PageWidth - 179)/2)-100;
    _loading.style.top = topOffset + "px";
    _error.style.top = topOffset + "px";
    _loading.style.left = leftOffset + "px";
    _error.style.left = leftOffset - 25 + "px";
}
//
// Load Map
//
function LoadMap()
{   
    try
    {
        var defaultLocation = new VELatLong(43.05584433592095,-88.08013916015625);
        var defaultZoom = 9;
        var defaultStyle = 'r';
        
        if( ReadCookie("mapCenter") != null )
        {
          var latlon = ReadCookie("mapCenter");
          var lat = latlon.substring(0,latlon.indexOf(","));
          var lon = latlon.substring(latlon.indexOf(", ")+2);
          defaultLocation = new VELatLong(lat,lon);
        }
        if( ReadCookie("mapZoom") != null )
        {
          defaultZoom = ReadCookie("mapZoom")/1;
        }
        
        map = new VEMap('map');
        map.LoadMap(defaultLocation,defaultZoom,defaultStyle,false,VEMapMode.Mode2D,false);
    }
    catch(err)
    { 
        //alert(err.message);
    }
}

function LoadMapHandlers()
{
    map.AttachEvent("onchangeview",UpdateSearchResults);
}

//
// resize map object
//
function ResizeMap()
{
    var oldHeight = PageHeight;
    var oldWidth = PageWidth;
    SetupLoadingMessage();
    UpdatePageDimensions();
    if( !(oldHeight == PageHeight && oldWidth == PageWidth) )
    {
        // get full height / width
        var mapheight = 380;
        // left panel = 177px
        var mapwidth = document.documentElement.clientWidth - 177 - 14;

        // minimum width: 640px
        if (mapwidth < 640) {
            mapwidth = 640;
        }

        if( view == "map" && map )
        {
            map.Resize(mapwidth, mapheight);
        }
        else
        {
            document.getElementById("map").style.height = mapheight;
            document.getElementById("map").style.width = mapwidth;
        }
    }
}

// update results
function UpdateSearchResults() {
    var oldNWLat = nwLat, oldNWLng = nwLng, oldSELat = seLat, oldSELng = seLng;
    UpdateMapBounds();
    
    if( oldNWLat != nwLat || oldNWLng != nwLng || oldSELat != seLat || oldSELng != seLng )
    {
        // show loading message
        ShowLoadingMessage("Updating...");
        EliteProp.MapService.HybridSearch(_category, _priceMin, _priceMax, _beds, _baths, _mls, _county, _city, _zip, _street, _subdiv, _school, _condo, _units, seLat, seLng, nwLat, nwLng, view, _firstName, _lastName, _email, _listingStatus, _listingCompany, _description, '', TryHybridUpdate);
        SetMapCookies(7);
    }
}


function HybridSearch(results)
{
    map.Clear();
    if( results.CountResults.Count <= maxResults )
    {
        PlotPoints(results.MapItems);
        // display property count
        ShowResultsMessage(results.CountResults);
        //ListWisconsin.MapService.search(_category, _priceMin, _priceMax, _beds, _baths, _mls, _county, _city, _zip, _street, _subdiv, _school, _condo, _units, seLat, seLng, nwLat, nwLng, view, _firstName, _lastName, _email, _listingStatus, "ListPrice asc", onSearchComplete, null, newSearch, null);
        
        if( results.CountResults.Count == 1 && _mls != "" )
        {
            // make sure MLS Cookie is cleared
            ClearCookie("mls");
            // only one results, redirect to property details page
            // 2 second delay needed to avoid postback error popup
            setTimeout("RedirectToDetails(" + results.MapItems[0].Id + ")", 2000);
        }
    }
    else
    {
        TooManyResults(results.CountResults);
    }
}

function RedirectToDetails(listingID)
{
    window.location = "PropertyDetails.aspx?id=" + listingID; 
}

function TryHybridUpdate(results)
{
    if( results.CountResults.Count <= maxResults )
    {
        map.Clear();
    
        PlotPoints(results.MapItems);
        // display property count
        ShowResultsMessage(results.CountResults);
    }
    else
    {
        TooManyResults(results.CountResults);
    }
}

//
// display loading message
//
function ShowLoadingMessage(message)
{
    document.getElementById("error").style.display = "none";
    document.getElementById("Message").style.display = "none";
    document.getElementById("loading").style.display = "block";
    document.getElementById("loadingMessage").innerHTML = message;
}

//
// display results message
//
function ShowResultsMessage(count)
{
    document.getElementById("loading").style.display = "none";

    document.getElementById("Message").style.display = "block";
    if( count.Count == 0 && count.TotalCount == 0 )
    {
        document.getElementById("Message").innerHTML = "No Properties Found";
    }
    else
    {
        if (count.Count != count.TotalCount)
        {
            if (count.Count > maxResults)
            {
                document.getElementById("Message").innerHTML = count.Count + " Properties Found";
            }
            else
            {
                document.getElementById("Message").innerHTML = count.Count + " of " + count.TotalCount + " Properties Shown";
            }
        }
        else
        {
            if( count.Count == 1)
            {
                document.getElementById("Message").innerHTML = count.Count + " Property Shown";
            }
            else if (count.Count > maxResults)
            {
                document.getElementById("Message").innerHTML = count.Count + " Properties Found";
            }
            else
            {
                document.getElementById("Message").innerHTML = count.Count + " Properties Shown";
            }
        }
    }
}
var lastlocation = "";
//
// perform search
//
function btnSearch_Click()
{
    NewResults = true;
    pageIndex = 0;
    document.getElementById("error").style.display = "none";
    ShowLoadingMessage("Loading...");
    document.getElementById("Message").style.display = "none";
    
    // get search parameters
    _category = document.getElementById(ddPropertyType).options[document.getElementById(ddPropertyType).selectedIndex].value;
    _priceMin = document.getElementById(ddMinPrice).options[document.getElementById(ddMinPrice).selectedIndex].value;
    _priceMax = document.getElementById(ddMaxPrice).options[document.getElementById(ddMaxPrice).selectedIndex].value;
    _beds = document.getElementById(ddBeds).options[document.getElementById(ddBeds).selectedIndex].value;
    _baths = document.getElementById(ddBaths).options[document.getElementById(ddBaths).selectedIndex].value;
    _county = document.getElementById(ddCounty).options[document.getElementById(ddCounty).selectedIndex].value;
    _city = document.getElementById(ddCity).options[document.getElementById(ddCity).selectedIndex].value;
    _units = document.getElementById(ddUnits).options[document.getElementById(ddUnits).selectedIndex].value;
    _mls = document.getElementById(txtMLS).value;
    if( options == "more" )
    {
        _zip = document.getElementById(txtZip).value;
        _street = document.getElementById(txtStreet).value;
        _subdiv = document.getElementById(txtSubdivision).value;
        _school = document.getElementById(ddSchoolDistrict).options[document.getElementById(ddSchoolDistrict).selectedIndex].value;
        _condo = document.getElementById(txtCondominium).value;
        if( document.getElementById("ctl00_cphMain_divAdmin") )
        {
            _firstName = document.getElementById("ctl00_cphMain_txtFirstName").value;
            _lastName = document.getElementById("ctl00_cphMain_txtLastName").value;
            _email = document.getElementById("ctl00_cphMain_txtEmail").value;
            _listingStatus = document.getElementById("ctl00_cphMain_ddListingStatus").value;
            _listingCompany = document.getElementById("ctl00_cphMain_ddlListingCompany").value;
            _description = document.getElementById("ctl00_cphMain_txtDescription").value;
        }
    }
    else
    {
        _zip = "";
        _street = "";
        _subdiv = "";
        _school = "";
        _condo = "";
        _firstName = "";
        _lastName = "";
        _email = "";
        _listingStatus = "2";
        _listingCompany = "";
        _description = "";
    }
    
    var location = "";
    
    if( _city != "" )
    {
        location = _city + ", WI";
    }
    else if ( _county != "" )
    {
        location = _county + " County, WI";
    }
    else if( _zip != "" )
    {
        location = _zip;
    }
    
    if( location != "" && location != lastlocation )
    {
        map.Find(null,location,null,null,null,null,null,null,false);
    }
    
    lastlocation = location;
    
    UpdateMapBounds();
    // get full results count
    EliteProp.MapService.HybridSearch(_category, _priceMin, _priceMax, _beds, _baths, _mls, _county, _city, _zip, _street, _subdiv, _school, _condo, _units, seLat, seLng, nwLat, nwLng, view, _firstName, _lastName, _email, _listingStatus, _listingCompany, _description, '', HybridSearch);
    // set cookies
    SetCookies();    
}

//
// Set sesion values for search parameters & map/list view
//
function SetCookies()
{
    // have cookies expire in 7 days
    var exp = 7;
    
    // only set cookies if values aren't default
    if( view != "map" )
      SetCookie("view", view, exp);
    else
      ClearCookie("view");
    
    if( resultsPerPage != 10 )
      SetCookie("resultsPerPage", resultsPerPage, exp);
    else
      ClearCookie("resultsPerPage");
    
    if( _category != 1 )
      SetCookie("category", _category, exp);
    else
      ClearCookie("category");    
    
    if( _priceMin != 0 || _priceMax != 999999999 )
      SetCookie("price", _priceMin + "," + _priceMax, exp);
    else
      ClearCookie("price");
    
    if( _beds != 0 )
      SetCookie("beds", _beds, exp);
    else
      ClearCookie("beds");
    
    if( _baths != 0 )
      SetCookie("baths", _baths, exp);
    else
      ClearCookie("baths");
      
    if( _county != "" )
      SetCookie("county", _county, exp);
    else
      ClearCookie("county");
      
    if( _city != "" )
      SetCookie("city", _city, exp);
    else
      ClearCookie("city");
    
    if( _zip != "" )
      SetCookie("zip", _zip, exp);
    else
      ClearCookie("zip");
    
    if( _street != "" )
      SetCookie("street", _street, exp);
    else
      ClearCookie("street");

    if( _subdiv != "" )
      SetCookie("subdiv", _subdiv, exp);
    else
      ClearCookie("subdiv");

    if( _school != "")
      SetCookie("school", _school, exp);
    else
      ClearCookie("school");

    if( _category == 6 && _condo != "")
      SetCookie("condo", _condo, exp);
    else
      ClearCookie("condo");

    if( _category == 6 || _category == 4 )
      SetCookie("units", _units, exp);
    else
      ClearCookie("units");

    if( SortOrder != "Price" || SortDir != "asc" )
      SetCookie("sort", SortOrder + "," + SortDir, exp);
    else
      ClearCookie("sort");
    
    // clear MLS cookie so user isn't stuck in a loopo
    ClearCookie("mls");
    
    SetMapCookies(exp);    
    
    if( document.getElementById("ctl00_cphMain_divAdmin") )
    {
        if( (_firstName != "") || ( _lastName != "" ) || ( _email != "") )
          SetCookie("user", _firstName + "," + _lastName + "," + _email,exp);
        else
          ClearCookie("user");
          
        if( _listingStatus != "2" )
          SetCookie("listingstatus", _listingStatus, exp);
        else
          ClearCookie("listingstatus");
          
        if( _listingCompany != "" )
          SetCookie("listingcompany", _listingCompany, exp);
        else
          ClearCookie("listingcompany");
          
        if( _description != "" )
            SetCookie("description", _description, exp);
        else    
            ClearCookie("description");
    }
    else
    {
        ClearCookie("user");
        ClearCookie("listingstatus");
        ClearCookie("listingcompany");
        ClearCookie("description");
    }
    
    if( options != "less" )
    {
        SetCookie("options", options, exp);
    }
    else
    {
        ClearCookie("options");
    }
}

function SetMapCookies(exp)
{
    if( view == "map" )
    {
      SetCookie("seCoords", seLat + "," + seLng, exp);
      SetCookie("nwCoords", nwLat + "," + nwLng, exp);
      SetCookie("mapCenter", map.GetCenter(), exp);
      SetCookie("mapZoom", map.GetZoomLevel(), exp);
    }
    else
    {
      ClearCookie("seCoords");
      ClearCookie("nwCoords");
      ClearCookie("mapCenter");
      ClearCookie("mapZoom");
    }
}

// Set cookie
function SetCookie(name, value, expOffset)
{
    var cookieExp = new Date();
    cookieExp.setDate(cookieExp.getDate()+expOffset);
    
    document.cookie = name + "=" + value + "; expires=" + cookieExp + "path=/";
}
// Clear cookie
function ClearCookie(name)
{
    var cookieExp = new Date();
    cookieExp.setDate(cookieExp.getDate()-1);
    document.cookie = name + "=; expires=" + cookieExp + "path=/";
}
// read the specified cookie
function ReadCookie(name)
{
    var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') 
		    c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) 
		    return c.substring(nameEQ.length,c.length);
	}
	return null;
}

// 
// Update the map bounds variables
//
function UpdateMapBounds()
{
    var nw;
    var se;
    var mapWidth = document.getElementById("map").clientWidth;
    var mapHeight = document.getElementById("map").clientHeight;
	
    var p1 = new VEPixel(0,0);
    var p2 = new VEPixel(0,0);

    if(map.vemapcontrol.GetMapStyle() == VEMapStyle.Birdseye)
    {
	    var scene = map.vemapcontrol.GetObliqueScene();
	    var zoom = map.vemapcontrol.GetZoomLevel();
	    if(zoom == 1)
	    {
		    p1.x = 20;
		    p1.y = 100;
		    p2.x = (scene.GetWidth()/2)-20;
		    p2.y = (scene.GetHeight()/2)-100;
	    }
	    else
	    {
		    p1.x = 40;
		    p1.y = 200;
		    p2.x = scene.GetWidth()-40;
		    p2.y = scene.GetHeight()-200;
	    }

	    nw = scene.PixelToLatLong(p1,zoom);
	    se = scene.PixelToLatLong(p2,zoom);
    }
    else
    {
	    p2.x = mapWidth;
	    p2.y = mapHeight;
	    nw = map.vemapcontrol.PixelToLatLong(p1,map.vemapcontrol.GetZoomLevel());
	    se = map.vemapcontrol.PixelToLatLong(p2,map.vemapcontrol.GetZoomLevel());
    }
    
    if( nw.latitude > se.latitude )
    {
        nwLat = nw.latitude;
        seLat = se.latitude;
    }
    else
    {
        nwLat = se.latitude;
        seLat = nw.latitude;
    }
    
    if( nw.longitude > se.longitude )
    {
        nwLng = se.longitude;
        seLng = nw.longitude;
    }
    else
    {
        nwLng = nw.longitude;
        seLng = se.longitude;
    }
    
    $get(hidNWLat).value = nwLat;
    $get(hidNWLng).value = nwLng;
    $get(hidSELat).value = seLat;
    $get(hidSELng).value = seLng;
    
    $get(prefix + 'btnHidSearch').click();
}

//
// update dropdowns when category changes
//
function onCategoryChange()
{
    var selected = document.getElementById(ddPropertyType).selectedIndex;
    var value = document.getElementById(ddPropertyType).options[selected].value;
    
    if( value != "1" && value != "2" && value != "3")
    {
        // hide subdivision & school district
        document.getElementById("Subdivision").style.display = "none";
        document.getElementById(txtSubdivision).value = "";
        document.getElementById("SchoolDistrict").style.display = "none";
        document.getElementById(ddSchoolDistrict).selectedIndex = 0;
    }
    else
    {
        // show subdivision & school district
        document.getElementById("Subdivision").style.display = "block";
        document.getElementById("SchoolDistrict").style.display = "block";
    }

    if( value == "6" )
    {
        // show condominium name
        document.getElementById("CondominiumName").style.display = "block";
    }
    else
    {
        // hide condominium name
        document.getElementById("CondominiumName").style.display = "none";
        document.getElementById(txtCondominium).value = "";
    }
    
    if( value == "4" || value == "6" )
    {
        // show units
        document.getElementById("Units").style.display = "block";
    }
    else
    {
        document.getElementById("Units").style.display = "none";
        document.getElementById(ddUnits).selectedIndex = 0;
    }
    
    if( value == "3" || value == "5" || value == "7" || value =="4" )
    {
        // hide bed & bath
        document.getElementById("Bedrooms").style.display = "none";
        document.getElementById(ddBeds).selectedIndex = 0;
        document.getElementById("Bathrooms").style.display = "none";
        document.getElementById(ddBaths).selectedIndex = 0;
    }
    else
    {
        document.getElementById("Bedrooms").style.display = "block";
        document.getElementById("Bathrooms").style.display = "block";
    }
}

// function to capture mouse clicks
function onMouseClick(mapEvent)
{
    document.location.href = "PropertyDetails.aspx?id=" + currentID;
}

// plot search results on map
function PlotPoints(results)
{
    document.getElementById("error").style.display = "none";
    // set appropriate icon
    var icon = setIcon();

    for ( var pinID = 0; pinID < results.length; pinID++ )
    {
        var pin = new VEPushpin(
            results[pinID].Id,
            new VELatLong(results[pinID].Latitude,results[pinID].Longitude),
            icon,
            null,
            "Loading...");
        try
        {
          map.AddPushpin(pin);
          document.getElementById(results[pinID].Id+"_"+map.GUID).onmousedown = null;
          document.getElementById(results[pinID].Id).href="PropertyDetails.aspx?id=" + results[pinID].Id;
          document.getElementById(results[pinID].Id).onclick = null;
        }
        catch(err)
        {
            //alert(err.message);
        }
    }
}

// set map icon to appropriate image
function setIcon()
{
    var icon = 'Images/house';
    
    // if birdseye view, use large image
    if( map.GetMapStyle() != VEMapStyle.Birdseye )
    {
        // check zoom level, set appropriate icon size
        if( map.GetZoomLevel() < 12 && map.GetZoomLevel() >= 6 )
        {
            icon += '_sm';
        }
        else if( map.GetZoomLevel() < 6 )
        {
            icon += '_xs';
        }
    }
    
    icon += '.gif';
    
    return icon;
}

// show more search options
function MoreOptions()
{
    document.getElementById("Divider").innerHTML = "<a href=\"javascript://\" onclick=\"LessOptions();\">&lt;&lt; Less Options</a>";
    document.getElementById(MoreOptionsDiv).style.display = "block";
    options = "more";
}

// hide advanced search options
function LessOptions()
{
    document.getElementById("Divider").innerHTML = "<a href=\"javascript://\" onclick=\"MoreOptions();\">More Options &gt;&gt;</a>";
    document.getElementById(MoreOptionsDiv).style.display = "none";
    options = "less";
}

// open map help window
function MapHelp() 
{
    window.open('Map_Help.htm','Help','width=420,height=600,resizable=yes,scrollbars=yes');
}

// OVERRIDDEN DISPOSE FUNCTION
VEPushpin.prototype.Dispose=function()
{
    this.DetailsStyle=null;
    this.TitleStyle=null;
    this.IconStyle=null;
    this.Details=null;
    this.Iconurl=null;
    this.Title=null;
    this.LatLong=null;
    this.ID=null;
    this.m_vemapcontrol=null;
    this.m_vemap=null
    this._SetMapInstance = null;
    this.GetContent = null;
}

var currentID = null;

// OVERRIDDEN HIDE FUNCTION
VEPushpin.Hide=function(a)
{
  map.DetachEvent("onclick",onMouseClick);
  currentID = null;
  var popupHolder = document.getElementById("PopupHolder");
  popupHolder.style.display = "none";
}

// OVERRIDDEN SHOW FUNCTION
// l = mapID, m = popupID, k = lat, h = long, d = title, c = details, g = title style, f = details style
VEPushpin.Show=function(l,m,k,h,d,c,g,f)
{
    map.AttachEvent("onclick",onMouseClick);
    currentID = m;
    var center = map.GetCenter();
    // determine what quadrant point is in
    // 1: top/left; 2: top/right; 3: bottom/left; 4: bottom/right;
    if( k > center.Latitude && h <= center.Longitude)
      q = 1;
    else if( k > center.Latitude && h > center.Longitude)
      q = 2
    else if( k <= center.Latitude && h <= center.Longitude )
      q = 3;
    else if( k <= center.Latitude && h > center.Longitude)
      q = 4;
      
    var popup = document.getElementById("Popup");
    var popupHolder = document.getElementById("PopupHolder");
    var beak = document.getElementById("Beak");
    var beak_top_left = document.getElementById("beak_top_left");
    var beak_bot_left = document.getElementById("beak_bot_left");
    var beak_top_right = document.getElementById("beak_top_right");
    var beak_bot_right = document.getElementById("beak_bot_right");
    var position = new VELatLong(k,h);
    var pixelPos = map.LatLongToPixel(position);
    
    // special case if in bird's eye mode
    if( map.GetMapStyle() == VEMapStyle.Birdseye )
    {
        // adjust popup if it isn't on map
        var maxX = document.getElementById("map").clientWidth + 8;
        if( pixelPos.y < 7 )
        {
            pixelPos.y = 7;
        }
        else if( pixelPos.y > 390 )
        {
            pixelPos.y = 390;
        }
        if( pixelPos.x < 2 )
        {
            pixelPos.x = 2;
        }
        if( pixelPos.x > maxX )
        {
            pixelPos.x = maxX;
        }
        
        // set q for bird's eye
        var center = map.LatLongToPixel(map.GetCenter());
        if( pixelPos.y <= center.y && pixelPos.x <= center.x )
          q = 1;
        else if( pixelPos.y <= center.y && pixelPos.x > center.x )
          q = 2;
        else if( pixelPos.y > center.y && pixelPos.x <= center.x )
          q = 3;
        else if( pixelPos.y > center.y && pixelPos.x > center.x )
          q = 4;
    }
   
    if (lastID != m)
    {
        lastQuery = lastQuery + 1;
        var args = new Array(3);
        args[0] = pixelPos.x;
        args[1] = pixelPos.y;
        args[2] = lastQuery;
        popup.innerHTML = "<table cellpadding='0' cellspacing='0'><tr><td><img src='Images/loading.gif' style='margin-top:12px' /></td><td valign='middle'><b>LOADING...&nbsp;</b></td></tr></table>";
        EliteProp.MapService.GetHtmlBody(m, onBodyComplete, null, args, null);
        lastID = m;
    }
    //popup.innerHTML = unescape(c);
    popupHolder.style.display = "block";
    var zoom = map.GetZoomLevel();
    switch(q)
    {
        case 1: // top left
        {
            if( zoom < 12 && zoom >= 6 )
            {
                popupHolder.style.top = pixelPos.y + 155 + 60 + "px";
                popupHolder.style.left = pixelPos.x + 177 + 5 + "px";
            }
            else if( zoom < 6 )
            {
                popupHolder.style.top = pixelPos.y + 155 + 55 + "px";
                popupHolder.style.left = pixelPos.x + 177 + "px";
            }
            else
            {
                popupHolder.style.top = pixelPos.y + 155 + 65 + "px";
                popupHolder.style.left = pixelPos.x + 177 + 17 + "px";
            }
            HideBeaks();
            beak_top_left.style.display = "block";
            break;
        }
        case 2: // top right
        {
            if( zoom < 12 && zoom >= 6 )
            {
                popupHolder.style.top = pixelPos.y + 155 + 60 + "px";
                popupHolder.style.left = pixelPos.x + 177 - 5 - popupHolder.clientWidth + "px";
            }
            else if( zoom < 6 )
            {
                popupHolder.style.top = pixelPos.y + 155 + 55 + "px";
                popupHolder.style.left = pixelPos.x + 177 - 5 - popupHolder.clientWidth + "px";
            }
            else
            {
                popupHolder.style.top = pixelPos.y + 155 + 65 + "px";
                popupHolder.style.left = pixelPos.x + 177 - 5 - popupHolder.clientWidth + "px";
            }
            HideBeaks();
            beak_top_right.style.display = "block";
            break;
        }
        case 3: // bottom left
        {
            if( zoom < 12 && zoom >= 6 )
            {
                popupHolder.style.top = pixelPos.y + 155 + 12 -  popupHolder.clientHeight + "px";
                popupHolder.style.left = pixelPos.x + 177 + 5 + "px";
            }
            else if (zoom < 6 )
            {
                popupHolder.style.top = pixelPos.y + 155 + 12 - popupHolder.clientHeight + "px";
                popupHolder.style.left = pixelPos.x + 177 + "px";
            }
            else
            {
                popupHolder.style.top = pixelPos.y + 155 + 12 -  popupHolder.clientHeight + "px";
                popupHolder.style.left = pixelPos.x + 177 + 17 + "px";
            }
            HideBeaks();
            beak_bot_left.style.display = "block";
            break;
        }
        case 4: // bottom right
        {
            if( zoom < 12 && zoom >= 6 )
            {
                popupHolder.style.top = pixelPos.y + 155 + 12 - popupHolder.clientHeight + "px";
                popupHolder.style.left = pixelPos.x + 177 - 5 - popupHolder.clientWidth + "px";
            }
            else if( zoom < 6 )
            {
                popupHolder.style.top = pixelPos.y + 155 + 12 - popupHolder.clientHeight + "px";
                popupHolder.style.left = pixelPos.x + 177 - 5 - popupHolder.clientWidth + "px";
            }
            else
            {
                popupHolder.style.top = pixelPos.y + 155 + 12 - popupHolder.clientHeight + "px";
                popupHolder.style.left = pixelPos.x + 177 - 5 - popupHolder.clientWidth + "px";
            }
            HideBeaks();
            beak_bot_right.style.display = "block";
            break;
        }
    }
};

function onBodyComplete(body, args, caller)
{
    var currentQuery= args[2];
    
    if (lastQuery == currentQuery)
    {
        $get("Popup").innerHTML = unescape(body);
    }
}
// Hide all popup beaks
function HideBeaks()
{
    document.getElementById("beak_top_left").style.display = "none";
    document.getElementById("beak_bot_left").style.display = "none";
    document.getElementById("beak_top_right").style.display = "none";
    document.getElementById("beak_bot_right").style.display = "none";
}

// change to listview
function ShowList()
{
    if( view != "list" )
    {
        view = "list";
        SetCookie("view", view, 7);
    }

    document.location.href="PropertySearchDetails.aspx";
} 

//
// get requested query string variable
//
function Query(variable)
{
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  } 
  return false
}

// capture key press
function keyPress(e)
{
    var key = e ? e.which : window.event.keyCode;
          
    if( key == 13)
    {
      btnSearch_Click();
      return false;
    }
    else
    {
        return true;
    }
}

// reads view cookie and sets search mode
function SetView()
{
    if( ReadCookie("view") != null )
    {
        view = ReadCookie("view");
    }
    else
    {
        view = "map";
    }
    // load last view mode
    if( view == "list" )
    {
        ShowList();
    }
}

// set options to more or less
function SetOptions()
{
    // load options
    if( ReadCookie("options") != null )
    {
        options = ReadCookie("options");
        if( options == "more" )
        {
            MoreOptions();
        }
        if( options == "less" )
        {
            LessOptions();
        }
    }  
}
// load page in correct mode
function PageMode()
{
    // load page in correct mode
    if( Query("mode") )
    {
        var mode = Query("mode");
        if( mode == "advanced" )
        {
            MoreOptions();
        }
        else if( mode == "advancedsearch")
        {
            MoreOptions();
            btnSearch_Click();
        }
        else if( mode == "search")
        {
            btnSearch_Click();
        }
    }
}
// set onresize
function SetOnResize()
{
    // set onresize function
    if( typeof window.onresize != 'function')
    {
        window.onresize = ResizeMap;
    }
    else
    {
        window.onresize = function(){ ResizeMap(); };
    }
}

function onMinPriceChange()
{
    var selected = document.getElementById(ddMinPrice).selectedIndex;
    var value = document.getElementById(ddMinPrice).options[selected].value;
    var maxSelected = document.getElementById(ddMaxPrice).selectedIndex;
    var maxValue = document.getElementById(ddMaxPrice).options[maxSelected].value;
    
    // clear current options
    for( var i=document.getElementById(ddMaxPrice).options.length; i > 0; i--)
    {
        document.getElementById(ddMaxPrice).options[i] = null;
    }
    for( var c=0; c < priceVal.length; c++)
    {
        if( priceVal[c]/1 >= value )
        {
            document.getElementById(ddMaxPrice).options[document.getElementById(ddMaxPrice).options.length] = new Option(priceTxt[c],priceVal[c]);
        }
    }
    
    if( value/1 <= maxValue/1 )
    {
        var found = false;
        for( var d=0; d < document.getElementById(ddMaxPrice).options.length && !found; d++ )
        {
            if( document.getElementById(ddMaxPrice).options[d].value == maxValue )
            {
                found = true;
                maxSelected = d;
            }
        }
        
        document.getElementById(ddMaxPrice).selectedIndex = maxSelected;
    }   
}

function onMaxPriceChange()
{
    var selected = document.getElementById(ddMaxPrice).selectedIndex;
    var value = document.getElementById(ddMaxPrice).options[selected].value;
    var minSelected = document.getElementById(ddMinPrice).selectedIndex;
    var minValue = document.getElementById(ddMinPrice).options[minSelected].value;
    
    // clear current options
    for( var i=document.getElementById(ddMinPrice).options.length; i > 0; i--)
    {
        document.getElementById(ddMinPrice).options[i] = null;
    }
    for( var c=0; c < priceVal.length; c++)
    {
        if( priceVal[c]/1 <= value )
        {
            document.getElementById(ddMinPrice).options[document.getElementById(ddMinPrice).options.length] = new Option(priceTxt[c],priceVal[c]);
        }
    }
    
    if( value/1 >= minValue/1 )
    {
        var found = false;
        for( var d=0; d < document.getElementById(ddMinPrice).options.length && !found; d++ )
        {
            if( document.getElementById(ddMinPrice).options[d].value == minValue )
            {
                found = true;
                minSelected = d;
            }
        }
        
        document.getElementById(ddMinPrice).selectedIndex = minSelected;
    }   
}

function TooManyResults(count)
{
    fullResults = new Array();
    if( map && view == "map" )
    {
        map.Clear();
    }
    //purge(document.getElementById("resultsDiv"));
    if( document.getElementById("resultsDiv"))
    {
        document.getElementById("resultsDiv").innerHTML = "";
    }
    //purge(document.getElementById("Pages"));
    if( document.getElementById("Pages"))
    {
        document.getElementById("Pages").innerHTML = "";
    }
    document.getElementById("error").style.display = "block";
    ShowResultsMessage(count);
}

function SaveSearch()
{
    var searchName = document.getElementById("ctl00_cphMain_txtSearchName").value;
    // check if user has a saved search with searchName already
    EliteProp.MapService.CheckSearchName(searchName,onNameCheckComplete);
}

function onNameCheckComplete(nameExists)
{
    var searchName = document.getElementById("ctl00_cphMain_txtSearchName").value;
    
    if( nameExists )
    {
        if(confirm("A saved search called '" + searchName + "' already exists. Would you like to replace it with this search?"))
        {
            DoSearchSave();
        }
    }
    else
    {
        // save search
        DoSearchSave();
    }
}

function DoSearchSave()
{
    // update search values
    var searchName = document.getElementById("ctl00_cphMain_txtSearchName").value;
    var autoElite = document.getElementById("ctl00_cphMain_chkElite").checked;
    var autoLW = document.getElementById("ctl00_cphMain_chkListWisconsin").checked;
    _category = document.getElementById(ddPropertyType).options[document.getElementById(ddPropertyType).selectedIndex].value;
    _priceMin = document.getElementById(ddMinPrice).options[document.getElementById(ddMinPrice).selectedIndex].value;
    _priceMax = document.getElementById(ddMaxPrice).options[document.getElementById(ddMaxPrice).selectedIndex].value;
    _beds = document.getElementById(ddBeds).options[document.getElementById(ddBeds).selectedIndex].value;
    _baths = document.getElementById(ddBaths).options[document.getElementById(ddBaths).selectedIndex].value;
    _county = document.getElementById(ddCounty).options[document.getElementById(ddCounty).selectedIndex].value;
    _city = document.getElementById(ddCity).options[document.getElementById(ddCity).selectedIndex].value;
    _zip = document.getElementById(txtZip).value;
    _street = document.getElementById(txtStreet).value;
    _subdiv = document.getElementById(txtSubdivision).value;
    _school = document.getElementById(ddSchoolDistrict).options[document.getElementById(ddSchoolDistrict).selectedIndex].value;
    _condo = document.getElementById(txtCondominium).value;
    _units = document.getElementById(ddUnits).options[document.getElementById(ddUnits).selectedIndex].value;
    _mls = document.getElementById(txtMLS).value;
    if( document.getElementById("ctl00_cphMain_divAdmin") )
    {
        _firstName = document.getElementById("ctl00_cphMain_txtFirstName").value;
        _lastName = document.getElementById("ctl00_cphMain_txtLastName").value;
        _email = document.getElementById("ctl00_cphMain_txtEmail").value;
        _listingStatus = document.getElementById("ctl00_cphMain_ddListingStatus").options[document.getElementById("ctl00_cphMain_ddListingStatus").selectedIndex].value;
        _listingCompany = document.getElementById("ctl00_cphMain_ddlListingCompany").options[document.getElementById("ctl00_cphMain_ddlListingCompany").selectedIndex].value;
        _description = document.getElementById("ctl00_cphMain_txtDescription").value;
    }
    else
    {
        _firstName = "";
        _lastName = "";
        _email = "";
        _listingStatus = "2";
        _listingCompany = "";
        _description = "";
    }
    // save search
    EliteProp.MapService.SaveSearch(_street, autoElite, autoLW, _baths, _beds, _city, _condo, _county, _category, _priceMax, _priceMin, _school, searchName, _subdiv, _units, _zip, _firstName, _lastName, _email, _listingStatus, _listingCompany, _description, SavedSearchResult);
}

function SavedSearchResult(success)
{
    if( !success )
    {
        document.location.href = "Login.aspx?ReturnUrl=%2fPropertySearch.aspx"
    }
}

function lnkSaveSearch_Click()
{
    var txtSearchName = document.getElementById("ctl00_cphMain_txtSearchName");
    var defaultName = document.getElementById(ddPropertyType).options[document.getElementById(ddPropertyType).selectedIndex].text;
    if( document.getElementById(txtZip).value != "" )
    {
        defaultName += " " + document.getElementById(txtZip).value;
    }
    else if( document.getElementById(ddCity).options[document.getElementById(ddCity).selectedIndex].value != "" )
    {
        defaultName += " " + document.getElementById(ddCity).options[document.getElementById(ddCity).selectedIndex].value;
    }
    else if( document.getElementById(ddCounty).options[document.getElementById(ddCounty).selectedIndex].value != "" )
    {
        defaultName += " " + document.getElementById(ddCounty).options[document.getElementById(ddCounty).selectedIndex].value + "County";
    }
    
    txtSearchName.value = defaultName;
}

function CheckLoggedIn(loggedIn)
{
    if( !loggedIn )
    {
        document.getElementById("tblSaveSearchError").style.display = "inline";
        document.getElementById("tblSaveSearch").style.display = "none";
        document.getElementById("ctl00_cphMain_btnSave").style.display = "none";
    }
    else
    {
        document.getElementById("tblSaveSearchError").style.display = "none";
        document.getElementById("tblSaveSearch").style.display = "inline";
        document.getElementById("ctl00_cphMain_btnSave").style.display = "inline";
    }
}

// 05/27/2010 - Automatically zoom in if too many properties are shown
function AutoZoom() {
    if (map.GetZoomLevel() < 14) {
        map.SetZoomLevel(14);
    }
    else {
        map.ZoomIn();
    }
}