﻿/// <reference path="googlemaps-intellisense.js" />
/// <reference path="GoogleStreetViewControl.js" />
/// <reference path="PolygonDrawerPrototype.js" />
/// <reference path="Identify.js" />
/// <reference path="Measure.js" />
/// <reference path="LocalLayerController.js" />

//----------------------------------Constant Decleration------------------------------------------------------
var GISP_MAPMODE_MAP = "MAP";
var GISP_MAPMODE_POLY = "POLY";
var GISP_MAPMODE_STREET = "STREET";
var GISP_MAPMODE_IDENTIFY = "IDENTIFY";
var GISP_MAPMODE_MEASURE = "MEASURE";
var GISP_MAPMODE_POINT = "POINT";
var GISP_MAPMODE_POINT = "LOCAL";

var GISP_LOCATION_SCRIPTS = "/common/scripts/";
var GISP_LOCATION_IMAGES = "/common/images/";
var GISP_LOCATION_CSS = "/common/styles/";

var GISP_TIME_TO_WAIT_WHEN_CHECKING_LOAD_OF_SCRIPT = 300;

var GISP_STREETVIEW_CONTROLLER = "StreetViewController" + _scriptType + ".js?V=" + _AssemblyVersion;
var GISP_MEAUSRE_TOOL = "measure" + _scriptType + ".js?V=" + _AssemblyVersion;
var GISP_IDENTIFY_TOOL = "identify" + _scriptType + ".js?V=" + _AssemblyVersion;
var GISP_LOCAL_LAYER_CONTROLLER = "locallayercontroller" + _scriptType + ".js?V=" + _AssemblyVersion;
var GISP_POLYGON_DRAWER_TOOL = "polygondrawer" + _scriptType + ".js?V=" + _AssemblyVersion;
var GISP_DRAGZOOM_TOOL = "DragZoom" + _scriptType + ".js?V=" + _AssemblyVersion;
var GISP_CIRCLEDRAW_TOOL = "CircleDrawer" + _scriptType + ".js?V=" + _AssemblyVersion;
var GISP_REPORT_EXPORTER = "ReportExporter" + _scriptType + ".js?V=" + _AssemblyVersion;
var GISP_BUSINESS_REPORT_FUNCTIONS = "BusinessReportFunctions" + _scriptType + ".js?V=" + _AssemblyVersion;
var GISP_DEMOGRAPHIC_REPORT_FUNCTIONS = "DemographicReportFunctions" + _scriptType + ".js?V=" + _AssemblyVersion;

var GISP_PROPERTY_WIDTH = 190;
var GISP_PROPERTY_HEIGHT = 500;
var GISP_PROPERTY_CONTAINER_MARGIN = 48; //what is this for?
var GISP_MAP_MARGIN = 28;
var GISP_PROPERTY_PAGE_BUFFER = 3; //the number of times the page size results are kept active
var GISP_PROPERTY_PAGER_BUFFER = 2; //the number of pages shown on eiter side of the active page

var GISP_MILES_PER_METER = 0.000621371192;

var GISP_ReloadingReportQueue = [];

var _propertyMarkers = [];
var _progressBar;
var _bounds;
var _popupTracker = new GISPlanning_PopupTracker();
var _GISP_Filtering_Poly_Overlay;
var map;
var _mapBar;
var _windowResizeTimer = null;
var _inputKeyUpTimer = null;
var _inputKeyDownTimer = null;
var _JavascriptSessionID = GISPlanning_MapUtilities_GUID();
var _largeControl3D;
var _smallControl3D;
var _defaultUIOptions;
var _windowWidth;


var addthis_options = 'email, facebook, twitter, favorites, delicious, digg, google, myspace, live, stumbleupon, more';
var addthis_exclude = 'print';

var _currentLayer = null;
var _currentOverlayType = null;
var _currentCheckedDataItem = null;

var _searchWindow = null;

//This sections deals with the business map.
var _businessMapClickHandlers = {}; //an object to hold the possible handlers
var _currentBusinessMapClickHander = ""; //A reference to the currently selected handler
var _currentBusinessMapRequestID = ""; //The currentRequestID
var _currentBusinessMapQueryParams = {}; //The query used to build the current business map

var _SubsetAttributes = null;

function GISPLoad()
{
    //Set up the modals
    $('#dynamicModalWindow').attr("ready", true);
    $("#dynamicModalWindow").draggable({ handle: "#moveDynamicWindow" });

    //Set up mouseover menus
    InitMouseOverMenus();

    //Bind to the browser resize(only for width resize)
    _windowWidth = $(window).width(); //capture the current width
    $(window).bind('resize', onWindowResizeDelegate);

    //add the right click option to my folder to clear it out
    $("#myFolder").rightClick(function ()
    {
        if (confirm("Do you really want to reset My Folder?")) {
            ClearSavedResults('SITES_SAVED', false, false);
            ClearSavedResults('BUILDINGS_SAVED', false, false);
            ClearSavedResults('REPORTS_SAVED', false, false);
            ClearSavedResults('BUSINESSES_SAVED', false, false);
            //note, on this last one, we want to call persist trackers to avoid parallel errors.
            ClearSavedResults('COMMUNITIES_SAVED', false, true);
        }
    });

    ExecuteClientHeaderLoadScript();

    //TWW Create Map object
    var myMapOptions = {
        MapBarColor: '#c0c0c0',
        SearchBar: false,
        StreetView: true,
        Satellite: true,
        Terrain: true,
        Earth: true,
        PolySelect: true,
        Identify: true,
        LocalData: true,
        Pinpoint: true,
        Distance: true,
        CircleDraw: true,
        DragZoom: true,
        PolyOptions: {},
        GMapOptions: null,
        ScrollWheelZoom: false,
        ClickHandler: null,
        StreetOptions: {
            PanoDiv: $("#streetView")[0],
            ShowFunction: function ()
            {
                $("#googleMap").css({ width: "200px", height: "200px", zIndex: 1, right: "0px", left: "" });
                //restore the map
                map.checkResize();
                map.removeControl(_largeControl3D);
                map.addControl(_smallControl3D);
            },
            HideFunction: function ()
            {
                $("#googleMap").css({ width: "100%", height: "364px", zIndex: 0, right: "", left: "0px" });
                //restore the map
                map.checkResize();
                map.addControl(_largeControl3D);
                map.removeControl(_smallControl3D);
            }
        },
        PolyStartedHandler: function ()
        {
            RemovePoly(); //remove any existing permanent polygon
            HideSearch(); //in case you are coming to this from the search screen
        },
        PolySelectedHandler:
					function (markers, poly)
					{
					    var polyPointsString = '';
					    var numVertex = poly.getVertexCount();
					    for (i = 0; i < numVertex; i++) {
					        var vertex = poly.getVertex(i);
					        var lat = vertex.lat().toString().substr(0, vertex.lat().toString().indexOf('.', 0) + 5);
					        var lng = vertex.lng().toString().substr(0, vertex.lng().toString().indexOf('.', 0) + 5)
					        polyPointsString += lat + ":" + lng;

					        if (i < numVertex - 1) {
					            polyPointsString += ",";
					        }; //end if not last point
					    }; //end for each point in polygon

					    document.getElementById('hfldPolyPoints').value = polyPointsString;
					    AddPersistantPolygonInidicatingSearchArea();
					    DisplaySearch(true, _SSR._CurrentViewType.toLowerCase());
					},
        LocalOptions: { LoadedHandler: LayerControlLoaded, IsOpenByDefault: true }
    };

    _mapBar = new MapBar(document.getElementById('googleMap'), myMapOptions);
    _searchWindow = new SearchWindow();

    _progressBar = new ProgressbarControl(map, { width: 150 });
    map.setCenter(new GLatLng(mySubsetLatLng.lat, mySubsetLatLng.lng), mySubsetZoom);


    //set the default UI options
    _defaultUIOptions = map.getDefaultUI();
    _defaultUIOptions.zoom.scrollwheel = false;
    _defaultUIOptions.controls.maptypecontrol = false;
    _defaultUIOptions.controls.menumaptypecontrol = false;
    _defaultUIOptions.controls.largemapcontrol3d = false;
    map.setUI(_defaultUIOptions);
    _largeControl3D = new GLargeMapControl3D(true)
    _smallControl3D = new GSmallZoomControl3D();
    map.addControl(_largeControl3D);

    ClearLegend();
}; //end function load

function unloadMap()
{
    _mapBar.googleEarth = null;
    _mapBar = null;
    GUnload();
};

