﻿// JScript File
var map = null;
var gdir = null;
var markers = new Array();
var overlay = new Array();
var htmls = new Array;
var displayIDs = new Array();
var clear = false;
var noZoom = false;
var tooltip = document.createElement("div");
var orgHeight;
var async_count = 0;
var startTime = 0;
var statusMsgs = false;
var locked = "N";
var reloaded = "N";
var cityIndex = -1;
var reportCounter = 0;
var reasons = [];
var to_htmls = [];
var from_htmls = [];
var myPano = null;
var svOverlay = null;
var notFoundWarning = "The address you selected is not in a neighborhood currently serviced by Peekacity, or may only be available to members of Peekacity. To become of member, go to login and sign up now. If you have questions about Peekacity membership, please call us at 888-810-7118. To view a list of currently supported neighborhoods click on the link in the Neighborhood area to the left.";
var notFoundWarningMember = "The address you selected is not in a neighborhood currently serviced by Peekacity. To view a list of currently supported neighborhoods click on the link in the Neighborhood area to the left.";
var mapExtension = null;
var gOverlays = null;
var circle;

showLoadingMessage(true);
            
function setupDragZoom() 
{
    //Doesn't work right 
    if (navigator.appName == "Microsoft Internet Explorer")
        return;

    // first set of options is for the visual overlay.
    var boxStyleOpts = 
        {
            opacity: .2,
            border: "2px solid red"
        };

    /* second set of options is for everything else */
    var otherOpts = 
        {
            buttonHTML: "<img src='images/zoom-button.png' />",
            buttonZoomingHTML: "<img src='images/zoom-button-activated.png' />",
            buttonStartingStyle: {width: '24px', height: '24px'},
            overlayRemoveTime: 1000
        };

    map.addControl(new DragZoomControl(boxStyleOpts, otherOpts, {}), new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(80, 36)));      
}

function setupAds()
{
    var publisher_id = "pub-7073758642655729"; 
    var adPos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(7, 20)); 

    adsManagerOptions = {
    maxAdsOnMap : 2,
    style: 'adunit',
    position: adPos
    };

    adsManager = new GAdsManager(map, publisher_id, adsManagerOptions);
    adsManager.enable();    
}

//Attempting to match the existing google buttons and blend in with them
function setupStreetviewToggle(bDisplayGoogleEarth)
{
    function MyStreetViewControl() {}
    MyStreetViewControl.prototype = new GControl();   
    MyStreetViewControl.prototype.initialize = function(map) 
    {               
        var outsideDiv = document.createElement("div");
        outsideDiv.style.border = '1px solid black';
        outsideDiv.style.position = 'absolute'; 
        outsideDiv.style.backgroundColor = 'white'; 
        outsideDiv.style.textAlign = 'center'; 
        outsideDiv.style.width = '7em'; 
        outsideDiv.style.cursor = 'pointer'; 
        outsideDiv.style.right = '10.2em';
                
        var container = document.createElement("div");
        container.innerHTML = 'Streetview';
        container.style.borderStyle = 'solid';
        container.style.borderColor = 'rgb(52, 86, 132) rgb(108, 157, 223) rgb(108, 157, 223) rgb(52, 86, 132)';
        container.style.borderWidth = '1px'; 
        container.style.fontSize = '12px';
        container.style.fontWeight = 'bold';
        outsideDiv.appendChild(container);
             
        GEvent.addDomListener(outsideDiv, "click", function() 
        {
            if (svOverlay == null)
            {
                svOverlay = new GStreetviewOverlay();
                map.addOverlay(svOverlay);
            }
            else
            {
                map.removeOverlay(svOverlay);
                svOverlay = null;
            }
        });
      
      map.getContainer().appendChild(outsideDiv);
      return outsideDiv;
    }

    // By default, the control will appear in the top left corner of the
    // map with 7 pixels of padding.
    MyStreetViewControl.prototype.getDefaultPosition = function() 
    {
        if (bDisplayGoogleEarth)
            return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(338, 7));  //272
        else
            return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(272, 7));  //206
    }
    map.addControl(new MyStreetViewControl());    
}
    
function load() 
{    
    var displayGoogleEarth = false;
    var info = document.getElementById('lblPeekaCityInfo');
    if (info != null && info.innerHTML.length > 0)
    {
        document.getElementById('divFloatInfo').style.visibility = 'visible';
        document.getElementById('divFloatInfo').style.height = document.getElementById("map").style.height;        
    }
            
    if (GBrowserIsCompatible()) 
    {
        //map = new GMap2(document.getElementById("map"));
        map = new google.maps.Map(document.getElementById("map"));
        map.setUIToDefault();
        gdir = new GDirections(map, document.getElementById("directions"));
 
        if (readQueryString("debug").length > 0)
        {
            statusMsgs = true;
            document.getElementById("floatDebug").style.visibility = "visible";
             
            map.addMapType(G_SATELLITE_3D_MAP);
            displayGoogleEarth = true;
            map.addOverlay(new GLayer("org.wikipedia.en"));
        }       
        
        setupDragZoom();
        setupStreetviewToggle(displayGoogleEarth);      
        
        function MyPrintControl() {}
        MyPrintControl.prototype = new GControl();  
        MyPrintControl.prototype.initialize = function(map) 
        {
            var container = document.createElement("div");

            //Print Map Style
            var printMap = document.createElement("img");
            printMap.src='Images/PrintMap.png';
            printMap.title = 'Print Map';
            printMap.height = 32;
            printMap.width = 32;
            container.appendChild(printMap);
            GEvent.addDomListener(printMap, "click", function() 
            {
                validateForm(true);
            });
                    
            //Print Report Style
            var printReport = document.createElement("img");
            printReport.src = 'Images/PrintReport.png';
            printReport.title = 'Print Report';
            printReport.height = 32;
            printReport.width = 32;        
            container.appendChild(printReport);
            GEvent.addDomListener(printReport, "click", function() 
            {
                validateForm(false);
            });            

            map.getContainer().appendChild(container);
            return container;
        }

        // By default, the control will appear in the top left corner of the
        // map with 7 pixels of padding.
        MyPrintControl.prototype.getDefaultPosition = function() 
        {
            return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 32));
        }
        map.addControl(new MyPrintControl());    
        closePan();               
         
        //  ======== Add a map overview ==========
        map.addControl(new GOverviewMapControl(new GSize(150,150)));         
        
        // ====== Array for decoding the failure codes ======
        reasons[G_GEO_SUCCESS]            = "Success";
        reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
        reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
        reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
        reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
        reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
        reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";                
    }
    
    // === catch Directions errors ===
    GEvent.addListener(gdir, "error", function() {
        var code = gdir.getStatus().code;
        var reason="Code "+code;
        if (reasons[code]) 
          reason = reasons[code]
        
        alert("Failed to obtain directions, "+reason);
    });   
    
     // ====== set up marker mouseover tooltip div ======    
    map.getPane(G_MAP_FLOAT_PANE).appendChild(tooltip);
    tooltip.style.visibility="hidden";

    var home = readQueryString("home");
    var propertyID = readQueryString("propertyID");   
    locked = document.getElementById('LockedForm').value;    
    if (document.getElementById('ReloadedForm') != null)
        reloaded = document.getElementById('ReloadedForm').value;
    if ((locked == 'Y') && (document.getElementById('div_butAddToMap') != null))
    {
        document.getElementById('div_butAddToMap').style.visibility = "hidden";
        document.getElementById('butClear').style.visibility = "hidden";                          
    }
    
    var neighborhoodID = document.getElementById('Neighborhood').value;
    if (neighborhoodID.length > 0)
    {
        var ddlCity = document.getElementById("ddlMyCity");
        var selectedItem = document.getElementById("CityID").value;
        //Change the current CityID value to ensure it is selected
        document.getElementById("CityID").value = -1;
        var results = [] 
        results[0] = neighborhoodID;
        results[1] = selectedItem;
        selectHood(results, true);       
    }
    else if (home.length > 0)
    {      
        if (document.getElementById('navArea1_pTimeC_address') != null)
            SetAddress(home);
        lookUpHome(home, null);        
    }
    else if (propertyID.length > 0)
    {
        home = document.getElementById('HomeAddress').value;       
        lookUpHome(home, propertyID);
    }
    else if (document.getElementById('HomeAddress').value != "")
    {
         home = document.getElementById('HomeAddress').value;
         lookUpHome(home, null);
    }
    else
    {
        var ddl = document.getElementById("ddlCity");
        if (ddl.options.length > 2)
        {
            var myCityID = ddl[1].value; 
            PageMethods.GetCityFromHood(myCityID, function(cityName) {
                    if (cityName.length > 0)
                        document.getElementById('neighborhoodLookup').innerHTML = "Neighborhood - " + cityName;
                    else
                        document.getElementById('neighborhoodLookup').innerHTML = "Neighborhood";
                });
        }
        try { map.setCenter(new GLatLng(37.062500, -95.677068), 4); }
        catch (err) {}
        showLoadingMessage(false);   
    }
    
    //Show ads for all guests
    if (document.getElementById('UserId').value == 'Guest') 
        setupAds();
        
    orgHeight = getHeight();
    window.onresize = redo;  
 
}

function computeAngle(endLatLng, startLatLng) 
{
    var DEGREE_PER_RADIAN = 57.2957795;
    var RADIAN_PER_DEGREE = 0.017453;

    var dlat = endLatLng.lat() - startLatLng.lat();
    var dlng = endLatLng.lng() - startLatLng.lng();
    // We multiply dlng with cos(endLat), since the two points are very closeby,
    // so we assume their cos values are approximately equal.
    var yaw = Math.atan2(dlng * Math.cos(endLatLng.lat() * RADIAN_PER_DEGREE), dlat)
             * DEGREE_PER_RADIAN;
    
    return wrapAngle(yaw);
}

function wrapAngle(angle) 
{
    if (angle >= 360) 
        angle -= 360;
    else if (angle < 0) 
        angle += 360;
        
    return angle;
  };
  
  
//Display the streetview for the selected lat/lon
function initializePan(lat, lon, header) 
{
    document.getElementById('headerText').innerHTML = header;
    var pan = document.getElementById("pano");
    pan.style.visibility = 'visible';
    myPano = new GStreetviewPanorama(document.getElementById("flashDiv"));
    GEvent.addListener(myPano, "error", handleNoFlash);   
    myPoint = new GLatLng(lat, lon);
    
    var panoClient = new GStreetviewClient();
    panoClient.getNearestPanoramaLatLng(myPoint, function(panoData) 
        {
            if (panoData != null) 
            {
                var angle = computeAngle(myPoint, panoData);
                myPano.setLocationAndPOV(panoData, {yaw: angle});                
            }
        });           
}

function closePan()
{
    var pan = document.getElementById("pano");
    if (pan != null)
        pan.style.visibility = 'hidden';
    if (myPano != null)
        myPano.remove();
}

//Handle errors trying to display streetview
function handleNoFlash(errorCode) 
{
    var pan = document.getElementById("pano");
    pan.style.visibility = 'hidden';
    if (errorCode == 603) 
    {
        alert("Error: Flash doesn't appear to be supported by your browser");
        return;
    }
    else if (errorCode == 600)
    {
        alert('This area is not currently covered by Streetview.  You can select the <Streetview> button to see which areas are covered (blue outline).');
    }        
}  
    
function getHeight()
{
    var myHeight = 0;
    if (typeof(window.innerHeight) == 'number') 
        myHeight = window.innerHeight;
    else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) 
        myHeight = document.documentElement.clientHeight;
    else if (document.body && (document.body.clientWidth || document.body.clientHeight)) 
        myHeight = document.body.clientHeight;
        
    return myHeight;
}

