﻿Sawbuck = window.Sawbuck || {}; Sawbuck.MapManager = function() {
    var loaded = false; var map, currentProjection, currentZoom, hoverTimer; var _data = {}; var _listings = {}; var RADIUS = 5; var _points = []; var _icons = []; var _markers = []; var _markerMgr; var _highlightedMarkerIcons = []; var _highlightedMarkers = []; var _polygonColors = ["#010101", "#555555", "#00a3e1", "#f68d1e", "#967347", "#24799B", "#2062B2", "#20AFB2", "#1FA884", "#1F38A8"]; var _polygon_added = false; var _polygons = []; var _padded_bounds; var _areas = []; var _fixed_area_type; var _tileLayer; var _areaID = 0; var moveTimer = null; var ignoreMove = false; var moveOverride; var _no_update = false; var options = { map_div: "map_canvas", zoom: 18, center: {}, tiles_on: true, movement_tracking: true }; function init(opts, force) {
        if (loaded && !force)
            return; $j.extend(options, opts); if (GBrowserIsCompatible()) {
            map = new GMap2(document.getElementById(options.map_div)); map.enableScrollWheelZoom(); map.setUIToDefault(); map.setCenter(options.center, parseInt(options.zoom)); currentProjection = G_NORMAL_MAP.getProjection(); currentZoom = map.getZoom(); var mapTypes = map.getMapTypes(); for (var i = 0; i < mapTypes.length; i++) { mapTypes[i].getMinimumResolution = function() { return 6; } }
            try { _areaID = Sawbuck.Page.getAreaID(); } catch (e) { }; if (options.polygon) { initializePolygons(options.polygon); if (!opts.zoom) fitPolygon(); }
            if (options.tiles_on) {
                var tileLayerOverlay = getTileLayer(); _tileLayer = new GTileLayerOverlay(tileLayerOverlay); map.addOverlay(_tileLayer); var isOverMarker = false; var detached = document.getElementById("detached"); var th = document.getElementById("th"); var condo = document.getElementById("condo"); var prevCount = { 1: 0, 2: 0, 4: 0, total: 0 }; GEvent.addListener(map, "click", function(d, latLng) {
                    if (!latLng) return; var listingIDs = tileClick(latLng, _data); if (Sawbuck.Page.getURL() == "/sold" && !Sawbuck.UserManager.isLoggedIn() && (!listingIDs || listingIDs.length)) { Sawbuck.Page.showMapLoginMessage(); return; }
                    if (!listingIDs) {
                        if (Sawbuck.Page.maximumReached()) { Sawbuck.Renderer.getMap().closeExtInfoWindow(); Sawbuck.Renderer.renderMaximumReached("map"); return; }
                        document.getElementById(options.map_div).firstChild.firstChild.style.cursor = "pointer"; loadListingsByPoint(latLng, locationClick);
                    }
                    else if (listingIDs.length) {
                        if (Sawbuck.Page.maximumReached()) { Sawbuck.Renderer.getMap().closeExtInfoWindow(); Sawbuck.Renderer.renderMaximumReached("map"); return; }
                        document.getElementById(options.map_div).firstChild.firstChild.style.cursor = "pointer"; loadListings(listingIDs, locationClick);
                    }
                    listingIDs = null;
                }); GEvent.addListener(map, "mousemove", function(latLng) {
                    if (!latLng) return; var markerCount = tileMousemove(latLng, _data, isOverMarker)
                    if (markerCount.total > 0 && prevCount.total == 0) { document.getElementById(options.map_div).firstChild.firstChild.style.cursor = "pointer"; clearTimeout(hoverTimer); hoverTimer = setTimeout(function() { showHoverPreview(markerCount, latLng) }, 200); } else if (markerCount.total > 0 && !Sawbuck.Utilities.isSame(markerCount, prevCount)) { clearTimeout(hoverTimer); hoverTimer = setTimeout(function() { showHoverPreview(markerCount, latLng) }, 250); } else if (markerCount.total > 0) { showHoverPreview(markerCount); } else if (markerCount.total == 0 && prevCount.total > 0) { document.getElementById(options.map_div).firstChild.firstChild.style.cursor = "url(http://maps.gstatic.com/intl/en_us/mapfiles/openhand_8_8.cur), default"; hideHoverPreview(); }
                    else
                        hideHoverPreview(); prevCount = markerCount;
                });
            } else loaded = true; if (options.movement_tracking) {
                GEvent.addListener(map, "moveend", function(d) {
                    $j(".lottaDots").hide(); if (!ignoreMove && !moveOverride) { clearTimeout(moveTimer); moveTimer = setTimeout(moveEnd, 650); }
                    if (moveOverride) { try { moveOverride(); } catch (e) { console.log(e); }; }
                    moveOverride = null; ignoreMove = false;
                }); GEvent.addListener(map, "movestart", function() { $j(".lottaDots").hide(); map.closeExtInfoWindow(); clearTimeout(teaserTimer); $j("#areaNameTeaser").hide(); });
            }
            initializeIcons(); map.checkResize();
        } 
    }
    function moveEnd() {
        var zoomChanged = false; if (currentZoom != map.getZoom()) { _data = {}; zoomChanged = true; try { map.closeExtInfoWindow(); } catch (e) { }; }
        currentZoom = map.getZoom(); if (Sawbuck.Page.loaded() && loaded) {
            Sawbuck.SearchManager.setValue("map_center", [map.getCenter().lat(), map.getCenter().lng()]); Sawbuck.SearchManager.setValue("zoom", [currentZoom]); if (!withinBounds() || zoomChanged) {
                if (Sawbuck.Page.onlyWithinArea() && !polygonOutsideBounds() && !zoomChanged) { Sawbuck.Page.loadListings(null, true); } else {
                    if (!zoomChanged) Sawbuck.Page.onlyWithinArea(false); updatePolygon(); Sawbuck.SearchManager.setValue("page", [1]); try { Sawbuck.Page.setPage(1); } catch (e) { }; if (!Sawbuck.Page.onlyWithinArea())
                        Sawbuck.Page.loadListings(null, true);
                }
                if (options.tiles_on) { loadTileData(); } 
            }
            Sawbuck.SearchManager.updateHash();
        } 
    }
    function showHoverPreview(markerCount, latLng) {
        var hoverData = document.getElementById("hoverData"); if (!hoverData) { hoverData = document.createElement("div"); hoverData.setAttribute("id", "hoverData"); hoverData.appendChild(document.createElement("div")); hoverData.firstChild.setAttribute("class", "data"); document.getElementById(options.map_div).parentNode.appendChild(hoverData); }
        if (latLng) {
            var point = map.fromLatLngToContainerPixel(latLng); var width = $j(hoverData).width(); var left = (point.x + 15); var top = (point.y + 5); var edge = $j(map.getContainer()).width(); if ((left + width) > edge - 10) { left = (left - width - 10); top += 10; }
            hoverData.style.left = left + "px"; hoverData.style.top = top + "px"; hoverData.style.display = 'block';
        }
        var countData = []; if (markerCount["1"])
            countData.push(markerCount["1"] + " Detached"); if (markerCount["2"] == 1)
            countData.push(markerCount["2"] + " Townhouse"); if (markerCount["2"] > 1)
            countData.push(markerCount["2"] + " Townhouses"); if (markerCount["4"] == 1)
            countData.push(markerCount["4"] + " Condo"); if (markerCount["4"] > 1)
            countData.push(markerCount["4"] + " Condos"); hoverData.firstChild.innerHTML = countData.join("<br/>"); hoverData = null;
    }
    function hideHoverPreview() {
        clearTimeout(hoverTimer); hoverTimer = null; if (document.getElementById("hoverData"))
            document.getElementById("hoverData").style.display = "none";
    }
    function addListings(loadedListings, cluster) {
        var ids = []; var factor = 1; for (var i = 0; i < loadedListings.length; i++) {
            var thisListing = loadedListings[i]; ids.push(thisListing.id); if (!_listings[thisListing.id]) {
                _listings[thisListing.id] = thisListing; if (cluster) {
                    var cachedListings = _data[thisListing.TileX / factor + "." + thisListing.TileY / factor][thisListing.InTileX][thisListing.InTileY]
                    var found = false; if (cachedListings && cachedListings.length) { for (var j = 0; j < cachedListings.length; j++) { if (cachedListings[j].i == thisListing.id) { cachedListings[j].c = 1; found = true; } } }
                    if (!found) cachedListings.push({ c: 1, t: thisListing.PropertyTypeID, i: thisListing.id });
                } 
            } 
        }
        return ids;
    }
    function getListings(listingIDs) {
        var requestedListings = []; for (var i = 0; i < listingIDs.length; i++) { requestedListings.push(_listings[listingIDs[i]]); }
        return requestedListings;
    }
    function loadListings(listingIDs, callback) {
        var unloadedListingIDs = []; for (var i = 0; i < listingIDs.length; i++) { if (!_listings[listingIDs[i]]) { unloadedListingIDs.push(listingIDs[i]); } }
        if (unloadedListingIDs.length) { criteria = "{listingIDs: [" + unloadedListingIDs.join(",") + "], SortBy: \"" + Sawbuck.SearchManager.getValue("sort")[0].replace(/-/, " desc") + "\"}"; $j.ajax({ type: "POST", url: "/service/WebService.asmx/GetListingsByIDs", data: criteria, contentType: "application/json; charset=utf-8", dataType: "json", dataFilter: function(data, type) { return data.replace(/"\\\/(Date\([0-9-]+\))\\\/"/gi, 'new $1'); }, processData: false, success: function(res) { callback(addListings(res.d)); }, error: function(e, t) { console.log(e); } }); }
        else
            callback(listingIDs);
    }
    function loadListingsByPoint(latLng, callback) { var criteria = Sawbuck.Page.getCriteria(); var point = currentProjection.fromLatLngToPixel(latLng, currentZoom); criteria["x"] = point.x; criteria["y"] = point.y; criteria["z"] = currentZoom; $j.ajax({ type: "POST", url: "/service/WebService.asmx/GetListingsByXY", data: Sawbuck.Utilities.toJson(criteria), contentType: "application/json; charset=utf-8", dataType: "json", dataFilter: function(data, type) { return data.replace(/"\\\/(Date\([0-9-]+\))\\\/"/gi, 'new $1'); }, processData: false, success: function(res) { callback(addListings(res.d, true)); }, error: function(e, t) { console.log(e); } }); }
    function loadTileData() {
        if (!Sawbuck.Page.loaded()) return; currentZoom = map.getZoom(); tiles = getVisibleTiles(); var coords = []; for (var t in tiles) {
            if (_data[tiles[t].x + "." + tiles[t].y] || !tiles[t].x)
                continue; coords.push({ x: tiles[t].x, y: tiles[t].y });
        }
        criteria = { coords: coords, z: currentZoom }; $j.extend(criteria, Sawbuck.Page.getCriteria()); $j.ajax({ type: "POST", url: "/service/WebService.asmx/GetListingsByTile", data: Sawbuck.Utilities.toJson(criteria), contentType: "application/json; charset=utf-8", dataType: "json", processData: false, success: function(res) { tileData = []; eval("tileData = [" + res.d + "]"); for (var o in tileData) { $j.extend(_data, tileData[o]); } }, error: function(e, t) { console.log(e); } }); loaded = true;
    }
    function getSerializedFields() {
        try { var hash = Sawbuck.HashManager.getCurrentHash().replace(/c_.+?\//, ""); hash = hash.replace(/_/g, "=").replace(/\//g, "&"); return hash; }
        catch (e) { return ""; } 
    }
    function getTileLayer() {
        var tileLayerOverlay = new GTileLayer(null, null, null, { tileUrlTemplate: Sawbuck.SERVER + '/tile/image.ashx?x={X}&y={Y}&z={Z}&stat=' + Sawbuck.SearchManager.getValue("status")[0] + '&' + getSerializedFields() + "&cf=" + (Sawbuck.Page.getURL() == "/classifieds").toString() }); tileLayerOverlay.isPng = function() { return true; }; tileLayerOverlay.getOpacity = function() { return 1.0; }
        return tileLayerOverlay;
    }
    function updateTiles() { if (!options.tiles_on) return false; _data = {}; map.removeOverlay(_tileLayer); _tileLayer = new GTileLayerOverlay(getTileLayer()); map.addOverlay(_tileLayer); loadTileData(); }
    function getVisibleTiles() {
        var min_x, min_y, max_x, max_y, ne, sw, ne, sw_tile, ne_tile; var tileRange = []; var bounds = map.getBounds(); ne = currentProjection.fromLatLngToPixel(bounds.getNorthEast(), currentZoom); sw = currentProjection.fromLatLngToPixel(bounds.getSouthWest(), currentZoom); min_x = Math.floor(sw.x / 256); min_y = Math.floor(ne.y / 256); max_x = Math.floor(ne.x / 256); max_y = Math.floor(sw.y / 256); for (var x = min_x; x <= max_x; x++) { for (var y = min_y; y <= max_y; y++) { tileRange.push({ x: x, y: y }); } }
        return tileRange;
    }
    function getTileAndPosition(latLng) { var point = currentProjection.fromLatLngToPixel(latLng, currentZoom); var tile = { x: Math.floor(point.x / 256), y: Math.floor(point.y / 256) }; var tilePoint = { x: point.x % 256, y: point.y % 256 }; return { tile: tile, tilePoint: tilePoint }; }
    function tileClick(latLng, data, isOverMarker) {
        var tap = getTileAndPosition(latLng); var tile = tap.tile; var tilePoint = tap.tilePoint; var tileData = _data[tile.x + "." + tile.y]; var listings = []; if (tileData) { for (x = (tilePoint.x - RADIUS); x <= (tilePoint.x + RADIUS); x++) { if (tileData[x]) { for (y = (tilePoint.y - RADIUS); y <= (tilePoint.y + RADIUS); y++) { if (tileData[x][y]) { if (Math.sqrt(Math.pow(Math.abs(x - tilePoint.x), 2) + Math.pow(Math.abs(y - tilePoint.y), 2)) <= RADIUS) { for (i = 0; i < tileData[x][y].length; i++) { if (tileData[x][y][i].c > 1) return false; listings.push(tileData[x][y][i].i); } } } } } } }
        return listings;
    }
    function tileMousemove(latLng, data, isOverMarker) {
        var isMarker = isOverMarker || false; var tap = getTileAndPosition(latLng); var tile = tap.tile; var tilePoint = tap.tilePoint; var tileData = _data[tile.x + "." + tile.y]; var count = { 1: 0, 2: 0, 4: 0, total: 0 }; if (document.getElementById("position")) {
            document.getElementById("position").innerHTML = "<h3>Where am I?</h3><b>lat:</b> " + latLng.lat().toFixed(6)
+ "<br /><b>lng:</b> " + latLng.lng().toFixed(6)
+ "<br /><b>tileX:</b> " + tile.x
+ "<br /><b>tileY:</b> " + tile.y
+ "<br /><b>inTileX:</b> " + tilePoint.x
+ "<br /><b>inTileY:</b> " + tilePoint.y
+ "<br /><b>zoom:</b> " + currentZoom; document.getElementById("position").style.display = "block";
        }
        if (tileData) {
            for (x = (tilePoint.x - RADIUS); x <= (tilePoint.x + RADIUS); x++) {
                if (tileData[x]) {
                    for (y = (tilePoint.y - RADIUS); y <= (tilePoint.y + RADIUS); y++) {
                        if (tileData[x][y]) {
                            if (Math.sqrt(Math.pow(Math.abs(x - tilePoint.x), 2) + Math.pow(Math.abs(y - tilePoint.y), 2)) <= RADIUS) {
                                for (i = 0; i < tileData[x][y].length; i++) {
                                    switch (tileData[x][y][i].t) { case 1: count[1] += tileData[x][y][i].c; break; case 2: count[2] += tileData[x][y][i].c; break; case 4: count[4] += tileData[x][y][i].c; break; }
                                    count.total++;
                                } 
                            } 
                        } 
                    } 
                } 
            } 
        }
        return count;
    }
    function locationClick(listingIDs, marker) {
        listings = getListings(listingIDs); var listing_id = listings[0].id
        var listing_url = "/property" + listings[0].url
        var html = ""; try { var previewHTML = tmpl("mapViewTemplate", { selectedListing: listings[0] }); } catch (e) { }
        html += previewHTML; if (listings.length == 1) {
            if (marker) { marker.openExtInfoWindow(map, "map_window", html, { paddingY: 35, paddingX: 75 }) }
            else
                map.openExtInfoWindow(new GLatLng(listings[0].lat, listings[0].lng), "map_window", html, { paddingY: 35, paddingX: 75 })
            return;
        }
        var zoomDiv = document.createElement("div"); zoomDiv.className = "zoom"; var zoomImage = document.createElement("img"); zoomImage.src = "/images/icons/magnifier.png"; zoomImage.className = "zoomImage"; zoomImage.align = "absmiddle"; zoomImage.hspace = "5"; var zoomText = document.createElement("a"); zoomText.innerHTML = "Zoom To Listing"; zoomText.href = "javascript:return false;"; zoomText.className = "zoomLink"; zoomDiv.appendChild(zoomImage); zoomDiv.appendChild(zoomText); var paginationDiv = document.createElement("div"); paginationDiv.className = "pagination"; var leftArrow = document.createElement("img"); leftArrow.src = "/images/left_arrow.gif"; leftArrow.alt = "Previous"; leftArrow.border = "0"; leftArrow.align = "absmiddle"; leftArrow.hspace = "10"; leftArrow.className = "leftArrow"; var rightArrow = document.createElement("img"); rightArrow.src = "/images/right_arrow.gif"; rightArrow.alt = "Next"; rightArrow.border = "0"; rightArrow.align = "absmiddle"; rightArrow.hspace = "10"; rightArrow.className = "rightArrow"; var span = document.createElement("span"); span.innerHTML = "Home <strong class='currentPage'>1</strong> of <strong>" + listings.length; paginationDiv.appendChild(zoomDiv); paginationDiv.appendChild(leftArrow); paginationDiv.appendChild(span); paginationDiv.appendChild(rightArrow); var container = document.createElement("div"); container.appendChild(paginationDiv); html += container.innerHTML; map.openExtInfoWindow(new GLatLng(listings[0].lat, listings[0].lng), "map_window_long", html, { paddingY: 35, paddingX: 75 }); var total = listings.length
        var counter = 0; $j("img.rightArrow").click(function() {
            if (Sawbuck.Page.maximumReached()) { map.closeExtInfoWindow(); Sawbuck.Renderer.renderMaximumReached("map"); return; }
            Sawbuck.Page.mapViewListingViewed()
            counter++; if (counter >= total) { counter = 0; }
            var listingHTML = tmpl("mapViewTemplate", { selectedListing: listings[counter] }); $j("#map_window_long .listing").replaceWith(listingHTML); $j("#map_window_long .currentPage").text(counter + 1);
        }); $j("img.leftArrow").click(function() {
            if (Sawbuck.Page.maximumReached()) { Sawbuck.Renderer.getMap().getMap().closeExtInfoWindow(); Sawbuck.Renderer.renderMaximumReached("map"); return; }
            Sawbuck.Page.mapViewListingViewed()
            counter--; if (counter < 0) { counter = total - 1; }
            var listingHTML = tmpl("mapViewTemplate", { selectedListing: listings[counter] }); $j("#map_window_long .listing").replaceWith(listingHTML); $j("#map_window_long .currentPage").text(counter + 1);
        }); $j(".zoomLink, .zoomImage").click(function(event) { map.setCenter(new GLatLng(listings[counter].lat, listings[counter].lng), 18); event.stopPropagation(); return false; }); $j(".listingLink").click(function(event) { listing_url = listings[counter].url; window.open("/property" + listing_url); event.stopPropagation(); return false; });
    }
    function initializeIcons() {
        var icon = new GIcon(); icon.image = "http://69.89.31.190/~sawbuckr/images/map/markers/0.png"; icon.shadow = "http://69.89.31.190/~sawbuckr/images/map/markers/shadow.png"; icon.blank = "http://69.89.31.190/~sawbuckr/images/blank.gif"
        icon.printImage = "http://69.89.31.190/~sawbuckr/images/map/markers/print/0.gif"; icon.iconSize = new GSize(18, 27); icon.shadowSize = new GSize(36, 27); icon.iconAnchor = new GPoint(6, 25); icon.infoWindowAnchor = new GPoint(9, 9); _icons.push(icon)
        var star_1 = new GIcon(); star_1.image = "http://69.89.31.190/~sawbuckr/images/map/markers/1.png"; star_1.shadow = "http://69.89.31.190/~sawbuckr/images/map/markers/shadow.png"; star_1.blank = "http://69.89.31.190/~sawbuckr/images/blank.gif"
        star_1.printImage = "http://69.89.31.190/~sawbuckr/images/map/markers/print/1.gif"; star_1.iconSize = new GSize(18, 27); star_1.shadowSize = new GSize(36, 27); star_1.iconAnchor = new GPoint(6, 25); star_1.infoWindowAnchor = new GPoint(9, 9); _icons.push(star_1)
        star_1 = null; var star_2 = new GIcon(); star_2.image = "http://69.89.31.190/~sawbuckr/images/map/markers/2.png"; star_2.shadow = "http://69.89.31.190/~sawbuckr/images/map/markers/shadow.png"; star_2.blank = "http://69.89.31.190/~sawbuckr/images/blank.gif"
        star_2.printImage = "http://69.89.31.190/~sawbuckr/images/map/markers/print/2.gif"; star_2.iconSize = new GSize(18, 27); star_2.shadowSize = new GSize(36, 27); star_2.iconAnchor = new GPoint(6, 25); star_2.infoWindowAnchor = new GPoint(9, 9); _icons.push(star_2)
        star_2 = null; var star_3 = new GIcon(); star_3.image = "http://69.89.31.190/~sawbuckr/images/map/markers/3.png"; star_3.shadow = "http://69.89.31.190/~sawbuckr/images/map/markers/shadow.png"; star_3.blank = "http://69.89.31.190/~sawbuckr/images/blank.gif"
        star_3.printImage = "http://69.89.31.190/~sawbuckr/images/map/markers/print/3.gif"; star_3.iconSize = new GSize(18, 27); star_3.shadowSize = new GSize(36, 27); star_3.iconAnchor = new GPoint(6, 25); star_3.infoWindowAnchor = new GPoint(9, 9); _icons.push(star_3)
        star_3 = null; var star_4 = new GIcon(); star_4.image = "http://69.89.31.190/~sawbuckr/images/map/markers/4.png"; star_4.shadow = "http://69.89.31.190/~sawbuckr/images/map/markers/shadow.png"; star_4.blank = "http://69.89.31.190/~sawbuckr/images/blank.gif"
        star_4.printImage = "http://69.89.31.190/~sawbuckr/images/map/markers/print/4.gif"; star_4.iconSize = new GSize(18, 27); star_4.shadowSize = new GSize(36, 27); star_4.iconAnchor = new GPoint(6, 25); star_4.infoWindowAnchor = new GPoint(9, 9); _icons.push(star_4)
        star_4 = null; for (var i = 0; i < 26; i++) {
            var letter = String.fromCharCode(97 + i); var letter_icon = new GIcon(); letter_icon.image = "/images/map/markers/blue_" + letter + ".png"; letter_icon.shadow = "http://69.89.31.190/~sawbuckr/images/map/markers/shadow.png"; letter_icon.blank = "http://69.89.31.190/~sawbuckr/images/blank.gif"
            letter_icon.printImage = "http://69.89.31.190/~sawbuckr/images/map/markers/print/" + letter + ".png"; letter_icon.iconSize = new GSize(18, 27); letter_icon.shadowSize = new GSize(36, 27); letter_icon.iconAnchor = new GPoint(6, 25); letter_icon.infoWindowAnchor = new GPoint(9, 9); _icons[letter] = (letter_icon)
            letter_icon = null;
        }
        var home_icon = new GIcon(); home_icon.image = "/images/icons/house.png"; home_icon.blank = "http://69.89.31.190/~sawbuckr/images/blank.gif"
        home_icon.iconSize = new GSize(16, 16); home_icon.iconAnchor = new GPoint(8, 11); home_icon.infoWindowAnchor = new GPoint(8, 1); _icons[99] = home_icon; home_icon = null; var new_icon = new GIcon(); new_icon.image = "/images/map/markers/news_feed/new.png"; new_icon.shadow = "/images/map/markers/news_feed/shadow.png"; new_icon.blank = "http://69.89.31.190/~sawbuckr/images/blank.gif"
        new_icon.iconSize = new GSize(35, 33); new_icon.iconAnchor = new GPoint(11, 31); new_icon.infoWindowAnchor = new GPoint(11, 16); _icons["new"] = new_icon; new_icon = null; var price_drop_icon = new GIcon(); price_drop_icon.image = "/images/map/markers/news_feed/price_drop.png"; price_drop_icon.shadow = "/images/map/markers/news_feed/shadow.png"; price_drop_icon.blank = "http://69.89.31.190/~sawbuckr/images/blank.gif"
        price_drop_icon.iconSize = new GSize(35, 33); price_drop_icon.iconAnchor = new GPoint(11, 31); price_drop_icon.infoWindowAnchor = new GPoint(11, 16); _icons["price_drop"] = price_drop_icon; price_drop_icon = null; var price_increase_icon = new GIcon(); price_increase_icon.image = "/images/map/markers/news_feed/price_increase.png"; price_increase_icon.shadow = "/images/map/markers/news_feed/shadow.png"; price_increase_icon.blank = "http://69.89.31.190/~sawbuckr/images/blank.gif"
        price_increase_icon.iconSize = new GSize(35, 33); price_increase_icon.iconAnchor = new GPoint(11, 31); price_increase_icon.infoWindowAnchor = new GPoint(11, 16); _icons["price_increase"] = price_increase_icon; price_increase_icon = null; var return_to_market_icon = new GIcon(); return_to_market_icon.image = "/images/map/markers/news_feed/return_to_market.png"; return_to_market_icon.shadow = "/images/map/markers/news_feed/shadow.png"; return_to_market_icon.blank = "http://69.89.31.190/~sawbuckr/images/blank.gif"
        return_to_market_icon.iconSize = new GSize(35, 33); return_to_market_icon.iconAnchor = new GPoint(11, 31); return_to_market_icon.infoWindowAnchor = new GPoint(11, 16); _icons["return_to_market"] = return_to_market_icon; return_to_market_icon = null; var contract_icon = new GIcon(); contract_icon.image = "/images/map/markers/news_feed/contract.png"; contract_icon.shadow = "/images/map/markers/news_feed/shadow.png"; contract_icon.blank = "http://69.89.31.190/~sawbuckr/images/blank.gif"
        contract_icon.iconSize = new GSize(35, 33); contract_icon.iconAnchor = new GPoint(11, 31); contract_icon.infoWindowAnchor = new GPoint(11, 16); _icons["contract"] = contract_icon; contract_icon = null; var sold_icon = new GIcon(); sold_icon.image = "/images/map/markers/news_feed/sold.png"; sold_icon.shadow = "/images/map/markers/news_feed/shadow.png"; sold_icon.blank = "http://69.89.31.190/~sawbuckr/images/blank.gif"
        sold_icon.iconSize = new GSize(35, 33); sold_icon.iconAnchor = new GPoint(11, 31); sold_icon.infoWindowAnchor = new GPoint(11, 16); _icons["sold"] = sold_icon; sold_icon = null; var highlightedMarkerIcon = new GIcon(); highlightedMarkerIcon.image = "/images/marker_on.png"; highlightedMarkerIcon.iconSize = new GSize(18, 27); highlightedMarkerIcon.iconAnchor = new GPoint(6, 25); highlightedMarkerIcon.infoWindowAnchor = new GPoint(9, 9); _highlightedMarkerIcons.push(highlightedMarkerIcon); for (var i = 0; i < 26; i++) {
            var highlightedLetterIcon = new GIcon(); highlightedLetterIcon.image = "/images/map/markers/orange_" + String.fromCharCode(97 + i) + ".png"; highlightedLetterIcon.blank = "http://69.89.31.190/~sawbuckr/images/blank.gif"
            highlightedLetterIcon.printImage = "http://69.89.31.190/~sawbuckr/images/map/markers/print/" + String.fromCharCode(97 + i) + ".png"; highlightedLetterIcon.iconSize = new GSize(18, 27); highlightedLetterIcon.shadowSize = new GSize(36, 27); highlightedLetterIcon.iconAnchor = new GPoint(6, 25); highlightedLetterIcon.infoWindowAnchor = new GPoint(9, 9); _highlightedMarkerIcons.push(highlightedLetterIcon);
        }
        var event_icon_types = ["new", "price_drop", "price_increase", "return_to_market", "contract", "sold"]; for (var i = 0; i < event_icon_types.length; i++) {
            var highlightedLetterIcon = new GIcon(); highlightedLetterIcon.image = "/images/map/markers/news_feed/" + event_icon_types[i] + "-bar.png"; highlightedLetterIcon.blank = "http://69.89.31.190/~sawbuckr/images/blank.gif"
            highlightedLetterIcon.printImage = "http://69.89.31.190/~sawbuckr/images/map/markers/print/" + event_icon_types[i] + ".png"; highlightedLetterIcon.iconSize = new GSize(35, 33); highlightedLetterIcon.iconAnchor = new GPoint(11, 31); highlightedLetterIcon.infoWindowAnchor = new GPoint(11, 16); _highlightedMarkerIcons[event_icon_types[i]] = highlightedLetterIcon;
        }
        return _icons;
    }
    function getMarkerManager() {
        if (!_markerMgr)
            _markerMgr = new ClusterMarker(map); return _markerMgr;
    }
    function addMarkerListeners(marker) {
        if (options.map_div == "listViewMap") {
            GEvent.addListener(marker, "click", function() {
                $j(".listing").removeClass("highlighted"); if (Sawbuck.Page.maximumReached && Sawbuck.Page.maximumReached()) { Sawbuck.Renderer.getMap().closeExtInfoWindow(); Sawbuck.Renderer.renderMaximumReached("map"); return; }
                var listingData = Sawbuck.Page.getListingByID(this.listing_id); _listings[this.listing_id] = listingData; locationClick([this.listing_id], this);
            });
        }
        else if (options.map_div == "newsFeedViewMap") {
            GEvent.addListener(marker, "click", function() {
                $j(".event .listingDetails:not(#" + marker.index + "_" + marker.listing_id + " .listingDetails)").slideUp('fast'); $j(".event:not(#" + marker.index + "_" + marker.listing_id + ")").removeClass("selected"); var listing = $j(".event#" + marker.index + "_" + marker.listing_id)
                if (listing && listing.length >= 1) { $j(listing).addClass("selected"); Sawbuck.Renderer.displayPreview(marker.listing_id, null, marker.index + "_" + marker.listing_id); } 
            });
        }
        GEvent.addListener(marker, "mouseover", function() { }); GEvent.addListener(marker, "mouseout", function() { isOverMarker = false; });
    }; function removeMarkerListeners() {
        if (!_markers || !_markers.length)
            return true; for (var i = 0; i < _markers.length; i++) { GEvent.clearListeners(_markers[i]); }
        return true;
    }; function clearMarkers() {
        removeMarkerListeners(); while (_markers.length)
            map.removeOverlay(_markers.pop()); for (var i in _highlightedMarkers) {
            if (typeof (_highlightedMarkers[i]) == "object")
                map.removeOverlay(_highlightedMarkers[i]);
        }
        _highlightedMarkers = []; _markers = []; return true;
    }; function fitAllMarkers() {
        var bounds; for (var m in _markers) {
            if (_markers[m].getLatLng) {
                if (!bounds) { bounds = new GLatLngBounds(_markers[m].getLatLng(), _markers[m].getLatLng()); }
                bounds.extend(_markers[m].getLatLng());
            } 
        }
        map.setZoom(map.getBoundsZoomLevel(bounds)); map.setCenter(bounds.getCenter()); return { zoom: map.getZoom(), center: map.getCenter() };
    }
    function initializeMarkers(points, clusteringOn, fitAll, lettersOff, eventIcons, leaveMarkers) {
        _points = (points == null) ? _points : points; if (!leaveMarkers) clearMarkers(); if (_points.length <= 0)
            return false; if (!_highlightedMarkers.length) { for (var i in _highlightedMarkerIcons) { if (typeof (_highlightedMarkerIcons[i]) != "object") continue; var highlightedMarker = new GMarker(map.getCenter(), { icon: _highlightedMarkerIcons[i], zIndexProcess: function() { return 500; } }); _highlightedMarkers[i] = highlightedMarker; map.addOverlay(highlightedMarker); highlightedMarker.hide(); } }
        for (var i = 0; i < _points.length; i++) {
            var address = _points[i].address || ""; if (eventIcons) { var iconIndex = Sawbuck.Renderer.getEventMapIcon(_points[i].utid, _points[i].nv, _points[i].ov); }
            else { var iconIndex = lettersOff ? 0 : String.fromCharCode(97 + i); }
            var rating = parseInt(_points[i].rat || 0); if (eventIcons) { var t_listing = Sawbuck.Page.getListingByID(_points[i].id); var eventSentence = t_listing.addr + " in " + (Sawbuck.MLS.getMLSBit(t_listing.mid, 7) ? t_listing.city : t_listing.sub || t_listing.city) + Sawbuck.Renderer.getEventSentence(t_listing, Sawbuck.MLS.getMLSBit(t_listing.mid, 16)) + "."; var markerOptions = { icon: _icons[iconIndex], title: eventSentence.replace(/<br[\/]*>/, " \n") }; }
            else { var markerOptions = { icon: _icons[iconIndex], title: address.replace(/<br[\/]*>/, " \n") }; }
            if (!_points[i].point && _points[i].lat && _points[i].lng)
                _points[i].point = new GLatLng(_points[i].lat, _points[i].lng); var marker = new GMarker(_points[i].point, markerOptions)
            marker.listing_id = _points[i].id; marker.ref_id = _points[i].ref_id; marker.listing_url = _points[i].url; marker.address = address; marker.rating = rating; marker.highlightID = (lettersOff ? eventIcons ? iconIndex : 0 : i + 1); marker.index = i; addMarkerListeners(marker); map.addOverlay(marker); _markers.push(marker); marker = null; address = null;
        }
        if (fitAll) fitAllMarkers(); return true;
    }; function highlightMarker(listingID) {
        if (_markers) { var marker = _markers.find(function(l) { return listingID == l.ref_id; }); if (!marker) marker = _markers.find(function(l) { return listingID == l.listing_id; }); var location = marker.getLatLng(); _highlightedMarkers[marker.highlightID || 0].setLatLng(location); _highlightedMarkers[marker.highlightID || 0].show(); }
        else
            return false;
    }; function withinBounds() {
        if (_padded_bounds) { return _padded_bounds.containsBounds(map.getBounds()) }
        else { return false; } 
    }
    function getMiniBounds() { map.checkResize(); var reductionPercent = .4; var mapBounds = map.getBounds(); var size = mapBounds.toSpan(); var sw = mapBounds.getSouthWest(); var ne = mapBounds.getNorthEast(); var width = size.lat() * (1 - reductionPercent); var height = size.lng() * (1 - reductionPercent); var reducedSW = new GLatLng(sw.lat() + (width / 2), sw.lng() + (height / 2)); var reducedNE = new GLatLng(ne.lat() - (width / 2), ne.lng() - (height / 2)); var miniBounds = new GLatLngBounds(reducedSW, reducedNE); return miniBounds; }
    var testBox; function drawMiniBounds() {
        var miniBounds = getMiniBounds(); var sw = miniBounds.getSouthWest(); var ne = miniBounds.getNorthEast(); var nw = new GLatLng(sw.lat(), ne.lng()); var se = new GLatLng(ne.lat(), sw.lng()); if (testBox)
            map.removeOverlay(testBox); testBox = new GPolygon([sw, nw, ne, se, sw], "#CC0000", 3); return map.addOverlay(testBox);
    }
    function polygonOutsideBounds() { var polygonBounds = _polygons[0].shape.getBounds(); return (!getMiniBounds().intersects(polygonBounds)); }
    function getBounds(forceRefresh, big) {
        map.checkResize(); var padding = 100; if (_padded_bounds && !forceRefresh) { var ne = _padded_bounds.getNorthEast(); var sw = _padded_bounds.getSouthWest(); }
        else { var ne = map.fromContainerPixelToLatLng(new GPoint($j("#" + options.map_div + ".map").width() + padding, -padding)); var sw = map.fromContainerPixelToLatLng(new GPoint(-padding, $j("#" + options.map_div + ".map").height() + padding)); _padded_bounds = new GLatLngBounds(sw, ne); big = true; }
        var latMin = map.getBounds().getSouthWest().lat(); var latMax = map.getBounds().getNorthEast().lat(); var lngMin = map.getBounds().getSouthWest().lng(); var lngMax = map.getBounds().getNorthEast().lng(); return { latMin: latMin, latMax: latMax, lngMin: lngMin, lngMax: lngMax, big: big };
    }; getAreaTypeID = function() {
        var currentAreaTypeID = options.areaTypeID; var zoomLevel = map.getZoom(); if (zoomLevel > 13 && currentAreaTypeID >= 6) { return 6; }
        if (zoomLevel > 11 && currentAreaTypeID == 5) { return 5; }
        if (zoomLevel > 11 && currentAreaTypeID >= 4) { return 4; }
        if (zoomLevel >= 9) { return 3; }
        if (zoomLevel < 9 && currentAreaTypeID >= 2) { return 2; }
        if (zoomLevel < 9 && currentAreaTypeID == 1) { return 1; }
        return currentAreaTypeID;
    }
    function updatePolygon(areaID) {
        areaID = areaID || ""; var criteria = {}; points = getBounds(); criteria["LatitudeMin"] = points.latMin; criteria["LatitudeMax"] = points.latMax; criteria["LongitudeMin"] = points.lngMin
        criteria["LongitudeMax"] = points.lngMax; criteria["AreaID"] = areaID; criteria["Page"] = Sawbuck.Page.getURL() == "/for_sale" ? 0 : Sawbuck.Page.getURL() == "/sold" ? 1 : 2; $j.ajax({ type: "POST", url: "/service/WebService.asmx/GetGeographicAreaByCentroid", data: Sawbuck.Utilities.toJson(criteria), contentType: "application/json; charset=utf-8", dataType: "json", processData: false, success: function(res) {
            if (!res) return false; Sawbuck.SearchManager.setValue("map_center", [map.getCenter().lat(), map.getCenter().lng()]); Sawbuck.SearchManager.setValue("zoom", [map.getZoom()]); if (_areaID != res.d.GeographicAreaID) {
                if (Sawbuck.Page.onlyWithinArea()) { Sawbuck.Page.onlyWithinArea(false); Sawbuck.Page.loadListings(false, true); }
                var areaName = res.d.AreaName; if (res.d.AreaTypeID == 5)
                    areaName += " (" + res.d.UspsCity + ", " + res.d.State + ")"; showAreaName(areaName, res.d.CentroidLat, res.d.CentroidLng); var areaPolygon = new Array({ levels: res.d.ModifiedGoogleLevels, points: res.d.ModifiedGooglePolygon }); initializePolygons(areaPolygon, true, 1); Sawbuck.Renderer.updateArea(res.d); _areaID = res.d.GeographicAreaID;
            }
            else if (Sawbuck.Page.onlyWithinArea())
                Sawbuck.Page.loadListings(false, true);
        }, error: function(e, t) { console.log(e); } 
        });
    }
    function switchArea(areaID, res, dontLoadListing) {
        areaID = areaID || ""; var criteria = {}; points = getBounds(); if (res) {
            if (_areaID != res.d.GeographicArea.GeographicAreaID) {
                Sawbuck.Page.onlyWithinArea(true); _areaID = res.d.GeographicArea.GeographicAreaID; Sawbuck.Page.setAreaID(_areaID); ignoreMove = true; if (options.tiles_on) { moveOverride = function() { Sawbuck.Page.loadListings(true, true); loadTileData(); } }
                else { moveOverride = function() { Sawbuck.Page.loadListings(true, true); } }
                var areaName = res.d.GeographicArea.AreaName; if (res.d.GeographicArea.AreaTypeID == 5)
                    areaName += " (" + res.d.GeographicArea.UspsCity + ", " + res.d.GeographicArea.State + ")"; showAreaName(areaName, res.d.GeographicArea.CentroidLat, res.d.GeographicArea.CentroidLng); var areaPolygon = new Array({ levels: res.d.GeographicArea.ModifiedGoogleLevels, points: res.d.GeographicArea.ModifiedGooglePolygon }); initializePolygons(areaPolygon, true); fitPolygon(); Sawbuck.Renderer.updateArea(res.d.GeographicArea);
            }
            return;
        }
        criteria["LatitudeMin"] = 0; criteria["LatitudeMax"] = 0; criteria["LongitudeMin"] = 0; criteria["LongitudeMax"] = 0; criteria["AreaID"] = areaID; criteria["Page"] = Sawbuck.Page.getURL() == "/for_sale" ? 0 : 1; $j.ajax({ type: "POST", url: "/service/WebService.asmx/GetGeographicAreaByCentroid", data: Sawbuck.Utilities.toJson(criteria), contentType: "application/json; charset=utf-8", dataType: "json", processData: false, success: function(res) {
            if (_areaID != res.d.GeographicAreaID) {
                _areaID = res.d.GeographicAreaID; Sawbuck.Page.onlyWithinArea(true); Sawbuck.Page.setAreaID(_areaID); ignoreMove = true; if (options.tiles_on) {
                    if (!dontLoadListing)
                        moveOverride = function() { loadTileData(); Sawbuck.Page.loadListings(true, true); }
                    else
                        moveOverride = function() { loadTileData(); } 
                }
                else { clearMarkers(); moveOverride = function() { try { Sawbuck.Page.showLoader(); Sawbuck.Page.loadListings(); } catch (e) { }; } }
                var areaName = res.d.AreaName; if (res.d.AreaTypeID == 5)
                    areaName += " (" + res.d.UspsCity + ", " + res.d.State + ")"; showAreaName(areaName, res.d.CentroidLat, res.d.CentroidLng); var areaPolygon = new Array({ levels: res.d.ModifiedGoogleLevels, points: res.d.ModifiedGooglePolygon }); initializePolygons(areaPolygon, true); fitPolygon(); Sawbuck.Renderer.updateArea(res.d);
            } 
        }, error: function(e, t) { console.log(e); } 
        });
    }
    var teaserTimer; function showAreaName(areaName, lat, lng) {
        clearTimeout(teaserTimer); var areaTeaser = document.getElementById("areaNameTeaser"); areaTeaser.innerHTML = areaName; var areaCenter = map.fromLatLngToContainerPixel(new GLatLng(lat, lng)); var width = $j(areaTeaser).width()
        var height = $j(areaTeaser).height(); var top = areaCenter.y; var left = areaCenter.x; var x_edge = $j(map.getContainer()).width(); var y_edge = $j(map.getContainer()).height(); if ((left + width) > x_edge - 10)
            left = (x_edge - width - 20); if ((top + height) > y_edge - 10)
            top = (y_edge - height - 50); if (top < 0) top = 30; if (left < 0) left = 30; areaTeaser.style.top = top + "px"; areaTeaser.style.left = left + "px"; $j("#areaNameTeaser").fadeIn("slow"); teaserTimer = setTimeout(function() { $j("#areaNameTeaser").fadeOut(); }, 2000);
    }
    function initializePolygons(polygons, forceReload, color) {
        var colors = _polygonColors; if (_polygon_added && !forceReload)
            return false; if (_polygon_added && forceReload) { _polygons.each(function(s) { s.shape.remove() }); _polygons = new Array(); }
        if (!polygons.length || !polygons[0])
            return false; for (var i = 0; i < polygons.length; i++) {
            var selectedColor = colors[color || i % colors.length]; if ($j(".polygon.colorBox") && $j(".polygon.colorBox").length)
                $j(".polygon.colorBox")[i].style.backgroundColor = selectedColor; var polygon = { shape: new SPolygon(map, polygons[i].points, polygons[i].levels, (polygons[i].color ? polygons[i].color : selectedColor), 2, 0.06), id: polygons[i].AreaID }; polygon.shape.add(); _polygons.push(polygon);
        }
        _polygon_added = true; return true;
    }
    function cleanUpPolygons() {
        for (var x = 0; x < _areas.length; x++) {
            var area = _areas[x]; if (!area.isVisible())
                area.disableTracking(); else
                area.enableTracking();
        } 
    }
    function clearPolygons() {
        _polygons.each(function(s) { s.shape.remove() }); while (_areas.length)
            _areas.pop().remove();
    }
    function loadPolygons(criteria, countOnly, forceRefresh) {
        if (!criteria)
            criteria = Sawbuck.Page.getCriteria(); if (_padded_bounds) {
            if (_areas.length <= 1) { criteria["Big"] = true; forceRefresh = true; }
            else if (countOnly && !Sawbuck.Utilities.isSame(criteria, options.criteria)) { criteria["Big"] = false; }
            else if (this.withinBounds() && _viewable_area_type_ID == getAreaTypeID() && !forceRefresh) { cleanUpPolygons(); return false; }
            else { criteria["Big"] = true; forceRefresh = true; if (_viewable_area_type_ID != getAreaTypeID()) { clearPolygons(); } } 
        }
        options.criteria = Sawbuck.Utilities.cloneObject(criteria); if (criteria["BathroomsMax"] === undefined || criteria["BedroomsMax"] === undefined)
            return false; var points = getBounds(forceRefresh, criteria["Big"]); criteria["LatitudeMin"] = points.latMin; criteria["LatitudeMax"] = points.latMax; criteria["LongitudeMin"] = points.lngMin
        criteria["LongitudeMax"] = points.lngMax; criteria["Big"] = points.big; criteria["AreaTypeID"] = _fixed_area_type || getAreaTypeID(); if (_no_update || !Sawbuck.Page.polygonsOn()) { return false; }
        else
            _no_update = true; _viewable_area_type_ID = getAreaTypeID(); Sawbuck.Page.showLoader(); $j.ajax({ type: "POST", url: "/service/WebService.asmx/GetSiblingAreasByLatLng", data: Sawbuck.Utilities.toJson(criteria), contentType: "application/json; charset=utf-8", dataType: "json", processData: false, success: function(data) {
                if (_viewable_area_type_ID != getAreaTypeID()) { _no_update = false; loadPolygons(); }
                else
                    renderPolygons(data);
            }, error: function() { _no_update = false; } 
            });
    }; function renderPolygons(data) {
        var areas = data.d; if (areas.length >= 1 && !areas[0].name && _areas) {
            for (var x = 0; x < areas.length; x++) {
                var thisArea = _areas.find(function(a) { return a.areaData_.id == areas[x].id }); if (thisArea)
                    thisArea.icon_.edit(areas[x].count.format(0, ","));
            } 
        }
        else {
            clearPolygons(); for (var x = 0; x < areas.length; x++) {
                var area = new SArea(areas[x], map, SAreaColors.orange); _areas.push(area); if (!area.isVisible())
                    area.disableTracking();
            } 
        }
        Sawbuck.Page.hideLoader(); _no_update = false; delete options.criteria["Big"]; options.criteria["Serial"]++;
    }; function fitPolygon(id, force) { id = id || 0; if (_polygons.length) _polygons[id].shape.fitAll(force); Sawbuck.SearchManager.setValue("map_center", [map.getCenter().lat(), map.getCenter().lng()]); Sawbuck.SearchManager.setValue("zoom", [map.getZoom()]); currentZoom = map.getZoom(); return; }; return { init: function(opts) { init(opts); }, loadTileData: loadTileData, initializeMarkers: initializeMarkers, getMarker: function(listingID) {
        if (_markers)
            return _markers.find(function(l) { return listingID == l.ref_id; }) || _markers.find(function(l) { return listingID == l.listing_id; }); else
            return false;
    }, highlightMarker: highlightMarker, moveHighlightedMarkerTo: function(coords) {
        if (!_highlightedMarker)
            return false; _highlightedMarker.setLatLng(coords); _highlightedMarker.show(); return true;
    }, hideHighlightedMarker: function(listingID) {
        if (_markers) { var marker = _markers.find(function(l) { return listingID == l.ref_id; }) || _markers.find(function(l) { return listingID == l.listing_id; }); _highlightedMarkers[marker.highlightID || 0].hide(); }
        else
            return false;
    }, getMarkers: function() { return { h: _highlightedMarkers, m: _markers }; }, initializePolygons: initializePolygons, loadPolygons: loadPolygons, updateTiles: updateTiles, switchArea: switchArea, fitAllMarkers: fitAllMarkers, fitPolygon: fitPolygon, getBounds: getBounds, getListings: getListings, zoomTo: function(point, level) { map.panTo(point, level); }, unload: function() { _data = null; _listings = null; GUnload(); }, getMap: function() { return map; }, getIcon: function(rating) { return _icons[rating]; }, getDefaultIcon: function() { return _icons[0]; }, resizeBy: function() { return map.checkResize(); }, clearMarkers: clearMarkers, clearPolygons: clearPolygons, getMiniBounds: getMiniBounds, drawMiniBounds: drawMiniBounds, polygonOutsideBounds: polygonOutsideBounds, t: function() { return _data; } }
    } (); function AerialMapManager(opts) {
        this.lat_ = opts["lat"]; this.lng_ = opts["lng"]; this.outerDiv_ = opts["div"]; this.icon_ = opts["icon"]; this.navItems_ = opts["navItems"]; this.point_ = { google: new GLatLng(this.lat_, this.lng_), ve: new VELatLong(this.lat_, this.lng_) }
        this.modes_ = { sat: null, street: null, birds: null, active: null }
        this.mapDivs_ = { sat: this.newDiv_(this.outerDiv_), street: this.newDiv_(this.outerDiv_), birds: this.newDiv_(this.outerDiv_) }
        this.maps_ = { sat: null, street: null, birds: null }
        this.maps_.sat = new GMap2(this.mapDivs_.sat); this.maps_.sat.setMapType(G_HYBRID_MAP); this.maps_.sat.setCenter(this.point_.google, 18); this.maps_.sat.setUIToDefault(); this.mapDivs_.sat.style.visibility = "visible"; this.marker_ = new GMarker(this.point_.google, { icon: this.icon_ }); this.maps_.sat.addOverlay(this.marker_); this.modes_.sat = true; this.navItems_[0].className = "current"; this.modes_.active = "sat"; this.mapDivs_.birds.id = '__birdsEyeViewDiv'; this.maps_.birds = new VEMap(this.mapDivs_.birds.id); this.maps_.birds.LoadMap(this.point_.ve, 17, VEMapStyle.BirdseyeHybrid); this.onObliqueEnterHandler_ = Sawbuck.Utilities.createDelegate(this, this.enterBirdseye); this.maps_.birds.AttachEvent("onobliqueenter", this.onObliqueEnterHandler_); var client = new GStreetviewClient(); client.getNearestPanorama(this.point_.google, Sawbuck.Utilities.createDelegate(this, this.testStreetView)); var resize = Sawbuck.Utilities.createDelegate(this, this.onResize); window.onresize = resize;
    }
    var degreesPerRadian = 180.0 / Math.PI; var radiansPerDegree = Math.PI / 180.0; AerialMapManager.prototype = { test: function() { }, newDiv_: function(parent) { var div; div = document.createElement("div"); div.style.position = "absolute"; div.style.top = "0px"; div.style.left = "0px"; div.style.width = "100%"; div.style.height = parent.style.height; div.style.visibility = "hidden"; parent.appendChild(div); return div; }, bearing: function(from, to) {
        var lat1 = from.latRadians(); var lon1 = from.lngRadians(); var lat2 = to.latRadians(); var lon2 = to.lngRadians(); var angle = -Math.atan2(Math.sin(lon1 - lon2) * Math.cos(lat2), Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(lon1 - lon2)); if (angle < 0.0)
            angle += Math.PI * 2.0; angle = angle * degreesPerRadian; angle = angle.toFixed(1); return parseInt(angle);
    }, testStreetView: function(results) {
        if (results.code != 200) { return; }
        this.maps_.street = {}; this.maps_.street = new GStreetviewPanorama(this.mapDivs_.street); GEvent.bind(this.maps_.street, "error", this, this.handleStreetViewError); var POV = { yaw: this.bearing(results.location.latlng, this.point_.google) }; this.maps_.street.setLocationAndPOV(results.location.latlng, POV); this.modes_.street = true; this.navItems_[1].className = "active"; this.switchMode("street");
    }, handleStreetViewError: function(error) { this.modes_.street = false; this.navItems_[1].className = "inactive"; this.modes_.birds ? this.switchMode("birds") : this.switchMode("sat"); }, enterBirdseye: function() { if (!this.maps_.birds.IsBirdseyeAvailable()) { this.dispose(); } else { var pushpin = new VEShape(VEShapeType.Pushpin, this.point_.ve); pushpin.SetCustomIcon(this.icon_.printImage); this.maps_.birds.AddShape(pushpin); this.maps_.birds.DetachEvent("onobliqueenter", this.onObliqueEnterHandler_); this.modes_.birds = true; this.navItems_[2].className = "active"; if (this.modes_.active != "street") this.switchMode("birds"); } }, dispose: function() { if (this.maps_.birds) { this.maps_.birds.Dispose(); this.maps_.birds = null; } }, onResize: function() { if (this.modes_.sat) this.maps_.sat.checkResize(); if (this.modes_.street) this.maps_.street.checkResize(); if (this.modes_.birds) { var h = this.outerDiv_.clientHeight; var w = this.outerDiv_.clientWidth; this.maps_.birds.Resize(w, h); } }, getModes: function() { return this.modes_; }, switchMode: function(mode) {
        switch (mode) {
            case "sat": if (this.modes_.sat) { this.mapDivs_.sat.style.visibility = "visible"; this.mapDivs_.street.style.display = "none"; this.mapDivs_.street.style.zIndex = -1; this.mapDivs_.birds.style.visibility = "hidden"; this.modes_.active = "sat"; if (this.navItems_[0]) this.navItems_[0].className = "current"; this.modes_.street && this.navItems_[1] ? this.navItems_[1].className = "active" : this.navItems_[1].className = "inactive"; this.modes_.birds && this.navItems_[2] ? this.navItems_[2].className = "active" : this.navItems_[2].className = "inactive"; }
                break; case "street": if (this.modes_.street) { this.mapDivs_.sat.style.visibility = "hidden"; this.mapDivs_.street.style.display = "block"; this.mapDivs_.street.style.zIndex = 1; this.mapDivs_.birds.style.visibility = "hidden"; this.modes_.active = "street"; this.modes_.sat && this.navItems_[0] ? this.navItems_[0].className = "active" : this.navItems_[0].className = "inactive"; if (this.navItems_[1]) this.navItems_[1].className = "current"; this.modes_.birds && this.navItems_[2] ? this.navItems_[2].className = "active" : this.navItems_[2].className = "inactive"; }
                break; case "birds": if (this.modes_.birds) { this.mapDivs_.sat.style.visibility = "hidden"; this.mapDivs_.street.style.display = "none"; this.mapDivs_.street.style.zIndex = -1; this.mapDivs_.birds.style.visibility = "visible"; this.modes_.active = "birds"; this.modes_.sat && this.navItems_[0] ? this.navItems_[0].className = "active" : this.navItems_[0].className = "inactive"; this.modes_.street && this.navItems_[1] ? this.navItems_[1].className = "active" : this.navItems_[1].className = "inactive"; if (this.navItems_[2]) this.navItems_[2].className = "current"; }
                break;
        } 
    } 
    }