function LayerControlLoaded(sender)
{
    //National Layers
    var myAirports = new GISP_POIOverlay("AIRPORTS", _GISP_POITileBaseURL);
    var myColleges = new GISP_POIOverlay("COLLEGES", _GISP_POITileBaseURL);
    var myHospitals = new GISP_POIOverlay("HOSPITALS", _GISP_POITileBaseURL);
    var myPorts = new GISP_POIOverlay("PORTS", _GISP_POITileBaseURL);



    sender.AddLayer(new GISPlanning_MapUtilities_LocalLayer("AIRPORTS", "Airports", myAirports, "TILEOVERLAY", null, false, null, {}, [{}]));
    sender.AddLayer(new GISPlanning_MapUtilities_LocalLayer("COLLEGES", "Colleges", myColleges, "TILEOVERLAY", null, false, null, {}, [{}]));
    sender.AddLayer(new GISPlanning_MapUtilities_LocalLayer("HOSPITALS", "Hospitals", myHospitals, "TILEOVERLAY", null, false, null, {}, [{}]));
    sender.AddLayer(new GISPlanning_MapUtilities_LocalLayer("PORTS", "Ports", myPorts, "TILEOVERLAY", null, false, null, {}, [{}]));


    var myPopulation = new GISP_POIOverlay("POP", _GISP_StaticSubsetTilesBaseURL + "?SST=" + _GISP_Theme, { opacity: .7 });
    var myBachelorsDegree = new GISP_POIOverlay("BACHDEGREE", _GISP_StaticSubsetTilesBaseURL + "?SST=" + _GISP_Theme, { opacity: .7 });
    var myBizEst = new GISP_POIOverlay("BUSEST", _GISP_StaticSubsetTilesBaseURL + "?SST=" + _GISP_Theme, { opacity: .7 });
    var myMedianHHIncome = new GISP_POIOverlay("MEDHHINC", _GISP_StaticSubsetTilesBaseURL + "?SST=" + _GISP_Theme, { opacity: .7 });

    var myRRLayer = new GISP_POIOverlay("RAILROAD", _GISP_StaticSubsetTilesBaseURL + "?SST=" + _GISP_Theme, { opacity: .7 });
    var myCountiesLayer = new GISP_POIOverlay("COUNTIES", _GISP_StaticSubsetTilesBaseURL + "?SST=" + _GISP_Theme, { opacity: .7 });
    var myCitiesLayer = new GISP_POIOverlay("CITIES", _GISP_StaticSubsetTilesBaseURL + "?SST=" + _GISP_Theme, { opacity: .7 });

    sender.AddLayer(new GISPlanning_MapUtilities_LocalLayer("POPULATION", "Population", myPopulation, "TILEOVERLAY", null, false, null, {}, [{}]));
    sender.AddLayer(new GISPlanning_MapUtilities_LocalLayer("BACHDEGREE", "Bachelors Degrees", myBachelorsDegree, "TILEOVERLAY", null, false, null, {}, [{}]));
    sender.AddLayer(new GISPlanning_MapUtilities_LocalLayer("BUSEST", "Total Business Establishments", myBizEst, "TILEOVERLAY", null, false, null, {}, [{}]));
    sender.AddLayer(new GISPlanning_MapUtilities_LocalLayer("MEDHHINC", "Median Household Income", myMedianHHIncome, "TILEOVERLAY", null, false, null, {}, [{}]));


    sender.AddLayer(new GISPlanning_MapUtilities_LocalLayer("RAILROAD", "Railroads", myRRLayer, "TILEOVERLAY", null, false, null, {}, [{}]));
    sender.AddLayer(new GISPlanning_MapUtilities_LocalLayer("CITIES", "Cities", myCitiesLayer, "TILEOVERLAY", null, false, null, {}, [{}]));
    sender.AddLayer(new GISPlanning_MapUtilities_LocalLayer("COUNTIES", "Counties", myCountiesLayer, "TILEOVERLAY", null, false, null, {}, [{}]));

    //setup toggeling of layer menu
    $("tr.GISPTileLayer a").click(
        function ()
        {
            var isChecked = $(this).hasClass("set");
            if (isChecked) {
                $(this).removeClass("set");
                var myLayerID = $($(this).parents("tr:first")[0]).attr("LayerID");
                sender.HideLayer(myLayerID);
                $(".layerCheck", $(this).parent("tr:first")).removeClass("set");
                $("#tblLegend tr[layerID='" + myLayerID + "']").remove();
                $("#tblLegend tr[layerID='" + myLayerID + "']").remove();
                $("#" + myLayerID).remove();
            } else {
                $(this).addClass("set"); //mark as active
                var thisParentTR = $($(this).parents("tr:first")[0]);
                var myLayerID = thisParentTR.attr("LayerID");
                sender.ShowLayer(thisParentTR.attr("LayerID")); //show the layer


                //add to the legend
                var myBackgroundImage = $($(this).parents("tr:first")[0]).children("td:first").children("a:first").css("background-image");
                var myLegendRaw = $($(this).parents("tr:first")[0]).attr("legend");
                var myLegendObject = null;
                if (myLegendRaw != null && myLegendRaw != "") {
                    myLegendObject = eval("(" + myLegendRaw + ")");
                }


                //set the layer current
                $(".layerCheck", thisParentTR).addClass("set"); //check the box


                //add the appropriate legend type
                if (myLegendObject == null) {
                    var myItem = '<tr layerID="@layerID"><td class="@layerClass"><span class="layerIcon" style=\'background:@backgroundImage no-repeat;\'><b>@layerName</b></span> <span class="layerLabel">@layerName</span></td></tr>';
                    myItem = myItem.replace(/@layerID/g, myLayerID);
                    myItem = myItem.replace(/@layerClass/g, thisParentTR.attr("class").replace(" GISPTileLayer", ""));
                    myItem = myItem.replace(/@layerName/g, thisParentTR.attr("label").replace(/_/g, " "));
                    myItem = myItem.replace("@backgroundImage", myBackgroundImage);
                    $("#tblLegend").append(myItem);
                }
                else {
                    //create a new legend for each heat map
                    var myBaseLegendHTML = '\
                    <td valign="top" id="@ID"><table width="220" border="0" cellspacing="0" cellpadding="0" id="legendHeatItems">\
                        <tr>\
                            <td>\
                                <span id="legendLabel">@LABEL</span>\
                            </td>\
                        </tr>\
                        @ROWS\
                    </table></td>';

                    var myLegendRows = "";
                    var myBaseLegendRow = '\
                    <tr>\
                        <td style="background:url(common/helpers/legendGenerator.ashx?color=@COLOR) no-repeat;">\
                            <span class="colorBlock"></span><span class="legendLabels">@VALUE</span>\
                        </td>\
                    </tr>';

                    for (var i = 0; i < myLegendObject.Data.length; i++) {
                        var myLegendItem = myLegendObject.Data[i];
                        var myRow = myBaseLegendRow.replace("@COLOR", myLegendItem.Color).replace("@VALUE", myLegendItem.Label);
                        myLegendRows += myRow;
                    }

                    var myLegend = myBaseLegendHTML.replace("@ROWS", myLegendRows).replace("@LABEL", myLegendObject.Title).replace("@ID", myLayerID);

                    $("#trLegend").append(myLegend);


                }

            } //end else

            ResizeLegend();
        } //end click function callback
    );          //end click

    LoadLayersBasedOnSubsite(sender);
    ShowSubsetBoundary(sender);
};


function ResizeLegend()
{
    var myAvailableWidth = GetClientWidth() - 500;
    var myLegendCols = $("#trLegend td").length;

    if (myLegendCols * 220 > myAvailableWidth) {
        var numCanShow = Math.floor(myAvailableWidth / 220);
        $("#legendHolder li:first").css("width", (numCanShow * 220 - 40) + "px");
    }
    else {
        $("#legendHolder li:first").css("width", "100%");
    };


    var myMaxHeight = 320;
    //loop thru each table in the legend and count the rows. Add 50 + 28 a row up to 320
    var myMaxRows = 0;
    $("#trLegend table").each(function ()
    {
        var myNumRows = $("tr", $(this)).length;
        if (myNumRows > myMaxRows) {
            myMaxRows = myNumRows;
        };
    });

    var myHeight = 50 + 28 * myMaxRows;
    if (myHeight > myMaxHeight) {
        myHeight = myMaxHeight;
    }
    $("#legendHolder li:first").css("height", myHeight + "px");


}

function ToggleLocalLayer(pLayerID)
{
    _mapBar.ToggleLocalLayer(pLayerID);
};

function RemoveMarkers(pMap, pMarkers)
{
    for (var i = 0; i < pMarkers.length; i++) {
        pMap.removeOverlay(pMarkers[i]);
    }; //end for

    //reset the property markers
}; //end method

function ZoomToProperty(pPropertyID, REF_bounds)
{
    var myMarker = FindPropertyMarker(pPropertyID);
    var myBounds = new GLatLngBounds();
    if (myMarker != null) {
        myBounds.extend(myMarker.getLatLng());

        var myZoomLevel = map.getBoundsZoomLevel(myBounds) - 4;
        if ((myZoomLevel > 12) && (map.getCurrentMapType() == G_PHYSICAL_MAP)) {
            //it is possible when zooming in from the physical map, that you cant get close enough, but we done want to switch this out if you are in different view
            map.setMapType(G_NORMAL_MAP);
        };
        map.setZoom(map.getBoundsZoomLevel(myBounds) - 4);
        map.setCenter(myBounds.getCenter());
        myMarker.openInfoWindow(myMarker.HTML);
    }; //end if marker found

    REF_bounds = myBounds;
};

function ZoomToPropertyModal(pPropertyID)
{
    tb_show("Interactive Map", '#TB_inline?height=460&width=960&inlineId=mapContainer');
    ZoomToProperty(pPropertyID);
}; //end function



function GetStaticMapURL(pLat, pLng, pOptions)
{

    var myLink = "http://maps.google.com/staticmap?size=@WIDTHx@HEIGHT&maptype=@TYPE&key=@KEY&sensor=false&markers=@LAT,@LNG,@COLOR&zoom=@ZOOM";
    myLink = myLink.replace("@LAT", pLat);
    myLink = myLink.replace("@LNG", pLng);

    var myOptions = {
        Width: 300,
        Height: 188,
        Type: 'Roadmap',
        Key: myGoogleAPIKey,
        Color: 'green',
        Zoom: 12
    };

    //get the passed in option, or use the default and update the link
    for (var o in myOptions) {
        if (typeof (pOptions[o]) != "undefined") {
            myOptions[o] = pOptions[o];
        }; //end if option was passed in
        myLink = myLink.replace("@" + o.toUpperCase(), myOptions[o]);

    }; //end for each option

    return myLink;

};
function RemoveProgressBar() { if (_progressBar != null) { _progressBar.remove(); } }



function CheckMapType(element)
{

    jqElem = null;
    isSet = false;
    if (element != null) {
        jqElem = $(element);
        isSet = jqElem.find(".layerCheck").hasClass("set");
    }

    //uncheck all elements
    checkMeItems = $(".layerCheck", $(element).parents("table:first"));
    checkMeItems.each(function (key, val)
    {
        $(val).removeClass("set");
    });
    if (element != null) {
        jqElem.find(".layerCheck").toggleClass("set", !isSet);
    }
}