//Reload the window on a resize event
function redo() 
{   
    var newHeight = getHeight();
    if (orgHeight != newHeight)
    {        
        //Ignore popup warnings bar adjustments. 
        if ((newHeight > (orgHeight -32)) && (newHeight < (orgHeight + 32)))
            return;
        orgHeight = newHeight;
        location.href = location.href;
    }
}

      
//Handle results from a geocode of the home by address
function addAddressToMap(search, response) 
{
    updateStatus("Address lookup results received.", false);
    if (response.Status.code != G_GEO_SUCCESS) 
    {
        var reason="Code " + response.Status.code;
        if (reasons[response.Status.code]) 
            reason = reasons[response.Status.code]
        
        alert("Sorry, we were unable to determine the location on the map.  " + reason);        
        //document.getElementById('tree1').style.visibility = 'visible';
        showLoadingMessage(false);
    }
    else 
    {   
        //Clear out all data first
        map.clearOverlays(); 
        markers.splice(0, markers.length);
        overlay.splice(0, overlay.length);
        htmls.splice(0, htmls.length);
        displayIDs.splice(0, displayIDs.length);
        
        var selectedPlacemark = 0;
        var firstMatch = different(search, response.Placemark[0].address);
        var misMatch = (response.Placemark.length == 1 && firstMatch);
        var forceFirstMatch = document.getElementById('ForceFirstMatch').value;
        
        //Check if the address are duplicates if so pick the first one.
        if ((response.Placemark.length == 2) && (response.Placemark[0].address == response.Placemark[1].address))
            selectedPlacemark = 0;
        else if ((locked == "Y") && (firstMatch == false)) 
            selectedPlacemark = 0;
        else if (response.Placemark.length == 1 && forceFirstMatch == "Y")
            selectedPlacemark = 0;
        else if ((response.Placemark.length > 1) || misMatch)
        {        
            var choiceArea = document.getElementById('replaceMe');
            var innerHTML = '<br /><img align="top" src="images/warning.png" height="20" /><font style="font-family: Arial; " size="2" color="black"><b>Select a location</b></font>';
            innerHTML += '<br /><div style="font-family: Arial; margin: 0 20px 0 20px; color:black; ">';
            if (misMatch)
                innerHTML += 'The exact location could not be found, here is the closest match: ';
            else
                innerHTML += 'Your search produced multiple matches. Please select your preferred location below: ';
            innerHTML += '</div><hr color="gray" noshade />' 
            // Loop through the results
            for (var i=0; i<response.Placemark.length; i++) 
            {
                var p = response.Placemark[i];
                var c = '';
                try { c = p.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName; }
                catch(ex){}	
                innerHTML += "<br />&nbsp;&nbsp;"+(i+1)+": <a href='javascript:processResults(" + p.Point.coordinates[1] + "," + p.Point.coordinates[0] + ", \"" + p.address + "\", \"" + c + "\")'>"+ p.address + "</a>";
            }           
            choiceArea.innerHTML = innerHTML;
            document.getElementById('floatingChoices').style.visibility = "visible";           
            //document.getElementById('div_floatCancelButton').style.visibility = "visible";
            showLoadingMessage(false);
            return false;
        }
        var place = response.Placemark[selectedPlacemark];
        var city;
        try { city = place.AddressDetails.Country.AdministrativeArea.Locality.LocalityName; }
        catch(ex){}	           
        if (city == null || city.length == 0)
        {
            try { city = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName; }
            catch(ex){}	           
        }
        
        if (place.address == "Chicago, IL, USA")
            processResults(41.879535, -87.627, place.address, city);
        else
            processResults(place.Point.coordinates[1], place.Point.coordinates[0], place.address, city);
    }    
    updateStatus("Address lookup complete.", false);
}

//Clear the floating choice list
function clearFloat()
{
   if (document.getElementById('floatingChoices'))
        document.getElementById('floatingChoices').style.visibility = 'hidden';
   
   if (document.getElementById('floatingCitySelect'))
        document.getElementById('floatingCitySelect').style.visibility = 'hidden';
   
   if (document.getElementById('div_floatCancelButton'))
        document.getElementById('div_floatCancelButton').style.visibility = 'hidden';
        
   if (document.getElementById('div_floatCityCancelBut'))
        document.getElementById('div_floatCityCancelBut').style.visibility = 'hidden';

   if (document.getElementById('div_floatCityOKBut'))
        document.getElementById('div_floatCityOKBut').style.visibility = 'hidden';
        
}
        
function processResults(lat, lon, addr, city)
{
    document.getElementById('tree1').style.visibility = 'hidden';
    document.getElementById('divAmenities').style.backgroundImage = 'url(images/searching.gif)';
    if (document.getElementById("CityName") != null)
        document.getElementById("CityName").value = city;
        
    clearFloat();           
    var point = new GLatLng(lat, lon);                
    var results = getCityInfo(lat, lon, addr, city).split(',');
    var maxDistance = getFilterValue("maxDistance").value;
    var zoomLevel = 15;
    //We are not using fixed user prefs then set by density rating
    if (document.getElementById('UserPrefs').value == "N") 
    {               
        if (results[2] > 350)
        {
            maxDistance = .58;
            zoomLevel = 15;
        }
        else if (results[2] > 220)    
        {
            maxDistance = 1.5;
            zoomLevel = 14;
        }       
        else if (results[2] > 100)
        {
            maxDistance = 1.5;
            zoomLevel = 14;
        }
        else
        {
            maxDistance = 3.0;        
            zoomLevel = 13;     
        }
        
        setFilterValue("maxDistance", maxDistance);        
        updateStatus('Using density ratings for distance and zoom: ' + maxDistance + ', ' + zoomLevel, false);
    }
//    else if (locked == 'Y')
//    {
//        if ((maxDistance > .82) || (maxDistance.length == 0))
//        {
//            maxDistance = .82
//            getFilterValue("maxDistance").value = "0.82";
//        }
//    }
    if (isNaN(maxDistance))
    {
        maxDistance = 0.72;        
        getFilterValue("maxDistance").value = "0.72";
        alert("The default distance of 0.72 miles is being used since a non-numeric entry was entered.");
    }
    var maxEntries = getFilterValue("maxEntries").value;
    var getOnePerCat = getFilterValue("onePerCategory").checked;
    
    //Google is throwing an error here..
    try 
    { 
        map.setCenter(new GLatLng(lat, lon), zoomLevel);         
        DrawCircle();
    }
    catch (err) {}
    
    document.getElementById('HomeLatitude').value=lat;
    document.getElementById('HomeLongitude').value=lon;
    var home = addr.replace(', USA', '');
    document.getElementById('HomeAddress').value = home;
    if (document.getElementById('navArea1_pTimeC_address') != null)
        SetAddress(home);
        
    SetCookie("HomeAddress", lat + "_" + lon , null);
    SetCookie("HomeName", home, null);
    createHomeMarker(point, home, "house", home);
    
    //Increment the async count for each process about to be started...
    //async_count++;
    async_count++;         
    async_count++;          
   
    //Find the neighborhood and select and draw polygon
    selectHood(results, false);
    
    //Reset the category tree
    cleanAmenities(lat, lon, null, false, maxDistance);
     
    //Add map and tree items        
    PageMethods.BuildItemListByLocation(maxDistance, lat, lon, maxEntries, getOnePerCat, onComplete);       
    
    //Find the Ward the location is in
    PageMethods.GetWard(lat, lon, selectWard);         
}

 // ===== list of words to be standardized =====
var standards = [   ["road","rd"],   
                    ["street","st"], 
                    ["avenue","ave"], 
                    ["av","ave"], 
                    ["drive","dr"],
                    ["saint","st"], 
                    ["north","n"],   
                    ["south","s"],    
                    ["east","e"], 
                    ["west","w"],
                    ["expressway","expy"],
                    ["parkway","pkwy"],
                    ["terrace","ter"],
                    ["turnpike","tpke"],
                    ["highway","hwy"],
                    ["lane","ln"]
               ];


// ===== convert words to standard versions =====
function standardize(a) 
{
    for (var i=0; i<standards.length; i++) 
    {
        if (a == standards[i][0])  
            a = standards[i][1];
    }
  
    return a;
}

// Removes leading whitespaces
function LTrim( value ) 
{	
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");	
}

// Removes ending whitespaces
function RTrim( value ) 
{	
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");	
}

// Removes leading and ending whitespaces
function trim( value ) 
{	
	return LTrim(RTrim(value));	
}


