/// <reference path="Utilities.js" />
/// <reference path="SearchResults.js" />
/// <reference path="SearchFunctions.js" />
/// <reference path="MapFunctions.js" />
/// <reference path="jquery-1.2.6.pack.js" />
/// <reference path="CommunitySearchSitesResultsBuilder.js" />

var _ReportScriptToEvalAfterLoadingReport = null; //this is used to store the script to evaluate so that when you call a report you can finish the async request
var GISP = GISP || {};

GISP.ReportFunctions = function (dependencies) {
    function ExecuteReportScriptToEvalAfterLoadingReport() {
        eval(_ReportScriptToEvalAfterLoadingReport);
    }
    function ViewSavedReport(pUniqueID, pResultID, pType, pTab, pRadius) {
        //because any given property of community report can have only one subreport of any one type and any time, we will set the id of the subreport to the unique
        //report for the parent report and then call view report.

        var mySavedReport = _SSR.GetReportByUniqueID(pUniqueID);
        var mySavedParentReport = _SSR.GetReportByUniqueID(mySavedReport.Properties.ParentReportID);

        mySavedParentReport.SubReports[pTab] = mySavedReport.UniqueID;

        ViewPropertyReport(pResultID, pType, pTab, pRadius);
    }
    function ViewPointReport(pID, pReportType) {
        log.info("ViewPointReport() ID: " + pID + " ReportType: " + pReportType);
        var myResult = _SSR.GetResultByID(pID, "POINTS");

        if (typeof (myResult) === "undefined" || myResult === null) {

            var decodedID = FindByLocation_DecodeID(pID);
            myResult = {
                ID: pID,
                UniqueID: pID,
                lat: decodedID.lat,
                lng: decodedID.lng,
                radius: decodedID.radius
            };

        }
        _SSR._StopProcessCurrentIterativeAsyncResultOperation = true;
        var myLink = "/main/PropertyDetails.aspx?ID=" + pID;
        myLink += "&SST=" + _GISP_Theme + "&ReportType=POINTS";

        CreateLoadingScreen("CONTENT");

        //if a pReportType or tab was specified, append that to the querystring
        if (typeof (pReportType) !== "undefined" && pReportType !== null) {
            myLink += "&tab=" + pReportType;
        }

        _SSR.NavigationHistory_Add(pReportType, "POINTS", 0, pID);

        var myReport = _SSR.GetReportByTypeAndID("POINTS", pID);
        myReport = new GISP_Report({ Name: "Points Report", Parameters: { Lat: myResult.lat, Lng: myResult.lng, SUBSET: _GISP_Theme, Radius: myResult.radius} });
        myReport.ID = pID;
        myReport.Type = "POINTS";
        myReport.UniqueID = pID;
        _SSR.AddReport(myReport);
        myLink += "&UniqueID=" + myReport.UniqueID;
        if (myResult.radius !== undefined && myResult.radius !== null) {
            myLink += "&Radius=" + myResult.radius;
        }
        DisplayReport(myLink, myReport.UniqueID);
    }
    function ViewPropertyReport(pID, pType, pTab, pRadius) {
        log.info("ViewPropertyReport() ID: " + pID + " Type: " + pType + " Tab: " + pTab + " Radius: " + pRadius);
        // Is the report in the tracker (i.e. in memory)?
        var myResult = _SSR.GetResultByID(pID, pType);

        if (typeof (myResult) === "undefined" || myResult === null) {
            //Report not found in js memory, get from db
            RequestPropertyByID(pID, { Tab: pTab, Radius: pRadius, ResultType: pType });
        } else {
            //stop async processes of loading pins
            _SSR._StopProcessCurrentIterativeAsyncResultOperation = true;

            if (ReportBeingViewed(pID)) {
                // Report is being viewed, no need to continue. Just switch tab
                ShowCurrentReportAndSwitchToTab(pTab, "FULL");
                LogViewPropertyReport(pID);
            }
            else {
                HideOtherPinsZoomToCurrent(map, _propertyMarkers, pID, myResult, pType);

                var myLink = CreateLink(pID, _GISP_Theme, pType, pTab);
                //Add navigation to the stack
                _SSR.NavigationHistory_Add("REPORT", pType, 0, pID);

                // Find report, see if it's already saved in the tracker
                var myReport = _SSR.GetReportByTypeAndID(pType, pID);

                //check and see if the report exists in the saved department
                if (typeof (myReport) === "undefined" && myReport === null) {
                    myReport = _SSR.GetReportByTypeAndID(pType, pID);
                }

                if (typeof (myReport) !== "undefined" && myReport !== null) {
                    log.info(" - Report was not null, and is already in tracker");
                    _SSR._CurrentReportID = myReport.UniqueID;
                    ShowCurrentReportAndSwitchToTab(pTab, "FULL");
                } else {
                    log.error("- Report was null, creating new report");
                    myReport = CreateNewReport(myResult, _GISP_Theme, pRadius, pID, pType);
                    _SSR.AddReport(myReport);
                    myLink += "&UniqueID=" + myReport.UniqueID;
                    if (pRadius !== null) {
                        myLink += "&Radius=" + pRadius;
                    }
                    log.info("- Displaying new report. Link: " + myLink + " UniqueID: " + myReport.UniqueID);
                    DisplayReport(myLink, myReport.UniqueID);
                } //end if report is null
            }
            LogViewPropertyReport(pID);
        } //end if result not null
    } // End ViewPropertyReport()
    function CreateNewReport(myResult, pToken, pRadius, pID, pType) {
        var myReport = new GISP_Report({ Name: "Property Report", Parameters: { Lat: myResult.lat, Lng: myResult.lng, SUBSET: pToken, Radius: pRadius} });
        myReport.ID = pID;
        myReport.Type = pType;
        log.info("-- New Report ID:" + myReport.ID + " Type: " + pType);
        log.info("-- New Report Lat:" + myReport.Parameters.Lat + " Lng: " + myReport.Parameters.Lng);
        return myReport;
    }
    function CreateLink(pID, _GISP_Theme, pType, pTab) {
        var myLink = "/main/PropertyDetails.aspx?ID=" + pID;

        myLink += "&SST=" + _GISP_Theme + "&ReportType=" + pType;

        //if a tab was specified, append that to the querystring
        if (typeof (pTab) !== "undefined" && pTab !== null) {
            myLink += "&tab=" + pTab;
        }
        return myLink;
    }
    function HideOtherPinsZoomToCurrent(map, _propertyMarkers, pID, myResult, pType) {
        log.info("HideOtherPinsZoomToCurrent()");
        log.info("- ID: " + pID);
        log.info("- map: " + typeof (map));
        log.info("- markers: " + typeof (_propertyMarkers));
        log.info("- result: " + typeof (myResult));
        log.info("- type: " + pType);
        //hide all other pins (Note, order of operations is important, must add to map before clearing array so that a refernce is kept.
        var myMarker = FindPropertyMarker(pID);
        log.info("- Did we find the marker for " + pID + "?: " + (typeof (myMarker) !== "undefined" && myMarker !== null).toString());
        RemoveMarkers(map, _propertyMarkers);
        if (typeof (myMarker) === "undefined" || myMarker === null) {
            log.info("Creating marker for property, since it was null or undef.");
            myMarker = _PropertySearchResultBuilder.CreateMarker(myResult, pType);
        } //end if marker is null
        myMarker.setMap(map);

        _propertyMarkers = [];
        _propertyMarkers.push(myMarker);

        log.info("- Done hiding other pins, about to zoom to propertyid: " + myMarker.ID);
        ZoomToProperty(myMarker.ID);
    }
    function ReportBeingViewed(pID) {
        return (_SSR._CurrentReportID !== null) && _SSR._CurrentReportID == pID;
    }
    function LogViewPropertyReport(pID) {
        var accessType;
        if (this.location.search.indexOf(pID, 0) === -1) {
            accessType = 3; // View property from search
        }
        else {
            if (this.location.search.indexOf('ZPEADMIN') > -1) {
                accessType = 5;  // Link from admin system
            }
            else {
                accessType = 4;  // Direct link
            }
        }
        LogAccessStatistic([pID], accessType);
    }
    function ShowCurrentReportAndSwitchToTab(pTab, pDefaultTab) {
        ShowCurrentReport();
        pTab = (typeof (pTab) === "undefined" || pTab === null || pTab === "undefined") ? pDefaultTab : pTab;
        $("#tabs li a[reportType='" + pTab + "']").click(); //switch to tab via click event
    }
    function SetupGalleria() {
      var $photoArea = $("#photoVar");
        log.info("SetupGalleria()");
        log.info("- Is #photoVar there? " + ($photoArea.length !== 0 ? "true" : "false"));
        if ($photoArea.length !== 0) {
            $('#galleria').empty().galleria({
                width: 300,
                height: 220,
                imageCrop: true,
                autoplay: 3000,
                data_source: $photoArea,
                extend: function (options) {
                    // listen to when an image is shown
                    this.bind('image', function (e) {
                        // lets make galleria open a lightbox when clicking the main image:
                        $(e.imageTarget).click(this.proxy(function () {
                            this.openLightbox();
                        }));
                    });
                }

            });
        }
    }
    function RequestPropertyByID(pID, pOptions) {
        CreateLoadingScreen("CONTENT");
        var myRequestId = GISPlanning_MapUtilities_GUID();
        var isBuilding = pOptions.ResultType === "BUILDINGS";
        $.ajax({
            type: "POST",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            url: "/common/services/Properties.asmx/GetPropertyByIDWithInputParams",
            data: JSON.stringify({ pPropertyID: pID, pIsBuilding: isBuilding, pToken: _GISP_Theme, pRequestParams: pOptions, pRequestID: myRequestId }),
            success: function (data, text) {
                RequestPropertyByIDSuccess(data.d);
            },
            error: function (xhr, text, error) {
                RequestPropertyByIDFailed(text);
            }
        });
        LogUsage({ "Type": "DIRECTLINK", "ID": pID, "Value": window.location.href });
    } //end method
    function RequestPropertyByIDSuccess(pResult) {
        if (typeof (pResult.Results) !== "undefined" && pResult.Results !== null && pResult.Results.length > 0) {
            _SSR._AddResult(pResult.Results[0], pResult.InputParameters[1].ResultType);
            ViewPropertyReport(pResult.Results[0].ID, pResult.InputParameters[1].ResultType, pResult.InputParameters[1].Tab, pResult.InputParameters[1].Radius);
        }
        else {
            DisplayNoResultsMessage("The property you are looking for could not be found.", "The property listing may have expired or was removed. Please contact the listing agent for more information.");
        }
    } //end method
    function RequestPropertyByIDFailed(pError) {
        alert("Unable to find site:" + pError._message);
    } //end method

    function LoadResultByIndex(pIndex, pType) {
        // Clean up the pType, we just want the text before the '_'
        log.info("LoadResultByIndex(). pIndex: " + pIndex + " pType: " + pType);
        //var rType = /([a-zA-Z]+)(?:(?:_)?(?:[A-Za-z]+)?)/;
        //pType = rType.exec(pType)[1];
        //log.info("Sanitized pType to: " + pType);
        var myTracker = _SSR._Trackers[pType];
        log.info("Got tracker: " + myTracker);

        myTracker.CurrentIndex = pIndex;
        var pageError = function () {
            log.error("Error trying to page. Index: " + pIndex + " Type: " + pType);
            alert("Paging the result type is not supported yet");
        };

        var _result = myTracker.Results[pIndex];
        log.info("Getting result from tracker. " + _result);
        var resultHasValue = typeof (_result) !== "undefined" && _result !== null && _result !== false;
        if (resultHasValue) {
            _ReportLoader.DiscardAllPendingExcept(_result.ID);
            if (/REPORTS_SAVED/.exec(pType) !== null) {
                log.info("Loading saved report by index.");
                //must set the parent report subtype report to this report.
                var mySubType = _result.SubType;
                log.info("Getting saved report from tracker, using id: " + _result.ID);
                var myReport = _SSR.GetReportByUniqueID(_result.ID);
                log.info("Getting parent report as well. ID: " + myReport.Properties.ParentReportID);
                var myParentReport = _SSR.GetReportByUniqueID(myReport.Properties.ParentReportID);
                log.info("Adding current report to parent report's subreports");
                myParentReport.SubReports[mySubType] = myReport.UniqueID;
                log.info("Now about to pull up a property report for propertyID: " + _result.PropertyID + " Type: " + _result.type + " SubType: " + mySubType);
                ViewPropertyReport(_result.PropertyID, _result.type, mySubType);
                LockNavigationBoundaries(myTracker);
            }
            else {
                //Else: Not a report type
                switch (pType) {
                    case "BUILDINGS_SAVED":
                    case "BUILDINGS":
                    case "SITES_SAVED":
                    case "SITES":
                        ViewPropertyReport(_result.ID, pType);
                        break;
                    case "COMMUNITIES_SAVED":
                    case "COMMUNITIES":
                        ViewCommunityReport(_result.ID);
                        break;
                    default:
                        pageError();
                        break;
                } //end switch

            } //end if not saved report
        } else {
            log.info("Requesting result from db.");
            //order data
            var myParams = myTracker.SearchParameters;
            myParams.StartRowID = pIndex - myTracker.PageSize;
            myParams.EndRowID = pIndex + myTracker.PageSize;

            //Fix up (remember, this is one based not zero)
            myParams.StartRowID = (myParams.StartRowID >= 0 ? myParams.StartRowID : 0) + 1;
            myParams.EndRowID = (myParams.EndRowID < myTracker.Count ? myParams.EndRowID : myTracker.Count - 1) + 1;
            myParams.RequestID = GISPlanning_MapUtilities_GUID();

            var myCallback = function () {
                var myResultID = myTracker.Results[pIndex].ID;
                _SSR.RemoveCallback(myResultID);
                switch (pType) {
                    case "BUILDINGS_SAVED":
                    case "SITES_SAVED":
                    case "BUILDINGS":
                    case "SITES":
                        ViewPropertyReport(myResultID, pType);
                        break;
                    case "COMMUNITIES_SAVED":
                    case "COMMUNITIES":
                        ViewCommunityReport(myResultID);
                        break;
                    default:
                        pageError();
                        break;
                } //end switch
            };

            //Load in the callback for this request
            _SSR.AddCallback(myParams.RequestID, myCallback);

            OrderData(pType, myParams, SearchAdditionalPageSuccess, SearchFail);
        } //end if/else result exists

    } //end function
    function ViewCommunityReportForCurrentProperty(pTab, pEntity) {
        _SSR.ClearCurrentReportOverlays();
        _SSR.ClearOtherReportOverlays();
        var myReport = _SSR.GetReportByUniqueID(_SSR._CurrentReportID);
        var myProperty = _SSR.GetResultByID(myReport.ID, myReport.Type);
        //Set the proper case of the pEntity (which is normally either 'CITY' or 'COUNTY')
        // Proper case will set it to 'City' or 'County'
        pEntity = pEntity.toLowerCase().replace(/^(.)|\s(.)/g,
        function ($1) { return $1.toUpperCase(); });
        //Then we use javascript's ability to find properties of an object with array-notation
        //So in this case, we're actually getting myProperty.CityID, or myProperty.CountyID
        ViewCommunityReport(myProperty[pEntity + "ID"], pTab);
    } //end function
    function ViewCommunityReport(pID, pTab) {
        log.info("ViewCommunityReport()");
        log.info("- ID: " + pID);
        log.info("- Tab: " + pTab);
        var myType = "COMMUNITIES";
        _SSR._CurrentViewType = myType;
        var myResult = _SSR.GetResultByID(pID, myType);

        if (typeof (myResult) === "undefined" || myResult === null) {
            // Load from db
            RequestCommunityByID(pID, { Tab: pTab });
        } else {
            //stop async processes of loading pins
            _SSR._StopProcessCurrentIterativeAsyncResultOperation = true;
            var tabIsNull = true;

            // Is this community report being viewed?
            if ((myResult.UniqueID !== null && _SSR._CurrentReportID !== null) && myResult.UniqueID == _SSR._CurrentReportID) {
                // Report is loaded, and currently being viewed
                log.info("- Community report being viewed, switch tabs");
                ShowCurrentReportAndSwitchToTab(pTab, "COMMUNITY");
            }
            else {
                _SSR.NavigationHistory_Add("REPORT", myType, 0, pID);
                log.info("- Community report not being viewed");
                //hide all other pins (Note, order of operations is important, must add to map before clearing array so that a refernce is kept.
                RemoveMarkers(map, _propertyMarkers);
                var myMarker = FindPropertyMarker(pID);

                if (myMarker === null) {
                    myMarker = _CommunitySearchResultBuilder.CreateMarker(myResult, myType);
                } //end if marker is null
                _propertyMarkers = [];
                _propertyMarkers.push(myMarker);

                var myLink = "/main/CommunityDetails.aspx?ID=" + pID + "&Placecode=" + myResult.Placecode;
                myLink += "&SST=" + _GISP_Theme + "&ReportType=" + myType;
                CreateLoadingScreen("CONTENT");

                //if a tab was specified, append that to the querystring
                tabIsNull = pTab === null || typeof (pTab) === "undefined" || pTab === "undefined";

                if (!tabIsNull) {
                    myLink += "&tab=" + pTab;
                }

                //check and see if the report already exists
                var myReport = _SSR.GetReportByTypeAndID(myType, pID);
                if (myReport !== undefined && myReport !== null) {
                    _SSR._CurrentReportID = myReport.UniqueID;
                    ShowCurrentReportAndSwitchToTab(pTab, "COMMUNITY");
                } else {
                    myReport = new GISP_Report({ Name: "Community Report", Parameters: { Lat: myResult.lat, Lng: myResult.lng, SUBSET: _GISP_Theme, Placecode: myResult.Placecode} });
                    myReport.ID = pID;
                    myReport.Type = myType;
                    _SSR._Reports.push(myReport);
                    myLink += "&UniqueID=" + myReport.UniqueID;
                    DisplayReport(myLink, myReport.UniqueID);

                } //end if result is null
            }

        } //end if result found
    }
    function RequestCommunityByID(pID, pOptions) {
        CreateLoadingScreen("CONTENT");
        var myRequestId = GISPlanning_MapUtilities_GUID();
        PostToService(
        "/common/services/Community.asmx/GetCommunityByIdWithInputParameters",
        JSON.stringify({
            pCommunityID: pID.replace("COMMUNITY_", ""),
            pRequestParams: pOptions,
            pRequestID: myRequestId
        }),
        function (data) { RequestCommunityByIDSuccess(data.d); },
        function (xhr, text) { RequestCommunityByIDFailed(text); });
    } //end method
    function RequestCommunityByIDSuccess(pResult) {
        _SSR._AddResult(pResult.Results[0], pResult.Type);
        ViewCommunityReport(pResult.Results[0].ID, pResult.InputParameters[1].Tab);
    } //end method

    function RequestCommunityByIDFailed(pError) {
        alert("Unable to find community:" + pError._message);
    } //end method

    function ShowFirstResult(pType) {
        // Lookup the tracker for pType
        // Show appropriate report for the first result
        var result = _SSR._GetFirstResult(pType);
        if (/BUILDING|SITE/i.exec(pType)) {
            ViewPropertyReport(result.ID, pType);
        }
        else if (/COMMUNIT/i.exec(pType)) {
            ViewCommunityReport(result.ID);
        }
        else if (/BUSINESS/i.exec(pType)) {
            ViewBusinessReport(result.ID);
        }
        else {
            log.error("- Could not load report for type " + pType);
        }

    }

    function ViewBusinessReport(pID) {
        var myReport = _SSR.GetReportByTypeAndID("SITES", pID);
        if (myReport !== undefined && myReport !== null) {
            _SSR._CurrentReportID = myReport.UniqueID;
            ShowCurrentReport();
            myReport.TabCollection.SetTabByToken("BUSINESSES");
        } //end if subreport is not null
        else {
            //property report does not exist, create and open to the correct tab
            ViewPropertyReport(pID, "BUSINESSES", "Business");
        } //end if report needs to be created
    }
    function ViewDemographicReport(pID, pType) {
        var myType = pID.substring(0, pID.indexOf("_"));
        var myResult = _SSR.GetResultByID(pID, myType);
        var myReport = _SSR.GetReportByTypeAndID(myType, pID);
        if (myReport !== undefined && myReport !== null) {
            var mySubReport = _SSR.GetReportByUniqueID(myReport.SubReports[pType]);
            _SSR._CurrentReportID = myReport.UniqueID;
            ShowCurrentReport();
            myReport.TabCollection.SetTabByToken(pType);
        } else {
            //property report does not exist, create and open to the correct tab
            switch (myType) {
                case "SITES": ViewPropertyReport(pID, pType); break;
                case "COMMUNITY": ViewCommunityReport(pID, pType); break;
                default: break;
            } //end swtich type 

        } //end if report needs to be created
    }
    function ViewComparisonReport(pIDs, pType) {
        //stop async processes of loading pins
        _SSR._StopProcessCurrentIterativeAsyncResultOperation = true;

        var myLink = "~/main/ComparisonReport.aspx?IDS=" + pIDs + "&Type=" + pType;
        CreateLoadingScreen("CONTENT");
        var myReport = new GISP_Report({ Name: "Comparison Report", Parameters: { IDs: pIDs, Type: pType} });
        myReport.ID = GISPlanning_MapUtilities_GUID();
        myReport.Type = "COMPARISON";
        _SSR._Reports.push(myReport);
        myLink += "&UniqueID=" + myReport.UniqueID;
        PostToService("/common/services/DocumentLoader.asmx/GetReportAsHTML",
        JSON.stringify({ pUrl: myLink, pID: myReport.UniqueID }),
        function (data) { DisplayReport(myLink, myReport.UniqueID); },
        function (xhr, text) { });
    }
    function CreateResultsReport(pReportContent) {
        var myReport = new GISP_Report({ Name: "Results Report", Parameters: { Title: "Results Report", Icon: "RESULTS"} });
        myReport.ID = myReport.UniqueID;
        myReport.Type = "GENERIC";
        myReport.Content = '<form>';
        myReport.Content += '   <div id="divScriptToEval">';
        myReport.Content += '       <script type="text/javascript">';
        myReport.Content += '           var myReport = _SSR.GetReportByUniqueID(\'' + myReport.UniqueID + '\');';
        myReport.Content += '           myReport.TabCollection = new GISP_ReportTabs([';
        myReport.Content += '               new GISP_ReportTab($(\'#hrefReportTab_0\')[0], { Token: "REPORT", Name: "Report", Active: true, Tooltip: "Click here to view the report", Callback: function() { LoadGenericSubReport(\'' + myReport.UniqueID + '\'); } })';
        myReport.Content += '           ]);';
        myReport.Content += '       </script>';
        myReport.Content += '   </div>';
        myReport.Content += '   <div>';
        myReport.Content += '       <table cellpadding="0" cellspacing="0" border="0" width="100%" class="ReportHeaderTable left">';
        myReport.Content += '           <tr>';
        myReport.Content += '               <td id="exportReportHeader"></td>';
        myReport.Content += '           </tr>';
        myReport.Content += '           <tr>';
        myReport.Content += '               <td colspan="3" id="tdSubReportPlaceholder">';
        myReport.Content += '                   <div id="SubReportNodeToReplace"></div>';
        myReport.Content += '               </td>';
        myReport.Content += '           </tr>';
        myReport.Content += '       </table>';
        myReport.Content += '   </div>';
        myReport.Content += '   <div id="rptParamaters"></div>';
        myReport.Content += '</form>';

        var mySubReport = new GISP_Report({ Name: "Results Report", Parameters: { Title: "Results Report", Icon: "RESULTS"} });
        mySubReport.Properties.ParentReportID = myReport.UniqueID;
        mySubReport.Type = "GENERIC";
        mySubReport.Content = pReportContent;
        myReport.SubReports.GENERIC = mySubReport.UniqueID;

        _SSR._Reports.push(myReport);
        _SSR._Reports.push(mySubReport);

        return mySubReport.UniqueID;
    } //end function
    function DisplayReport(pReportURL, pReportUniqueID) {
        log.info("DisplayReport() Url: " + pReportURL + " ReportUniqueID: " + pReportUniqueID);
        _SSR.ClearCurrentReportOverlays();
        _SSR.ClearOtherReportOverlays();
        ClearHeaderAndFooter();
        $.ajax({
            url: pReportURL,
            success: function (html, textStatus, jqXhr) {
                var myTempDOMElement = document.createElement("div");
                var uniqueIDFromUrl = /UniqueID=([a-zA-Z0-9\-]+)&?/.exec(this.url)[1];

                log.info("DisplayReport() ajax success()");
                log.info("-- Url: " + this.url);
                log.info("-- UniqueIDFromUrl: " + uniqueIDFromUrl);
                myTempDOMElement.innerHTML = html; //Note, this will not execute any JS

                var myForm = $("#report", myTempDOMElement);
                var myReport = _SSR.GetReportByUniqueID(uniqueIDFromUrl);

                if (typeof (myReport) !== "undefined" && myReport !== null) {
                    myReport.Content = myForm[0].innerHTML;
                    _SSR._CurrentReportID = myReport.UniqueID;
                }
                else {
                    log.error("Report was null when trying to display report for id " + pReportUniqueID);
                    log.info("- Incoming content length: " + myForm[0].innerHTML.length);
                }
                ShowCurrentReport();
            }
        });
    }
    function ShowCurrentReport() {
        //reset map and contents
        _SSR.ClearCurrentReportOverlays();
        _SSR.ClearOtherReportOverlays();
        ResetContentItemHolder();
        SetContentItemContainerForReports();
        _SSR._CurrentViewClass = "REPORT";

        //set up the menu
        var myType = _SSR.GetReportByUniqueID(_SSR._CurrentReportID).Type;
        ClearHeaderAndFooter();

        //set tracker current index to this report
        _SSR.SetTrackerIndexToCurrentReport(myType);

        if (_SSR._CurrentReportID === null) {
            DisplayNoResultsMessage("There is not a report currently being viewed. Select a report from a property or the menu.", "");
        }
        else {
            var myReport = _SSR.GetCurrentReport();
            ClearHeaderAndFooter();
            ReplaceView("CONTENT", myReport.Content);
            myReport.ZoomBounds();

        } //end if current report
        LoadContentMenu(myType.replace(/_SAVED/g, "") + "_DETAIL");

        LockNavigationBoundaries(_SSR._Trackers[myType]);
        SendDocumentHeight();
    }
    function SaveReport(pUniqueReportID, pPersist) {

        var myReport = _SSR.GetReportByUniqueID(pUniqueReportID);

        if (!_SSR.IsResultSaved(pUniqueReportID)) {
            _SSR.SaveReport(pUniqueReportID);
            if (myReport.SaveFunction !== null) {
                myReport.SaveFunction();
            } //end if show param function not nulls
        } //end if not already saved

        if (pPersist !== false) {
            PersistTrackers();
        }

        _SSR.UpdateMyFolder();
    } //
    function SaveAllSubReports(pUniqueReportID) {
        var myReport = _SSR.GetReportByUniqueID(pUniqueReportID);
        var subreport = null;
        for (subreport in myReport.SubReports) {
            SaveReport(myReport.SubReports[subreport], false);
        } //end for each option

        PersistTrackers();
    }
    function ViewReportHistory() {
        alert("This has not been implemented yet");
    } //
    function GetReportHeaderHtml() {
        var myHtml = "  <div class='header' style='width:100%;'>";
        myHtml += "         <img class='logo' src='http://images.zoomprospector.com/client/assets/" + _GISP_Theme + "/InfoWindowLogo.jpg' />";
        myHtml += "     </div>";
        return myHtml;
    }
    function GetViewablePropertiesHtml(pPreHtml, pPostHtml) {
        var myHtml = '';
        if (typeof (pPreHtml) !== "undefined" && pPreHtml !== null) {
            myHtml += pPreHtml;
        }
        var clientWidth = GetClientWidth();
        var count = 0;
        $("#ContentItemHolder .property").each(function (index, value) {
            var prop = $(this);
            if (prop.offset().left >= 0) { //only print if property is to the right of the left side of the screen
                if (prop.offset().left <= (clientWidth - GISP_PROPERTY_WIDTH)) {
                    //only print if the property is to the left of the right side of the screen
                    myHtml += $("<div>").append(prop.eq(0).clone()).html();
                    count++;
                }
            }
        });
        log.info("Grabbed " + count + " viewable properties' html for export");
        if (typeof (pPostHtml) !== "undefined" && pPostHtml !== null) {
            myHtml += pPostHtml;
        }
        return myHtml;
    } // end function
    function PrintPropertyResults() {
        //Get html from screen
        var myHtml = GetReportHeaderHtml() + GetViewablePropertiesHtml();
        //Assign a unique id to the printout
        var myUnique = GISPlanning_MapUtilities_GUID();
        //Sanitize html
        myHtml = GISP_RemoveNonExportable(myHtml);
        myHtml = GISP_RemoveNonPopout(myHtml);
        myHtml = GISP_RemoveFunctionHyperlinks(myHtml);
        //Send to popup tracker
        _popupTracker.AddContent(myUnique, myHtml);

        //Open popup
        var myLink = "main/reportViewers/printreport.aspx";

        myLink += "?id=" + myUnique;

        GISPlanning_Popup_Window(myLink, {});
    }
    function PrintReport(pReportID) {
        var myReport = _SSR.GetReportByUniqueID(pReportID);
        var myParentReport = _SSR.GetReportByUniqueID(myReport.Properties.ParentReportID);
        var myPopupGuid = GISPlanning_MapUtilities_GUID();

        var myParentContent = myParentReport === null ? "" : myParentReport.Content;
        //var myReportContent = myReport.Content;

        var myReportElements = $(myReport.Content);
        var myReportContent = myReportElements.find("#exportableContent").html();


        //Log that it is being used
        LogUsage({ "Type": "PRINTRPT", "ID": myParentReport.ID, "Value": myReport.Type });
        //remove the non exportable/popoutable elements
        myReportContent = GISP_RemoveNonExportable(myReportContent);
        myReportContent = GISP_RemoveNonPopout(myReportContent);
        myReportContent = GISP_RemoveFunctionHyperlinks(myReportContent);

        myReportContent = "<div style='width:100%'>" + myReportContent + "</div>"; //myParentHeader.innerHTML + myReportContent.innerHTML;

        var myContent = GetReportHeaderHtml() + myReportContent;


        //add content to tracker
        _popupTracker.AddContent(myPopupGuid, myContent);



        var myLink = "main/reportViewers/printreport.aspx";

        myLink += "?id=" + myPopupGuid + "&type=" + myReport.Type;

        GISPlanning_Popup_Window(myLink, { toolbar: "1", scrollbars: "1", location: "1", statusbar: "1", menubar: "1", resizable: "1", width: "960px", height: "650", left: "300", top: "0" });
    } //
    function ExportCommunitiesHtml(pReportType) {
        $("body").append("<input type='hidden' id='hfldExporterParams'/>");
        var myType = _SSR._CurrentViewType;
        var myTracker = _SSR._Trackers[myType];
        var myHtml = "";
        var myStart = 0;
        var myEnd = 0;
        var propertiesTemplateHtml;
        var propertiesTemplateCss;
        var myCommunitiesRegex = /COMMUNITIES/;
        var mySitesRegex = /SITES/;
        var myBuildingsRegex = /BUILDINGS/;
        var i = 0;

        $.ajax({
            type: "GET",
            url: "/fragments/property/propertytemplate.htm",
            async: false,
            success: function (msg) {
                propertiesTemplateHtml = msg;
            }
        });
        $.ajax({
            type: "GET",
            url: "/fragments/property/properties.css",
            async: false,
            success: function (msg) {
                propertiesTemplateCss = "<style type='text/css'>" + msg + "</style>";
            }
        });

        myHtml = "<html><head>" + propertiesTemplateCss + "</head><body><table>";

        myStart = myTracker.CurrentIndex;
        myEnd = myStart + myTracker.PageSizeDefault - 1 < myTracker.Results.length - 1 ? myStart + myTracker.PageSizeDefault - 1 : myTracker.Results.length - 1;

        var domain = /https?:\/\/[\w\d\.]+\//.exec(location.href);
        var fullUrl = domain + "?SST="+_GISP_Theme+"&DID=COMMUNITIES_"; 
        //Alright, this is going to look crazy, admittedly. I'm pulling in the html for a properties export
        //and using that same html for a communities export. So the .replace() statements to follow
        //are going to look quite crazy, but, for now, trust me, this will work. What needs to be done
        //is to create a new html file for communities, called CommunityTemplate.htm and use a similar
        //format that PropertyTemplate.htm uses, but replace the placeholder with better-named ones.
        for (i = myStart; i <= myEnd; i++) {
            var myCommunity = myTracker.Results[i];
            var myTempPropHtml = propertiesTemplateHtml + " ";

            /*jsl:ignore*/
            myTempPropHtml = myTempPropHtml.replace(/@PROPERTY_PHOTO/, myCommunity.Thumbnail)
              .replace(/@PROPERTY_NAME/, myTracker.Results[i].Name + " - " + myCommunity.State)
              .replace(/@PROPERTY_CITY,/, '')
              .replace(/@PROPERTY_STATE/, '')
              .replace(/@PROPERTY_ZIP/, 'Population: ' + myCommunity.Population)
              .replace(/Building: @PROPERTY_BUILDING/, 'Laborforce size: ' + myCommunity.LaborForceSize)
              .replace(/County: @PROPERTY_COUNTY/, 'Bachelors or higher: ' + myCommunity.BachelorsHigherPct)
              .replace(/Type: @PROPERTY_TYPE /, 'Household Income Median: $' + myCommunity.HHIncomeMedian)
              .replace(/Min. Subdivide: @PROPERTY_DIV_MIN /, 'Travel time: ' + myCommunity.TravelTime)
              .replace(/Available: @PROPERTY_SQFT /, 'Job Growth: ' + myCommunity.JobGrowth)
              .replace(/Total SQFT: @PROPERTY_SQFT /, '')
              .replace(/@PROPERTY_SQFT/, '')
              .replace(/Sale\/Lease: @PROPERTY_IS_FOR_SALE\/@PROPERTY_IS_FOR_LEASE /, 'Domestic airports: ' + myCommunity.DomesticAirports)
              .replace(/Sale Price: @PROPERTY_SALE_PRICE /, 'Distance to Intl. Airport: ' + myCommunity.DistanceToInt)
              .replace(/Lease Rate: @PROPERTY_LEASE_RATE /, 'Distance to Rail: ' + myCommunity.DistanceToRail)
              .replace(/Lease Terms: @PROPERTY_LEASE_TERMS /, '')
              .replace(/# Floors:: @PROPERTY_FLOOR_NUM /, '')
              .replace(/Ceiling: @PROPERTY_CEILING_MAX ft /, '')
              .replace(/Property @CURRENT_PROPERTY/, "Community " + (i - myStart + 1))
              .replace(/@TOTAL_PROPERTIES/, myEnd - myStart)
              .replace(/@FULL_REPORT_URL/, fullUrl+myCommunity.ID);
            /*jsl:end*/
            // http://beta2.gisplanning.net/default.aspx?DID=COMMUNITIES_0901080

            myHtml += myTempPropHtml;
        }
        myHtml += "</table></body></html>";
        myHtml = GISP_RemoveNonExportable(myHtml);
        myHtml = GISP_RemoveNonPopout(myHtml);
        myHtml = GISP_RemoveFunctionHyperlinks(myHtml);
        $.ajax({
            type: "POST",
            url: "/common/services/DocumentLoader.asmx/ExportReportHtmlToSession",
            data: "{'pHtml':" + JSON.stringify(myHtml) + "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                var myExportFormContent = GetExportFormContent();
                var myReportID = msg.d;
                ShowDynamicModal(myExportFormContent);
                SetExporterParameters(pReportType, myReportID, false, false);

                $('#tboxReportHeader').focus();

                SetupExportButton();

                $('#tboxReportHeader').unbind("keyup").bind("keyup", onInputKeyUpDelegate);
                $('#tboxReportHeader').unbind("keydown").bind("keydown", onInputKeyDownDelegate);

                $("#tblExport").css("display", "block");
            },
            error: function () { alert('Failed to print report. Please try again.'); HideDynamicModal(); }
        });


    }
    function ExportAllPropertiesHtml(pReportType) {
        var builder = null;
        var myType = _SSR._CurrentViewType;
        var myTracker = _SSR._Trackers[myType];
        var myHtml = "";
        var myStart = 0;
        var myEnd = 0;
        var zpeAllCss = "";
        var exportListCSS = "";
        var helper = new UrlHelper(window.location.href);
        var myCommunitiesRegex = /COMMUNITIES/;
        var mySitesRegex = /SITES/;
        var myBuildingsRegex = /BUILDINGS/;
        var i = 0;


        // pReportType: 'WORD' 'EXCEL' 'PDF' 'EMAIL'
        if ($("#hfldExporterParams").length === 0) {
            $("body").append("<input type='hidden' id='hfldExporterParams'/>");
        }
        if ((/BUILDINGS/).exec(myType) !== null || (/SITES/).exec(myType)) {
            builder = new GISP_PropertySearchResultBuilder();
        }
        else if (/COMMUNITIES/.exec(myType) !== null) {
            builder = new GISP_CommunitySearchResultBuilder();
        }
        else if (/BUSINESSES/.exec(myType) !== null) { // probably not used
            builder = new GISP_BusinessSearchResultBuilder();
        }
        else if (/REPORTS/.exec(myType) !== null) { // probably not used
            builder = new GISP_ReportResultBuilder();
        }

        myHtml = "<html><head>";
        myHtml += "</head><body>";
        myHtml += '<link type="text/css" rel="stylesheet" href="' + helper.domain + helper.port + '/common/styles/exportList.css?' + helper.fullQueryString + '"/>';

        myStart = myTracker.CurrentIndex;
        myEnd = myTracker.Results.length - 1;

        for (i = myStart; i <= myEnd; i++) {
            var basetype = '';
            if (myBuildingsRegex.exec(myType) !== null) {
                basetype = 'BUILDINGS';
            }
            else if (mySitesRegex.exec(myType) !== null) {
                basetype = 'SITES';
            }
            else if (myCommunitiesRegex.exec(myType) !== null) {
                basetype = 'COMMUNITIES';
            }

            var myTempPropHtml = builder.CreateListing(myTracker.Results[i], i, basetype, 'vertical') + " ";

            myHtml += myTempPropHtml;
        }
        myHtml += "</body></html>";

        myHtml = GISP_RemoveNonExportable(myHtml);
        myHtml = GISP_RemoveNonPopout(myHtml);
        myHtml = GISP_CleanPropertyLinks(myHtml);
        myHtml = GISP_ConvertHtmlToTables(myHtml);
        myHtml = GISP_SetWordExcelStyles(pReportType, myHtml);

        $.ajax({
            type: "POST",
            url: "/common/services/DocumentLoader.asmx/ExportReportHtmlToSession",
            data: "{'pHtml':" + JSON.stringify(myHtml) + "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                var myExportFormContent = GetExportFormContent();
                var myReportID = msg.d;
                ShowDynamicModal(myExportFormContent);
                SetExporterParameters(pReportType, myReportID, false, false);

                $('#tboxReportHeader').focus();

                SetupExportButton();

                $('#tboxReportHeader').bind("keyup", onInputKeyUpDelegate);
                $('#tboxReportHeader').bind("keydown", onInputKeyDownDelegate);

                $("#tblExport").css("display", "block");
            },
            error: function () { alert('Failed to export report. Please try again.'); HideDynamicModal(); }
        });

    }
    function ExportPropertiesHtml(pReportType) {
        log.info("ExportPropertiesHtml. ReportType: " + pReportType);
        if ($("#hfldExporterParams").length === 0) {
            $("body").append("<input type='hidden' id='hfldExporterParams'/>");
        }
        var myType = _SSR._CurrentViewType;
        var myTracker = _SSR._Trackers[myType];
        log.info("Current View Type: " + myType);
        var helper = new UrlHelper(window.location.href);

        //Get html from screen
        var myHtml = GetViewablePropertiesHtml();

        log.info("Gathered basic html for listed property cards. Length: " + myHtml.length);

        //Sanitize html
        myHtml = GISP_RemoveNonExportable(myHtml);
        log.info("Removed nonexportable. Length: " + myHtml.length);
        myHtml = GISP_RemoveNonPopout(myHtml);
        log.info("Removed nonpopout. Length: " + myHtml.length);

        //Clean up property links (makes links clickable externally)
        myHtml = GISP_CleanPropertyLinks(myHtml);
        log.info("Cleaned property links. Length: " + myHtml.length);
        myHtml = GISP_ConvertHtmlToTables(myHtml);
        log.info("Converted html to tables. Length: " + myHtml.length);

        //if word or excel, make sure font size is small inside tables of .propertyInfofg
        myHtml = GISP_SetWordExcelStyles(pReportType, myHtml);
        log.info("Set Word/Excel styles. Length: " + myHtml.length);
        log.info("Sanitized html. Length: " + myHtml.length);

        // if 'debug' in query string, output html to debug area on page
        DumpToDebugArea(myHtml);

        // minify html before sending
        myHtml = minify(myHtml, { removeConments: true, removeCommentsFromCDATA: true, collapseWhitespace: true });
        log.info("Done minifying html before transfer. Length: " + myHtml.length);
        $.ajax({
            type: "POST",
            url: "/common/services/DocumentLoader.asmx/ExportReportHtmlToSession",
            data: "{'pHtml':" + JSON.stringify(myHtml) + "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                var myExportFormContent = GetExportFormContent();
                var myReportID = msg.d;
                ShowDynamicModal(myExportFormContent);
                SetExporterParameters(pReportType, myReportID, false, false);

                $('#tboxReportHeader').focus();

                SetupExportButton();

                $('#tboxReportHeader').bind("keyup", onInputKeyUpDelegate);
                $('#tboxReportHeader').bind("keydown", onInputKeyDownDelegate);

                $("#tblExport").css("display", "block");
            },
            error: function () { alert('Failed to print report. Please try again.'); HideDynamicModal(); }
        });

        LogUsage({ "Type": "EXPORTSEARCHRESULTS", "ID": null, "Value": null });
    } //end function
    function GISP_ConvertHtmlToTables(myHtml) {
        // Modify HTML if the export type is Word or Excel. Need to use <table> based layout for those
        var _html = myHtml;

        if ($("#ContentItemHolder .property").length > 0) {
            log.info("Converting property cards to tables. Length: " + _html.length);
            _html = GISP_ConvertPropertyCardsToTables(_html);
            log.info("Done converting property cards to tables. Length: " + _html.length);
        }
        else {
            log.info("Converting report to tables. Length: " + _html.length);
            _html = (GISP_ConvertReportToTables(_html));
            log.info("Done converting report to tables. Length: " + _html.length);
        }

        return _html;
    }
    function GISP_ConvertReportToTables(myHtml) {
        log.info("GISP_ConvertReportToTables()");
        // This doesn't do anything with tables... What happened?
        var export_html = $(myHtml);
        export_html.find("#propertyImageSlider #photos li:not(:first)").remove();
        log.info("Removed #propertyImageSlider #photos li:not(:first)");
        export_html.find("#propertyImageSlider #photos > a").remove();
        log.info("Removed #propertyImageSlider #photos > a");
    }
    function GISP_ConvertPropertyCardsToTables(myHtml) {
        // wrap all .property elements in a table
        var $exportHtml = $("<div>" + myHtml + "</div>");
        log.info("GISP_ConvertPropertyCardsToTables. Length:" + $exportHtml.html().length);

        // put each property in table
        var $propertiesTable = $("<table class='properties'></table>");
        $propertiesTable.append($exportHtml.find(".property"));

        // convert each div.property to a tr
        var propertiesTable = $propertiesTable;
        $propertiesTable.find(".property").each(function (key, val) {
            var prop_html = $(this).clone().html();
            var new_prop = $("<tr class='property' style='height:130px;'></tr>").html(prop_html);
            propertiesTable.append(new_prop);
            $(this).remove(); // remove old element
        });
        $exportHtml.append($propertiesTable);
        log.info("Converted .property to tr. Length:" + $exportHtml.html().length);
        // convert each .property .propertyImageBox to a td
        $exportHtml.find(".propertyImageBox").each(function () {
            var parent_prop = $(this).parent();
            var propImage_html = $(this).clone().html();
            var new_prop_image = $("<td class='propertyImageBox' style='width:150px;'></td>").html(propImage_html);
            parent_prop.append(new_prop_image);
            $(this).remove();
        });
        log.info("Converted .propertyImageBox to td. Length:" + $exportHtml.html().length);

        // convert each .property .propertyInfoBox to a td
        $exportHtml.find(".propertyInfoBox").each(function () {
            var parent_prop = $(this).parent();
            var propInfo_html = $(this).clone().html();
            var new_prop_info = $("<td class='propertyInfoBox' style='width:600px;'></td>").html(propInfo_html);
            // wrap the innards of .propertyInfofg in a table
            var prop_info_fg = new_prop_info.find(".propertyInfofg");
            prop_info_fg.find("h4").remove();
            prop_info_fg.children().wrapAll("<table/>");
            // wrap the h3 in .propertyInfofg in a <tr>
            prop_info_fg.find("h3:first").wrap("<tr><td/></tr>");
            // wrap the uls in a tr
            prop_info_fg.find("ul").wrapAll("<tr/>");
            // wrap each ul with a td, width 165px
            prop_info_fg.find("ul").wrap("<td style='width:165px;' />");

            prop_info_fg.find(".pagerControl").wrap("<tr><td/></tr>");
            parent_prop.append(new_prop_info);
            $(this).remove();
        });
        log.info("Converted .propertyInfoBox to td. Length:" + $exportHtml.html().length);

        // remove saveslider area
        $exportHtml.find(".properties .saveSlider").remove();
        // Need to put in some manual, in-line styles for Word

        $exportHtml.find(".properties .property").css({ 'height': '110px', 'margin': '0 0 10px 0' });
        $exportHtml.find(".properties .propertyImageBox img").css({ 'margin': '0' });

        $exportHtml.find(".properties .propertyInfoBox, .properties .propertyImagefg").css({ 'height': '110px' });
        $exportHtml.find(".properties .propertyInfoBox").css({ 'margin': '0 5px 0 20px', 'background-color': '#EFEFEF' });
        $exportHtml.find(".properties .propertyImageBox .decorated").css({ 'left': '65px', 'top': '0px' });
        $exportHtml.find(".properties .propertyImageBox .saved").css({ 'left': '0px', 'top': '50px' });
        // all text needs to be gray, #5d5d5d
        $exportHtml.find(".properties .propertyInfoBox table").css({ 'color': '#5d5d5d', 'font-family': 'arial', 'font-size': '65%' });
        // li.ellipsis strong need to be black (#000)
        $exportHtml.find(".property .propertyInfoBox li.ellipsis strong").css({ 'color': '#000' });

        return $("<div>").append($exportHtml.eq(0).clone()).html();
    }
    function GISP_SetWordExcelStyles(pReportType, pHtml) {
        var $fontChangeArea = $("<div id='word_excel_font_change'>" + pHtml + "</div>");
        if (pReportType === 'WORD' || pReportType === 'EXCEL') {
            var the_html = $fontChangeArea;
            var the_tables = the_html.find(".propertyInfofg table, .propertyReport table, table.subtable, .demographicsReport table.subtable, #businessResultsTable");
            the_tables.css({ 'font-size': '65%' });
            the_tables.filter(".rightCol table, .leftCol table").attr("width", "100%");
            the_html.find("th,tr.groupHeader").css({ 'background-color': '#8A8A8A', 'color': '#fff' });
            the_html.find("tr.alt td, tr.alt td, tr.even td").css({ 'background-color': '#CFCCCA' });

            var $property_image_box = the_html.find("#propertyImageBox");
            $property_image_box.wrapAll("<table style='width:300px;height:188px; margin:10px;'><tr><td colspan='2' rowspan='13'></td></tr></table>");
        }
        else {
            $fontChangeArea.find(".propertyInfofg table").css({ 'font-size': '100%' });
        }
        return $fontChangeArea.html();
    }
    function GISP_CleanPropertyLinks(pHtml) {
        //- Put "myHtml" onto site, and hide it.
        $("body").append("<div id='emailExportHtml' style='display:none;'>" + pHtml + "</div>");

        var helper = new UrlHelper(window.location.href);
        // clean up fullQueryString.
        // - Remove ShowSearch
        helper.fullQueryString = helper.fullQueryString.replace(/showsearch=[^&]+/i,"");
        // - Remove Mode
        helper.fullQueryString = helper.fullQueryString.replace(/mode=[^&]+/i,"");
        // - Remove existing DID
        helper.fullQueryString = helper.fullQueryString.replace(/did=[^&]+/i,"");

        var url = helper.domain + helper.port;

        // REGEX: (GUID)|([0-9]+)','([A-Z]+)'
        // e.g.: 00000000-0000-0000-0000-000000000000','bbb'
        // e.g.: 12345','a'
        // e.g.: 49e6d732-9ae1-48e9-83e7-d53d6ae2f1f1','BUILDINGS'
        var regex = /(([0-9a-f]{8,8}-([0-9a-f]{4,4}-){3,3}[0-9a-f]{12,12})|([\d]+))','([A-Z]+)'/;
        //- Use jQuery to find all property links
        $("#emailExportHtml a[href*=ViewPropertyReport], #emailExportHtml a[href*=ViewCommunityReport]").each(function () {
            //- For each link found, translate it to the property external link-type
            // -- Find this: javascript:ViewPropertyReport('49e6d732-9ae1-48e9-83e7-d53d6ae2f1f1','BUILDINGS');
            // -- Get the href of each of the links found. 
            var href = this.href;

            // -- Do a regex match of the GUID and the type, save each in var
            // --- This regex matches both communities and buildings or sites
            var match = regex.exec(href);
            var propertyID = match[1];
            var type = match[5];

            if (type === "COMMUNITY") {
                type = "COMMUNITIES";
            }
            // -- Replace link with one of these:
            // Site Link: http://princewilliamcounty.zoomprospector.com/default.aspx?DID=SITES_c9d1c92b-a010-45da-9cb0-6a4fdd88d25d
            // Building link:  http://princewilliamcounty.zoomprospector.com/default.aspx?DID=BUILDINGS_49e6d732-9ae1-48e9-83e7-d53d6ae2f1f1
            // Community link: http://princewilliamcounty.zoomprospector.com/default.aspx?DID=COMMUNITIES_5111230
            var newhref = url + "/default.aspx?DID=" + type + "_" + propertyID + '&' + helper.fullQueryString;

            this.href = newhref;
        });

        var exportHtml = $("#emailExportHtml").html();
        $("#emailExportHtml").remove();
        return exportHtml;
    }
    function ExportReport(pReportType) {

        var myReportID = GISPlanning_MapUtilities_GUID();
        SetExporterParameters(pReportType, myReportID, true, true);
        ShowLoadingWindow();

        var myRegcontentFunction = function () {

            var myExportFormContent = GetExportFormContent();
            ShowDynamicModal(myExportFormContent);
            SetupExportButton();

            // "register" the content
            var myReport = _SSR.GetReportByUniqueID($("#hfldUniqueID").val());
            var myParentReport = _SSR.GetReportByUniqueID(myReport.Properties.ParentReportID);
            var myReportElements = $(myReport.Content);
            var myReportContent = null;

            myReportContent = myReportElements.find("#exportableContent").clone()[0];

            //remove the non exportable elements
            myReportContent = GISP_RemoveNonExportable($(myReportContent).html());
            myReportContent = GISP_SetWordExcelStyles(pReportType, myReportContent);
            //modify all hyperlinks to remove JS Functions
            myReportContent = GISP_RemoveFunctionHyperlinks(myReportContent);

            if ($(".businessReport", myReportContent).length > 0) {
                // This code only needs to be here if it's a biz report.
                var $exportReportUpdateBizReport = $("<div id='ExportReport_UpdateEmployeeColumn'>" + myReportContent + "</div>");
                $exportReportUpdateBizReport.find(".businessReport tr").each(function () {
                    $(this).find("td:last").css({ "padding": "0 20px 0 0" });
                });
                $exportReportUpdateBizReport.find(".tableCont").css({ "margin": "0px" });
                myReportContent = $exportReportUpdateBizReport.html();
                $exportReportUpdateBizReport.remove();
            }
            // minify from: https://github.com/kangax/html-minifier (js files: htmlparser.js and htmlminifier.js)
            myReportContent = minify(myReportContent, { removeComments: true, removeCommentsFromCDATA: true, collapseWhitespace: true });
            // if 'debug' in query string, output html to debug area on page
            DumpToDebugArea(myReportContent);

            //create a collection of pages
            var myPages = [];
            myPages.push("", myReportContent); // for now, first push is a blank page for the map we don't use.

            PostToService("/common/services/DocumentLoader.asmx/RegisterExportReport",
            JSON.stringify({
                pGuid: myReportID,
                pContent: myPages,
                pRequestId: GISPlanning_MapUtilities_GUID()
            }),
            function (data) { ExportReport_Success(data.d); },
            function (xhr, text) { ExportReport_Failure(text); });

            var $reportHeaderTextbox = $('#tboxReportHeader');
            $reportHeaderTextbox.focus();
            $reportHeaderTextbox.bind("keyup", onInputKeyUpDelegate);
            $reportHeaderTextbox.bind("keydown", onInputKeyDownDelegate);

            //Log Usage
            LogUsage({ "Type": "EXPORTRPT", "ID": myParentReport.ID, "Value": pReportType });
        };                   //end function
        setTimeout(myRegcontentFunction, 10);
    } //
    function DumpToDebugArea(pHtml) {
        if (/debug=1/.exec(location.href)) {
            $("#debug_area").remove();
            var $iframe = $("<iframe id='debug_area' style='width:1024px;height:768px;'></iframe>").appendTo("body");
            var iframe = $iframe[0];
            var doc = iframe.document;
            if (iframe.contentDocument) {
                doc = iframe.contentDocument;
            }
            else if (iframe.contentWindow) {
                doc = iframe.contentWindow.document;
            }
            doc.open();
            doc.writeln(pHtml);
            doc.close();
        }
    }
    function SetupExportButton() {
        var myIframe = $get("ifrmExport");
        myIframe.setAttribute("src", $get("hfldExporterParams").value);
    }
    function DisableExportButton() {
        var myIframe = $get("ifrmExport");
        myIframe.setAttribute("src", "/fragments/content/ExportReportDisabled.htm");
    }
    function ShowLoadingExportButton() {
        var myIframe = $get("ifrmExport");
        myIframe.setAttribute("src", "/fragments/content/ExportReportLoading.htm");
    }
    function SetExporterParameters(pReportType, pReportID, pHasMap, pSingleReportOnly) {
        $("#hfldExporterParams").val("/main/exporter.aspx?type=" + pReportType + "&ID=" + pReportID + "&map=" + pHasMap + "&single=" + pSingleReportOnly + "&callBack=HideDynamicModal&SST=" + _GISP_Theme);
    }
    function GetBaseExportFormContent() {
        var html = "";
        html += ' <div id="dynamicWindowMenu">';
        html += '   <div id="dynamicWindowMenuText">@message</div>';
        html += ' </div>';
        html += ' <table id="tblExport" cellpadding="0" cellspacing="0" border="0">';
        html += '   <tr>';
        html += '     <td>';
        html += '       <input type="text" class="jumbo" ID="tboxReportHeader" />';
        html += '     </td>';
        html += '   </tr>';
        html += ' </table>';
        html += ' <div>@additionalContent</div>';
        html += ' <iframe id="ifrmExport" scrolling="no" frameborder="0"></iframe>';
        return html;
    }
    function GetExportFormContent() {
        return GetBaseExportFormContent().replace("@message", "Please enter a report title and click Export").replace("@additionalContent", "");
    }
    function onInputKeyUpDelegate() {
        if (_inputKeyUpTimer) {
            clearTimeout(_inputKeyUpTimer);
        }
        _inputKeyUpTimer = setTimeout(onInputKeyUpHandler, 800);
    }
    function onInputKeyDownDelegate() {
        $("#ifrmExport").css('display', 'none');
    }
    function onInputKeyUpHandler() {

        var myIframe = $get("ifrmExport");
        myIframe.setAttribute("src", $get("hfldExporterParams").value + "&title=" + escape($get("tboxReportHeader").value));
        $("#ifrmExport").css('display', 'block');
    }
    function GISPlanning_SetImageInactive(pImageElement) {
        //This little jquery removes the -on
        var myImageName = $(pImageElement).attr("src");
        if (myImageName != undefined) {
            myImageName = myImageName.replace("_active", "_inactive");
            $(pImageElement).attr({ src: myImageName });
        }

    } //end function
    function SetupExportForm(pType) {
        $(".exportButton").each(function () { GISPlanning_SetImageInactive($(this).find("img:first")[0]); });
        GISPlanning_SetImageActive($(pType).find("img:first")[0]);
        var myType = pType.getAttribute("exportType");
        var myIframe = $("#ifrmExport");
        var myID = $("#hfldExport").val();
        var myTitle = escape($("input[id$=tboxReportHeader]").val());
        myIframe.attr("src", "/main/exporter.aspx?type=" + myType + "&ID=" + myID + "&title=" + myTitle + "&callBack=CloseExportForm&SST=" + _GISP_Theme);
        myIframe.css("display", "inline");

    } //end function
    function ExportReport_Success(result) {
        $("#tblExport").show();
        $("#tblExportLoading").hide();
    } //end function
    function ExportReport_Failure(error) {
        alert('exporting failed. ' + error._message);
    } //end function
    function CloseExportForm() {
        $find("mpeExport").hide();
        $get("tblExport").style.display = "block";
        $get("tblExportLoading").style.display = "none";

        return false;
    }
    function ResetExportForm() {
        $(".exportButton").each(function () { GISPlanning_SetImageInactive($(this).find("img:first")[0]); });
        $("#hfldExport").val("");
        $("#hfldExportType").val("");
        $("#ifrmExport").hide();
        $("input[id$=tboxReportHeader]").val("");

        return false;
    }
    function ShowExportLoading() {
        $get("tblExport").style.display = "none";
        $get("tblExportLoading").style.display = "block";
    }
    function FindAllReportInCollectionByTypeAndID(pType, pID, pCollection) {
        var myReports = [];
        for (var i = 0; i < pCollection.length; i++) {
            if (pCollection[i].Type == pType && pCollection[i].ID == pID) {
                myReports.push(pCollection[i]);
                break;
            } //end if found
        } //end for each report
        return myReports;

    }
    function FindFirstReportInCollectionByTypeAndID(pType, pID, pCollection) {
        var myReports = FindAllReportInCollectionByTypeAndID(pType, pID, pCollection);
        return myReports.length > 0 ? myReports[0] : null;
    }
    function CancelModifyReport() {
        $("#modifyReport ul:first").css("display", "none");
    }
    function ModifyReport(pReportUniqueID) {
        var myReport = _SSR.GetReportByUniqueID(pReportUniqueID);
        if (typeof (myReport) !== "undefined" && myReport !== null) {
            if (typeof (myReport.ModifyFunction) !== "undefined" && myReport.ModifyFunction !== null) {
                myReport.ModifyFunction();
            } //end if modify function not null
        }

        _SSR.DeleteReportIfNotSaved(pReportUniqueID);
    }
    function ResetReport(pReportUniqueID) {
        var myReport = _SSR.GetReportByUniqueID(pReportUniqueID);
        if (myReport.ResetFunction !== null) {
            myReport.ResetFunction();
        } //end if modify function not null
    }
    function VerifySaveBeforeModify() {
        var myModal = $find('mpeSaveModify');
        myModal.show();

    }
    function LazyLoadSubPropertyReports(pID, pExcludeType, pReportUniqueID) {

        var myReport = _SSR.GetReportByUniqueID(pReportUniqueID);

        if (pExcludeType != "BUSINESS") {
            LoadSubPropertyReportIfNotCached(myReport, pID, "BUSINESS", pReportUniqueID);
        }

        if (pExcludeType != "CONSUMERSPENDING") {
            LoadSubPropertyReportIfNotCached(myReport, pID, "CONSUMERSPENDING", pReportUniqueID);
        }

        if (pExcludeType != "DEMOGRAPHICS") {
            LoadSubPropertyReportIfNotCached(myReport, pID, "DEMOGRAPHICS", pReportUniqueID);
        }

        if (pExcludeType != "LABORFORCE") {
            LoadSubPropertyReportIfNotCached(myReport, pID, "LABORFORCE", pReportUniqueID);
        }
        if (pExcludeType != "WAGES") {
            LoadSubPropertyReportIfNotCached(myReport, pID, "WAGES", pReportUniqueID);
        }

        if (pExcludeType != "FULL") {
            LoadSubPropertyReportIfNotCached(myReport, pID, "FULL", pReportUniqueID);
        }

        if (_ReportLoader.HasItems() && !_ReportLoader.IsProcessing) {
            _ReportLoader.ProcessNext(pReportUniqueID);
        }
        // TODO: add other subreports once implemented
    }
    function LoadSubPropertyReportIfNotCached(pReport, pID, pType, pReportUniqueID) {
        if (!_SSR.GetReportByUniqueID(pReport.SubReports[pType])) {
            _ReportLoader.QueueRequest(pID, pType, pReportUniqueID);
        }
        else {
            setTimeout(function () { EnableSaveReportMenu(pType); }, 250);
        }
    }
    function LazyLoadSubCommunityReports(pID, pExcludeType, pReportUniqueID) {

        var myReport = _SSR.GetReportByUniqueID(pReportUniqueID);

        if (pExcludeType != "CONSUMERSPENDING") {
            LoadSubPropertyReportIfNotCached(myReport, pID, "CONSUMERSPENDING", pReportUniqueID);
        }

        if (pExcludeType != "DEMOGRAPHICS") {
            LoadSubPropertyReportIfNotCached(myReport, pID, "DEMOGRAPHICS", pReportUniqueID);
        }

        if (pExcludeType != "LABORFORCE") {
            LoadSubPropertyReportIfNotCached(myReport, pID, "LABORFORCE", pReportUniqueID);
        }

        if (pExcludeType != "WAGES") {
            LoadSubPropertyReportIfNotCached(myReport, pID, "WAGES", pReportUniqueID);
        }

        if (pExcludeType != "COMMUNITY") {
            LoadSubPropertyReportIfNotCached(myReport, pID, "COMMUNITY", pReportUniqueID);
        }

        if (_ReportLoader.HasItems() && !_ReportLoader.IsProcessing) {
            _ReportLoader.ProcessNext(pReportUniqueID);
        }
        // TODO: add other subreports once implemented
    }
    function LoadSubReport(pResultID, pType, pReportUniqueID, pShowReport, pReload) {
        var myReport = _SSR.GetReportByUniqueID(pReportUniqueID);

        var mySubtype;
        switch (pResultID.toString().length) {
            case 5: mySubtype = 'COUNTY&'; break;  // all county codes are 5 digits
            case 7: mySubtype = 'CITY&'; break; // all city codes are 7 digits
            default: mySubtype = 'POINT&';  // guids for property ids 
                break;
        }

        var myLink = '';
        switch (pType) {
            case "FULL": myLink = "/main/reports/FullProperty.aspx?"; break;
            case "COMMUNITY": myLink = "/main/reports/FullCommunity.aspx?"; break;
            case "BUSINESS": myLink = "/main/reports/Business.aspx?Type=" + mySubtype; break;
            case "CONSUMERSPENDING": myLink = "/main/reports/ConsumerSpending.aspx?Type=" + mySubtype; break;
            case "DEMOGRAPHICS": myLink = "/main/reports/DEMOGRAPHICS.aspx?Type=" + mySubtype; break;
            case "LABORFORCE": myLink = "/main/reports/LABORFORCE.aspx?Type=" + mySubtype; break;
            case "WAGES": myLink = "/main/reports/Wages.aspx?Type=" + mySubtype; break;
            default: break;
        } //end switch
        myLink += "ID=" + pResultID + "&lat=" + myReport.Parameters["Lat"] + "&lng=" + myReport.Parameters["Lng"] + "&SST=" + myReport.Parameters["SUBSET"] + "&ReportType=" + myReport.Type;

        //add placecode for community reports
        if (myReport.Type == "COMMUNITIES") {
            myLink += "&Placecode=" + myReport.Parameters["Placecode"];
        } //end of community report

        if (pShowReport) {
            map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
            CreateLoadingScreen("SUBREPORT");
            _SSR.ClearCurrentReportOverlays();
        }


        var mySubReport = _SSR.GetReportByUniqueID(myReport.SubReports[pType]);
        if (mySubReport !== null) {
            var myRadius = 1;
            if (pReload !== true) {
                //this is the traditional functionallity (pre 1.17)
                ReplaceView("SUBREPORT", mySubReport.Content);
                mySubReport.ZoomBounds();

                var myShowOverlaysFunction = function () {
                    _SSR.LoadReportOverlays(mySubReport.UniqueID);
                };

                RemoveReportFromReloadingQueue(mySubReport.UniqueID);
                setTimeout(myShowOverlaysFunction, 1);
                setTimeout(function () { EnableSaveReportMenu(pType); }, 250);
            }
            else {
                //this is a reload (New functionality as of 1.17)
                myRadius = mySubReport.Parameters["Radius"] > 0 ? mySubReport.Parameters["Radius"] : (pType == "BUSINESS" ? 1 : 10);
                //double check that radius isnt negative(Drivetime)
                if (mySubReport.Parameters["Radius"] < 0) {
                    myRadius = mySubReport.Parameters["Radius"]; //this will override the default from above and restore the negative value.
                }
                if (mySubtype != 'POINT&') { myRadius = 0; }
                myLink += "&UniqueID=" + mySubReport.UniqueID + "&Radius=" + myRadius;
                LoadSubReportResult(myLink, mySubReport.UniqueID, pShowReport);
            }
        }
        else {
            //TODO: Make the read from the database. Maybe we have a ASHX file that spits out subset constants (The default for business search is 1 mile versus 10 for the rest)
            myRadius = myReport.Parameters["Radius"] > 0 ? myReport.Parameters["Radius"] : (pType == "BUSINESS" ? 1 : 10);
            //double check that radius isnt negative(Drivetime)
            if (myReport.Parameters["Radius"] < 0) {
                myRadius = myReport.Parameters["Radius"]; //this will override the default from above and restore the negative value.
            }
            if (mySubtype != 'POINT&') { myRadius = 0; }
            mySubReport = new GISP_Report({ Parameters: { Lat: myReport.Parameters["Lat"], Lng: myReport.Parameters["Lng"],
                ID: pResultID, SUBSET: myReport.Parameters["SUBSET"], Radius: myRadius
            }
            });

            if (myReport.Type == "COMMUNITIES") {
                mySubReport.Parameters["Placecode"] = myReport.Parameters["Placecode"];
            } //end if community

            mySubReport.Properties["ParentReportID"] = myReport.UniqueID;
            mySubReport.Type = pType;
            _SSR._Reports.push(mySubReport);
            myReport.SubReports[pType] = mySubReport.UniqueID;
            myLink += "&UniqueID=" + mySubReport.UniqueID + "&Radius=" + myRadius;
            LoadSubReportResult(myLink, mySubReport.UniqueID, pShowReport);
        }
    }
    function LoadSubReportResult(pReportURL, pReportUniqueID, pShowReport) {
        _ReportLoader.IsProcessing = true;
        $.ajax({
            dataType: 'html',
            url: pReportURL,
            cache: false, //TODO: insures the latest version (we may want to consider turning this off after development)
            success: function (html, textstatus, xhr) {
                var $tempDOMElem = $("<div style='display:none;'></div>");
                $tempDOMElem[0].innerHTML = html; // note: does not execute js
                var $myForm = $tempDOMElem.find("#tabbedContent");
                var myReport = _SSR.GetReportByUniqueID(pReportUniqueID);
                myReport.Content = $myForm.html();

                // Don't load UI (replaceView) if lazy-loading subreports, unless we're on the tab for this subreport
                if ((pShowReport) || ($("#tabs li#current a").attr("reportType") == myReport.Type)) {
                    ReplaceView("SUBREPORT", myReport.Content);
                }

                FixIE7IndexingContainer($("#tabbedContent"), 5000);
                EnableSaveReportMenu(myReport.Type);
                _ReportLoader.ProcessNext(pReportUniqueID);
                RemoveReportFromReloadingQueue(pReportUniqueID);
                SendDocumentHeight();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                RemoveReportFromReloadingQueue(pReportUniqueID);
                var myReport = _SSR.GetReportByUniqueID(pReportUniqueID);
                myReport.Content = "<div class='error'><h3>Report loading error</h3><div class='message'>We're sorry, the report you requested timed out while rendering its HTML. Please try again by browsing away from, and coming back to this report.</div></div>";
            }
        });    //end ajax load of subreport
    }
    function RemoveReportFromReloadingQueue(pReportID) {
        for (var i = 0; i < GISP_ReloadingReportQueue.length; i++) {
            IfReportIsFoundInLoadingQueueRemoveIt(i, pReportID);
        }
    }
    function IfReportIsFoundInLoadingQueueRemoveIt(pIndex, pReportID) {
        if (GISP_ReloadingReportQueue[pIndex] == pReportID) {
            GISP_ReloadingReportQueue.remove(pIndex); //from GISP_CORE.js
        }
    }
    function EnableSaveReportMenu(pType) {
        var myMenu = $(".saveReportMenu[reportType='" + pType + "'] span");
        myMenu.filter('.disabledMenu').hide();
        myMenu.filter('.enabledMenu').show();

        if (!_ReportLoader.HasItems()) {
            var myMenuAll = $(".saveReportMenu[reportType='ALL'] span");
            myMenuAll.filter('.disabledMenu').hide();
            myMenuAll.filter('.enabledMenu').show();
        }
    }
    function ShowAllCharts() {
        //setup interactive charts
        $(".groupHeader .groupChart").each(
          function () {
              $(this).addClass("current").children("ul:first").show();
          }
      );
        $(".groupHeader .groupChart li .pin").each(
          function () {
              $(this).html("Unpin").parents(".groupHeader:first").find("ul:first").attr("pinned", "1");
          }
      );
    }
    function PanPropertyImages(pDirection) {
        var myImageWidth = 300;
        var myBaseMoveAmount = myImageWidth;
        var myMoveAmount = myBaseMoveAmount * pDirection;
        var myTotalWidth = $("#photos li").length * myImageWidth;
        var myCurrentPosition = parseInt($("#propertyImageSlider").attr("currentPosition"), 10);
        $("#imageNav .back").show();
        $("#imageNav .next").show();
        if (myCurrentPosition + (pDirection * myImageWidth) <= 0) {
            //hide left button
            $("#imageNav .back").hide();
        }
        else if (myCurrentPosition + (pDirection * myImageWidth) == ($("#photos li").length - 1) * myImageWidth) {
            //hide right button
            $("#imageNav .next").hide();
        }

        //adjust the width (add one picture worth of padding in case browswers dont render exactly the same
        $("#propertyImageSlider").css("width", (myTotalWidth + myImageWidth) + "px");

        //stop from clicking the left button when at the begining
        if ((pDirection == -1) && (myMoveAmount + myCurrentPosition < 0)) {
            myBaseMoveAmount = myCurrentPosition;
        }
        //stop from cliking the right button when at the end
        if ((pDirection == 1) && (myMoveAmount + myCurrentPosition) >= myTotalWidth) {
            myBaseMoveAmount = 0;
        }

        //animate the movement
        $("#propertyImageSlider").animate({ "left": (pDirection == 1 ? "-=" : "+=") + myBaseMoveAmount + "px" },
                  "slow", "easeOutElastic", function () {
                      $("#propertyImageSlider").attr("currentPosition", myCurrentPosition += myBaseMoveAmount * pDirection);
                  });
    } //end function
    function ReloadReport(pReportUniqueID) {
        var myReport = _SSR.GetReportByUniqueID(pReportUniqueID);
        if (myReport !== null) {
            var myResultID = myReport.Parameters["ID"];
            var myType = myReport.Type;
            var myParentReportID = myReport.Properties["ParentReportID"];


            //Before trying to load a subreport, we have to set the subreport to this reports id because any report can only have one subreport at any one time.
            //This manifiests itself when LoadSubReport tries to find this report by type and can only ever find the last report created.

            var myParentReport = _SSR.GetReportByUniqueID(myParentReportID);
            myParentReport.SubReports[myType] = myReport.UniqueID;

            LoadSubReport(myResultID, myType, myParentReportID, true, true);
        } else {
            alert("Unable to reload report, could not find report with ID: " + pReportUniqueID);
        }
    } //end function
    function ChangeSavePropertyText() {
        var myCurrentReportID = _SSR.GetCurrentReport().ID;
        var myCurrentReportType = _SSR.GetCurrentReport().Type;
        var myIsSaved = _SSR.IsResultSaved(myCurrentReportID);
        var $mySaveMenu = $("li.ContentToolsItem > a:contains('Save')").parent();
        var $mySaveSiteBuildingItem = $("ul.popDownMenu li:first a", $mySaveMenu);
        if (myIsSaved) {
            var myText = myCurrentReportType.toLowerCase().replace(/^(.)|\s(.)/g,
              function ($1) { return $1.toUpperCase(); }).replace(/s$/, '');
            $mySaveSiteBuildingItem.text("Remove " + myText);
        }
    }
    function UrlHelper(pUrl) {
        // get domain name
        this.domain = /(https?:\/\/([a-z0-9\.]+))/.exec(pUrl)[1];
        // get port
        var portMatch = /(:(\d+))/.exec(pUrl);
        if (portMatch !== null) {
            this.port = portMatch[1];
            if (this.port === null) {
                this.port = "";
            }
        }
        else {
            this.port = "";
        }
        // get query string
        var fullQueryStringMatch = /\?((.*))/.exec(pUrl);
        if (fullQueryStringMatch !== null) {
            this.fullQueryString = fullQueryStringMatch[1];
            // split up query string
            this.queryStrings = this.fullQueryString.split('&');
        }
        else {
            this.fullQueryString = "";
        }
    }
    function HideWordExcelExport() {
        $(function () {
            var $links = $("#contentHeaderMenu ul.popDownMenu li, #contentFooterMenu ul.popDownMenu li");
            $links.find("a:contains('Word'),a:contains('Excel')").parent().hide();
        });
    }
    function ShowWordExcelExport() {
        $(function () {
            var $links = $("#contentHeaderMenu ul.popDownMenu li, #contentFooterMenu ul.popDownMenu li");
            $links.find("a:contains('Word'),a:contains('Excel')").parent().show();
        });
    }

    //For now, registering all functions on the window object. Until we get serious about the module pattern, and pass the functions/objects as dependencies
    window.ShowWordExcelExport = ShowWordExcelExport;
    window.HideWordExcelExport = HideWordExcelExport;
    window.UrlHelper = UrlHelper;
    window.ChangeSavePropertyText = ChangeSavePropertyText;
    window.ReloadReport = ReloadReport;
    window.PanPropertyImages = PanPropertyImages;
    window.ShowAllCharts = ShowAllCharts;
    window.EnableSaveReportMenu = EnableSaveReportMenu;
    window.IfReportIsFoundInLoadingQueueRemoveIt = IfReportIsFoundInLoadingQueueRemoveIt;
    window.RemoveReportFromReloadingQueue = RemoveReportFromReloadingQueue;
    window.LoadSubReportResult = LoadSubReportResult;
    window.LoadSubReport = LoadSubReport;
    window.LazyLoadSubCommunityReports = LazyLoadSubCommunityReports;
    window.LoadSubPropertyReportIfNotCached = LoadSubPropertyReportIfNotCached;
    window.LazyLoadSubPropertyReports = LazyLoadSubPropertyReports;
    window.VerifySaveBeforeModify = VerifySaveBeforeModify;
    window.ResetReport = ResetReport;
    window.ModifyReport = ModifyReport;
    window.CancelModifyReport = CancelModifyReport;
    window.FindFirstReportInCollectionByTypeAndID = FindFirstReportInCollectionByTypeAndID;
    window.FindAllReportInCollectionByTypeAndID = FindAllReportInCollectionByTypeAndID;
    window.ShowExportLoading = ShowExportLoading;
    window.ResetExportForm = ResetExportForm;
    window.CloseExportForm = CloseExportForm;
    window.ExportReport_Failure = ExportReport_Failure;
    window.ExportReport_Success = ExportReport_Success;
    window.SetupExportForm = SetupExportForm;
    window.GISPlanning_SetImageInactive = GISPlanning_SetImageInactive;
    window.onInputKeyUpHandler = onInputKeyUpHandler;
    window.onInputKeyDownDelegate = onInputKeyDownDelegate;
    window.onInputKeyUpDelegate = onInputKeyUpDelegate;
    window.GetExportFormContent = GetExportFormContent;
    window.GetBaseExportFormContent = GetBaseExportFormContent;
    window.SetExporterParameters = SetExporterParameters;
    window.ShowLoadingExportButton = ShowLoadingExportButton;
    window.DisableExportButton = DisableExportButton;
    window.SetupExportButton = SetupExportButton;
    window.DumpToDebugArea = DumpToDebugArea;
    window.ExportReport = ExportReport;
    window.GISP_CleanPropertyLinks = GISP_CleanPropertyLinks;
    window.GISP_SetWordExcelStyles = GISP_SetWordExcelStyles;
    window.GISP_ConvertPropertyCardsToTables = GISP_ConvertPropertyCardsToTables;
    window.GISP_ConvertReportToTables = GISP_ConvertReportToTables;
    window.GISP_ConvertHtmlToTables = GISP_ConvertHtmlToTables;
    window.ExportPropertiesHtml = ExportPropertiesHtml;
    window.ExportAllPropertiesHtml = ExportAllPropertiesHtml;
    window.ExportCommunitiesHtml = ExportCommunitiesHtml;
    window.PrintReport = PrintReport;
    window.PrintPropertyResults = PrintPropertyResults;
    window.GetViewablePropertiesHtml = GetViewablePropertiesHtml;
    window.GetReportHeaderHtml = GetReportHeaderHtml;
    window.ViewReportHistory = ViewReportHistory;
    window.SaveAllSubReports = SaveAllSubReports;
    window.SaveReport = SaveReport;
    window.ShowCurrentReport = ShowCurrentReport;
    window.DisplayReport = DisplayReport;
    window.CreateResultsReport = CreateResultsReport;
    window.ViewComparisonReport = ViewComparisonReport;
    window.ViewDemographicReport = ViewDemographicReport;
    window.ExecuteReportScriptToEvalAfterLoadingReport = ExecuteReportScriptToEvalAfterLoadingReport;
    window.ViewSavedReport = ViewSavedReport;
    window.ViewPointReport = ViewPointReport;
    window.ViewPropertyReport = ViewPropertyReport;
    window.SetupGalleria = SetupGalleria;
    window.RequestPropertyByID = RequestPropertyByID;
    window.RequestPropertyByIDSuccess = RequestPropertyByIDSuccess;
    window.RequestPropertyByIDFailed = RequestPropertyByIDFailed;
    window.LoadResultByIndex = LoadResultByIndex;
    window.ViewCommunityReportForCurrentProperty = ViewCommunityReportForCurrentProperty;
    window.ViewCommunityReport = ViewCommunityReport;
    window.RequestCommunityByID = RequestCommunityByID;
    window.RequestCommunityByIDSuccess = RequestCommunityByIDSuccess;
    window.RequestCommunityByIDFailed = RequestCommunityByIDFailed;
    window.ShowFirstResult = ShowFirstResult;
    window.ViewBusinessReport = ViewBusinessReport;
};
// Right now, run the function right away
GISP.ReportFunctions();