function ChangeMapType(pMapType)
{
    var myService = '';
    var myLegendType = 'R';
    var myLegendValues = null;
    var myLegend = '';
    var myLayer = 0;

    switch (pMapType) {
        case 0: myService = "STATIC_POPULATION"; myLegendType = 'S'
            myLegendValues = GISP_GetSubsetAttribute(_GISP_Theme, "LEGEND_POPULATION");
            myLegend = "Population by Block Group";
            break;
        case 1: myService = "STATIC_BACHDEGREE"; myLegendType = 'S'
            myLegendValues = GISP_GetSubsetAttribute(_GISP_Theme, "LEGEND_BACHDEGREE");
            myLegend = "Bachelors Degree % by Block Group";
            break;
        case 2: myService = "STATIC_BUSEST"; myLegendType = 'S'
            myLegendValues = GISP_GetSubsetAttribute(_GISP_Theme, "LEGEND_BUSEST");
            myLegend = "Total Business Establishments by Block Group";
            break;
        case 3: myService = "STATIC_MEDHHINC"; myLegendType = 'S'
            myLegendValues = GISP_GetSubsetAttribute(_GISP_Theme, "LEGEND_HHINCOME");
            myLegend = "Median Household Income by Block Group";
            break;
        case 4: myService = "http://gpvm002.gisplanning.net/ArcGIS/rest/services/zpdc_thematicDotMaps/MapServer"; myLayer = 2;
            myLegendValues = ["1.0% - 2.6%", "2.7% - 3.6%", "3.7% - 4.1%", "4.2% - 4.9%", "5.0% - 5.7%", "5.8% - 7.1%", "7.2% - 18.5%"];
            myLegend = "Young and Educated % by County";
            break;
        case 5: myService = "http://gpvm002.gisplanning.net/ArcGIS/rest/services/zpdc_thematictalent/MapServer"; myLegendType = 'S'
            myLegendValues = ["0.0 - 223.5", "223.6 - 269.3", "269.4 - 304.2", "304.3 - 338.5", "338.6 - 384.3", "384.4 - 456.0", "456.1 - 1962.5"];
            myLegend = "Small Business per 10K People By County";
            break;
        case 6: myService = "http://gpvm002.gisplanning.net/ArcGIS/rest/services/zpdc_thematicCOsoleprop11/MapServer"; myLegendType = 'S'
            myLegendValues = ["0 - 435", "436 - 816", "817 - 1,272", "1,273 - 2,079", "2,080 - 3,445", "3,446 - 8,227", "8,228 - 799,108"];
            myLegend = "Sole Proprietors by County";
            break;
        case 7: myService = "http://gpvm002.gisplanning.net/ArcGIS/rest/services/zpdc_thematicDotMaps/MapServer";
            myLegendValues = ["$75,000 - $1,770,000", "$1,770,000 - $4,000,000", "$4,000,000 - $8,000,000", "$8,000,000 - $16,770,000", "$16,770,000 - $36,500,000", "$36,500,000 - $80,740,000", "$80,740,000 - $994,077,000"];
            myLegend = "Venture Capital By City";
            break;
        case 8: myService = "http://gpvm002.gisplanning.net/ArcGIS/rest/services/zpdc_thematicCOstartups1/MapServer"; myLegendType = 'S'
            myLegendValues = ["0.0 - 13.4", "13.5 - 16.3", "16.4 - 18.6", "18.7 - 21.3", "21.4 - 25.0", "25.1 - 30.6", "30.7 - 153.6"];
            myLegend = "Startups per 10K People by County";
            break;
        case 9: myService = "http://gpvm002.gisplanning.net/ArcGIS/rest/services/zpdc_thematicCOavghhexp11/MapServer"; myLegendType = 'S'
            myLegendValues = ["$28,454 - $39,652", "$39,652 - $41,655", "$41,655 - $43,400", "$43,400 - $45,309", "$45,309 - $47,657", "$47,657 - $51,946", "$51,946 - $87,003"];
            myLegend = "Median Household Expenditures by County";
            break;
        case 10: myService = "http://gpvm002.gisplanning.net/ArcGIS/rest/services/zpdc_thematicmusuemszoos/MapServer"; myLegendType = 'T'
            myLegendValues = ["0", "1 - 5", "6 - 10", "11 - 50", "51 - 100", "101 - 200", "201 - 301"];
            myLegend = "Museums by County";
            break;
        case 11: myService = "http://gpvm002.gisplanning.net/ArcGIS/rest/services/zpdc_thematicrestaurants/MapServer"; myLegendType = 'S'
            myLegendValues = ["0 - 10", "11 - 50", "51 - 100", "101 - 500", "501 - 1,000", "1,001 - 5,000", "5,001+"];
            myLegend = "Restaurants by County";
            break;
        case 12: myService = "http://gpvm002.gisplanning.net/ArcGIS/rest/services/zpdc_thematicDotMaps/MapServer"; myLegendType = 'S'
            myLegendValues = ["0 - 600", "601 - 1,800", "1,801 - 3,934", "3,935 - 7,800", "7,801 - 15,612", "15,613 - 39,254", "39,255 - 82,340"];
            myLegend = "Stimulus Projects: Proposed New Jobs by City";
            break;
        case 13: myService = "http://gpvm002.gisplanning.net/ArcGIS/rest/services/zpdc_thematicDotMaps/MapServer"; myLegendType = 'S'
            myLegendValues = ["$40,000 - $69,539,100", "$69,539,100 - $223,758,769", "$223,758,769 - $473,000,000", "$473,000,000 - $884,492,300", "$884,492,300 - $1,882,706,520", "$1,882,706,520 - $3,693,249,885", "$3,693,249,885 - $6,985,021,458"];
            myLegend = "Stimulus Projects: Proposed Spending by City";
            break;
    };



    if (pMapType > 10000) {
        var myLayerInfo = GetSubsetLayerInfo(pMapType);
        myService = myLayerInfo.Service;
        myLegendType = myLayerInfo.LegendType;
        myLegendValues = [""];
        myLegend = myLayerInfo.LegendTitle;
    }


    if (_currentLayer != null) {
        if (myService.indexOf("STATIC", 0) == 0) {
            var myLayerID = myService.split("_")[1];
            _mapBar.GetLayerController().HideLayer(myLayerID);
        } else {

            map.removeOverlay(_currentLayer);
        }
    }


    //If the current overlay being displayed is also the requested overlay. Hide the overlay.
    //This is equivalent to an "un-check", as in, "I no longer want to see this overlay."
    if (_currentOverlayType != pMapType) {
        //show the layer
        //Currently two possibilities exist, our own static stiles or the Dynamic tile service
        if (myService.indexOf("STATIC", 0) == 0) {
            var myLayerID = myService.split("_")[1];
            _mapBar.GetLayerController().ShowLayer(myLayerID);
            _currentLayer = _mapBar.GetLayerController().GetLayer(myLayerID).Overlay;
        } else {
            var myResponse = function (overlay)
            {
                _currentLayer = overlay;
                map.addOverlay(overlay);
                var myLayers = [];
                myLayers.push(myLayer);
                overlay.setVisibleLayers(myLayers);
                overlay.show();
            };
            var myDynamicMap = new esri.arcgis.gmaps.DynamicMapServiceLayer(myService, null, 0.4, myResponse);
        }

        //update the legend
        UpdateLegend(myLegend, myLegendValues, myLegendType);
    }
    else {
        _currentOverlayType = null;
        ClearLegend();
        return;
    }
    _currentOverlayType = pMapType;
};

function ShowSubsetBoundary(sender)
{
    var myBounaryLayer = new GISP_POIOverlay("SUBSETBOUNDARY", _GISP_LocalTilesBaseURL + '?SST=' + _GISP_Theme, { opacity: 1 });
    sender.AddLayer(new GISPlanning_MapUtilities_LocalLayer("SUBSETBOUNDARY", "Subset Boundary", myBounaryLayer, 'TILEOVERLAY', null, false, null, {}, [{}]));
    sender.ShowLayer("SUBSETBOUNDARY");
}
function ClearLegend()
{
    var myLegendHolder = $("ul#legendHolder");
    var myLegendLabel = $("#legendLabel", myLegendHolder);
    var myLegendItems = $("#legendHeatItems", myLegendHolder);
    myLegendItems.hide();
    var myColors = ["purple", "blue", "lightblue", "yellow", "lightorange", "orange", "red"];
    //myLegendLabel.html("Select an item from the data menu...");
    for (i = 0; i < myColors.length; i++) {
        var myIncomeLabel = $("td." + myColors[i] + " span.legendLabels");
        myIncomeLabel.parent().removeClass("T").removeClass("R").removeClass("S");
        myIncomeLabel.html("");
    }
}
function UpdateLegend(pLegendLabel, pLegendValues, pLegendType)
{
    ClearLegend();
    var myLegendHolder = $("ul#legendHolder");
    var myLegendLabel = $("#legendLabel", myLegendHolder);
    var myLegendItems = $("#legendHeatItems", myLegendHolder);
    myLegendItems.show();
    var myColors = ["purple", "blue", "lightblue", "yellow", "lightorange", "orange", "red"];

    myLegendLabel.html(pLegendLabel);

    for (i = 0; i < myColors.length; i++) {
        var myIncomeLabel = $("td." + myColors[i] + " span.legendLabels");
        myIncomeLabel.parent().addClass(pLegendType);
        myIncomeLabel.html(pLegendValues[i]);
    }
    myLegendItems.show();
};



//----------------------------------Map Bar Object Definition------------------------------------------------------