// ===== check if two addresses are sufficiently different =====
function different(a,b) 
{
    //Clear off any whitespace.
    a = trim(a);
    b = trim(b);
    // only interested in the bit before the first comma in the reply
    var c = b.split(",");
    b = c[0];
    
    // convert to lower case
    a = a.toLowerCase();
    b = b.toLowerCase();
    
    // remove apostrophies
    a = a.replace(/'/g ,"");
    b = b.replace(/'/g ,"");
    
    // replace all other punctuation with spaces
    a = a.replace(/\W/g," ");
    b = b.replace(/\W/g," ");
    
    // replace all multiple spaces with a single space
    a = a.replace(/\s+/g," ");
    b = b.replace(/\s+/g," ");
    
    // split into words
    awords = a.split(" ");
    bwords = b.split(" ");
    
    // perform the comparison
    var nonMatch = 0;
    for (var i=0; i<bwords.length; i++) 
    {
        if (standardize(awords[i]) != standardize(bwords[i]))
        {
            //There may have been an extra directional term let's allow for that...
            if ((i+1 < bwords.length) && (standardize(awords[i]) != standardize(bwords[i + 1])))
                nonMatch++;
        }
    }

    return (nonMatch > 1);
}

//A Ward was selected by entering in an address
function selectWard(results)
{
    updateStatus("Selecting Ward.", false);
    //We could not find the ward
    if (results == null)
    {
        showLoadingMessage(false);
        return;
    }
    
    //Load the selected items onto the map...
    var key = "chk_" + results.CategoryID;
    var box = document.getElementById(key);
    var parentID = "category_" + results.CategoryID;
    var nodeID = "amenities_" + results.Id;
    displayIDs[nodeID] = results.DisplayID;
    var isChecked = false;
    
    //If the entry doesn't exist yet add it now...
    if (!document.getElementById(nodeID))
    {    
        var treeIcon = "Markers.aspx?type=png&count=" + results.DisplayID + "&category=blank";
        var chkHTML = "<input type='checkbox' ";
        if (isChecked)
            chkHTML += " CHECKED ";
        chkHTML += "class='chk' id='" + nodeID + "' name='AO' onclick='ac(this)' />";
        chkHTML += results.DisplayID + ' - ' + results.Name;           
        var testHTML = "<span title='" + results.Name + "' onmouseover='st(\"" + nodeID +"\")' onmouseout='ht()' style='cursor: pointer;' onclick=';sn(\"" + nodeID +"\")'>" + chkHTML +"</span>";
        ob_t2_AddNew(parentID, nodeID, testHTML, false, treeIcon, null);    
        
        collapseTree();    
        
        var firstTreeNode = ob_getFirstNodeOfTree();  
        ob_t26(firstTreeNode.id);            
    }    
}        


//A Neighborhood was selected by entering in an address
function selectHood(results, noDecode)
{
    updateStatus("Selecting neighborhood.", noDecode);
    //We could not find the city
    if (results[0] == -1)
    {
        //Clear out the cookies 
        SetCookie("HomeAddress", "", null);
        SetCookie("HomeName", "", null);
        SetCookie("neighborhoodID", "-1", null);
        showLoadingMessage(false);
        //Only show the warning if you are not logged in.
        if (document.getElementById('UserId').value == 'Guest') 
            alert(notFoundWarning);
        else if ((document.getElementById("CityName") != null) && (document.getElementById("CityName").value != "Chicago"))        
            alert(notFoundWarningMember);
            
        if (document.getElementById('navArea1_pTimeC_address') != null)
        {
            var address = document.getElementById('navArea1_pTimeC_address').value
            var user = document.getElementById('UserId').value;
            var ip = document.getElementById('IPAddress').value;
            PageMethods.SendAddressFailedMail(user, address, ip);
        }
        var ddl = document.getElementById("ddlCity");    
        ddl.selectedIndex = ddl.options.length - 1;
        return;
    }
    
    //Get the new city selection
    if (document.getElementById("CityID").value != results[1])
    {
        document.getElementById("CityID").value = results[1];
        var ddlCity = document.getElementById("ddlMyCity");
        for (var i=1;i<ddlCity.options.length;i++)
        {
            var opt = ddlCity.options[i];
            if (opt.value == results[1])
            {
                ddlCity.selectedIndex = i;
                break;
            }
        }
        loadNeighborHoods(results[0]);
    }
    else
    {
        ddl = document.getElementById("ddlCity");  
        var bFound = false;  
        for (i = 1; i < ddl.options.length; i++) 
        {
            opt = ddl.options[i];
            if (opt.value == results[0])
            {
                bFound = true;
                ddl.selectedIndex = i;
                cityIndex = i;
                break;
            }
        }
    }
    noZoom = !noDecode;
      
    //We are now tracking the neighborhood hits 
    var UserId = document.getElementById('UserId').value;
    ip = document.getElementById('IPAddress').value;
    PageMethods.AuditNeighborhood(UserId, results[0], ip);
    
    //Draw polygon for area
    if (noDecode == false)
        PageMethods.GetLocationInformation(results[0], decodeLine);
    else
    {
        //Coming in from new page
        updateStatus("Getting the new city selection", false);  
        var id = results[0];
        var getOnePerCat = getFilterValue("onePerCategory").checked;
        PageMethods.GetCityFromHood(id, function(neighborhoodResults) 
        {
            if (neighborhoodResults.length > 0)
                document.getElementById('neighborhoodLookup').innerHTML = "Neighborhood - " + neighborhoodResults;
            else
                document.getElementById('neighborhoodLookup').innerHTML = "Neighborhood";
        });
  
        //Increment the async count for each process about to be started.
        async_count++;
        async_count++;
        async_count++;
    
        //Draw polygon for area
        PageMethods.GetLocationInformation(id, function(locationResults) 
            {
                decodeLine(locationResults);
                
                //Reset the categories in the tree
                cleanAmenities(locationResults.Latitude, locationResults.Longitude, id, false, locationResults.MaxDistance);            
                  
                //Add map and tree items
                PageMethods.GetMapItems(id, getOnePerCat, onComplete);     
            }
        );
    
        //Set the cookie with the selected ID
        document.cookie = "neighborhoodID="+id+"; path=/";                
    }       
}

function handleKeyPress(e)
{
    var key=e.keyCode || e.which;
    if (key==13)
    {
        var address = document.getElementById('navArea1_pTimeC_address').value;
        lookUpHome(address, null);
        return false;
    }
}

function lookUpHome(address, propertyID) 
{       
    //Let's reset these values now...If we are locked the amenities are already selected.
    if ((locked != 'Y') && (reloaded != 'Y'))
        document.getElementById('SelectedAmenities').value=checked_list('amenities_');
    document.getElementById('SelectedCategories').value=checked_list('chk_');
    
    updateStatus("Looking up address", true);
    showLoadingMessage(true);
    
    if (propertyID != null)
    {
        PageMethods.GetLatLon(propertyID, function (results)
            {
                //If we don't already have it try looking it up now...
                if (results.length == 0)
                {
                    var geocoder = new GClientGeocoder();
                    geocoder.getLatLng(address, function(point) 
                        {
                            if (point)                
                            {
                                var lat = point.y;
                                var lon = point.x;
                            
                                processResults(point.y, point.x, address, '');                    
                            }
                        }
                    );    
                }
                else
                    processResults(results[0], results[1], address, '');                       
            }  
        );         
    }       
    else if (address.length == 0)
    {
        var marker = markers['house'];
        if (marker != null)
        {
            tooltip.style.visibility="hidden";
            map.removeOverlay(marker);
            markers['house'] = null;
        }
        document.getElementById('HomeAddress').value='';
        document.getElementById('HomeLatitude').value=0;
        document.getElementById('HomeLongitude').value=0;
        if (document.getElementById('navArea1_pTimeC_address') != null)
            SetAddress('');
        SetCookie("HomeAddress", '', null);
        SetCookie("HomeName", '', null);
        showLoadingMessage(false);
    }
    else
    {
        var geocoder = new GClientGeocoder();
        geocoder.getLocations(address, function (result)
            {
                addAddressToMap(address, result);
            }
        );
        document.getElementById('HomeAddress').value=address;
    
        //Audit the lookup
        var UserId = document.getElementById('UserId').value;
        var ip = document.getElementById('IPAddress').value;
        PageMethods.AuditLookup(UserId, address, ip);
    }
}

function updateFilters(address)
{
    var maxDistance = getFilterValue("maxDistance").value;
    //If we changed the value then stop using the density rating
    if ((locked == 'Y') && (maxDistance > .82))
        alert("A search radius of .82 is the maximum supported.");
    else
        document.getElementById('UserPrefs').value = 'Y'
        
    if (address.length > 0)
        lookUpHome(address, null);
    else
        citySelect();
}

function saveFilters()
{   
    //Get current filter values...    
    var maxDistance = getFilterValue("maxDistance").value;
    var maxEntries = getFilterValue("maxEntries").value;
    var getOnePerCat = getFilterValue("onePerCategory").checked;    
    var radiusDisplay = getFilterValue("radiusDisplay").checked;    
    
    
    //Get logged on user id
    var userID = document.getElementById("UserId").value;
    PageMethods.SaveFilter(userID, maxDistance, maxEntries, getOnePerCat, radiusDisplay, applyFilter);          
}

//Apply the new filter
function applyFilter()
{
    updateFilters(document.getElementById('navArea1_pTimeC_address').value);
}


//Validate that at least on amenity has been selected 
//and an address or neighborhood has been selected
function validateForm(showMap)
{
    clearFloat();
    document.getElementById('SelectedAmenities').value=checked_list('amenities_');
       
    //Check if at least one amenity is selected
    if (document.getElementById('SelectedAmenities').value.length == 0)
    {
        alert("Please make sure you have selected a neighborhood (or home) and one or more amenities first.");
        return false;
    }
    
    //Check neighborhood selection
    var ddl = document.getElementById("ddlCity");
    if ((ddl.selectedIndex == 0) && (document.getElementById('HomeAddress').value == ""))
    {
        alert("Please make sure you have selected a neighborhood (or home) and one or more amenities first.");
        return false;
    }
    
    runReport(showMap);
    return false;
 }
 
 //Display the wiki for the selected neighborhood
 function validateWiki()
 { 
    var ddl = document.getElementById("ddlCity");
    if (ddl.selectedIndex == 0)
    {
        alert("Please make sure you have selected a neighborhood.");
        return false;
    }
    var myCityID = ddl[ddl.selectedIndex].value; 
    var cityDisplay = ddl[ddl.selectedIndex].text;
    PageMethods.WikiLookup(myCityID, displayWiki);
}
 
  //Let's display the actual report now...
 function displayWiki(results)
 {  
    if (results.length == 0)
    {
        alert("There is currently no wiki entry available for the selected neighborhood.");
        return;
    }   
    
    var mapWindow = window.open(results,'WikiDisplay','');
    if (!mapWindow)
        location.href = location.href.replace(/Default.aspx/i, 'Help/popup.aspx');    
 }
 
 //Fix the predefined template...
 function runCustomReport(reportID)
 {      
    var ddl = document.getElementById("ddlCity");
    if ((ddl.selectedIndex == 0) && (document.getElementById('HomeAddress').value == ""))
    {
        alert("Please make sure you have selected a neighborhood or home first.");
        return false;
    }
  
    document.getElementById('waitReport').style.visibility = "visible";    
    ddl = document.getElementById("ddlCity");
    var userID = document.getElementById('UserId').value;
    var reportUserId = document.getElementById('ReportUserID').value;
    if (reportUserId.length > 0)
        userID = reportUserId;
    var myCityID = ddl[ddl.selectedIndex].value;
    var lat = document.getElementById('HomeLatitude').value;
    var lon = document.getElementById('HomeLongitude').value;
    var addr = document.getElementById('HomeAddress').value;
    var center = map.getCenter();
    var centerString = center.y + ':' + center.x;
    var zoom = map.getZoom();
    //Get page settings incase templates are not set...
    var maxDistance = getFilterValue("maxDistance").value;
    var maxEntries = getFilterValue("maxEntries").value;
    var getOnePerCat = getFilterValue("onePerCategory").checked;    
    
    PageMethods.PDFReportTemplate(reportID, addr, centerString, lat, lon, myCityID, zoom, maxDistance, maxEntries, getOnePerCat, userID, displayReport);
 }
 
 //See if we can run the map report from here...
 function runReport(showMap)
 {
    var bCustomReport = false;
    if (showMap == null)
    {
        bCustomReport = true;
        showMap = true;
    }
        
    if (showMap && map.getZoom() < 13)
    {
        alert("You must zoom in to display the legend map.");
        return;        
    }
    
    var reportID = readQueryString('ReportID');
    var userID = document.getElementById('UserId').value;
    var reportUserId = document.getElementById('ReportUserID').value;
    if (reportUserId.length > 0)
        userID = reportUserId;    
    var amenities = checked_list('amenities_').replace(/amenities_/g, "");
    var homeLocation = document.getElementById('HomeLatitude').value + ":" + document.getElementById('HomeLongitude').value;
    var addr = document.getElementById('HomeAddress').value;
    var center = map.getCenter();
    var centerString = center.y + ':' + center.x;
    var zoom = map.getZoom();
    var mapDisplay = "Y";
    if (!showMap)
        mapDisplay = "N";
    
    if (bCustomReport)
        PageMethods.PDFReport(reportID, addr, '', amenities, mapDisplay, centerString, homeLocation, zoom, userID, customReport);
    else
        PageMethods.PDFReport(reportID, addr, '', amenities, mapDisplay, centerString, homeLocation, zoom, userID, displayReport);
    return;
    
   }
 
 //Let's display the actual report now...
 function displayReport(results)
 {   
    if (results == "")
    {
        document.getElementById('waitReport').style.visibility = "hidden";  
        alert("Unable to generate a report for the selected location and settings.");
        return;
    }
    
    var userID = document.getElementById('UserId').value;
    if (userID == 'Guest')
    {
        alert('This feature is only available to registered users.');
        return;
    }
    
    var url = 'PDF/PrintOptions.aspx?NoOptions=true&ReportId=' + results;
    if (locked == "Y")
        url += "&Locked=Y";
    
    reportCounter++;
    var mapWindow = window.open(url,'ReportMap' + reportCounter,'');
    if (!mapWindow)
    {
        document.getElementById('waitReport').style.visibility = "hidden";  
        location.href = location.href.replace(/Default.aspx/i, 'Help/popup.aspx');            
    }
    else if (mapWindow.opener == null) 
        mapWindow.opener = self;
 }
 
  //Let's build the report options now
 function customReport(results)
 {  
    var userID = document.getElementById('UserId').value;
    if (userID == 'Guest')
    {
        alert('This feature is only available to registered users.');
        return;
    }
    
    var url = 'PDF/PrintOptions.aspx?ReportId=' + results;
    if (locked == "Y")
        url += "&Locked=Y";
        
    reportCounter++;
    var mapWindow = window.open(url,'ReportMap' + reportCounter,'');
    if (!mapWindow)
        location.href = location.href.replace(/Default.aspx/i, 'Help/popup.aspx');
 }

//Draw a circle around the radius of the search area...
function DrawCircle()
{
	if (circle) 
		map.removeOverlay(circle);
		   
    //Check if we are displaying the radius or not
	if (getFilterValue("radiusDisplay").checked == false)
	    return;
	    
    var circleRadius = getFilterValue("maxDistance").value;
	var center = map.getCenter();
	var bounds = new GLatLngBounds();
	var circlePoints = Array();

	with (Math) 
	{
	    var d = circleRadius/3963.189;	// radians
		var lat1 = (PI/180)* center.lat(); // radians
		var lng1 = (PI/180)* center.lng(); // radians

		for (var a = 0 ; a < 361 ; a++ ) 
		{
			var tc = (PI/180)*a;
			var y = asin(sin(lat1)*cos(d)+cos(lat1)*sin(d)*cos(tc));
			var dlng = atan2(sin(tc)*sin(d)*cos(lat1),cos(d)-sin(lat1)*sin(y));
			var x = ((lng1-dlng+PI) % (2*PI)) - PI ; // MOD function
			var point = new GLatLng(parseFloat(y*(180/PI)),parseFloat(x*(180/PI)));
			circlePoints.push(point);
			bounds.extend(point);
		}

		circle = new GPolygon(circlePoints, '#000000', 2, 1, '#28FFFF', 0.20);			
		map.addOverlay(circle); 
		map.setZoom(map.getBoundsZoomLevel(bounds));
	}
}

 // Decode an encoded polyline into a list of lat/lng tuples.
 function decodeLine(results) 
 {
    if (!noZoom)
    {
        try { map.setCenter(new GLatLng(37.062500, -95.677068), 4); }
        catch (err) {}
    }
        
    updateStatus("Begining decoding of polygon", false);
    var mypolyline = [];
    var encoded = results.EncodedPolygon;
    var len = encoded.length;
    if (len == 0)
        return;
        
     //Clear out all data first
    var bounds = new GLatLngBounds();
	var index = 0;
    var lat = 0;
    var lng = 0;

    while (index < len) 
    {
        var b;
        var shift = 0;
        var result = 0;
        do 
        {
            b = encoded.charCodeAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
    
        var dlat = ((result & 1) ? ~(result >> 1) : (result >> 1));
        lat += dlat;

        shift = 0;
        result = 0;    
        do 
        {
            b = encoded.charCodeAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
    
        var dlng = ((result & 1) ? ~(result >> 1) : (result >> 1));
        lng += dlng;

	    var point = new GLatLng(lat * 1e-5, lng * 1e-5);
        mypolyline.push(point);
        bounds.extend(point);                
    }

    updateStatus("About to render line.", false);
   	if (mypolyline.length)
	{
	    var polygon = new GPolygon(mypolyline, "#000000", 2, 1, "#F4B41C", 0.15)
		map.addOverlay(polygon);	
		if (readQueryString("debug").length > 0)
		{  
		    GEvent.addListener(polygon,'click', function(point) 
		        {
		           mapExtension.removeFromMap(gOverlays);                   
                }
            );
        }       	
	}
    updateStatus("Done rendering line", false);
     
     // ===== determine the zoom level from the bounds =====
    if (!noZoom)
    {
        updateStatus("About to set zoom level and map center", false);
        map.setZoom(results.ZoomLevel);
        try { map.setCenter(new GLatLng(results.Latitude, results.Longitude)); }
        catch (err) {}
    }
    else
        updateStatus("Skipping zoom and center...", false);
    
    noZoom = false;
        
    showLoadingMessage(false);
    updateStatus("Done positioning map.", false);
        
    //Now add any holes that may exist
    PageMethods.GetLocationHoles(results.Id, decodeHole);    
}

   // Decode an encoded polyline into a list of lat/lng tuples.
 function decodeHole(results) 
 {        
    updateStatus("Begining decoding of polygon holes", false);
    for (i=0;i<results.length;i++)
    {
        var mypolyline = [];
        var encoded = results[i].EncodedPolygon;
        var len = encoded.length;
        if (len == 0)
            return;
            
         //Clear out all data first
	    var index = 0;
        var lat = 0;
        var lng = 0;

        while (index < len) 
        {
            var b;
            var shift = 0;
            var result = 0;
            do 
            {
                b = encoded.charCodeAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
        
            var dlat = ((result & 1) ? ~(result >> 1) : (result >> 1));
            lat += dlat;

            shift = 0;
            result = 0;    
            do 
            {
                b = encoded.charCodeAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
        
            var dlng = ((result & 1) ? ~(result >> 1) : (result >> 1));
            lng += dlng;

	        var point = new GLatLng(lat * 1e-5, lng * 1e-5);
            mypolyline.push(point);
        }

   	    if (mypolyline.length)
	    {
	        var polygon = new GPolygon(mypolyline, "#000000", 2, 1, "#FFFFFF", .4);
		    map.addOverlay(polygon);		
	    }
    }
         
    showLoadingMessage(false);
    updateStatus("Done positioning map.", false);
}

//Change the neighborhood dropdownlist for the new city
function changeNeighborhood()
{
    lookUpHome('', null);
    document.getElementById('floatingCitySelect').style.visibility = "visible";              
}

//The neighborhood has changed let's load the new values and hide the selection window
function loadNeighborHoods(defaultID)
{
    var ddlCity = document.getElementById("ddlMyCity");
    var selectedItem = ddlCity[ddlCity.selectedIndex];
    var id = selectedItem.value;
        
    if (id == -1)
        return;
    
    //Only clean the amenities out if we are changing cities.
    if (readCookie("MyCity") != defaultID)
        cleanAmenities(null, null, id, true, null);

    SetCookie("MyCity", id, null);
    document.getElementById('CityID').value = id;
    var ddl = document.getElementById("ddlCity");
    ddl.options.length = 0;
   
    PageMethods.GetCityLocationDDL(id, function(results)
        {
            var firstID = -1;
            for (i = 0;i<results.length;i++)
            {
                var loc = results[i];
                ddl.options[ddl.options.length] = new Option(loc.Name, loc.Id);
                if (i == 1)
                    firstID = loc.Id;
                if (loc.Id == defaultID)
                {
                    ddl.selectedIndex = i;
                    cityIndex = i;
                }
            }   
            //Don't select unknown select Please select entry
            if (defaultID == -1)
                ddl.selectedIndex = 0;
            
             PageMethods.GetCityFromHood(firstID, function(cityName) {
                if (cityName.length > 0)
                    document.getElementById('neighborhoodLookup').innerHTML = "Neighborhood - " + cityName;
                else
                    document.getElementById('neighborhoodLookup').innerHTML = "Neighborhood";
            });
        });       
     
   if (document.getElementById('floatingCitySelect'))
        document.getElementById('floatingCitySelect').style.visibility = 'hidden';
      
   if (document.getElementById('div_floatCityCancelBut'))
        document.getElementById('div_floatCityCancelBut').style.visibility = 'hidden';   
}


function resetCity()
{ 
    var ddl = document.getElementById("ddlCity");
    ddl.selectedIndex = cityIndex;
}
    
//Change the map to use the newly selected city
function citySelect()
{
    updateStatus("Starting citySelect function", true);

    //Clear out all data first
    clearFloat();
    showLoadingMessage(true);
    map.clearOverlays();
    markers.splice(0, markers.length);
    overlay.splice(0, overlay.length);
    htmls.splice(0, markers.length);
    displayIDs.splice(0, displayIDs.length);
    lookUpHome("", null);
    //Reset this since lookup home will clear it out.
    showLoadingMessage(true);
    document.getElementById('tree1').style.visibility = 'hidden';
    document.getElementById('divAmenities').style.backgroundImage = 'url(images/searching.gif)';
    
    //Get the new city selection
    updateStatus("Getting the new city selection", false);  
    var ddl = document.getElementById("ddlCity");
    var selectedItem = ddl[ddl.selectedIndex];
    var id = selectedItem.value;
    cityIndex = ddl.selectedIndex;
    updateStatus("Done getting the new city selection", false);  
    var getOnePerCat = getFilterValue("onePerCategory").checked;
    if (id == -1)
    {
        document.getElementById('neighborhoodLookup').innerHTML = "Neighborhood";             
        document.getElementById('tree1').style.visibility = 'visible';
        document.getElementById('divAmenities').style.backgroundImage = 'none';
        showLoadingMessage(false);
        return;
    }
    else
    {        
        PageMethods.GetCityFromHood(id, function(results) {
                if (results.length > 0)
                    document.getElementById('neighborhoodLookup').innerHTML = "Neighborhood - " + results;
                else
                    document.getElementById('neighborhoodLookup').innerHTML = "Neighborhood";
            });
    }

    //Increment the async count for each process about to be started.
    async_count++;
    async_count++;
    async_count++;
    
    //Draw polygon for area
    PageMethods.GetLocationInformation(id, function(results) 
        {
            decodeLine(results);
            
            //Reset the categories in the tree
            cleanAmenities(results.Latitude, results.Longitude, id, false, results.MaxDistance);            
              
            //Add map and tree items
            PageMethods.GetMapItems(id, getOnePerCat, onComplete);     
        }
    );
    
    //Set the cookie with the selected ID
    document.cookie = "neighborhoodID="+id+"; path=/";    
    
    //Audit the lookup
    var UserId = document.getElementById('UserId').value;
    var ip = document.getElementById('IPAddress').value;
    PageMethods.AuditLookup(UserId, selectedItem.text, ip);
    PageMethods.AuditNeighborhood(UserId, id, ip);
}
    
//Mark the status of the amenity as "D" in the database
function removeObject(nodeID)
{
    map.closeInfoWindow();
    if (confirm("Are you sure you wish to remove this amenity?"))
    { 
        var marker = markers[nodeID.name];
        if (marker != null)
        {
            tooltip.style.visibility="hidden";
            map.removeOverlay(marker);
            markers[nodeID.name] = null;
        }
        ob_t2_Remove(nodeID.name);
        var userId = document.getElementById('UserId').value;
        PageMethods.RemoveAmenity(nodeID.name, userId);                
    }
}

//Remove the object from the neighborhood
function removeObjectNeighborhood(nodeID)
{
    map.closeInfoWindow();
    if (confirm("Are you sure you wish to remove this amenity from it's current neighborhood(s)?"))
        PageMethods.RemoveLocation(nodeID.name);
}

// A function to create the home marker with a tooltip
function createHomeMarker(point, myHtml, nodeID, name) 
{
    var nodeIDNumber = 0;
    if (nodeID == "house")
        myHtml = '<br />' + myHtml;
    else
        nodeIDNumber = nodeID.replace('property_', '');    
        
    var html = '<div align="left" style="white-space:nowrap;font-family: Arial;font-size: 10pt;">' + myHtml + '</div>';     
    
    to_htmls[nodeIDNumber] = html + '<br>Directions: <b>To here</b> - <a href="javascript:fromhere(' + nodeIDNumber + ')">From here</a>' +
           '<br>Start address:<form action="javascript:getDirections()">' +
           '<input type="text" SIZE=40 MAXLENGTH=40 name="saddr" id="saddr" value="" /><br>' +
           '<INPUT value="Get Directions" TYPE="SUBMIT">' +
           '<input type="hidden" id="daddr" value="'+name+"@"+ point.lat() + ',' + point.lng() + 
           '"/>';
           
    // The info window version with the "to here" form open
    from_htmls[nodeIDNumber] = html + '<br>Directions: <a href="javascript:tohere(' + nodeIDNumber + ')">To here</a> - <b>From here</b>' +
           '<br>End address:<form action="javascript:getDirections()">' +
           '<input type="text" SIZE=40 MAXLENGTH=40 name="daddr" id="daddr" value="" /><br>' +
           '<INPUT value="Get Directions" TYPE="SUBMIT">' +
           '<input type="hidden" id="saddr" value="'+name+"@"+ point.lat() + ',' + point.lng() +
           '"/>';
    
    // The inactive version of the direction info
    html += '<br /><div align="left"><b>Directions: </b><a href="javascript:tohere('+nodeIDNumber+')">To here</a> | <a href="javascript:fromhere('+nodeIDNumber+')">From here</a></div>';
    var panoClient = new GStreetviewClient();
    panoClient.getNearestPanoramaLatLng(point, function(panoData) 
        {
            if (panoData != null) 
                html += '<div align="left"><b>Streetview: </b><a href="javascript:initializePan(' + point.lat() + ',' + point.lng() + ', \'' + name.replace(/[^a-zA-Z 0-9]+/g,'') + '\')">Open</a>&nbsp;|&nbsp;<a href="javascript:closePan()">Close</a></div>';
        }
    );
      
    var myIcon = new GIcon();
    if (nodeID == "house")
        myIcon.image = "images/house-icon.png";
    else
         myIcon.image = "images/openhouse.gif";
    
    myIcon.iconAnchor = new GPoint(20, 32);
    myIcon.iconSize= new GSize(39,34);
    myIcon.shadow = "images/house-icon-shadow.png"; 
    myIcon.shadowSize = new GSize(57.0, 34.0);
    myIcon.infoWindowAnchor = new GPoint(19.0, 17.0);
    
    // === marker with tooltip ===
    var marker = new GMarker(point, {icon:myIcon, draggable:true, zIndexProcess:zind} );
            GEvent.addListener(marker, "dragstart", function() {
            map.closeInfoWindow();
        });            
            
    GEvent.addListener(marker, "dragend", function() {
        moveHome(marker);
        });    
    
    GEvent.addListener(marker, "click", function() {
        tooltip.style.visibility="hidden";
        marker.openInfoWindowHtml(html);
    });
    marker.tooltip = '<div class="tooltip">'+name+'</div>';
    
    //  ======  The new marker "mouseover" and "mouseout" listeners  ======
    GEvent.addListener(marker,"mouseover", function() {
      showTooltip(marker);
    });        
    
    GEvent.addListener(marker,"mouseout", function() {
	tooltip.style.visibility="hidden"
    });           

    map.addOverlay(marker);
    markers[nodeID] = marker;
    htmls[nodeID] = html;
    overlay[nodeID] = true;
  }

 // ===== request the directions =====
  function getDirections()  
  {
    var saddr = document.getElementById("saddr").value
    var daddr = document.getElementById("daddr").value
    gdir.load("from: "+saddr+" to: "+daddr);
    document.getElementById('directions').style.visibility = "visible";
    map.closeInfoWindow();
  }
  
// functions that open the directions forms
function tohere(i) 
{     
    var nodeID = 'amenities_' + i;
    if (i == 0)
        nodeID = 'house';
    else if (markers[nodeID] == null)
        nodeID = 'property_' + i;
    markers[nodeID].openInfoWindowHtml(to_htmls[i]);  
    if ((i != 0) && (document.getElementById('navArea1_pTimeC_address').value != ''))
        document.getElementById("saddr").value = document.getElementById('navArea1_pTimeC_address').value;  
}
  
function fromhere(i) 
{
    var nodeID = 'amenities_' + i;
    if (i == 0)
        nodeID = 'house';
    else if (markers[nodeID] == null)
        nodeID = 'property_' + i;
    markers[nodeID].openInfoWindowHtml(from_htmls[i]);
    if ((i != 0) && (document.getElementById('navArea1_pTimeC_address').value != ''))
        document.getElementById("daddr").value = document.getElementById('navArea1_pTimeC_address').value;
}

//Someone flagged this object send the email to the admins (whether they follow thru or not).
function flagClicked(category, amenity, body)
{
    map.closeInfoWindow();
    var subject = 'Amenity flag was clicked';
    if (document.getElementById('UserName') != null)
        body += '<br />Clicked By: ' + document.getElementById('UserName').value;
    
    document.getElementById('amenityDescription').innerHTML = body;
    document.getElementById('amenityID').innerHTML = amenity;  
    document.getElementById('categoryName').innerHTML = category;
    body = amenity + '<br />' + body;
    PageMethods.SendAdminMessage(subject, body);
    var floatFlag = document.getElementById('floatFlag');
    var left = Math.floor((screen.availWidth - 240) / 2);
    var top = Math.floor((screen.availHeight - 360) / 2);
    floatFlag.style.left = left + 'px';
    floatFlag.style.top = top + 'px';
    floatFlag.style.visibility = 'visible';
}

function notifyAmenity()
{
    var subject = 'Amenity was flagged.';
    var body = document.getElementById('amenityDescription').innerHTML;
    var len = document.mapForm.rbAmenityReason.length;
    var reason = '';
    for (i=0; i<len; i++)
    {
		if (document.mapForm.rbAmenityReason[i].checked) 
		{
		    reason = document.mapForm.rbAmenityReason[i].value
		    document.mapForm.rbAmenityReason[i].checked = false;
		    break;
		}
	}
	body += '<br />Reason: ' + reason;
	body += '<br />Amenity ID: ' + document.getElementById('amenityID').innerHTML;
	body += '<br />Category Name: ' + document.getElementById('categoryName').innerHTML;
	body += '<br /><br />Details: ' + document.getElementById('txtAmenityDetails').value;
	var ddl = document.getElementById('ddlCity');
	body += '<br /><br />Neighborhood: ' + ddl[ddl.selectedIndex].text;
	var hood = document.getElementById('neighborhoodLookup').innerHTML.replace('Neighborhood', '');
	if (hood.length == 0)
	    hood = 'Chicago';
    else
        hood = hood.substring(3, hood.length);
	body += '<br /><br />Area: ' + hood;
	var email = document.getElementById('emailNotify').value;
	if (email.length > 0)
	    body += '<br /><br />Email Notification Address: ' + email;
	
    PageMethods.SendAdminMessage(subject, body);
    document.getElementById('floatFlag').style.visibility = 'hidden';
    document.getElementById('txtAmenityDetails').value = '';
    alert('A message about your concern with this amenity has been sent and will be addressed shortly.');
}


// A function to create the marker with a tooltip
function createMarker(point, name, html, nodeID, category, show) 
{
    var nodeIDNumber = nodeID.replace('amenities_', '');
    var admin = document.getElementById("Admin").value;
    var body = html.replace(/<BR \/>/i, ' - ').replace(/<br\/>/i, ' - ');
    if (body.indexOf("<IMG") != -1)
    {
        var last = body.indexOf("/>");
        body = body.substr(last + 2);
    }
    html = '<div align="left" style="white-space:nowrap;font-family: Arial;font-size: 10pt;"><br/>' + html + '</div></td><td valign="bottom" align="right">';
     
    var imagePath = "images/" + category + ".png";
    if (category.length == 0)
        imagePath = "";
    var myIcon = new GIcon(G_DEFAULT_ICON);
    var displayID = displayIDs[nodeID];
    imagePath = "images/bubble/" + category + "_" + displayID + ".png";
    myIcon.image = imagePath;  
    myIcon.iconAnchor = new GPoint(0, 24);   
    myIcon.infoWindowAnchor = new GPoint(5, 2);  
    myIcon.shadow = "images/shadow-bubble.png";   
    myIcon.iconSize=new GSize(19,24);     
    myIcon.shadowSize = new GSize(32.0, 24.0);
  
    var subject = 'Amenity Adjustment: ' + nodeID;
    var wikiUser = document.getElementById("AllowWiki").value;
    if (wikiUser == "true")
        html = '<table width="100%"><tr><td><a target="_blank" href="wiki/Home.aspx?topic=Amenity&entry=' + nodeIDNumber + '">' + html + '</a></td><td valign="bottom" align="right">';
    else
        html = '<table><tr><td>' + html;

    //Add the update this listing link
    var jsFunction = 'flagClicked(\'' + category + '\', \'' + subject.replace('\'', '') + '\', \'' + body.replace('\'', '') + '\');';
    html += '<div align="left" style="vertical-align: middle;" onclick="' + jsFunction + '"><img src="images/RedFlag.png" title="Communicate that this amenity\'s data is not 100% correct." /><a href="javascript:' + jsFunction + '" style="font-family: Arial;font-size: 8pt;" >Update this listing</a></div></td></tr></table>';
    
    to_htmls[nodeIDNumber] = html + '<br>Directions: <b>To here</b> - <a href="javascript:fromhere(' + nodeIDNumber + ')">From here</a>' +
           '<br>Start address:<form action="javascript:getDirections()">' +
           '<input type="text" SIZE=40 MAXLENGTH=40 name="saddr" id="saddr" value="" /><br>' +
           '<INPUT value="Get Directions" TYPE="SUBMIT">' +
           '<input type="hidden" id="daddr" value="'+name+"@"+ point.lat() + ',' + point.lng() + 
           '"/>';
           
    // The info window version with the "to here" form open
    from_htmls[nodeIDNumber] = html + '<br>Directions: <a href="javascript:tohere(' + nodeIDNumber + ')">To here</a> - <b>From here</b>' +
           '<br>End address:<form action="javascript:getDirections()">' +
           '<input type="text" SIZE=40 MAXLENGTH=40 name="daddr" id="daddr" value="" /><br>' +
           '<INPUT value="Get Directions" TYPE="SUBMIT">' +
           '<input type="hidden" id="saddr" value="'+name+"@"+ point.lat() + ',' + point.lng() +
           '"/>';             
   
    // The inactive version of the direction info
    html += '<br /><div align="left"><b>Directions: </b><a href="javascript:tohere('+nodeIDNumber+')">To here</a> | <a href="javascript:fromhere('+nodeIDNumber+')">From here</a></div>';
    html += '<div align="left"><b>Streetview: </b><a href="javascript:initializePan(' + point.lat() + ',' + point.lng() + ',\'' + name.replace(/[^a-zA-Z 0-9]+/g,'')  + '\')">Open</a>&nbsp;|&nbsp;<a href="javascript:closePan()">Close</a></div>';
                       
    // === marker with tooltip ===
    var marker;
    if (admin == "true") 
    {
        marker = new GMarker(point, {icon:myIcon, draggable:true} );
         GEvent.addListener(marker, "dragstart", function() {
        map.closeInfoWindow();
        });            
                
        GEvent.addListener(marker, "dragend", function() {
            moveMarker(marker, nodeID);
            });    
        
        GEvent.addListener(marker, "click", function() 
        {
            var editHTML = '<div align="right" style="vertical-align:bottom;width:264px;"><a href="Maintenance/AmenityManagement.aspx?nodeID=' + nodeID + '" target="_blank">[Edit]</a></div>';          
            var tabs = [];
            tabs.push(new GInfoWindowTab("Info", html + editHTML));
                        
            var adminHTML = '<input type="button" id="remove_' + nodeID + '" name="' + nodeID + '" value="Remove this Object" onclick="removeObject(this);" /><br />'
            adminHTML += '<input type="button" id="removeNeighborhood_' + nodeID + '" name="' + nodeID + '" value="Remove from Neighborhood" onclick="removeObjectNeighborhood(this);" /><br />'
            adminHTML += '<a href="Maintenance/AmenityManagement.aspx?nodeID=' + nodeID + '" target="_blank" >Edit this object</a>';
            adminHTML = '<div style="white-space:nowrap;">' + adminHTML + '</div>';
            
            tabs.push(new GInfoWindowTab("Admin", adminHTML));                                   
                                      
            marker.openInfoWindowTabsHtml(tabs);
        });    
                            
    }    
    else 
    {
        marker = new GMarker(point, {icon:myIcon} );
        GEvent.addListener(marker, "click", function () { marker.openInfoWindow(html); });
    }
    marker.tooltip = '<div class="tooltip">'+name+'</div>';        
    GEvent.addListener(marker,"mouseover", function() { showTooltip(marker); });        
    GEvent.addListener(marker,"mouseout", function() { tooltip.style.visibility="hidden" });        
    
    if (show)
    {          
        map.addOverlay(marker);
        overlay[nodeID] = true;
    } 
    markers[nodeID] = marker;
    htmls[nodeID] = html;    
  }
  
  function zind()
  {
    return 60000;
  }

  
  //Allow the admin to move the marker to a new location
  function moveHome(marker)
  {     
    if (confirm("Are you sure you wish to move the home to this new position?"))
    {
        var pointNew = marker.getPoint(); 
        document.getElementById('HomeLatitude').value=pointNew.y;
        document.getElementById('HomeLongitude').value=pointNew.x;
        var home = document.getElementById('HomeAddress').value;
        SetCookie("HomeAddress", pointNew.y + "_" + pointNew.x , null);        
        var admin = document.getElementById('Admin').value;
        var propertyID = document.getElementById('PropertyID');
        if (admin == "true" && propertyID != null)
            PageMethods.MoveHome(propertyID.value, pointNew.y, pointNew.x);        
    }
    else
    {
        tooltip.style.visibility="hidden";
        map.removeOverlay(marker);
        markers["house"] = null;
        
        //Restore original marker
        var point = new GLatLng(document.getElementById('HomeLatitude').value, document.getElementById('HomeLongitude').value);
        home = document.getElementById('HomeAddress').value;
        createHomeMarker(point, home, "house", home);
    }
}

//Allow the admin to move the marker to a new location
function moveMarker(marker, nodeID)
{     
    if (confirm("Are you sure you wish to move the marker to this new position permanantly?"))
    {
        var pointNew = marker.getPoint(); 
        var id = nodeID.replace("amenities_", "");
        PageMethods.UpdateLatLon(id, pointNew.y, pointNew.x);
    }
    else
    {
        tooltip.style.visibility="hidden";
        map.removeOverlay(marker);
        markers[nodeID] = null;
        
        //Restore original marker
        clear = false;
        PageMethods.GetMapItem(nodeID, updateMarkers);
    }
}

function showLoadingMessage(bShow)
{
    var waitImage = document.getElementById("waitImage");
    if (bShow)
    {
        if (waitImage != null)
            waitImage.style.visibility="visible";         
    }
    else
    {
        //Wait till the last process is complete
        if (async_count > 0)
            async_count--;
        if (async_count == 0)
        {
            if (waitImage != null)
                waitImage.style.visibility="hidden";
        }
    }
}
 
// ====== This function displays the tooltip ======
// it can be called from an icon mousover or a sidebar mouseover
function showTooltip(marker) 
{
    tooltip.innerHTML = marker.tooltip;
    var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0,0),true),map.getZoom());
    var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),map.getZoom());
    var anchor=marker.getIcon().iconAnchor;
	var width=marker.getIcon().iconSize.width;
    var height=tooltip.clientHeight;
	var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x - anchor.x + width, offset.y - point.y -anchor.y -height)); 
    pos.apply(tooltip);
    tooltip.style.visibility="visible";
}

