var prefix = "ctl00_cphMain_";
ddPropertyType = prefix + "ddPropertyType";
ddBeds = prefix + "ddBeds";
ddBaths = prefix + "ddBaths";
ddCounty = prefix + "ddCounty";
ddCity = prefix + "ddCity";
ddMinPrice = prefix + "ddMinPrice";
ddMaxPrice = prefix + "ddMaxPrice";
var q = 1;
var ddSchoolDistrict = prefix + "ddSchoolDistrict";
var ddResultsPerPage = prefix + "ddResultsPerPage";
var hidNWLat = prefix + "hidNWLat";
var hidNWLng = prefix + "hidNWLng";
var hidSELat = prefix + "hidSELat";
var hidSELng = prefix + "hidSELng";
var txtZip = prefix + "txtZip";
//var txtStreet = prefix + "txtStreet";
//var txtSubdivision = prefix + "txtSubdivision";
//var txtCondominium = prefix + "txtCondominium";
//var ddUnits = prefix + "ddUnits";
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 map = null;
var pageIndex = 0;
var totalPages = 0;
var totalCount = 0;
var lastQuery = 0;
var maxResults = 250;
var resultsPerPage = 10;
//var searched = false;
var SortOrder = "Price";
var SortDir = "asc";
var SortImg = "arrowup";
var NewResults = false;
var mapID;
var view = "map";
var lastID;
var currentID = null;
// map bounds
var nwLat = 0, nwLng = 0, seLat = 0, seLng  = 0;
// set search parameters to default
var _zip = "", _street = "", _subdiv = "", _condo = "", _category = 0, _priceMin = 0, _priceMax = 999999999, _beds = 0, _baths = 0, _county = 0, _city = 0, _school = "", _units = 0;
var _firstName = "", _lastName = "", _email = "", _listingStatus = "2";

if( document.getElementById("ctl00_siteMap") )
{
    document.getElementById("ctl00_siteMap").style.display = "none";
}

//ListWisconsin.MapService.set_defaultFailedCallback(ShowErrorMessage);

document.onkeypress = keyPress;

// 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;
    }
}

function Load()
{
    SetView();
    onTypeChange();
    SetSortOrder();
    ListWisconsin.MapService.LoggedIn(CheckLoggedIn);
}

function onMouseClick(mapEvent)
{
    document.location.href = "PropertyDetails.aspx?id=" + currentID;
}

//
// 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);
    }
    if( map )
    {
        map.AttachEvent("onchangeview",UpdateSearchResults);
        /*
        map.AttachEvent("onendzoom",CheckZoom);
        map.AttachEvent("onresize",UpdateSearchResults);
        map.AttachEvent("onendcontinuouspan",UpdateSearchResults);
        map.AttachEvent("onobliquechange", UpdateSearchResults);
        */
    }
}
var lastlocation = "";
function btnSearch_Click()
{
    //searched = true;
    NewResults = true;
    pageIndex = 0;
    ShowLoadingMessage("Loading...");
/*
    if( view == "map" && map )
    {
        map.Clear();
        // set map bounds
        UpdateMapBounds();
    }
    */
    // 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;
    _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;
    
    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;
    }
    
    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
    //ListWisconsin.MapService.count(_category, _priceMin, _priceMax, _beds, _baths, _county, _city, _zip, _street, _subdiv, _school, _condo, _units, seLat, seLng, nwLat, nwLng, view, _firstName, _lastName, _email, _listingStatus, TrySearch);
    ListWisconsin.MapService.HybridSearch(_category, _priceMin, _priceMax, _beds, _baths, _county, _city, _zip, _street, _subdiv, _school, _condo, _units, seLat, seLng, nwLat, nwLng, view, _firstName, _lastName, _email, _listingStatus, '', HybridSearch);
    // set cookies
    SetCookies();
}


function HybridSearch(results)
{
    if( results.CountResults.Count < maxResults )
    {
        map.Clear();
    
        PlotPoints(results.MapItems);
        // display property count
        ShowResultsMessage(results.CountResults);
        //ListWisconsin.MapService.search(_category, _priceMin, _priceMax, _beds, _baths, _county, _city, _zip, _street, _subdiv, _school, _condo, _units, seLat, seLng, nwLat, nwLng, view, _firstName, _lastName, _email, _listingStatus, "ListPrice asc", onSearchComplete, null, newSearch, null);
    }
    else
    {
        TooManyResults(results.CountResults);
    }
}