function MapBar(pMapDIV, pOptions)
{

    var me = this;
    this._map = null;
    this._markers = [];
    this._mapMode = "MAP";
    this._streetViewController = null;
    this._localLayerController = null;
    this._mapDIV = pMapDIV;
    this._dragZoomControl = null;
    this._polySelectControl = null;
    this._PolySelectedHandler = (pOptions.PolySelectedHandler != undefined ? pOptions.PolySelectedHandler : null);
    this._PolyStartedHandler = (pOptions.PolyStartedHandler != undefined ? pOptions.PolyStartedHandler : null);
    this._identifyControl = null;
    this._circleDrawerControl = null;
    this._measureControl = null;
    this._googleEarth = null;
    this._googleEarthAdded = false;
    this._googleEarthMode = false;


    //component options
    this._mapOptions = (pOptions.GMapOptions != undefined ? pOptions.GMapOptions : null);
    this._googleSearchBarOptions = (pOptions.GGoogleBarOptions != undefined ? pOptions.GGoogleBarOptions : null);
    this._streetViewOptions = (pOptions.StreetOptions != undefined ? pOptions.StreetOptions : null);
    this._localOptions = (pOptions.LocalOptions != undefined ? pOptions.LocalOptions : null);


    //feature flags
    this._isGoogleSearchBarEnabled = (pOptions.SearchBar != undefined ? pOptions.SearchBar : false);
    this._isStreetViewEnabled = (pOptions.StreetView != undefined ? pOptions.StreetView : false);
    this._isPolySelectEnabled = (pOptions.PolySelect != undefined ? pOptions.PolySelect : false);
    this._isIdentifyEnabled = (pOptions.Identify != undefined ? pOptions.Identify : false);
    this._isLocalDataEnabled = (pOptions.LocalData != undefined ? pOptions.LocalData : false);
    this._isPinpointEnabled = (pOptions.Pinpoint != undefined ? pOptions.Pinpoint : false);
    this._isMeasureEnabled = (pOptions.Distance != undefined ? pOptions.Distance : false);
    this._isCircleDrawEnabled = (pOptions.CircleDraw != undefined ? pOptions.CircleDraw : false);
    this._isDragZoomEnabled = (pOptions.DragZoom != undefined ? pOptions.DragZoom : false);
    this._isScrollWheelEnabled = (pOptions.ScrollWheelZoom != undefined ? pOptions.ScrollWheelZoom : false);

    //map types
    this._isSatelliteEnabled = (pOptions.Satellite != undefined ? pOptions.Satellite : false);
    this._isTerrainEnabled = (pOptions.Terrain != undefined ? pOptions.Terrain : false);
    this._isHybridEnabled = (pOptions.Hybrid != undefined ? pOptions.Hybrid : false);
    this._isEarthEnabled = (pOptions.Earth != undefined ? pOptions.Earth : false);

    //mapbar options
    this._mapBarColor = (pOptions.MapBarColor != undefined ? pOptions.MapBarColor : '#5c5c5c');

    //handlers
    this._externalClickHandler = (pOptions.ClickHandler != undefined ? pOptions.ClickHandler : null);

    //Tooltip service
    this._tooltipService = null;

    //events
    this._loadedEvent = {};





    this._HandleMapClicks = function (pOverlay, pPoint)
    {

        //determine what was clicked on
        var myClickObjectType = null;

        if (pOverlay) {
            if (pOverlay instanceof GMarker) {
                myClickObjectType = "MARKER";
            } else if (pOverlay instanceof GPolygon) {
                myClickObjectType = "POLYGON";
            } else if (pOverlay instanceof GPolyline) {
                myClickObjectType = "POLYLINE";
            };
        };
        if (!pOverlay && pPoint) {
            myClickObjectType = "MAP";
        }; //end if not overlay and point

        //if you click on a polygon, its possible the point is null, check the second argument
        if (pPoint == null && myClickObjectType == "POLYGON") {
            if (arguments.length >= 3) {
                if (arguments[2].x != null && arguments[2].y != null) {
                    pPoint = arguments[2];
                }; //end if argument 2 is a point
            }; //end if there is a third argument
        }; //end if point is null

        //based on the map mode, process the click event
        if (me._GetMapMode() == 'IDENTIFY' && (myClickObjectType == "MAP" || myClickObjectType == "POLYGON")) {
            me._identifyControl.Identify(pOverlay, pPoint);
        } //end if mode polydraw
        else if (me._GetMapMode() == 'STREET') {
            if (myClickObjectType == "MAP") {
                me._streetViewController.MapClicked(pOverlay, pPoint);
            }; //end if object type map
        } //end if mode street
        else if (myClickObjectType == "MAP" && map.getCurrentMapType().getName() == "GISP_BUSINESS") {
            FindBusinessByClick(pPoint);
        }; //end if business layer
    };      //end click handler function


    this._SetMarkers = function (pMarkers)
    {
        me._markers = pMarkers;
        if (me._polySelectControl != null) {
            me._polySelectControl.SetFilterMarkers(pMarkers);
        }; //end if poly control not null
    }; //end set markers

    this._GetMarkers = function ()
    {
        return me._markers;
    }; //end get markers

    this._GetMap = function ()
    {
        return map;
    }; //end function get map

    this._GetPolySelectControl = function ()
    {
        return me._polySelectControl;
    }; //end function

    this._GetCircleDrawerControl = function ()
    {
        return me._circleDrawerControl;
    };

    this._GetFunctionControl = function ()
    {
        return me._functionControls;
    }; //end method




    //declare prototype methods****************************************************
    this._GetMapMode = function ()
    {
        return me._mapMode;
    };
    this._SetMapMode = function (pMapMode)
    {
        me._mapMode = pMapMode;
    };
    this._SetMapType = function (pWhatType)
    {
        //rests the map
        map.setMapType(G_NORMAL_MAP);
        //remove streetview if it is there
        if (pWhatType != "STR" && me._streetViewController != null) {
            me._streetViewController.StopStreetView();
        }; //end if not street and street was enabled

        switch (pWhatType) {
            case "HYB": map.setMapType(G_HYBRID_MAP); break;
            case "SAT": map.setMapType(G_SATELLITE_MAP); break;
            case "TER": map.setMapType(G_PHYSICAL_MAP); break;
            case "ERT": me._StartEarth(); break;
            case "STR": me._streetViewController.ToggleStreetViewOverlay(); break;

        }; //end switch maptype
    };       //end function SetMapType



    this._SetGoogleEarthObject = function (obj)
    {
        me._googleEarth = obj;
        me._googleEarthAdded = true;
        me._StartEarth();
    };

    this._StartEarth = function ()
    {
        if (me._googleEarthAdded == false) {
            map.addMapType(G_SATELLITE_3D_MAP);
            me._googleEarth = map.getEarthInstance(GISPlanning_MapUtilities_AssociateObjWithEvent(this, "_SetGoogleEarthObject"));
        }
        else {
            map.setMapType(G_SATELLITE_3D_MAP);
            me._googleEarthMode = true;
        }

    };  //end method start earch






    //DRAG ZOOM********************************************************************
    this._AddDragZoomControlWhenLoaded = function ()
    {

        var myDragZoomControl = new DragZoomControl({ opacity: .2, border: "2px solid red" }, { stickyZoomEnabled: true, buttonZoomingHTML: "", buttonStartingStyle: { display: 'none' }, buttonZoomingStyle: { display: 'none' }, overlayRemoveTime: 500 }, { dragend: null });

        me._dragZoomControl = myDragZoomControl;
        me._dragZoomControl.Start = function () { this.initiateZoom(); }; //Extend to meet the standard framework
        me._dragZoomControl.Stop = function () { this.initiateZoom(); }; //Extend to meet the standard framework (note, this looks a littly hacky, but the internal application is due to the sticky feature.)

        //here we need to create an event handler bound to the actual instance of the control, this is done with a little magic...
        var myDragZoomInstanceOfInitiateZoom = GISPlanning_MapUtilities_AssociateObjWithEvent(me._dragZoomControl, "initiateZoom")

        //because this is special control initself, we need to add it to the map (it should not physically look like anything until its activated)
        map.addControl(myDragZoomControl, new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(0, 0)));


    };         //end add drag zoom when loaded


    //POLY SELECT******************************************************************
    this._AddPolyZoomControlWhenLoaded = function ()
    {

        //create a new polydrawer object and associate it with the bar
        var myEndHandler = function ()
        {
            me._DeactivateTools();
        };

        var myPolyDrawer = new GISPlanning_MapUtilities_PolygonDrawer(me._markers,
           me._tooltipService, me._PolySelectedHandler, myEndHandler, me._PolyStartedHandler);
        me._polySelectControl = myPolyDrawer;



    };      //end add poly when loaded


    //LOCAL LAYER CONTROLLER*******************************************************
    this._AddLocalWhenESRILoaded = function ()
    {
        var myScriptLoader = new GISPlanning_MapUtilities_ScriptLoader(
            GISP_LOCATION_SCRIPTS + GISP_LOCAL_LAYER_CONTROLLER,
            "GISPlanning_MapUtilities_LocalLayerController", GISPlanning_MapUtilities_AssociateObjWithEvent(this, "_AddLocalDataWhenLoaded"));
        myScriptLoader.Load();
    };  //end add api when loaded

    this._AddLocalDataWhenLoaded = function ()
    {
        me._localLayerController = new GISPlanning_MapUtilities_LocalLayerController(me._localOptions);
    };    //end add local when loaded


    //IDENTIFY*********************************************************************
    this._AddIdentifyControlWhenLoaded = function ()
    {
        me._identifyControl = new GISPlanning_MapUtilities_Identify(me._tooltipService);

        var myActivateCallback = GISPlanning_MapUtilities_AssociateObjWithEvent(me._identifyControl, "Start");
        var myDeactivateCallback = GISPlanning_MapUtilities_AssociateObjWithEvent(me._identifyControl, "Stop");
        var activeImage = GISP_LOCATION_IMAGES + "info_active.png";
        var inactiveImage = GISP_LOCATION_IMAGES + "info_inactive.png";
        var tootip = "Get information about a point on the map including lat, lng, reverse geocode and local information";

    };    //end add identify control when loaded


    //MEASURE**********************************************************************
    this._AddMeasureControlWhenLoaded = function ()
    {
        var myEndHandler = function ()
        {
            me._DeactivateTools();
        };
        me._measureControl = new GISPlanning_MapUtilities_Ruler(me._tooltipService, myEndHandler);
    };    //end add measure when loaded

    //CIRCLE DRAWER****************************************************************
    this._AddCircleDrawerControlWhenLoaded = function ()
    {
        var myEndHandler = function ()
        {
            me._DeactivateTools();
        };
        me._circleDrawerControl = new GISPlanning_MapUtilities_CircleDrawer(me._tooltipService, me._markers, me._PolySelectedHandler, myEndHandler, me._PolyStartedHandler);
    };    //end add measure when loaded


    //STREET VIEW******************************************************************
    this._AddStreetViewWhenLoaded = function ()
    {
        me._streetViewController = new GISPlanning_MapUtilities_StreetViewController(me._streetViewOptions.PanoDiv, me._streetViewOptions.HideFunction, me._streetViewOptions.ShowFunction, null);
    };  //end add measure when loaded





    this._ActivateTool = function (pWhatTool)
    {
        //its possible that a user is trying to use more than one map tool at a time.
        if (me._CurrentlyActiveTool != null) {
            me._CurrentlyActiveTool.Stop();
        };

        var myStopUsingClass;
        var myFunctionRequiresStop = true;
        switch (pWhatTool) {
            case "PINPOINT": me._identifyControl.Start(); me._SetMapMode("IDENTIFY"); me._CurrentlyActiveTool = me._identifyControl; myStopUsingClass = "Pinpoint"; break;
            case "MEASURE": me._measureControl.Start(); me._SetMapMode("MEASURE"); me._CurrentlyActiveTool = me._measureControl; myStopUsingClass = "Measure"; break;
            case "SELECT_R": me._circleDrawerControl.Start(); me._SetMapMode("CIRCLE"); me._CurrentlyActiveTool = me._circleDrawerControl; myStopUsingClass = "Area"; break;
            case "SELECT_P": me._polySelectControl.Start(); me._SetMapMode("POLY"); me._CurrentlyActiveTool = me._polySelectControl; myStopUsingClass = "Area"; break;
            case "DRAGZOOM": me._dragZoomControl.Start(); me._SetMapMode("DRAG"); me._CurrentlyActiveTool = me._dragZoomControl; myStopUsingClass = "Zoom"; break;
            case "PRINT": myFunctionRequiresStop = false; GISP_MapUtilities_PrintMap(); break;
        }; //end switch

        if (myFunctionRequiresStop) {
            $("#stopUsingTool").css("display", "block").unbind().click(me._DeactivateTools);
            var myStopUsingClasses = ['Pinpoint', 'Measure', 'Area', 'Zoom'];
            for (var i = 0; i < myStopUsingClasses.length; i++) {
                $("#stopUsingTool").removeClass(myStopUsingClasses[i]);
            }
            $("#stopUsingTool").addClass(myStopUsingClass);
        }; //end if requires stop

    };                      //end function

    this._DeactivateTools = function ()
    {
        me._CurrentlyActiveTool.Stop();
        me._CurrentlyActiveTool = null;
        me._SetMapMode("MAP");
        $("#stopUsingTool").html("").css("display", "none").unbind();
    };      //end function


    //note: you cannot directly expose this private variable as its does not exists upon creation of the object.
    this._GetLocalLayerController = function ()
    {
        return me._localLayerController;
    }






    //==============================INITIALIZE==============================================
    this._Initialize = function ()
    {
        //create the map opject
        map = new GMap2(me._mapDIV);




        map.enableRotation();

        //enable search bar
        if (me._isGoogleSearchBarEnabled) { map.enableGoogleBar(); };

        //enable zooming with scroll wheel
        if (me._isScrollWheelEnabled) { map.enableScrollWheelZoom(); };


        //add click listener to the map
        GEvent.addListener(map, "click", me._HandleMapClicks);


        //add the tooltip service
        me._tooltipService = new GISPlanning_MapUtilities_TooltipService(map);

        //set up streetview
        if (me._isStreetViewEnabled) {
            var myScriptLoader = new GISPlanning_MapUtilities_ScriptLoader(
             GISP_LOCATION_SCRIPTS + GISP_STREETVIEW_CONTROLLER,
            "GISPlanning_MapUtilities_StreetViewController", GISPlanning_MapUtilities_AssociateObjWithEvent(me, "_AddStreetViewWhenLoaded"));
            myScriptLoader.Load();
        }; //end if streetview enabled


        //Add in Drag Zoom
        if (me._isDragZoomEnabled) {
            var myScriptLoader = new GISPlanning_MapUtilities_ScriptLoader(
            GISP_LOCATION_SCRIPTS + GISP_DRAGZOOM_TOOL,
            "DragZoomControl", GISPlanning_MapUtilities_AssociateObjWithEvent(me, "_AddDragZoomControlWhenLoaded"));
            myScriptLoader.Load();
        };


        //Add in poly Zoom
        if (me._isPolySelectEnabled) {
            var myScriptLoader = new GISPlanning_MapUtilities_ScriptLoader(
            GISP_LOCATION_SCRIPTS + GISP_POLYGON_DRAWER_TOOL,
            "GISPlanning_MapUtilities_PolygonDrawer", GISPlanning_MapUtilities_AssociateObjWithEvent(me, "_AddPolyZoomControlWhenLoaded"));
            myScriptLoader.Load();
        };

        //add in local
        if (me._isLocalDataEnabled) {
            var myScriptLoader = new GISPlanning_MapUtilities_ScriptLoader(
            "http://serverapi.arcgisonline.com/jsapi/gmaps/?v=1.4",
            "esri", GISPlanning_MapUtilities_AssociateObjWithEvent(me, "_AddLocalWhenESRILoaded"));
            myScriptLoader.Load();
        };

        //add in identify
        if (me._isIdentifyEnabled) {
            var myScriptLoader = new GISPlanning_MapUtilities_ScriptLoader(
            GISP_LOCATION_SCRIPTS + GISP_IDENTIFY_TOOL,
            "GISPlanning_MapUtilities_Identify", GISPlanning_MapUtilities_AssociateObjWithEvent(me, "_AddIdentifyControlWhenLoaded"));
            myScriptLoader.Load();
        };

        //add in measure
        if (me._isMeasureEnabled) {
            var myScriptLoader = new GISPlanning_MapUtilities_ScriptLoader(
            GISP_LOCATION_SCRIPTS + GISP_MEAUSRE_TOOL,
            "GISPlanning_MapUtilities_Ruler", GISPlanning_MapUtilities_AssociateObjWithEvent(me, "_AddMeasureControlWhenLoaded"));
            myScriptLoader.Load();
        };


        //_isCircleDrawEnabled
        if (me._isCircleDrawEnabled) {
            var myScriptLoader = new GISPlanning_MapUtilities_ScriptLoader(
            GISP_LOCATION_SCRIPTS + GISP_CIRCLEDRAW_TOOL,
            "GISPlanning_MapUtilities_CircleDrawer", GISPlanning_MapUtilities_AssociateObjWithEvent(me, "_AddCircleDrawerControlWhenLoaded"));
            myScriptLoader.Load();
        };

        //raise the loaded event
        GEvent.trigger(me._loadedEvent, "Raised");
    };          //end function initializeMap





    //=====================================CONSTRUCTOR=====================================
    return new function ()
    {
        me._Initialize();

        this.SetMarkers = me._SetMarkers;
        this.GetMarkers = me._GetMarkers;
        this.LoadedEvent = me._loadedEvent;
        this.SetMapType = me._SetMapType;

        this.PolygonDrawer = me._GetPolySelectControl;
        this.CircleDrawer = me._GetCircleDrawerControl;

        this.ActivateTool = me._ActivateTool;
        this.GetLayerController = me._GetLocalLayerController;

    };            //end constructor
}; //end mapbar definition






