function getCategories(selected, lat, lon, id, parentID) 
{
    if (window.XMLHttpRequest) 
        AJAX = new XMLHttpRequest();              
    else
        AJAX = new ActiveXObject("Microsoft.XMLHTTP");
  
    if (AJAX) 
    {
        AJAX.open("POST", "GetMyXml.aspx?type=GetCategories&lat=" + lat + "&lon=" + lon + "&id=" + id + "&parentID=" + parentID, false);
        AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        AJAX.send(selected);                                      
        return AJAX.responseText;
    } 
    else 
     return false;
}

function getCityInfo(lat, lon, addr, city)
{
    if (window.XMLHttpRequest) 
        AJAX = new XMLHttpRequest();              
    else
        AJAX = new ActiveXObject("Microsoft.XMLHTTP");
  
    if (AJAX) 
    {
        var url = "GetMyXml.aspx?type=GetCityInfo&lat=" + lat + "&lon=" + lon + "&addr=" + addr + "&city=" + city;
        AJAX.open("POST", url, false);
        AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        AJAX.setRequestHeader("Content-length", url.length);
        AJAX.send(url);                                      
        return AJAX.responseText;
    } 
    else 
     return false;

}

  
//clear out all of the amenities from the tree control
function cleanAmenities(lat, lon, id, forceUpdate, maxDistance)
{      
    var user_intid = document.getElementById('AgentID').value;
    
    //No amenities loaded we can skip this for now...
    if ((forceUpdate == false) && (document.getElementsByName('AO').length == 0))
    {
        //Nuke the old one if it exists first...
        if (document.getElementById('openHouses') != null)
            ob_t2_Remove('openHouses');
            
        if ((lat != null) && (user_intid.length > 0))
        {
            var root = ob_getFirstNodeOfTree();
            var open_houses = 'LoadAgentProperties.aspx?OpenHouse=Y&Latitude=' + lat + '&Longitude=' + lon + '&MaxDistance=' + maxDistance + '&UserId=' + user_intid;
            //var ohHTML = "<input type='checkbox' class='chk' id='openHouses' name='openHouses' style='vertical-align:middle;' onclick='myClick(this)' /> Open Houses";
            ob_t2_Add(root.id, 'openHouses', 'Open Houses', false, 'equalhousing.png', open_houses);
        }
        return;
    }
        
    updateStatus("Rebuilding Categories", false);
    var bUnHide = true;
    if (document.getElementById('tree1').style.visibility == 'hidden')
        bUnHide = false;
    else
        document.getElementById('tree1').style.visibility = 'hidden';
    
    // To check/uncheck checkboxes in children.
    root = ob_getFirstNodeOfTree();
    var child = ob_getFirstChildOfNode(root, true);
    while (child != null)
    {
        var nodeBase = child;        
        child = ob_getNextSiblingOfNode(nodeBase);
        ob_t2_Remove(nodeBase.id);            
    }		
    
    updateStatus("Adding in base categories", false);
    var selected = document.getElementById('SelectedCategories').value;
    var parentID = null;    
    //Get the categories syncronously
    if (forceUpdate)
    {
        parentID = id;
        id = null;        
    }
    
    var categoryXML = getCategories(selected, lat, lon, id, parentID);
    var categories = categoryXML.split('^');
    for (i=0;i<categories.length;i++)
	{
	    if (categories[i].length == 0)
	        break;
	    var category = categories[i];
	    var entry = category.split(',');
	    ob_t2_Add(entry[0], entry[1], entry[2], false, entry[3], null);
    }        
    
    if ((lat != null) && (user_intid.length > 0))
    {
        open_houses = 'LoadAgentProperties.aspx?OpenHouse=Y&Latitude=' + lat + '&Longitude=' + lon + '&MaxDistance=' + maxDistance + '&UserId=' + user_intid;
        ob_t2_Add(root.id, 'openHouses', 'Open Houses', false, 'equalhousing.png', open_houses);
    }
    
    //This was a forced update no data will be loaded just make visible again
    if (forceUpdate)
    {
        collapseTree();
        if (bUnHide)
            document.getElementById('tree1').style.visibility = 'visible';
    }
}
  