function TryHybridUpdate(results)
{
    if( results.CountResults.Count < maxResults )
    {
        map.Clear();
    
        PlotPoints(results.MapItems);
        // display property count
        ShowResultsMessage(results.CountResults);
    }
    else
    {
        TooManyResults(results.CountResults);
    }
}

function btnReset_Click()
{ 
    document.getElementById(ddPropertyType).selectedIndex = 0;
    document.getElementById(ddBeds).selectedIndex = 0;
    document.getElementById(ddBaths).selectedIndex = 0;
    document.getElementById(ddMinPrice).selectedIndex = 0;
    document.getElementById(ddMaxPrice).selectedIndex = 0;
    document.getElementById(ddCounty).selectedIndex = 0;
    document.getElementById(ddCity).selectedIndex = 0;
    document.getElementById(txtZip).value = "";
    document.getElementById(ddSchoolDistrict).selectedIndex = 0;
    if( document.getElementById("ctl00_cphMain_divAdmin") )
    {
        document.getElementById("ctl00_cphMain_txtFirstName").value = "";
        document.getElementById("ctl00_cphMain_txtLastName").value = "";
        document.getElementById("ctl00_cphMain_txtEmail").value = "";
        document.getElementById("ctl00_cphMain_ddListingStatus").selectedIndex = 0;
    }
    onCountyChange();
    onTypeChange();
}

function onTypeChange()
{
    var selected = document.getElementById(ddPropertyType).selectedIndex;
    var type = document.getElementById(ddPropertyType).options[selected].value;
    
    switch( type )
    {
        case "1":
            SingleFamily();
            break;
        case "2":
            TwoFamily();
            break;
        case "3":
            VacantLand();
            break;
        case "4":
            MultiFamily();
            break;
        case "5":
            BusinessOpportunity();
            break;
        case "6":
            Condominium();
            break;
        case "7":
            CommercialIndustrial();
            break;
        default:
            AllTypes();
            break;
    }
}

function onCountyChange()
{
    var selected = document.getElementById(ddCounty).selectedIndex;
    var cty = document.getElementById(ddCounty).options[selected].value;
    
    ListWisconsin.MapService.UpdateCities(cty,updateCities);
    ListWisconsin.MapService.UpdateSchoolDistricts(cty,updateSchoolDistricts);
}

function updateCities(newCities)
{
    var selectedCity = document.getElementById(ddCity).options[document.getElementById(ddCity).selectedIndex].value;
    var selectedIndex = 0;
    
    // clear current options
    for( var i=document.getElementById(ddCity).options.length; i > 0; i--)
    {
        document.getElementById(ddCity).options[i] = null;
    }
    for( var c=0; c < newCities.length; c++)
    {
        document.getElementById(ddCity).options[c+1] = new Option(newCities[c],newCities[c]);
        if( newCities[c] == selectedCity )
        {
            selectedIndex = c+1;
        }
    }
    
    document.getElementById(ddCity).selectedIndex = selectedIndex;
}

function updateSchoolDistricts(newSchools)
{
    // clear current options
    for( var i=document.getElementById(ddSchoolDistrict).options.length; i > 0; i--)
    {
        document.getElementById(ddSchoolDistrict).options[i] = null;
    }
    for( var c=0; c < newSchools.length; c++)
    {
        document.getElementById(ddSchoolDistrict).options[c+1] = new Option(newSchools[c].SchoolDistrictName,newSchools[c].SchoolDistrictName);
    }
}

function AllTypes()
{
    EnableField("SchoolDistrict");
    EnableField("Beds");
    EnableField("Baths");
}