function GISPlanning_MapUtilities_ScriptLoader(pScriptURL, pType, pCallback)
{
    var me = this;
    this._type = pType;
    this._Callback = pCallback;
    this._LoadScript = function ()
    {
        //append the script
        var myHead = document.getElementsByTagName("head").item(0);
        var myLink = document.createElement("script");
        myLink.setAttribute("src", pScriptURL);
        myLink.setAttribute("type", "text/javascript");
        myHead.appendChild(myLink);

        //verify its loaded
        me._ExecuteCallbackWhenScriptLoaded();
    };   //end method LoadScript

    this._ExecuteCallbackWhenScriptLoaded = function ()
    {
        if (eval("typeof(" + me._type + ") == 'undefined'")) {
            setTimeout(me._ExecuteCallbackWhenScriptLoaded, GISP_TIME_TO_WAIT_WHEN_CHECKING_LOAD_OF_SCRIPT);
        }
        else {
            if (me._Callback != null) {
                me._Callback();
            }
        }; //end if loaded
    };   //end function execute when loaded

    //CONSTRUCTOR**************************************************************
    return new function ()
    {
        this.Load = me._LoadScript;
    }; //end constructor
}; //end class Script loader



function GISPlanning_MapUtilities_CreateMarker(point, htmltext, markerType, pOptions)
{
    var myIcon = new GIcon();
    var myIconSize = null;
    var myShadowSize = null;
    var myIconAnchor = null;
    var myInfoWindowAnchor = null;
    var myIconURL = null;
    var myIconShadowURL = null;
    var myIconHighlightURL = null;

    var myOptions = { hide: false, title: null, ID: "", Modifier: "" };
    pOptions = pOptions != null ? pOptions : {};
    for (var o in myOptions) {
        if (typeof (pOptions[o]) != "undefined" && pOptions[o] != null) {
            myOptions[o] = pOptions[o];
        }; //end if option was passed in
    }; //end for each option

    // clean up markertype string. Remove _SAVED, etc
    var markerTypes = /(BUILDINGS?|SITES?|COMMUNITIES|COMMUNITY|PINPOINT|BUSINESS|OFFICE|INDUSTRIAL|RETAIL)/;

    markerType = markerTypes.exec(markerType)[0];

    // property search (building icon)
    switch (markerType) {
        case "BUILDINGS":
        case "BUILDING":
            myIconSize = new GSize(58, 36);
            myIconShadowSize = new GSize(56, 36);
            myIconAnchor = new GPoint(15, 30);
            myIconInfoWindowAnchor = new GPoint(30, 5);
            myIconURL = "/common/images/pins/multi/multiuse_pin" + myOptions.Modifier + ".png";
            myIconShadowURL = "/common/images/pins/multi/multiuse_shadow.png";
            myIconHighlightURL = "/common/images/pins/multi/multiuse_pin_over.png";
            break;
        case "SITE":
        case "SITES":
            myIconSize = new GSize(58, 36);
            myIconShadowSize = new GSize(56, 36);
            myIconAnchor = new GPoint(15, 30);
            myIconInfoWindowAnchor = new GPoint(30, 5);
            myIconURL = "/common/images/pins/land/land_pin" + myOptions.Modifier + ".png";
            myIconShadowURL = "/common/images/pins/land/land_shadow.png";
            myIconHighlightURL = "/common/images/pins/land/land_pin_over.png";
            break;
        case "PINPOINT":
            myIconSize = new GSize(15, 35);
            myIconShadowSize = new GSize(30, 35);
            myIconAnchor = new GPoint(7, 29);
            myIconInfoWindowAnchor = new GPoint(7, 5);
            myIconURL = "/common/helpers/pushpinsgenerator.ashx?color=FFCC00";
            myIconShadowURL = "/common/images/Pins/Push/shadow.png";
            myIconHighlightURL = null;
            break;
        case "BUSINESS":
            myIconSize = new GSize(15, 35);
            myIconShadowSize = new GSize(30, 35);
            myIconAnchor = new GPoint(7, 29);
            myIconInfoWindowAnchor = new GPoint(7, 5);
            myIconURL = "/common/helpers/pushpinsgenerator.ashx?color=" + myOptions.ID;
            myIconShadowURL = "/common/images/Pins/Push/shadow.png";
            myIconHighlightURL = null;
            break;
        case "COMMUNITIES":
        case "COMMUNITY":
            myIconSize = new GSize(58, 35);
            myIconShadowSize = new GSize(58, 35);
            myIconAnchor = new GPoint(18, 35);
            myIconInfoWindowAnchor = new GPoint(18, 5);
            myIconURL = "/common/images/pins/community/community_pin" + myOptions.Modifier + ".png";
            myIconShadowURL = "/common/images/pins/community/community_shadow.png";
            myIconHighlightURL = "/common/images/pins/community/community_pin_over.png";
            break;
        case "OFFICE":
            myIconSize = new GSize(58, 35);
            myIconShadowSize = new GSize(58, 35);
            myIconAnchor = new GPoint(18, 35);
            myIconInfoWindowAnchor = new GPoint(18, 5);
            myIconURL = "/common/images/pins/office/office_pin" + myOptions.Modifier + ".png";
            myIconShadowURL = "/common/images/pins/office/office_shadow.png";
            myIconHighlightURL = "/common/images/pins/office/office_pin_over.png";
            break;
        case "INDUSTRIAL":
            myIconSize = new GSize(58, 35);
            myIconShadowSize = new GSize(58, 35);
            myIconAnchor = new GPoint(18, 35);
            myIconInfoWindowAnchor = new GPoint(18, 5);
            myIconURL = "/common/images/pins/industrial/industrial_pin" + myOptions.Modifier + ".png";
            myIconShadowURL = "/common/images/pins/insustrial/industrial_shadow.png";
            myIconHighlightURL = "/common/images/pins/industrial/industrial_pin_over.png";
            break;
        case "RETAIL":
            myIconSize = new GSize(58, 35);
            myIconShadowSize = new GSize(58, 35);
            myIconAnchor = new GPoint(18, 35);
            myIconInfoWindowAnchor = new GPoint(18, 5);
            myIconURL = "/common/images/pins/retail/retail_pin" + myOptions.Modifier + ".png";
            myIconShadowURL = "/common/images/pins/retail/retail_shadow.png";
            myIconHighlightURL = "/common/images/pins/retail/retail_pin_over" + myOptions.ID + ".png";
            break;
        default:
            myIconSize = new GSize(58, 35);
            myIconShadowSize = new GSize(58, 35);
            myIconAnchor = new GPoint(18, 35);
            myIconInfoWindowAnchor = new GPoint(18, 5);
            myIconURL = null;
            myIconShadowURL = null;
            myIconHighlightURL = null;
            break;

    }; //end switch marker type




    myIcon.iconSize = myIconSize;

    if (myIconShadowSize != null) {
        myIcon.shadowSize = myIconShadowSize;
    }; //end if shadow
    myIcon.iconAnchor = myIconAnchor;
    myIcon.infoWindowAnchor = myIconInfoWindowAnchor;

    var myGIcon = new GIcon(myIcon, myIconURL, null, (myIconShadowURL != null ? myIconShadowURL : null));     // building marker for properties
    var myGMarker = new GMarker(point, { icon: myGIcon, title: myOptions.title, hide: myOptions.hide });
    myGMarker.HTML = htmltext;
    myGMarker.Highlight = function ()
    {
        this.setImage(myIconHighlightURL);
    };
    myGMarker.Lowlight = function ()
    {
        this.setImage(this.getIcon().image);
        this.setLatLng(this.getLatLng()); //this is undocumented hack to bring icon to the front
    };


    myGMarker.ClickEventHandler = GEvent.addListener(myGMarker, "click", function ()
    {
        this.openInfoWindowHtml(this.HTML);
    });

    if (myIconHighlightURL != null) {
        GEvent.addListener(myGMarker, "mouseover", function ()
        {
            this.Highlight();
            $("#" + myOptions.ID).addClass("mouseover");
        });
        GEvent.addListener(myGMarker, "mouseout", function ()
        {
            this.Lowlight();
            $("#" + myOptions.ID).removeClass("mouseover");
        });
    };

    return myGMarker;
}; //end function createMarker