//Event handler for category check box selection
function myClick(e)
{   
    map.closeInfoWindow();
    updateStatus("Loading node.", true);
    showLoadingMessage(true);
    var filter = "";
    
    // To check/uncheck checkboxes in children.
    if (ob_hasChildren(e.parentNode)) 
    {
	    var ob_t2in=e.parentNode.parentNode.parentNode.parentNode.nextSibling.getElementsByTagName("input");
	    for (var i=0; i<ob_t2in.length; i++) 
	    {
		    if (e.checked != ob_t2in[i].checked) 
		    {
		        ob_t2in[i].checked = e.checked;
		        if (ob_t2in[i].id.indexOf("amenities_") > -1)
		        {
    			    if (filter.length > 0)
    			        filter += ",";
    			    filter += ob_t2in[i].id.replace("amenities_", "");
    			}
    	    }
	    }
    }
    
    if (e.checked==false) 
    {
        ob_t2_unchk_parent(e.parentNode);
        clear = true;
    }
    else
        clear = false;
                  
    //Just send the direct list of amenities
    PageMethods.GetMapItemsFiltered(filter, updateMarkers);
}

//Handle individual amenity click here...
function ac(e)
{
    updateStatus("Loading node.", true);  
    var marker = markers[e.id];
    if (marker != null)
    {
        if (e.checked)
        {
            if (overlay[e.id] == null)
            {
                map.addOverlay(marker);
                overlay[e.id] = true;
                GEvent.addListener(marker,"mouseover", function() { showTooltip(marker); });        
                GEvent.addListener(marker,"mouseout", function() { tooltip.style.visibility="hidden" });
            }
            if (marker.isHidden())
                marker.show();                        
        }
        else
        {
            map.closeInfoWindow();
            tooltip.style.visibility="hidden";
            marker.hide();
        }
    }
    else if (e.checked)
    {
        clear = false;
        PageMethods.GetMapItem(e.id, updateMarkers);          
    }
}