function SingleFamily() 
{
    //HideField("divCondominium");
    //ShowField("divSubdivision");
    //EnableField("Subdivision");
    EnableField("SchoolDistrict");
    //DisableField("Units");
    EnableField("Beds");
    EnableField("Baths");
}
function TwoFamily() 
{
    //HideField("divCondominium");
    //ShowField("divSubdivision");
    //EnableField("Subdivision");
    EnableField("SchoolDistrict");
    //DisableField("Units");
    EnableField("Beds");
    EnableField("Baths");
}
function VacantLand()
{
    //HideField("divCondominium");
    //ShowField("divSubdivision");
    //EnableField("Subdivision");
    EnableField("SchoolDistrict");
    //DisableField("Units");
    DisableField("Beds");
    DisableField("Baths");
}
function MultiFamily() 
{
    //HideField("divCondominium");
    //ShowField("divSubdivision");
    //EnableField("Subdivision");
    EnableField("SchoolDistrict");
    //EnableField("Units");
    DisableField("Beds");
    DisableField("Baths");
}
function BusinessOpportunity()
{
    //HideField("divCondominium");
    //ShowField("divSubdivision");
    //DisableField("Subdivision");
    //DisableField("Units");
    DisableField("SchoolDistrict");
    DisableField("Beds");
    DisableField("Baths");
}
function Condominium() 
{
    //HideField("divSubdivision");
    //ShowField("divCondominium");
    //EnableField("Units");
    DisableField("SchoolDistrict");
    EnableField("Beds");
    EnableField("Baths");
}
function CommercialIndustrial() 
{
    //HideField("divCondominium");
    //ShowField("divSubdivision");
    //DisableField("Subdivision");
    //DisableField("Units");
    DisableField("SchoolDistrict");
    DisableField("Beds");
    DisableField("Baths");
}

function HideField(field)
{
    document.getElementById(field).style.display = "none";
}

function ShowField(field)
{
    document.getElementById(field).style.display = "inline";
}

function DisableField(field)
{
    var holder = "div" + field;
    switch( field )
    {
        case "Beds":
            field = ddBeds;
            document.getElementById(ddBeds).selectedIndex = 0;
            break;
        case "Baths":
            field = ddBaths;
            document.getElementById(ddBaths).selectedIndex = 0;
            break;
        /*case "Subdivision":
            field = txtSubdivision;
            document.getElementById(txtSubdivision).value = "";
            break;
        case "Condominium":
            field = txtCondominium;
            document.getElementById(txtCondominium).value = "";
            break;
            */
        case "SchoolDistrict":
            field = ddSchoolDistrict;
            document.getElementById(ddSchoolDistrict).selectedIndex = 0;
            break;
            /*
        case "Units":
            field = ddUnits;
            document.getElementById(ddUnits).selectedIndex = 0;
            break;
            */
        default:
            break;
    }
    
    document.getElementById(field).disabled = true;
    document.getElementById(holder).disabled = true;
}

function EnableField(field)
{
    var holder = "div" + field;
    switch( field )
    {
        case "Beds":
            field = ddBeds;
            break;
        case "Baths":
            field = ddBaths;
            break;
            /*
        case "Subdivision":
            field = txtSubdivision;
            break;
        case "Condominium":
            field = txtCondominium;
            break;
            */
        case "SchoolDistrict":
            field = ddSchoolDistrict;
            break;
            /*
        case "Units":
            field = ddUnits;
            break;
            */
        default:
            break;
    }
    
    document.getElementById(holder).disabled = false;
    document.getElementById(field).disabled = false;
}

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;
    }   
}

// display loading message
function ShowLoadingMessage(message)
{
    document.getElementById("error").style.display = "none";
    document.getElementById("Message").style.display = "none";
    document.getElementById("ListMessage").style.display = "none";
    document.getElementById("loading").style.display = "block";
    SetupLoadingMessage();
    document.getElementById("loadingMessage").innerHTML = message;
}

// 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 != 0 )
      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 != "" && _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( searched )
    //{
      //SetCookie("searched", searched, exp);
      if( SortOrder != "Price" || SortDir != "asc" )
        SetCookie("sort", SortOrder + "," + SortDir, exp);
      else
        ClearCookie("sort");
    //}
    //else
    //{
      //ClearCookie("searched");
     // ClearCookie("sort");
    //}
    
    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");
    }
    else
    {
        ClearCookie("user");
        ClearCookie("listingstatus");
    }
}

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;
}

// pad input string with wildcard
function WildcardPad(param)
{
    if( param != "" && param != " " && param != null )
    {
        return "%" + param + "%";
    }
    else
    {
        return "";
    }
}

// plot search results on map
function PlotPoints(results)
{
    document.getElementById("error").style.display = "none";
    // set category
//    if( results.length > 0 )
//    {
//        category = results[0].Category;
//    }
    // 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="javascript:ShowDetails(" + results[pinID].Id + ")";
          document.getElementById(results[pinID].Id).onclick = null;
//        }
//        catch(err)
//        {}
    }
}