/* A general function that associates an object instance with an event
handler. The returned inner function is used as the event handler.
The object instance is passed as the - obj - parameter and the name
of the method that is to be called on that object is passed as the -
methodName - (string) parameter.
*/
function GISPlanning_MapUtilities_AssociateObjWithEvent(obj, methodName, args)
{
    /* The returned inner function is intended to act as an event
    handler for a DOM element:-
    */
    return (function (e)
    {
        /* The event object that will have been parsed as the - e -
        parameter on DOM standard browsers is normalised to the IE
        event object if it has not been passed as an argument to the
        event handling inner function:-
        */
        e = e || window.event;
        /* The event handler calls a method of the object - obj - with
        the name held in the string - methodName - passing the now
        normalised event object and a reference to the element to
        which the event handler has been assigned using the - this -
        (which works because the inner function is executed as a
        method of that element because it has been assigned as an
        event handler):-
        */
        return obj[methodName](e, this, args);
    });
};


//attaches an event listener
function AddEventHandler(obj, eventName, handler)
{
    //add event handlers
    if (obj.addEventListener == undefined) {//this occurs when using IE
        obj.attachEvent(eventName, handler);
    }
    else {//hopefully everything else
        obj.addEventListener(eventName, handler, false);
    }; //end attaching events
};


//adds a click handler (specialized version of AddEventHandler)
function AddClickHandler(obj, handler)
{
    //add event handlers
    if (obj.addEventListener == undefined) {//this occurs when using IE
        obj.attachEvent("onclick", handler);
    }
    else {//hopefully everything else
        obj.addEventListener("click", handler, false);
    }; //end attaching events
};



function GISP_MapUtilities_PrintMap()
{
    var myMapGuid = GISPlanning_MapUtilities_GUID();

    //NOTE: Must use jquery clone in order to remove the event references so that removing the nonexportable and nonpopout methods
    //doesnt destroy the events
    var myMapClone = $("#map").clone()[0];
    GISP_RemoveNonExportable(myMapClone);
    GISP_RemoveNonPopout(myMapClone);
    var myMapContent = myMapClone.innerHTML;


    _popupTracker.AddContent(myMapGuid, myMapContent);

    GISPlanning_Popup_Window('main/reportViewers/map.aspx?id=' + myMapGuid, { width: 960, height: 420 });

}; //end function


function GISP_RemoveNonExportable(pHtml)
{
    $("body").append("<div id='GISP_RemoveNonExportable' style='display:none;'>" + pHtml + "</div>");

    var $nonExportable = $("#GISP_RemoveNonExportable");

    $nonExportable.find(".nonexportable").remove();
    $nonExportable.find("#__VIEWSTATE").remove();
    $nonExportable.find(".saveSlider").remove();
    $nonExportable.find(".propertyInfofg h4").remove();

    var html = $nonExportable.html();
    $nonExportable.remove();
    return html;
}; //end function

function GISP_RemoveNonPopout(pDomElement)
{
    $("body").append("<div id='GISP_RemoveNonPopout' style='display:none;'>" + pDomElement + "</div>");

    $("#GISP_RemoveNonPopout").find(".nonpopout").remove();

    var html = $("#GISP_RemoveNonPopout").html();

    $("#GISP_RemoveNonPopout").remove();
    return html;
}; //end function

function GISP_RemoveFunctionHyperlinks(pDomElement)
{
    //modify all hyperlinks to remove JS Functions
    $(pDomElement).find("a").each(function ()
    {
        if (this.href.indexOf("javascript:") != -1) {
            this.setAttribute("href", "");
        }; //end if function link
    });
}; //end function



//This function takes a collection of attributes and sets each one on the HTML element
function GISPlanning_MapUtilities_SetHTMLAttributes(element, attributeCollection)
{
    for (var attribute in attributeCollection) {
        element[attribute] = attributeCollection[attribute];
    } //end for each attribute
} //end function