//Handle a propertyClick
function propertyClick(e)
{
    updateStatus("Loading property.", true);  
    var nodeID = e.id.replace('chk_oh', 'property_');
    var marker = markers[nodeID];
    if (marker != null)
    {
        if (e.checked)
        {
            if (overlay[nodeID] == null)
            {
                map.addOverlay(marker);
                overlay[nodeID] = true;
                GEvent.addListener(marker,"mouseover", function() { showTooltip(marker); });        
                GEvent.addListener(marker,"mouseout", function() { tooltip.style.visibility="hidden" });
            }
            if (marker.isHidden())
                marker.show();                        
        }
        else
        {
            map.closeInfoWindow();
            tooltip.style.visibility="hidden";
            marker.hide();
        }
    }
    else if (e.checked)
    {
        //Load the selected items onto the map...
        if (marker == null)
        {                       
            //Load the selected items onto the map...  
            var link = "<a target='_blank' href='AgentPage.aspx?propertyid=" + ob_t2_Data[nodeID].PropertyGuid + "&UserId=" + ob_t2_Data[nodeID].UserGuid + "' >";
            var html = "<table><tr><td colspan='3'><div align='center' style='font-weight:bold; color:Blue; font-size:Large;'>Open House Listing</div></td></tr><tr>";
            var agent = ob_t2_Data[nodeID].Agent;
            var appt = ob_t2_Data[nodeID].Appointment;
            var name = ob_t2_Data[nodeID].Name;
            if (ob_t2_Data[nodeID].ImageURL.length > 0)
            {
                html += '<td rowspan="3">' + link + '<IMG src=\"'; 
                html += ob_t2_Data[nodeID].ImageURL + '\" width=100 height=75 align=left /></a></td>';
            }            
            
            html += '<td><b>Address: </b></td><td>' + link + name + '</a></td></tr>';
            html += '<tr><td><b>Agent Name: </b></td><td>' + agent + '</td></tr>';
            html += '<tr><td><b>Open House: </b></td><td>' + appt + '</td></tr></table>';
            
            var lat = ob_t2_Data[nodeID].Latitude;
            var lon = ob_t2_Data[nodeID].Longitude;
            var point = new GLatLng(lat, lon);

            createHomeMarker(point, html, nodeID, name);
        }
        else 
        {
            if (overlay[nodeID] == null)
            {
                map.addOverlay(marker);
                overlay[nodeID] = true;
            }
            else if (marker.isHidden())
                marker.show();
        }        
    }
}