// set map icon to appropriate image
function setIcon()
{
    var icon = 'Images/house';
    
    if( map )
    {
        // 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;
}

// redirect to property details page of given mls#
function ShowDetails(mlsnumber)
{
    window.location = "PropertyDetails.aspx?id=" + mlsnumber;
}

// OVERRIDDEN HIDE FUNCTION
VEPushpin.Hide=function(a)
{
  var popupHolder = document.getElementById("PopupHolder");
  popupHolder.style.display = "none";
  map.DetachEvent("onclick",onMouseClick);
  currentID = null;
}

// 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
    purge(this);
}

// 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)
{
    if( map )
    {
        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>";
            ListWisconsin.MapService.GetHtmlBody(m, onBodyComplete, null, args, null);
            lastID = m;
        }
        //popup.innerHTML = unescape(c);
        popupHolder.style.display = "block";
        var yOffset = 25;
        var xOffset = 10;
        var zoom = map.GetZoomLevel();
        /*
        if( map.GetZoomLevel() < 12 && map.GetZoomLevel() >= 6 )
        else if( map.GetZoomLevel() < 6 )
        */
        switch(q)
        {
            case 1: // top left
            {
                if( zoom < 12 && zoom >= 6 )
                {
                    // medium logo
                    popupHolder.style.top = pixelPos.y + 20 + "px";
                    popupHolder.style.left = pixelPos.x - 2 + "px";
                }
                else if( zoom < 6 )
                {
                    // small logo
                    popupHolder.style.top = pixelPos.y + 20 + "px";
                    popupHolder.style.left = pixelPos.x - 10 + "px";
                }
                else
                {
                    // large logo
                    popupHolder.style.top = pixelPos.y + yOffset + "px";
                    popupHolder.style.left = pixelPos.x + xOffset + "px";
                }
                HideBeaks();
                beak_top_left.style.display = "block";
                break;
            }
            case 2: // top right
            {
                if( zoom < 12 && zoom >= 6 )
                {
                    // medium logo
                    popupHolder.style.top = pixelPos.y + 20 + "px";
                    popupHolder.style.left = pixelPos.x - 10 - popupHolder.clientWidth + "px";
                }
                else if( zoom < 6 )
                {
                    // small logo
                    popupHolder.style.top = pixelPos.y + 20 + "px";
                    popupHolder.style.left = pixelPos.x - 10 - popupHolder.clientWidth + "px";
                }
                else
                {
                    popupHolder.style.top = pixelPos.y + yOffset + "px";
                    popupHolder.style.left = pixelPos.x - xOffset - popupHolder.clientWidth + "px";
                }
                HideBeaks();
                beak_top_right.style.display = "block";
                break;
            }
            case 3: // bottom left
            {
                if( zoom < 12 && zoom >= 6 )
                {
                    // medium logo
                    popupHolder.style.top = pixelPos.y - 27 - popupHolder.clientHeight + "px";
                    popupHolder.style.left = pixelPos.x + "px";
                }
                else if( zoom < 6 )
                {
                    // small logo
                    popupHolder.style.top = pixelPos.y - 24 - popupHolder.clientHeight + "px";
                    popupHolder.style.left = pixelPos.x - 4 + "px";
                }
                else
                {
                    popupHolder.style.top = pixelPos.y - yOffset - popupHolder.clientHeight + "px";
                    popupHolder.style.left = pixelPos.x + xOffset + "px";
                }
                HideBeaks();
                beak_bot_left.style.display = "block";
                break;
            }
            case 4: // bottom right
            {
                if( zoom < 12 && zoom >= 6 )
                {
                    // medium logo
                    popupHolder.style.top = pixelPos.y - 27 - popupHolder.clientHeight + "px";
                    popupHolder.style.left = pixelPos.x - 10 - popupHolder.clientWidth + "px";
                }
                else if( zoom < 6 )
                {
                    // small logo
                    popupHolder.style.top = pixelPos.y - 24 - popupHolder.clientHeight + "px";
                    popupHolder.style.left = pixelPos.x - 5 - popupHolder.clientWidth + "px";
                }
                else
                {
                    popupHolder.style.top = pixelPos.y - yOffset - popupHolder.clientHeight + "px";
                    popupHolder.style.left = pixelPos.x - xOffset - popupHolder.clientWidth + "px";
                }
                HideBeaks();
                beak_bot_right.style.display = "block";
                break;
            }
        }
    }
}