//------------------------ Tooltip Service --------------------------------------------------------------------------


function GISPlanning_MapUtilities_TooltipService(map)
{
    this._map = map;
    this.tooltip = document.createElement("div");
    this.tooltip.className = "GISPlanning_MapUtilities_Tooltip";
    map.getPane(G_MAP_MARKER_PANE).appendChild(this.tooltip);

    //methods
    this.HideTooltip = function ()
    {
        this.tooltip.innerHTML = '';
        this.tooltip.style.display = "none";
    };  //end function

    this.DisplayTooltip = function (latlng, tooltipText)
    {
        if (typeof latlng != "undefined") {
            this.tooltip.innerHTML = tooltipText;
            this.tooltip.style.display = "block";

            var currtype = map.getCurrentMapType().getProjection();
            var point = currtype.fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0, 0), true), map.getZoom());
            var offset = currtype.fromLatLngToPixel(latlng, map.getZoom());
            var width = 10;
            var height = 10;
            var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x + width, offset.y - point.y - height));
            pos.apply(this.tooltip);
        };
    };     //end function
}; //end function class



function GISPlanning_MapUtilities_OptionCollection(pOptions)
{
    /// <summary>
    ///	Provides generic wrapper for working with the object literal collection
    /// </summary>
    /// <returns type="Object"></returns>
    /// <param name="Option Collection" type="Literal" optional="false">The Javascript object literal to wrap</param>
    var me = this;
    //FIELDS*******************************************************************
    this._options = pOptions;

    //FUNCTIONS****************************************************************
    this._getOption = function (option)
    {
        ///<summary>Returns the option or null if it doesnt exist</summary>
        return typeof me._options[option] != "undefined" ? me._options[option] : null;
    };  //end function getOption
    this._setOption = function (option, value)
    {
        ///<summary>Sets the option even if it doesnt exist</summary>
        me._options[option] = value;
    }; //end function setOption

    //CONSTRUCTOR**************************************************************
    return new function ()
    {
        this.GetOption = me._getOption;
        this.SetOption = me._setOption;
    }; //end constructor
};


function GISPlanning_MapUtilities_latLonInMapBounds(lat, lon)
{
    var bounds = map.getBounds();
    if (lat < bounds.minY || lat > bounds.maxY ||
         lon < bounds.minX || lon > bounds.maxX) {
        return false;
    } else {
        return true;
    }; //end if/else
}; //end function

function GISPlanning_MapUtilities_RegisterCSSFile(pURL)
{
    var myHead = document.getElementsByTagName("head").item(0);
    var myCSSLink = document.createElement("link");
    myCSSLink.setAttribute("href", pURL);
    myCSSLink.setAttribute("rel", "stylesheet");
    myCSSLink.setAttribute("type", "text/css");
    myHead.appendChild(myCSSLink);
}; //end function register CSS

function GISPlanning_MapUtilities_RegisterScript(pURL)
{
    //append the script
    var myHead = document.getElementsByTagName("head").item(0);
    var myLink = document.createElement("script");
    myLink.setAttribute("src", pURL);
    myLink.setAttribute("type", "text/javascript");
    myHead.appendChild(myLink);
}; //end method



function GISPlanning_MapUtilities_GUID()
{
    this._R4 = function ()
    {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    }; //end function R4
    this._GetNewRequestID = function GetRequestID()
    {
        return (this._R4() + this._R4() + "-" + this._R4() + "-" + this._R4() + "-" + this._R4() + "-" + this._R4() + this._R4() + this._R4());
    }; //end function GetNewRequestID

    return this._GetNewRequestID();
}; //end



function GISPlanning_GetListboxOptionsAsList(pListbox, pDelimiter)
{
    var myReturnString = '';
    for (var i = 0; i < pListbox.options.length; i++) {
        myReturnString = myReturnString + pListbox.options[i].value;
        if (i < pListbox.options.length - 1) {
            myReturnString = myReturnString + pDelimiter;
        }; //end if not last option
    }; //end for each option

    return myReturnString;
};

function GISPlanning_GetListboxDisplayItemsAsList(pListbox, pDelimiter)
{
    var myReturnString = '';
    for (var i = 0; i < pListbox.options.length; i++) {
        myReturnString = myReturnString + pListbox.options[i].text;
        if (i < pListbox.options.length - 1) {
            myReturnString = myReturnString + pDelimiter;
        }; //end if not last option
    }; //end for each option

    return myReturnString;
};


function GISPlanning_Popup_Window(pURL, pOptions)
{
    var myWindowOptions = { toolbar: "0", scrollbars: "1", location: "0", statusbar: "0", menubar: "0", resizable: "1", width: "970", height: "650", left: "300", top: "0" };
    pOptions = pOptions != null ? pOptions : {};
    for (var o in myWindowOptions) {
        if (typeof (pOptions[o]) != "undefined") {
            myWindowOptions[o] = pOptions[o];
        }; //end if option was passed in
    }; //end for each option
    var myDay = new Date();
    var myId = myDay.getTime();
    window.open(pURL, myId, 'toolbar=' + myWindowOptions["toolbar"] + ',scrollbars=' + myWindowOptions["scrollbars"] + ',location=' + myWindowOptions["location"] + ',statusbar=' + myWindowOptions["statusbar"] + ',menubar=' + myWindowOptions["menubar"] + ',resizable=' + myWindowOptions["resizable"] + ',width=' + myWindowOptions["width"] + ',height=' + myWindowOptions["height"] + ',left =' + myWindowOptions["left"] + ',top = ' + myWindowOptions["top"]);
}; //end function

function GISPlanning_PopupTracker()
{
    this.Container = {};
    this.GetContent = function (pKey)
    {
        return this.Container[pKey];
    }; //end method
    this.AddContent = function (pKey, pContent)
    {
        this.Container[pKey] = pContent;
    }; //end method
}; //end class GISPlanning_PopupTracker



function GISPlanning_AddPopup(pElement, pEM_HTML)
{
    $(pElement).append(pEM_HTML);

    $(pElement).click(function ()
    {
        $(this).find("em").animate({ opacity: "show" }, "slow");
    });
    $(pElement).hover(function () { }, function ()
    {
        $(this).find("em").animate({ opacity: "hide" }, "fast");
    });
}; //end function

function GISPlanning_HidePopup(pID)
{
    var myPopup = $get(pID);
    $(myPopup).find("em").animate({ opacity: "hide" }, "fast");
}; //end function


function GISPlanning_CreateGCircle(pLat, pLng, pRadius)
{
    var myRadiusX = pRadius / (69.1);
    var myRadiusY = pRadius / (69.1 * Math.cos(pLat / 57.3));
    var myCirclePoints = [];


    for (var k = 0; k < 6.28; k += 0.10) {
        var myPoint = new GLatLng(
			    pLat + (myRadiusX * Math.sin(k)), pLng + (myRadiusY * Math.cos(k))
			);

        myCirclePoints.push(myPoint);
    }; //end for

    myCirclePoints.push(myCirclePoints[0]);

    var myCircle = new GPolyline(myCirclePoints);

    return myCircle;

}; //end function

function GISP_NullOrInputValue(pElementID)
{
    var myInputElement = $get(pElementID);
    var myReturnValue = null;
    switch (myInputElement.type) {
        case "text":
            myReturnValue = myInputElement.value; break;
        case "select-one":
            for (var i = 0; i < myInputElement.options.length; i++) {
                if (myInputElement.options[i].selected) {
                    myReturnValue = myInputElement.options[i].value;
                    break;
                }; //end if selected
            }; //end for
            break;
        case "checkbox":
            myReturnValue = myInputElement.checked; break;
    }; //end switch
    return myReturnValue != "" ? myReturnValue : null;
};


function GISP_GetDropDownSelectedDisplayValue(pDropDown)
{
    var myReturnValue = null;
    for (var i = 0; i < pDropDown.options.length; i++) {
        if (pDropDown.options[i].selected) {
            myReturnValue = pDropDown.options[i].text;
            break;
        }; //end if selected
    }; //end for
    return myReturnValue;
}; //end function

function DisplayInlineTable(pTableID)
{
    if ($.browser.msie) {
        $get(pTableID).style.display = "inline";
    } else {
        $get(pTableID).style.display = "inline-table";
    }; //end ifelse IE
}; //end function

function GetClientWidth()
{
    var x = 0;
    if (self.innerHeight) {
        x = self.innerWidth;
    }
    else if (document.documentElement && document.documentElement.clientHeight) {
        x = document.documentElement.clientWidth;
    }
    else if (document.body) {
        x = document.body.clientWidth;
    }
    return x;
}
function GetClientHeight()
{
    var y = 0;
    if (self.innerHeight) {
        y = self.innerHeight;
    }
    else if (document.documentElement && document.documentElement.clientHeight) {
        y = document.documentElement.clientHeight;
    }
    else if (document.body) {
        y = document.body.clientHeight;
    }
    return y;
}

function FixIE7IndexingContainer(pContainer, pStartZIndex)
{
    if (($.browser.msie && jQuery.browser.version < 8) || ($.browser.msie && $("meta[content='IE=EmulateIE7']").length == 1)) {
        //pContainer is a jquery container, pStartZIndex is optional
        var zIndexNumber = pStartZIndex != null ? pStartZIndex : 1000;
        $('div:not(.zSpecial), ul:not(.zSpecial), li:not(.zSpecial), span:not(.zSpecial), a:not(.zSpecial)', pContainer).andSelf().each(function ()
        {
            $(this).css('zIndex', zIndexNumber);
            zIndexNumber -= 1;
        });
    }
};

function formatNumber(nStr)
{
    if (isNaN(nStr)) { return nStr; }
    nStr += ''; x = nStr.split('.'); x1 = x[0]; x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) { x1 = x1.replace(rgx, '$1' + ',' + '$2'); }
    return x1 + x2;
}; //end function

// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function (from, to)
{
    var rest = this.slice((to || from) + 1 || this.length);
    this.length = from < 0 ? this.length + from : from;
    return this.push.apply(this, rest);
};


function ExecuteClientHeaderLoadScript()
{
    if (typeof (HeaderLoad) != "undefined") {
        HeaderLoad();
        return true;
    }
    else {
        return false;
    }
}


function ExecuteHeaderCommand(pCommand, pOptions)
{
    switch (pCommand) {
        case "FINDPROPERTIES": DisplaySearch(false, "SITES"); break;
        case "FINDBUILDINGS": DisplaySearch(false, "BUILDINGS"); break;
        case "FINDCOMMUNITIES": DisplaySearch(false, "COMMUNITIES"); break;
        case "FINDBUSINESSES": DisplaySearch(false, "BUSINESSES"); break;
        case "RESOURCES": throw "Not implemented yet"; break;
        case "COMMUNITYREPORTS": DisplaySearch(false, "COMMUNITIES"); break;
        case "ADMINLOGIN": throw "Not implemented yet"; break;
    }
}


//domCorners by Alessandro Fulciniti on web-graphics.com

function DomCheck()
{
    return (document.createElement && document.getElementById)
}

function DomCorners(id, bk, h, tries)
{
    var el = document.getElementById(id);
    if (el == null) {                              // if the element isn't ready in the DOM...
        if (tries == null) tries = 200;
        if (tries > 0)                            // and there are still tries...
            setTimeout("DomCorners('" + id + "','" + bk + "'," + h + "," + (--tries) + ")", 50);  // back in 50ms
        return;
    }
    var c = new Array(4);
    for (var i = 0; i < 4; i++) {                      // create the four elements for rounded corners
        c[i] = document.createElement("b");
        c[i].style.display = "block";            // with necessary style declarations
        c[i].style.height = h + "px";
        c[i].style.fontSize = "1px";
        if (i % 2 == 0)
            c[i].style.background = "url(" + bk + ") no-repeat 0 -" + i * h + "px";
        else
            c[i].style.background = "url(" + bk + ") no-repeat 100% -" + i * h + "px";
    }
    c[0].appendChild(c[1]);
    c[2].appendChild(c[3]);
    el.style.padding = "0";
    el.insertBefore(c[0], el.firstChild);       // add top corners
    el.appendChild(c[2]);                      // and bottom ones
}


function GetStateAbbreviation(pStateID)
{
    var myAbbrev = {
        "01": "AL",
        "02": "AK",
        "04": "AZ",
        "05": "AR",
        "06": "CA",
        "08": "CO",
        "09": "CT",
        "10": "DE",
        "11": "DC",
        "12": "FL",
        "13": "GA",
        "15": "HI",
        "16": "ID",
        "17": "IL",
        "18": "IN",
        "19": "IA",
        "20": "KS",
        "21": "KY",
        "22": "LA",
        "23": "ME",
        "24": "MD",
        "25": "MA",
        "26": "MI",
        "27": "MN",
        "28": "MS",
        "29": "MO",
        "30": "MT",
        "31": "NE",
        "32": "NV",
        "33": "NH",
        "34": "NJ",
        "35": "NM",
        "36": "NY",
        "37": "NC",
        "38": "ND",
        "39": "OH",
        "40": "OK",
        "41": "OR",
        "42": "PA",
        "44": "RI",
        "45": "SC",
        "46": "SD",
        "47": "TN",
        "48": "TX",
        "49": "UT",
        "50": "VT",
        "51": "VA",
        "53": "WA",
        "54": "WV",
        "55": "WI",
        "56": "WY",
        "72": "PR"
    };

    return myAbbrev[pStateID];
}



function GISP_GetSubsetAttribute(pSubsetToken, pAttributeToken)
{


    var myAttributeValue = null;
    $.ajax({
        url: "/common/services/Utilities.asmx/GetSubsetAttribute",
        async: false,
        data: "{'pSubsetToken': '" + pSubsetToken + "','pAttributeToken':'" + pAttributeToken + "'}",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        type: "POST",
        cache: false, //TODO: insures the latest version (we may want to consider turning this off after development)
        success: function (result)
        {
            myAttributeValue = result.d;
        }
    });

    return myAttributeValue.split('|');
}


function GISP_MergeOptionsWithDefault(pDefault, pOptions)
{

    var myOptions = pDefault;
    pOptions = pOptions != null ? pOptions : {};
    for (var o in myOptions) {
        if (typeof (pOptions[o]) != "undefined" && pOptions[o] != null) {
            myOptions[o] = pOptions[o];
        }; //end if option was passed in
    }; //end for each option
}


function ShowBusinessMapTileLayer(pRequestID)
{

    //see if the maptype is already registered (this happens when modifying)
    var myCurrentMapTypes = map.getMapTypes();
    $(myCurrentMapTypes).each(function ()
    {
        if (this.getName() == "GISP_BUSINESS") {
            map.removeMapType(this);
        };
    });

    var businessLayer = new GTileLayer(new GCopyrightCollection("GISPlanning"), 5, 9);
    businessLayer.getCopyright = function (a, b)
    {
        return { prefix: "Imagery: GISPlanning", copyrightTexts: ["GISPlanning"] };
    };
    businessLayer.isPng = function () { return true; };

    var myBusinessMap = new GMapType([G_NORMAL_MAP.getTileLayers()[0], businessLayer], G_NORMAL_MAP.getProjection(), "GISP_BUSINESS", { maxResolution: 17, minResolution: 8, errorMessage: "No Data Available" });
    map.addMapType(myBusinessMap);

    // Custom tile URL function for an image generated "on the fly" by a script...;
    businessLayer.getTileUrl = function (point, zoom)
    {
        return "/common/helpers/GetBusinessTile.ashx?Z=" + zoom + "&X=" + point.x + "&Y=" + point.y + "&R=" + pRequestID;
    };

    map.addMapType(myBusinessMap);
    map.setMapType(myBusinessMap);
};

function GetAllBusinessTypes(pCallback)
{
    var myBusinessTypes = null;
    $.ajax({
        type: "POST",
        dataType: "json",
        data: "{}",
        async: true,
        contentType: "application/json; charset=utf-8",
        url: "/common/services/Business.asmx/GetAllBusinessTypes",
        success: function (msg, status)
        {
            myBusinessTypes = msg.d;
            pCallback(myBusinessTypes);
        }
    });
};

//Get's all NAICS 2-digit classes, and returns them to a callback function
function GetAllNaicsClasses(pCallback)
{
    var myNaicsClasses = null;
    $.ajax({
        type: "POST",
        dataType: "json",
        data: "{}",
        async: true,
        contentType: "application/json; charset=utf-8",
        url: "/common/services/Business.asmx/GetAllNAICS",
        success: function (msg, status)
        {
            myNaicsClasses = msg.d;
            pCallback(myNaicsClasses);
        },
        error: function () { }
    });
};

//Get's all NAICS 6 digits, and returns them to a callback function
function GetAllNAICS(pCallback)
{
    var myNaicsClasses = null;
    $.ajax({
        type: "POST",
        dataType: "json",
        data: "{}",
        async: true,
        contentType: "application/json; charset=utf-8",
        url: "/common/services/Business.asmx/GetAllNAICSCodes",
        success: function (msg, status)
        {
            myNaicsCodes = msg.d;
            pCallback(myNaicsCodes);
        },
        error: function () { }
    });
};


function FindBusinessByClick(pPoint)
{
    $.ajax({
        type: "POST",
        async: true,
        url: "/common/services/Business.asmx/FindBusinessIDByLatLngRequestID",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        data: "{'pLat':'" + pPoint.lat() + "','pLng':'" + pPoint.lng() + "','pRequestID':'" + _currentBusinessMapRequestID + "' }",
        success: function (msg)
        {
            //call the currently set click handler for business mapping.

            delete msg.d.__type;  //remove this pesky attribute that causes seralization failure when present
            _businessMapClickHandlers[_currentBusinessMapClickHander](msg.d);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown)
        {
            alert(errorThrown);
        }
    });
}; //end function

function GetBusinessInformation(pBusinessID, pSuccessCallback, pFailCallback)
{
    //Ajax request to get additional business info
    $.ajax({
        type: "POST",
        async: true,
        url: "/common/services/Business.asmx/GetAdditionalBusinessInformation",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        data: "{'pBusinessID':'" + pBusinessID + "'}",
        success: function (msg)
        {
            delete msg.d.__type;  //remove this pesky attribute that causes seralization failure when present
            pSuccessCallback(msg);
        },
        error: pFailCallback
    });
}


function ShowErrorMessage(pError)
{
    var myMessage = JSON.stringify(pError);
    $("#errorMessage").html(myMessage);
}

function LogUsage(pUsage)
{
    pUsage.SubsetTOKEN = _GISP_Theme;
    pUsage.SessionID = _JavascriptSessionID;
    var myUsage = { "pUsage": pUsage };
    //record usage and move on, nothing to see here.
    $.ajax({
        type: "POST",
        async: true,
        url: "/common/services/Analysis.asmx/RecordUsage",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(myUsage),
        success: function (msg)
        {
            //Do nothing
        },
        error: function (XMLHttpRequest, textStatus, errorThrown)
        {
            alert(XMLHttpRequest);
        }
    });
}

function LogReportUsage(pID, pReport, pValue)
{
    var myUsageType = "";
    switch (pReport) {
        case "FULL": myUsageType = "FULLPROPERTYRPT"; break;
        case "COMMUNITY": myUsageType = "COMMUNITYRPT"; break;
        case "BUSINESS": myUsageType = "BUSINESSRPT"; break;
        case "CONSUMERSPENDING": myUsageType = "CONSUMERRPT"; break;
        case "DEMOGRAPHICS": myUsageType = "DEMOGRAPHICSRPT"; break;
        case "LABORFORCE": myUsageType = "LABORFORCERPT"; break;
    } //end switch
    LogUsage({ "Type": myUsageType, "ID": pID, "Value": pValue });
}