//Clear out the amenities from the map of the unchecked node...
function updateMarkers(results)
{
    updateStatus("Received nodes from server.", false);
     //Load the selected items onto the map...
    for (var i=0;i<results.length;i++)
    {
        var nodeID = "amenities_" + results[i].Id;
        var marker = markers[nodeID];
        if (clear)
        {
            if (marker != null && !marker.isHidden())
                marker.hide();                
        }
        else if (marker == null)
        {
            //Load the selected items onto the map...  
            var html = "";
            if (results[i].ImageUrl.length > 0)
            {
                html = '<IMG src=\"'; 
                html += results[i].ImageUrl + '\" width=100 height=75 align=left />';
            }
            
            if (results[i].SubCategory)
                html += results[i].Parent_Category + ' - ' + results[i].Category + '<br />';
            html += '<b>' + results[i].Name + '</b><br/><br/>' + results[i].Description;
            
            var point = new GLatLng(results[i].Latitude, results[i].Longitude);
            createMarker(point,results[i].Name, html, nodeID, results[i].PinImage, true);             
        }
        else
        {
            if (overlay[nodeID] == null)
            {
                map.addOverlay(marker);
                overlay[nodeID] = true;
            }
            else if (marker.isHidden())
                marker.show();
        }
        
    }
    showLoadingMessage(false);
    updateStatus("Done showing markers.", false);
}

//Display the tool tip based on the markers ID
function st(marker_id)
{
    var marker = markers[marker_id];
    if ((marker != null) && (!marker.isHidden()) && (overlay[marker_id] != null))   
        showTooltip(marker);
}

//Hide the tooltip
function ht()
{
    tooltip.style.visibility="hidden";
}

function sn(marker_id)
{
    map.closeInfoWindow();

    var marker = markers[marker_id];
    if ((marker != null) && (!marker.isHidden()) && (overlay[marker_id] != null)) 
        marker.openInfoWindowHtml(htmls[marker_id]);
}
    
//Display the results of the server queries on the map and tree
function onComplete(results)
{
    updateStatus("Received results", false);    
    var amenities = document.getElementById('SelectedAmenities').value;
    var amenitiesList = new Array();
    if (amenities.value != "")
    {
        var amenitiesSplit = amenities.split(',');
        for (var i=0;i<amenitiesSplit.length;i++)
        {
            var amenityID = amenitiesSplit[i]; 
            if (amenityID.indexOf('amenities_') == -1)
                amenityID = 'amenities_' + amenityID;
            amenitiesList[amenityID] = true;
        }
    }
    
    //Special error code result
    if (results.length == 1 && results[0].Name == "Error")
    {
        document.getElementById('tree1').style.visibility = 'visible';
        document.getElementById('divAmenities').style.backgroundImage = 'none';
        showLoadingMessage(false);
        var msg = results[0].Description;
        alert(msg);
        return;
    }
    
    //Load the selected items onto the map...
    for (i=0;i<results.length;i++)
    {
       //Load the selected items onto the map...
        var key = "chk_" + results[i].CategoryID;
        var box = document.getElementById(key);
        var parentID = "category_" + results[i].CategoryID;
        var nodeID = "amenities_" + results[i].Id;
        displayIDs[nodeID] = results[i].DisplayID;
        var isChecked = false;
        if (box != null)
            isChecked = (box.checked || (amenitiesList[nodeID] != null));

        var html = "";
        if (results[i].ImageUrl.length > 0)
        {
            html = '<IMG src=\"'; 
            html += results[i].ImageUrl + '\" width=100 height=75 align=left />';
        }
         
        if (results[i].SubCategory)
            html += results[i].Parent_Category + ' - ' + results[i].Category + '<br />';
        html += '<b>' + results[i].Name + '</b><br/><br/>' + results[i].Description;
        
        var point = new GLatLng(results[i].Latitude, results[i].Longitude);
        createMarker(point,results[i].Name, html, nodeID, results[i].PinImage, isChecked); 
        
        //If the entry doesn't exist yet add it now...
        if (!document.getElementById(nodeID))
        {
            var treeIcon = "Markers.aspx?type=png&count=" + results[i].DisplayID + "&category=blank";
            var chkHTML = "<input type='checkbox' ";
            if (isChecked)
                chkHTML += " CHECKED ";
            chkHTML += "class='chk' id='" + nodeID + "' name='AO' onclick='ac(this)' /> ";            
            chkHTML += results[i].DisplayID + ' - ' + results[i].Name;           
            var testHTML = "<span title='" + results[i].Name + "' onmouseover='st(\"" + nodeID +"\")' onmouseout='ht()' style='cursor: pointer;' onclick=';sn(\"" + nodeID +"\")'>" + chkHTML +"</span>";
            //We can't do this until we are done loading the tree's base...
            var bResult = false;
            ob_t2_AddNew(parentID, nodeID, testHTML, false, treeIcon, null);                 
        }
    }        
    collapseTree(); 
    
    if ((document.getElementById('HomeAddress').value != "") && (markers['house'] == null))
    {
         var home = document.getElementById('HomeAddress').value;
         var lat = document.getElementById('HomeLatitude').value;
         var lon = document.getElementById('HomeLongitude').value;
         point = new GLatLng(lat, lon);
         createHomeMarker(point, home, "house", home);
    }
    
    showLoadingMessage(false);
    document.getElementById('tree1').style.visibility = 'visible';
    document.getElementById('divAmenities').style.backgroundImage = 'none';
    updateStatus("Done displaying.", false);
}

function startDrive()
{
    load();
    PageMethods.GetMapItem('10782', showDrive);    
}

function showDrive(results)
{
    var driveArea = document.getElementById('locationViewer');
    if (results.length == 0)
        return;
    
    var amenity = results[0];
    var nodeID = "amenities_" + amenity.Id;

    //Load the selected items onto the map...  
    var html = "";
    if (amenity.ImageUrl.length > 0)
    {
        html = '<IMG src=\"'; 
        html += amenity.ImageUrl + '\" width=100 height=75 align=left>';
    }
    
    if (amenity.SubCategory)
        html += amenity.Parent_Category + ' - ' + amenity.Category + '<br />';
    
    html += '<b>' + amenity.Name + '</b><br/><br/>' + amenity.Description;                       
    driveArea.innerHTML = html;
}
    
//Generic method to read a 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;
}

function SetCookie(cookieName,cookieValue,nDays) 
{
    var today = new Date();
    var expire = new Date();
    if (nDays==null || nDays==0) 
        nDays=1;
    expire.setTime(today.getTime() + 3600000*24*nDays);
    document.cookie = cookieName+"="+cookieValue + ";expires="+expire.toGMTString();
}

//Read the query string and return the keys value
function readQueryString(key)
{ 
    var qs = location.search.substring(1,location.search.length)
    //There was no query string we are done
    if (qs.length == 0) 
        return "";

    qs = qs.replace(/\+/g, ' ');
    var args = qs.split('&');
	
    // split out each name=value pair
    for (var i=0;i<args.length;i++) 
    {
        var pair = args[i].split('=');
	    var name = unescape(pair[0]);
	   
	    if (name == key)
	    {
	        if (pair.length == 2)
		        return unescape(pair[1]);
	        else
		        return "";
        }    		
    }
    return "";
}

function updateStatus(message, reset)
{
    if (!statusMsgs)
        return;

    var status = document.getElementById("lblStatus");
    var now = new Date();            
    
    if (reset)
        startTime = now.getTime();
     
    now = new Date();
    var fromStart = (now.getTime() - startTime) / 1000;
            
    status.innerHTML += "&nbsp;&nbsp;" + fromStart + ": " + message + "<br />"    
}

//Collapse the tree
function collapseTree()
{
    ob_t2_ExpandCollapseLevel(2, false);
    ob_t2_ExpandCollapseLevel(1, false);
}

var arr_ob_t2_IndexedNodes = null, arr_ob_t2_NodesParents = null, arr_ob_t2_NodesLevels = null;
function ob_t2_ExpandCollapseLevel(iLevel, bType)
{
    // the first time the function is executed
    // the levels of the nodes must be calculated
    if(arr_ob_t2_NodesLevels == null)
    {
        arr_ob_t2_IndexedNodes = new Array();    
        arr_ob_t2_NodesParents = new Array();
        arr_ob_t2_NodesLevels = new Array();
          
        var oTempNode = ob_getFirstNodeOfTree();    
        var oTempParent = null;
        var i=0;
        while(oTempNode != null)
        {                  
            arr_ob_t2_IndexedNodes[i] = oTempNode.id;
        
            oTempParent = ob_getParentOfNode(oTempNode);        
            if(oTempParent)
            {
                arr_ob_t2_NodesParents[oTempNode.id] = oTempParent.id;
            }                 	    
 	        oTempNode = ob_getNodeDown(oTempNode, true); 	
 	        i++;      	           
        }
        
        for(i=0; i<arr_ob_t2_IndexedNodes.length; i++)
        {
            var iTempLevel = 0;
            var sTempParent = arr_ob_t2_NodesParents[arr_ob_t2_IndexedNodes[i]];
            while(sTempParent != null)
            {
                iTempLevel++;
                sTempParent = arr_ob_t2_NodesParents[sTempParent];
            }
            arr_ob_t2_NodesLevels[arr_ob_t2_IndexedNodes[i]] = iTempLevel;            
        }    
    }
    
    for(i=0; i<arr_ob_t2_IndexedNodes.length; i++)
    {
        if(arr_ob_t2_NodesLevels[arr_ob_t2_IndexedNodes[i]] == iLevel)
        {
            try
            {
                oImg = document.getElementById(arr_ob_t2_IndexedNodes[i]).parentNode.firstChild.firstChild;
            }
            catch (err) {}
            if (oImg != null)
            {
                var lensrc = (oImg.src.length - 8);
	            var s = oImg.src.substr(lensrc, 8);
                if (bType == true) 
                {
		            if ((s == "usik.gif") || (s == "ik_l.gif")) 
		                oImg.onclick();				
	            }
	            else if ((s == "inus.gif") || (s == "us_l.gif")) 
		            oImg.onclick();				
            }            
        }
    }
    
}

//Return all of the checked items by the type
function checked_list(chkType) 
{
	// Make string with checked checkboxes IDs.	
	var ob_t2in,ob_t2s,ob_t2checked="";
	ob_t2in=document.getElementsByTagName("input");
	for (var i=0; i<ob_t2in.length; i++) {
		ob_t2s=ob_t2in[i].id;
		if ((ob_t2s.substr(0,chkType.length)==chkType) && (ob_t2in[i].checked)) {
			ob_t2checked=ob_t2checked+ob_t2s+",";
		}
	}
	return ob_t2checked;
}