function onBodyComplete(body, args, caller)
{
    var pixelPos = new VEPixel(args[0], args[1]);
    var currentQuery= args[2];
    
    if (lastQuery == currentQuery)
    {
        $get("Popup").innerHTML = unescape(body);
        
        var yOffset = 25;
        var xOffset = 10;
        var popupHolder = $get("PopupHolder");
        var zoom = map.GetZoomLevel();
        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");
        /*
        if( map.GetZoomLevel() < 12 && map.GetZoomLevel() >= 6 )
        else if( map.GetZoomLevel() < 6 )
        */
        switch(q)
        {
            case 1: // top left
            {
                if( zoom < 12 && zoom >= 6 )
                {
                    // medium logo
                    popupHolder.style.top = pixelPos.y + 20 + "px";
                    popupHolder.style.left = pixelPos.x - 2 + "px";
                }
                else if( zoom < 6 )
                {
                    // small logo
                    popupHolder.style.top = pixelPos.y + 20 + "px";
                    popupHolder.style.left = pixelPos.x - 10 + "px";
                }
                else
                {
                    // large logo
                    popupHolder.style.top = pixelPos.y + yOffset + "px";
                    popupHolder.style.left = pixelPos.x + xOffset + "px";
                }
                HideBeaks();
                beak_top_left.style.display = "block";
                break;
            }
            case 2: // top right
            {
                if( zoom < 12 && zoom >= 6 )
                {
                    // medium logo
                    popupHolder.style.top = pixelPos.y + 20 + "px";
                    popupHolder.style.left = pixelPos.x - 10 - popupHolder.clientWidth + "px";
                }
                else if( zoom < 6 )
                {
                    // small logo
                    popupHolder.style.top = pixelPos.y + 20 + "px";
                    popupHolder.style.left = pixelPos.x - 10 - popupHolder.clientWidth + "px";
                }
                else
                {
                    popupHolder.style.top = pixelPos.y + yOffset + "px";
                    popupHolder.style.left = pixelPos.x - xOffset - popupHolder.clientWidth + "px";
                }
                HideBeaks();
                beak_top_right.style.display = "block";
                break;
            }
            case 3: // bottom left
            {
                if( zoom < 12 && zoom >= 6 )
                {
                    // medium logo
                    popupHolder.style.top = pixelPos.y - 27 - popupHolder.clientHeight + "px";
                    popupHolder.style.left = pixelPos.x + "px";
                }
                else if( zoom < 6 )
                {
                    // small logo
                    popupHolder.style.top = pixelPos.y - 24 - popupHolder.clientHeight + "px";
                    popupHolder.style.left = pixelPos.x - 4 + "px";
                }
                else
                {
                    popupHolder.style.top = pixelPos.y - yOffset - popupHolder.clientHeight + "px";
                    popupHolder.style.left = pixelPos.x + xOffset + "px";
                }
                HideBeaks();
                beak_bot_left.style.display = "block";
                break;
            }
            case 4: // bottom right
            {
                if( zoom < 12 && zoom >= 6 )
                {
                    // medium logo
                    popupHolder.style.top = pixelPos.y - 27 - popupHolder.clientHeight + "px";
                    popupHolder.style.left = pixelPos.x - 10 - popupHolder.clientWidth + "px";
                }
                else if( zoom < 6 )
                {
                    // small logo
                    popupHolder.style.top = pixelPos.y - 24 - popupHolder.clientHeight + "px";
                    popupHolder.style.left = pixelPos.x - 5 - popupHolder.clientWidth + "px";
                }
                else
                {
                    popupHolder.style.top = pixelPos.y - yOffset - popupHolder.clientHeight + "px";
                    popupHolder.style.left = pixelPos.x - xOffset - popupHolder.clientWidth + "px";
                }
                HideBeaks();
                beak_bot_right.style.display = "block";
                break;
            }
        }
    }
}

// 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";
}

// capture key press
function keyPress(e)
{
    var key = e ? e.which : window.event.keyCode;
          
    if( key == 13)
    {
      btnSearch_Click();
      return false;
    }
    else
    {
        return true;
    }
}

// fix icon size depending on zoom level
function CheckZoom()
{       
//    var pinID;
//    // alter image according to zoomLevel
//    for( var c=0; c < fullResults.length; c++ )
//    {
//        pinID = fullResults[c].Id+"_"+mapID;
//        if( document.getElementById(pinID))
//        {
//            if( document.getElementById(pinID).src != setIcon() )
//            {
//                document.getElementById(pinID).src = setIcon();
//            }
//        }
//    }

    UpdateSearchResults();
}