function ob_t2_AddNew(parentId, childId, textOrHTML, expanded, image, subTreeURL)
{		
	if (!ob_OnBeforeAddNode(parentId, childId, textOrHTML, expanded, image, subTreeURL))
		return;    
		
	var pNode = document.getElementById(parentId);
		
	if (!pNode) 
	    return;		
	
	if(pNode)	
	{
		if (pNode.className.toLowerCase() != 'ob_t2' && pNode.className.toLowerCase() != 'ob_t3')
		{
			alert("Parent node is not a valid tree node.");
			return;
		}
	}
	
	dParent = pNode.parentNode.parentNode.parentNode.parentNode;
	    	
	if (document.getElementById(childId) != null) 
	{
		alert("An element with the specified childId already exists.");
		return;
	}		
    if (!ob_hasChildren(pNode))
    {
	    var e = dParent.firstChild.firstChild.firstChild.firstChild.firstChild;
	    e.src=ob_style+"/minus" + (ob_getLastChildOfNode(ob_getParentOfNode(pNode)) == pNode ? "_l.gif" : ".gif");
	    e.onclick=function(){ob_t21(this,'')};
		
	    e = dParent.appendChild(document.createElement("TABLE"));		    
		e.className = "ob_t2g";
		
		if (document.all)
		{			
			e.cellSpacing = "0";
		}
		else
		{			
			e.setAttribute("cellspacing", "0");
		}
		
	    e.appendChild(document.createElement("tbody"));
	    var e2=e.firstChild.appendChild(document.createElement("TR"));
	    e=e2.appendChild(document.createElement("TD"));
	    if(dParent.parentNode.lastChild!=dParent)
		    e.style.backgroundImage="url("+ob_style+"/vertical.gif)";
	    e.innerHTML="<div class=ob_d5></div>";
	    e=e2.appendChild(document.createElement("TD"));
	    e.className="ob_t5";	    
	    dParent.className = 'ob_d2b';
    }
    else
    {	    				
	    prevS = ob_getLastChildOfNode(pNode, true);
	    if (prevS != null && prevS.parentNode != null)
	    {
	        var oPrevSImg = prevS.parentNode.parentNode.parentNode.parentNode.firstChild.firstChild.firstChild.firstChild.firstChild;
    	    if (!ob_hasChildren(prevS)) 
    	        oPrevSImg.src = ob_style + "/hr.gif";
		    else 
		    {				
			    if (!ob_isExpanded(prevS))
			        oPrevSImg.src = ob_style + "/plusik.gif";										
			    else 
			        oPrevSImg.src = ob_style + "/minus.gif";
			    prevS.parentNode.parentNode.parentNode.parentNode.firstChild.nextSibling.firstChild.firstChild.firstChild.style.backgroundImage = "url(" + ob_style + "/vertical.gif)";				
		    }		    			
    		
	        if (dParent.parentNode.lastChild!=dParent)
		        prevS.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.firstChild.style.backgroundImage = "url(" + ob_style + "/vertical.gif)";
	    }
    }
	
	div = document.createElement('div');
	div.className = 'ob_d2c';	
	
	//Original code here this is what we have modified...
//	sInnerHtml = '<table cellspacing="0" class="ob_t2g"><tr><td class="ob_t6"><img ' + ((subTreeURL != null) ? 'src="' + ob_style + '/plusik_l.gif" onclick="ob_t21(this, \'' + subTreeURL + '\')"' : 'src="' + ob_style + '/hr_l.gif"') + '></td>';
//	sInnerHtml += '<td class="ob_t4"' + (ob_t2_showicons == false ? ' style="display:none;"' : '') + '>' + (ob_t2_showicons == true ? '<div class="ob_d4">' : '') + ((image != null && typeof(ob_icons) != 'undefined' && ob_t2_showicons == true) ? '<img src="' + ob_icons + '/' + image + '">' : '') + (ob_t2_showicons == true ? '</div>' : '') + '</td>';
//	sInnerHtml += '<td id=' + childId + ' onclick="ob_t22(this, event)" class="ob_t2">' + textOrHTML + '</td></tr></table>';	
	
	var innerHTML = '<table cellspacing="0" class="ob_t2g"><tr><td class="ob_t6"><img ' + ((subTreeURL != null) ? 'src="' + ob_style + '/plusik_l.gif" onclick="ob_t21(this, \'' + subTreeURL + '\')"' : 'src="' + ob_style + '/hr_l.gif"') + '></td>';
	innerHTML += '<td class=ob_t2></td><td id=' + childId + ' class="ob_t2" onclick="ob_t22(this, event);" >';
	innerHTML += textOrHTML + '</td></tr></table>';
	
	div.innerHTML = innerHTML;
	node = div.firstChild.firstChild.firstChild.firstChild.nextSibling.nextSibling;
	node.className = 'ob_t2';
	node.nowrap = "true";
	if (subTreeURL != null) div.innerHTML += '<table cellspacing="0" style="display: none;"><tbody><tr><td><div class=ob_d5></div></td><td class="ob_t7">Loading ...</td></tr></tbody>';	
						
	try
	{			
		if(dParent.firstChild.nextSibling.firstChild.firstChild.firstChild.nextSibling.innerHTML == "Loading ...")
		{										
			dParent.removeChild(dParent.childNodes[1]);
		}			
	}
	catch(ex){}	
    dParent.firstChild.nextSibling.firstChild.firstChild.firstChild.nextSibling.appendChild(div);
    
    if(typeof(ob_tree_dnd_enable) != "undefined" && ob_tree_dnd_enable == true)
    {
	    if(typeof(ob_t18) != 'undefined') {
			ob_t18(dParent);
	    }
	}
	
	tree_node_exp_col = true;	
	if (tree_selected_id != parentId && document.getElementById(parentId)) try{document.getElementById(parentId).onclick();}catch(ex){}
	tree_node_exp_col = false;
		
	if(typeof ob_HighlightOnDnd != "undefined" && ob_HighlightOnDnd == true)
	{
	    ob_t51();
	}
		
    ob_OnAddNode(parentId, childId, textOrHTML, expanded, image, subTreeURL);    
	return node;
}

//Functions for the Index.aspx page...
function go()
{
    var home = document.getElementById('ctl00_Main_entry_address').value;
    var url = location.href.replace(/Index.aspx/i, '');
    url = url.replace(/LearnMore.aspx/i, '');
    url += 'Default.aspx?home=' + home;       
    var addressList = readCookie("recentAddresses");
    if ((addressList == null) || (addressList.indexOf(home) == -1))
    {
        if (addressList == null) 
            addressList = home;
        else
        {   
            var addresses = addressList.split("&");
            if (addresses.length > 4)
            {
                addressList = home;
                var last = addresses.length - 4;
                for(i=addresses.length;i>last;i--)
                    addressList = addresses[i - 1] + "&" + addressList;                
            }
            else
                addressList += "&" + home;
        }
        SetCookie("recentAddresses", addressList, 90);
    }    
    window.location = url;  
}

function getFilterValue(type)
{
    //var base = "navArea3";
    //var key = base + "_ctl01_" + type;
    var base = "navArea4";
    var key = base + "_ctl00_" + type;    
    var maxDistance = document.getElementById(key);
    if (maxDistance == null)
    {
        key = base + "_ctl02_" + type;
        maxDistance = document.getElementById(key);
    }
    
    return maxDistance;
}

function setFilterValue(type, val)
{
    //var base = "navArea3";
    //var key = base + "_ctl01_" + type;
    var base = "navArea4";
    var key = base + "_ctl00_" + type;
    var maxDistance = document.getElementById(key);
    if (maxDistance == null)
    {
        key = base + "_ctl02_" + type;
        maxDistance = document.getElementById(key);
    }
    
    maxDistance.value = val;
}

function clearList()
{
    SetCookie("recentAddresses", "", 90);
    window.location.reload();
}

function clearText()
{
    var home = document.getElementById('ctl00_Main_entry_address');
    if (home.value == "Address and city, state or zip code")
    {
        home.value = "";
        home.style.color = "Black";
    }            
}

function resetText()
{
    var home = document.getElementById('ctl00_Main_entry_address');
    if (home.value == "")
    {
        home.value = "Address and city, state or zip code";
        home.style.color = "Gray";
    }            
}

//Toggle the display of the frame in height/width dimensions
function toggleFrameIn()
{
    var chkFrameIn = document.getElementById('chkFrame');
     var divFrameIn = document.getElementById('divFrameIn');
    if (chkFrameIn.checked)
    {
        var pcid = document.getElementById('PCID').value;
        if (pcid.length == 0)
        {   
            chkFrameIn.checked = false;
            if (confirm('A PCID is required to generate a frame. Do you want to sign up for one now?'))
                window.location = location.href.replace(/Default.aspx/i, 'AdminOptions/DeveloperSignup.aspx');
            else
                return;
        }
        divFrameIn.style.visibility = 'visible';
    }
    else
        divFrameIn.style.visibility = 'hidden';        
}

//Toggle the link text display and frame if we are using RAW URL only
function toggleRawURL()
{
    var rawURL = document.getElementById('chkRawURL').checked;
    var linkText = document.getElementById('navArea3_ctl01_txtTinyAddress');
    var generateFrame = document.getElementById('chkFrame');
    linkText.disabled = rawURL;
    generateFrame.disabled = rawURL;
    toggleFrameIn();
}

//Determine if user is allowed to access this feature...
function checkPreSelect()
{
    //We don't care if you are unselecting this option.
    if (document.getElementById('chkGenerateReport').checked == false)
        return;
        
    var amenities = checked_list('amenities_').replace(/amenities_/g, "");
    if (amenities.length == 0)
    {
        document.getElementById('chkGenerateReport').checked = false;
        alert('Please select one or more amenities first.');
        return;
    }
        
    var userID = document.getElementById('UserId').value;
    if (userID == 'Guest')
    {
        alert('Please login before attempting to use this feature.');
        document.getElementById('chkGenerateReport').checked = false;
    }
    else 
    {
        //We must validate you are a realtor here
        PageMethods.CheckUserRole(userID, 'Realtor', function(results)
            {
                if (results == false)
                {
                    document.getElementById('chkGenerateReport').checked = false;                    
                    if (confirm('You must have realtor access to enable this feature. Do you wish to sign up now?'))
                        window.location = location.href.replace(/Default.aspx/i, 'AdminOptions/Signup.aspx');                    
                }
            }
        );   
    }    
}

function generateURL()
{
    if (document.getElementById('UserId').value == 'Guest')
    {
        alert('Please login before attempting to use this feature.');
        return;
    }
    var address = document.getElementById('navArea1_pTimeC_address').value;
    if (address.length == 0)
    {
        alert('Please select a valid address first.');
        return;
    }
    var generateReport = document.getElementById('chkGenerateReport').checked;
    var generateFrame = document.getElementById('chkFrame').checked;
    var PCID = document.getElementById('PCID').value;
    if (generateReport)
    {
        var amenities = checked_list('amenities_').replace(/amenities_/g, "");
        if (amenities.length == 0)
        {
            document.getElementById('chkGenerateReport').checked = false;
            alert('Please select one or more amenities.');
            return;
        }
            
        var userID = document.getElementById('UserId').value;
        var homeLocation = document.getElementById('HomeLatitude').value + ":" + document.getElementById('HomeLongitude').value;        
        var center = map.getCenter();
        var centerString = center.y + ':' + center.x;
        var zoom = map.getZoom();
        PageMethods.PDFReport('', address, '', amenities, 'Y', centerString, homeLocation, zoom, userID, function(results)
            {
                PageMethods.GenerateMapURL('', results, generateFrame, PCID, setLinkText);
            }
        );    
    }
    else
        PageMethods.GenerateMapURL(address, '', generateFrame, PCID, setLinkText);        
}

function setLinkText(results)
{
    var linkText = document.getElementById('navArea3_ctl01_txtTinyAddress').value;
    var generateFrame = document.getElementById('chkFrame').checked;
    var rawURL = document.getElementById('chkRawURL').checked;
    var url = document.getElementById('generatedURL');
    url.style.visibility = 'visible';
    document.getElementById('copyText').style.visibility = 'visible';
    if (results.length == 0)
        url.value = "Error generating URL";
    else if (generateFrame)
    {
        var frameHeight = document.getElementById('frameHeight').value;
        var frameWidth = document.getElementById('frameWidth').value;
        var link = '<iframe src="' + results + '" height="' + frameHeight + 'px" width="' + frameWidth + 'px">Inline Frame Not Supported</iframe>';
        url.value = link;
    }
    else if (rawURL == false)
    {        
        link = '<a href="' + results + '" >' + linkText + '</a>';
        url.value = link;
    }
    else
        url.value = results;    
}

//If the user is logged in bring them to their list of URLs to manage...
function manageURLs()
{ 
    if (document.getElementById('UserId').value == 'Guest')
    {
        alert('Please login before attempting to use this feature.');
        return;
    }
    
    var mapWindow = window.open('AdminOptions/ManageMyURLS.aspx','ManageMyURLS','');
    if (!mapWindow)
        location.href = location.href.replace(/Default.aspx/i, 'Help/popup.aspx');       
}

function autoSelectText()
{
    var generatedURL = document.getElementById('generatedURL');
    generatedURL.focus();
    generatedURL.select();
}

function SetAddress(addr)
{
    document.getElementById('navArea1_pTimeC_address').value = addr;
    if (document.getElementById('navArea3_ctl01_txtTinyAddress') != null)
        document.getElementById('navArea3_ctl01_txtTinyAddress').value= addr;
}