// update results
function UpdateSearchResults()
{
    //if( searched)
    //{
        var oldNWLat = nwLat, oldNWLng = nwLng, oldSELat = seLat, oldSELng = seLng;
        UpdateMapBounds();
        
        if( oldNWLat != nwLat || oldNWLng != nwLng || oldSELat != seLat || oldSELng != seLng )
        {
            // show loading message
            ShowLoadingMessage("Updating...");
            //ListWisconsin.MapService.count(_category, _priceMin, _priceMax, _beds, _baths, _county, _city, WildcardPad(_zip), WildcardPad(_street), WildcardPad(_subdiv), _school, WildcardPad(_condo), _units, seLat, seLng, nwLat, nwLng, view, _firstName, _lastName, _email, _listingStatus, TryUpdate);
            ListWisconsin.MapService.HybridSearch(_category, _priceMin, _priceMax, _beds, _baths, _county, _city, WildcardPad(_zip), WildcardPad(_street), WildcardPad(_subdiv), _school, WildcardPad(_condo), _units, seLat, seLng, nwLat, nwLng, view, _firstName, _lastName, _email, _listingStatus, '', TryHybridUpdate);
            SetMapCookies(7);
        }
    //}
}

// 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( searched )
        //{
            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";
                }
            }
        //}
    }
}

function popup(id)
{
    var pin = $get(id);
    
    if (pin != null)
    {
        pin.onmouseover();
    }
}

function popout(id)
{
    var pin = $get(id);
    
    if (pin != null)
    {
        pin.onmouseout();
    }
}

// 
// Update the map bounds variables
//
function UpdateMapBounds()
{
    if( view == "map" )
    {
        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();
    }
}

// switch views
function SwitchViews()
{
    /*if( view == "map" )
        ShowList();
    else
        ShowMap();*/
    ShowList();
}

// change to listview
function ShowList()
{
    if( view != "list" )
    {
        view = "list";
        SetCookie("view", view, 7);
    }
    document.location.href="PropertySearchResults.aspx";
} 

// change to mapview
function ShowMap()
{
    if( view != "map" )
    {
        view = "map";
        SetCookie("view", view, 7);
    }
    document.getElementById("lnkSwitchViews").innerHTML = "Switch To List View";
    document.getElementById("map").style.display = "block";
    document.getElementById("ListMessage").style.display = "none";
    if( !map )
    {
        LoadMap();
    }
    
    btnSearch_Click();
}

// 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();
    }
    else
    {
        ShowMap();
    }
}

// set results per page from cookie
function SetResultsPerPage()
{
    // load resultsPerPage
    if( ReadCookie("resultsPerPage") != null )
    {
        resultsPerPage = ReadCookie("resultsPerPage");
    }
    else
    {
        resultsPerPage = 10;
    }
}

function SetSortOrder()
{
    if( ReadCookie("sort") != null )
    {
        var s_order = ReadCookie("sort");
        s_order = s_order.split(",");
        SortOrder = s_order[0];
        SortDir = s_order[1];
    }
}

function SetupLoadingMessage()
{
    if( view == "map" )
    {
        document.getElementById("loading").style.top = "188px";
        document.getElementById("loading").style.left = "286px";
        document.getElementById("error").style.top = "188px";
        document.getElementById("error").style.left = "286px";
    }
    else
    {
        document.getElementById("loading").style.top = "-65px";
        document.getElementById("error").style.top = "-65px";
    }
}

function TooManyResults(count)
{
    if( map && view == "map" )
    {
        map.Clear();
    }
    //purge(document.getElementById("resultsDiv"));
    document.getElementById("resultsDiv").innerHTML = "";
    //purge(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
    ListWisconsin.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;
    // save search
    ListWisconsin.MapService.SaveSearch(_street, autoElite, autoLW, _baths, _beds, _city, _condo, _county, _category, _priceMax, _priceMin, _school, searchName, _subdiv, _units, _zip, SavedSearchResult);
}

function SavedSearchResult(success)
{
    if( !success )
    {
        document.location.href = "Login.aspx?ReturnUrl=%2fPropertySearch.aspx"
    }
}

function lnkSavedSearch_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";
    }
}

//
// open map help window
//
function MapHelp() 
{
    window.open('Map_Help.htm','Help','width=420,height=600,resizable=yes,scrollbars=yes');
}

function ShowErrorMessage(error)
{
    document.getElementById("loading").style.display = "none";
    document.getElementById("error").style.display = "inline";
}