﻿/// <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


function ExecuteReportScriptToEvalAfterLoadingReport() {
    eval(_ReportScriptToEvalAfterLoadingReport);
};

function ViewPropertyReport(pID, pTab, pRadius) {
    var myResult = _SSR.GetResultByID(pID, "SITES");

    if (myResult == null) {
        RequestSiteByID(pID, { Tab: pTab, Radius: pRadius });
    } else {
        //stop async processes of loading pins
        _SSR._StopProcessCurrentIterativeAsyncResultOperation = true;

        //hide all other pins (Note, order of operations is important, must add to map before clearing array so that a refernce is kept.
        RemoveMarkers(_mapBar.map, _propertyMarkers);
        var myMarker = FindPropertyMarker(pID)
        if (myMarker == null) {
            myMarker = _SiteSearchResultBuilder.CreateMarker(null, myResult);
        }; //end if marker is null
        _mapBar.map.addOverlay(myMarker);
        _propertyMarkers = [];
        _propertyMarkers.push(myMarker);

        ZoomToProperty(myMarker.ID);


        var myLink = "~/main/PropertyDetails.aspx?ID=" + pID;
        myLink += "&RIDA=" + _GISP_Theme;
        CreateLoadingScreen("CONTENT");
        CreateCurrentReportHeaderAndFooter();

        //if a tab was specified, append that to the querystring
        if (pTab != null) {
            myLink += "&tab=" + pTab;
        };


        //check and see if the report already exists
        var myReport = _SSR.GetReportByTypeAndID("SITES", pID);
        if (myReport != null) {
            _SSR._CurrentReportID = myReport.UniqueID;
            ShowCurrentReport();
            myReport.TabCollection.SetTabByToken("FULL");
        } else {
            myReport = new GISP_Report({ Name: "Property Report", Parameters: { Lat: myResult.lat, Lng: myResult.lng, RIDA: _GISP_Theme, Radius: pRadius} });
            myReport.ID = pID;
            myReport.Type = "SITES";
            _SSR._Reports.push(myReport);
            myLink += "&UniqueID=" + myReport.UniqueID;
            if (pRadius != null) {
                myLink += "&Radius=" + pRadius
            }
            TVAGoogle.common.services.DocumentLoader.GetReportAsHTML(myLink, myReport.UniqueID, DisplayReport);
        }; //end if result is null
    }; //end if result not null
};

function RequestSiteByID(pID, pOptions) {
    CreateLoadingScreen("CONTENT");
    var myRequestId = GISPlanning_MapUtilities_GUID();
    TVAGoogle.common.services.Sites.GetSiteByIDWithInputParams(pID.replace("SITES_", ""), pOptions, myRequestId, RequestSiteByIDSuccess, RequestSiteByIDFailed);
}; //end method

function RequestSiteByIDSuccess(pResult) {
    //do to the formatting of this object, we have to prepend the SITES_ to the ID here
    pResult.Results[0].ID = "SITES_" + pResult.Results[0].ID;
    _SSR._AddResult(pResult.Results[0], pResult.Type);
    ViewPropertyReport(pResult.Results[0].ID, pResult.InputParameters[1].Tab, pResult.InputParameters[1].Radius);
}; //end method

function RequestSiteByIDFailed(pError) {
    alert("Unable to find site:" + pError._message);
}; //end method

function ViewCommunityReport(pID, pTab) {
    var myResult = _SSR.GetResultByID(pID, "COMMUNITY");

    if (myResult == null) {
        RequestCommunityByID(pID, { Tab: pTab });
    } else {
        //stop async processes of loading pins
        _SSR._StopProcessCurrentIterativeAsyncResultOperation = true;

        //hide all other pins (Note, order of operations is important, must add to map before clearing array so that a refernce is kept.
        RemoveMarkers(_mapBar.map, _propertyMarkers);
        var myMarker = FindPropertyMarker(pID)

        if (myMarker == null) {
            myMarker = _CommunitySearchResultBuilder.CreateMarker(null, myResult);
        }; //end if marker is null
        _mapBar.map.addOverlay(myMarker);
        _propertyMarkers = [];
        _propertyMarkers.push(myMarker);





        var myLink = "~/main/CommunityDetails.aspx?ID=" + pID + "&Placecode=" + myResult.Placecode;
        CreateLoadingScreen("CONTENT");
        CreateCurrentReportHeaderAndFooter();

        //if a tab was specified, append that to the querystring
        if (pTab != null) {
            myLink += "&tab=" + pTab;
        };


        //check and see if the report already exists
        var myReport = _SSR.GetReportByTypeAndID("COMMUNITY", pID);
        if (myReport != null) {
            _SSR._CurrentReportID = myReport.UniqueID;
            ShowCurrentReport();
            myReport.TabCollection.SetTabByToken("FULL");
        } else {
            myReport = new GISP_Report({ Name: "Community Report", Parameters: { Lat: myResult.lat, Lng: myResult.lng, Placecode: myResult.Placecode} });
            myReport.ID = pID;
            myReport.Type = "COMMUNITY";
            _SSR._Reports.push(myReport);
            myLink += "&UniqueID=" + myReport.UniqueID;
            TVAGoogle.common.services.DocumentLoader.GetReportAsHTML(myLink, myReport.UniqueID, DisplayReport);

        }; //end if result is null
    }; //end if result found
};

function RequestCommunityByID(pID, pOptions) {
    CreateLoadingScreen("CONTENT");
    var myRequestId = GISPlanning_MapUtilities_GUID();
    TVAGoogle.common.services.Community.GetCommunityByIdWithInputParameters(pID.replace("COMMUNITY_", ""), pOptions, myRequestId, RequestCommunityByIDSuccess, RequestCommunityByIDFailed);
}; //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 ViewBusinessReport(pID) {
    var myReport = _SSR.GetReportByTypeAndID("SITES", pID);
    if (myReport != null) {
        _SSR._CurrentReportID = myReport.UniqueID;
        ShowCurrentReport();
        myReport.TabCollection.SetTabByToken("BUSINESS");
    } //end if subreport is not null
    else {
        //property report does not exist, create and open to the correct tab
        ViewPropertyReport(pID, "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 != 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;
        }; //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");
    CreateCurrentReportHeaderAndFooter();

    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;
    TVAGoogle.common.services.DocumentLoader.GetReportAsHTML(myLink, myReport.UniqueID, DisplayReport);
};


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>\
            <div id="divScriptToEval">\
                <script type="text/javascript">\
                    var myReport = _SSR.GetReportByUniqueID(\'' + myReport.UniqueID + '\');\
                    myReport.TabCollection = new GISP_ReportTabs([\
                        new GISP_ReportTab($(\'#hrefReportTab_0\')[0], { Token: "REPORT", Name: "Report", Active: true, Tooltip: "Click here to view the report", Callback: function() { LoadGenericSubReport(\'' + myReport.UniqueID + '\'); } })\
                    ]);\
                </script>\
            </div>\
            <div>\
                <table cellpadding="0" cellspacing="0" border="0" width="100%" class="ReportHeaderTable left">\
                    <tr>\
                        <td id="exportReportHeader"></td>\
                    </tr>\
                    <tr>\
                        <td colspan="3" id="tdSubReportPlaceholder">\
                            <div id="SubReportNodeToReplace"></div>\
                        </td>\
                    </tr>\
                </table>\
            </div>\
            <div id="rptParamaters"></div>\
            </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 ViewGenericReport(pReportUniqueID) {
    var myReport = _SSR.GetReportByUniqueID(pReportUniqueID);

    //stop async processes of loading pins
    _SSR._StopProcessCurrentIterativeAsyncResultOperation = true;

    //hide all other pins (Note, order of operations is important, must add to map before clearing array so that a refernce is kept.
    RemoveMarkers(_mapBar.map, _propertyMarkers);


    var myLink = "~/main/GenericReport.aspx?UniqueID=" + pReportUniqueID;
    myLink += "&Title=" + myReport.Parameters["Title"];
    myLink += "&Icon=" + myReport.Parameters["Icon"];
    CreateLoadingScreen("CONTENT");
    CreateCurrentReportHeaderAndFooter();

    TVAGoogle.common.services.DocumentLoader.GetReportAsHTML(myLink, myReport.UniqueID, DisplayReport);
}; //end function


function DisplayReport(pReport) {

    //create a dom element that used to pares the results
    var myTempDOMElement = document.createElement("div");
    myTempDOMElement.innerHTML = pReport.Value;
    var myForm = myTempDOMElement.getElementsByTagName("form")[0];
    var myScripts = myTempDOMElement.getElementsByTagName("script");



    var myReportDiv = document.createElement("div");
    myReportDiv.innerHTML = myForm.innerHTML;

    var myReport = _SSR.GetReportByUniqueID(pReport.Key);
    myReport.Content = myReportDiv;

    _SSR._CurrentReportID = myReport.UniqueID;
    ShowCurrentReport();
    //once the page is loaded, execute javascript
    if (myScripts.length > 0) {
        var myCallback = function() {
            eval(myScripts[0].innerHTML);
        };
        setTimeout(myCallback, 10); //execute out of the context of the async call

    };
};

function ShowCurrentReport() {
    SetCurrentTypeButton("Current");
    _SSR.ClearCurrentReportOverlays();
    CreateCurrentReportHeaderAndFooter();

    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();
        ReplaceView("CONTENT", myReport.Content);
        myReport.ZoomBounds();
    }; //end if current report

};
function CreateCurrentReportHeaderAndFooter() {
    ClearHeaderAndFooter();
}; //end function




function ShowSavedReports() {
    SetCurrentTypeButton("Reports");
    _SSR.ClearCurrentReportOverlays();
    if (_SSR._SavedReports.length == 0) {
        DisplayNoResultsMessage("You currently have not saved a report. When viewing a report, click the SAVE button and it will be viewable here.");
    } else {
        var myDiv = document.createElement("div");
        var myHTML = '<table cellpadding="2" cellspacing="0" border="0" style="width:100%">';
        for (var i = 0; i < _SSR._SavedReports.length; i++) {
            var myReport = _SSR.GetReportByUniqueID(_SSR._SavedReports[i]);
            var myStyle = i % 2 == 0 ? "rowStyle_a" : "rowStyle_b";
            myHTML += '<tr class="' + myStyle + '"><td><img src="' + myReport.Icon + '" alt="icon"/></td><td><div class="title">' + myReport.Description + '</div></td><td><a href="javascript:ViewSavedReport(\'' + myReport.UniqueID + '\')">View Report</a></td></tr>';
        }
        myHTML += "</table>";
        myDiv.innerHTML = myHTML;

        ReplaceView("CONTENT", myDiv, true);
    }; //end if saved reports


    //create the header
    var myHeader = document.createElement("div");
    GISPlanning_MapUtilities_SetHTMLAttributes(myHeader, { className: "right" });
    GISPlanning_MapUtilities_SetHTMLAttributes(myHeader.style, { paddingRight: "10px", paddingBottom: "3px" });
    //add the links and content to the top row
    var myExportLink = document.createElement("a");
    GISPlanning_MapUtilities_SetHTMLAttributes(myExportLink, { className: "tinyButtonLink PagingLink", href: "javascript:ShowReportExporter();", innerHTML: "<img src='/common/images/buttons/export_inactive.png' align='absmiddle'><span>Export</span>" });

    myHeader.appendChild(myExportLink);
    ReplaceView("HEADER", myHeader);

};

function ViewSavedReport(pUniqueReportID) {
    SetCurrentTypeButton("Current");
    var myReport = _SSR.GetReportByUniqueID(pUniqueReportID);
    var myParentReport = _SSR.GetReportByUniqueID(myReport.Properties["ParentReportID"]);

    //Add the propertyMarker if one exists
    if ((FindPropertyMarker('<%=_ID %>') == null) && (myParentReport.PropertyMarker != null)) {
        _propertyMarkers.push(myParentReport.PropertyMarker);
        _mapBar.map.addOverlay(myParentReport.PropertyMarker);

        ZoomToProperty(myParentReport.PropertyMarker.ID);
    };



    ReplaceView("CONTENT", myParentReport.Content);
    myParentReport.TabCollection.SetTabByToken(myReport.Type);
}

function SaveReport(pUniqueReportID) {
    var myReport = _SSR.GetReportByUniqueID(pUniqueReportID);
    _SSR.SaveReport(pUniqueReportID);
    if (myReport.SaveFunction != null) {
        myReport.SaveFunction();
    }; //end if show param function not nulls


    jQuery.noticeAdd({
        text: 'Your report has been saved, you can view it here.',
        stay: false,
        appendTo: '#divSavedReportsCell'
    });
}; //


function PopoutReport(pReportID) {
    var myReport = _SSR.GetReportByUniqueID(pReportID);
    var myParentReport = _SSR.GetReportByUniqueID(myReport.Properties.ParentReportID);
    var myPopupGuid = GISPlanning_MapUtilities_GUID();
    var myParentContent = $(myParentReport.Content).clone()[0];
    var myReportContent = $(myReport.Content).clone()[0];

    //remove the non exportable elements
    GISP_RemoveNonPopout(myParentContent);
    GISP_RemoveNonPopout(myReportContent);

    //modify all hyperlinks not marked as functionOverride to point to the opener if they link is actucally a JS function
    $(myReportContent).find("a:not(.functionOveride)").each(function() {
        this.setAttribute("href", this.href.replace("javascript:", "javascript:window.opener."));
    });
    $(myParentContent).find("a:not(.functionOveride)").each(function() {
        this.setAttribute("href", this.href.replace("javascript:", "javascript:window.opener."));
    });
    var myContent = myParentContent.innerHTML; //+ myReportContent.innerHTML;

    //add content to tracker
    _popupTracker.AddContent(myPopupGuid, myContent);

    var myLink = "main/reportViewers/default.aspx";
    switch (myReport.Type) {
        case "BUSINESS": myLink = "main/reportViewers/business.aspx";
    };
    myLink += "?id=" + myPopupGuid;

    GISPlanning_Popup_Window(myLink, {});
}; //
function ViewReportHistory() {
    alert("This has not been implemented yet");
}; //
function PrintReport(pReportID) {
    var myReport = _SSR.GetReportByUniqueID(pReportID);
    var myParentReport = _SSR.GetReportByUniqueID(myReport.Properties.ParentReportID);
    var myPopupGuid = GISPlanning_MapUtilities_GUID();
    var myParentContent = $(myParentReport.Content).clone()[0];
    var myReportContent = $(myReport.Content).clone()[0];

    //remove the non exportable/popoutable elements
    GISP_RemoveNonPopout(myParentContent);
    GISP_RemoveNonPopout(myReportContent);
    GISP_RemoveNonExportable(myParentContent);
    GISP_RemoveNonExportable(myReportContent);


    var myContent = myParentContent.innerHTML; //+ myReportContent.innerHTML;

    //add content to tracker
    _popupTracker.AddContent(myPopupGuid, myContent);

    var myLink = "main/reportViewers/printreport.aspx";

    myLink += "?id=" + myPopupGuid;

    GISPlanning_Popup_Window(myLink, {});
}; //



function ExportReport(pReportID) {
    $find("mpeExport").show();

    ResetExportForm();
    var myExportHField = $get("hfldExport");
    myExportHField.value = pReportID;

    var myExportButton = $get("ifrmExport")
    myExportButton.style.display = "none";

    $get("tblExport").style.display = "none";
    $get("tblExportLoading").style.display = "block";

    var myExportHField = $get("hfldExport");
    var myReportID = myExportHField.value;

    var myRegcontentFunction = function() {
        // "register" the content
        var myReport = _SSR.GetReportByUniqueID(myReportID);
        var myParentReport = _SSR.GetReportByUniqueID(myReport.Properties.ParentReportID);
        var myParentHeader = $(myParentReport.Content).find("#exportReportHeader").clone()[0];
        var myReportContent = $(myReport.Content).clone()[0];

        //remove the non exportable elements
        GISP_RemoveNonExportable(myParentHeader);
        GISP_RemoveNonExportable(myReportContent);


        //modify all hyperlinks to remove JS Functions
        GISP_RemoveFunctionHyperlinks(myParentHeader);
        GISP_RemoveFunctionHyperlinks(myReportContent);

        //get the map, remove unwanted elements
        var myMapClone = $("#mapCell").clone()[0];
        GISP_RemoveNonExportable(myMapClone);
        $(myMapClone).find(".gmnoprint").remove();
        var myMapContent = "<div style='padding:10px'><div style='position:relative;width:960px;height:450px;'>" + myMapClone.innerHTML + "</div></div>";

        var myReportContent = myParentHeader.innerHTML + myReportContent.innerHTML;

        //create a collection of pages
        var myPages = [];
        myPages.push(escape(myMapContent), escape(myReportContent));
        TVAGoogle.common.services.DocumentLoader.RegisterExportReport(myReportID, myPages, myReportID, ExportReport_Success, ExportReport_Failure);
    };        //end function
    setTimeout(myRegcontentFunction, 10);

}; //

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 = $get("ifrmExport");
    var myID = $get("hfldExport").value;
    var myTitle = escape($get("ctl00_cphModal_tboxReportHeader").value);
    myIframe.setAttribute("src", "/main/exporter.aspx?type=" + myType + "&ID=" + myID + "&title=" + myTitle + "&callBack=CloseExportForm");
    myIframe.style.display = "inline";

}; //end function

function ExportReport_Success(result) {
    _ExportContentLoadedInSession = true;
    $get("tblExport").style.display = "block";
    $get("tblExportLoading").style.display = "none";

}; //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() {
    _ExportContentLoadedInSession = false;
    $(".exportButton").each(function() { GISPlanning_SetImageInactive($(this).find("img:first")[0]) });
    $get("hfldExport").value = "";
    $get("hfldExportType").value = "";
    $get("ifrmExport").style.display = "none";
    $get("ctl00_cphModal_tboxReportHeader").value = "";

    return false;
};
function ShowExportLoading() {
    $get("tblExport").style.display = "none";
    $get("tblExportLoading").style.display = "block";
};



//This export section deals with merged export
function ShowReportExporter() {
    $get("tblExportParams").style.display = "none";
    $get("tblReportExporter").style.display = "none";
    $get("tblReportExporterLoading").style.display = "block";

    $("#ctl00_cphModal_pnlReportExporter").css({ height: "310px", width: "500px" });
    $find("mpeReportExporter").show();

    if (typeof (ReportExporter) == "undefined") {
        var myScriptLoader = new GISPlanning_MapUtilities_ScriptLoader("/common/scripts/ReportExporter.js", "ReportExporter", ShowReportExporter);
        myScriptLoader.Load();
    } else {

        DestroyREExistingDragDrop();
        DisplayInlineTable("tblExportParams");

        $get("tblReportExporter").style.display = "none";
        $get("tblReportExporterLoading").style.display = "none";
        ResetExportForm();

        var myExportHField = $get("hfldReportExport");
        var myID = GISPlanning_MapUtilities_GUID();
        myExportHField.value = myID;

        var myExportButton = $get("ifrmReportExport")
        myExportButton.style.display = "none";
    }; //end ifelse script loaded
};

function SetupReportExportForm(pType) {
    var myType = pType.getAttribute("exportType");
    var myID = $get("hfldReportExport").value;
    var myTitle = escape($get("ctl00_cphModal_tboxReportExportHeader").value);
    var myExportHField = $get("hfldReportExport");
    myExportHField.value = "/main/exporter.aspx?type=" + myType + "&ID=" + myID + "&title=" + myTitle + "&callBack=CloseReportExportForm";

    $get("tblExportParams").style.display = "none";
    $get("tblReportExporter").style.display = "block";

    CreateReportExorterSelectionList();

}; //end function

function CloseReportExportForm() {
    $find("mpeReportExporter").hide();
    $get("tblExportParams").style.display = "none";
    $get("tblReportExporter").style.display = "none";
    $get("tblReportExporterLoading").style.display = "block";

    return false;
};














function GISP_Report(pOptions) {
    var me = this;
    this._UniqueID = GISPlanning_MapUtilities_GUID();
    this._Type = '';
    this._ID = '';
    this._SubReports = {};
    this._Content = document.createElement("div");
    this._Overlays = {};
    this._Bounds = null;
    this._ZoomModifier = 0;
    this._Parameters = {};
    this._Properties = {};


    this._ZoomBounds = function(pBounds, pZoomModifer) {
        if (pBounds != null) {
            me._Bounds = pBounds;
        }; //end if bounds were passed as paramater
        if (pZoomModifer != null) {
            me._ZoomModifier = pZoomModifer;
        }; //end if bounds were passed as paramater
        if (me._Bounds != null) {
            _mapBar.map.setZoom(_mapBar.map.getBoundsZoomLevel(me._Bounds) + (me._ZoomModifier));
            _mapBar.map.setCenter(me._Bounds.getCenter());
        }; //end if bounds not null
    };  //end function

    this._SetBounds = function(pBounds) {
        me._Bounds = pBounds;
    };
    this._GetBounds = function() {
        return me._Bounds;
    };

    //Load options
    var myOptions = { Name: "", Icon: null, Parameters: null, Description: "", DisplayImageURL: "" };
    for (var o in myOptions) {
        if (typeof (pOptions[o]) != "undefined") {
            me['_' + o] = pOptions[o];
        }; //end if option was passed in
    }; //end for each option





    this._Dispose = function() {
        me._Bounds = null;
        me._Content = null;

        //null each overlay
        for (var o in me._Overlays) {
            if (me._Overlays[o].ClickEventHandler != undefined) {
                GEvent.removeListener(me._Overlays[o].ClickEventHandler);
            }
            me._Overlays[o] = null;
        }; //end for each overlay
        me._Overlays = 0;

        //null each property
        for (var o in me._Properties) {

            me._Properties[o] = null;
        }; //end for each overlay
        me._Properties = null;

        //null each parameter
        for (var o in me._Parameters) {
            me._Parameters[o] = null;
        }; //end for each overlay
        me._Parameters = null;

        if (me.TabCollection != undefined) {
            me.TabCollection.Dispose();
        }
        me.TabCollection = null;


        me.ModifyFunction = null;
        me.SaveFunction = null;
        me.ResetFunction = null;
        me.ShowParametersFunction = null;

        me = null;
    };             //end method




    return new function() {
        this.UniqueID = me._UniqueID;
        this.ID = me._ID;
        this.Type = me._Type;
        this.Content = me._Content;
        this.Name = me._Name;
        this.Icon = me._Icon;
        this.Description = me._Description;
        this.DisplayImageURL = me._DisplayImageURL;
        this.Parameters = me._Parameters;
        this.Properties = me._Properties;
        this.Overlays = me._Overlays;
        this.SubReports = me._SubReports;
        this.SetBounds = me._SetBounds;
        this.GetBounds = me._GetBounds;
        this.ZoomBounds = me._ZoomBounds;
        this.Dispose = me._Dispose;
    };                 //end constructor
};

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 ShowReportParameterInput(pReportUniqueID) {
    var myReport = _SSR.GetReportByUniqueID(pReportUniqueID);

    $get('ctl00_cphSubreportContent_pnlParameters').style.display = 'block';
    $get('ctl00_cphSubreportContent_pnlReport').style.display = 'none';
    if (myReport.ShowParametersFunction != null) {
        myReport.ShowParametersFunction();
    }; //end if show param function not null

}; //end function
function CancelModifyReport() {
    $get('ctl00_cphSubreportContent_pnlParameters').style.display = 'none';
    $get('ctl00_cphSubreportContent_pnlReport').style.display = 'block';
};
function ModifyReport(pReportUniqueID) {
    var myReport = _SSR.GetReportByUniqueID(pReportUniqueID);
    if (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 LoadSubPropertyReport(pID, pType, pReportUniqueID) {
    var myReport = _SSR.GetReportByUniqueID(pReportUniqueID);

    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?"; break;
        case "CONSUMERSPENDING": myLink = "~/main/reports/ConsumerSpending.aspx?"; break;
        case "DEMOGRAPHICS": myLink = "~/main/reports/DEMOGRAPHICS.aspx?"; break;
        case "LABORFORCE": myLink = "~/main/reports/LABORFORCE.aspx?"; break;
        case "COMMUNITY": myLink = "~/main/reports/community.aspx?"; break;
        case "DRIVETIME": myLink = "~/main/reports/drivetime.aspx?"; break;
    }; //end switch
    myLink += "ID=" + pID + "&lat=" + myReport.Parameters["Lat"] + "&lng=" + myReport.Parameters["Lng"] + "&RIDA=" + myReport.Parameters["RIDA"]

    if (myReport.Parameters["Radius"] != null) {
        myLink += "&Radius=" + myReport.Parameters["Radius"]
    }


    //add placecode for community reports
    if (myReport.Type == "COMMUNITY") {
        myLink += "&Placecode=" + myReport.Parameters["Placecode"];
    }; //end of community report


    CreateLoadingScreen("SUBREPORT");
    _SSR.ClearCurrentReportOverlays();


    var mySubReport = _SSR.GetReportByUniqueID(myReport.SubReports[pType]);
    if (mySubReport != null) {
        ReplaceView("SUBREPORT", mySubReport.Content);
        mySubReport.ZoomBounds();
        //               

        var myShowOverlaysFunction = function() {
            _SSR.LoadReportOverlays(mySubReport.UniqueID);
        };
        setTimeout(myShowOverlaysFunction, 1);

    }
    else {
        mySubReport = new GISP_Report({ Parameters: { Lat: myReport.Parameters["Lat"], Lng: myReport.Parameters["Lng"],
            ID: pID, RIDA: myReport.Parameters["RIDA"], Radius: myReport.Parameters["Radius"]
        }
        });




        if (myReport.Type == "COMMUNITY") {
            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;
        TVAGoogle.common.services.DocumentLoader.GetReportAsHTML(myLink, mySubReport.UniqueID, LoadSubReportResult);
    }

};

function LoadComparisonSubReport(pReportUniqueID) {
    var myReport = _SSR.GetReportByUniqueID(pReportUniqueID);
    var myType = myReport.Parameters["Type"];

    var myLink = "~/main/reports/";
    switch (myType) {
        case "SITES": myLink += "SiteComparison.aspx"; break;
        case "COMMUNITY": myLink += "CommunityComparison.aspx"; break;
    }; //end switch type
    myLink += "?IDs=" + myReport.Parameters["IDs"];

    CreateLoadingScreen("SUBREPORT");
    _SSR.ClearCurrentReportOverlays();


    var mySubReport = _SSR.GetReportByUniqueID(myReport.SubReports[myType]);
    if (mySubReport != null) {
        ReplaceView("SUBREPORT", mySubReport.Content);
        mySubReport.ZoomBounds();
        //               

        var myShowOverlaysFunction = function() {
            _SSR.LoadReportOverlays(mySubReport.UniqueID);
        };
        setTimeout(myShowOverlaysFunction, 1);

    }
    else {
        mySubReport = new GISP_Report({ Parameters: { IDs: myReport.Parameters["IDs"]} });
        mySubReport.Properties["ParentReportID"] = myReport.UniqueID;
        mySubReport.Type = myType;
        _SSR._Reports.push(mySubReport);
        myReport.SubReports[myType] = mySubReport.UniqueID;
        myLink += "&UniqueID=" + mySubReport.UniqueID;
        TVAGoogle.common.services.DocumentLoader.GetReportAsHTML(myLink, mySubReport.UniqueID, LoadSubReportResult);
    }
};


function LoadGenericSubReport(pReportUniqueID) {
    var myReport = _SSR.GetReportByUniqueID(pReportUniqueID);

    var myLink = "~/main/reports/Generic.aspx";
    myLink += "?Title=" + myReport.Parameters["Title"];
    myLink += "?Icon=" + myReport.Parameters["RESULTS"];

    CreateLoadingScreen("SUBREPORT");
    _SSR.ClearCurrentReportOverlays();


    var mySubReport = _SSR.GetReportByUniqueID(myReport.SubReports[myType]);
    if (mySubReport != null) {
        ReplaceView("SUBREPORT", mySubReport.Content);
        mySubReport.ZoomBounds();
        //               

        var myShowOverlaysFunction = function() {
            _SSR.LoadReportOverlays(mySubReport.UniqueID);
        };
        setTimeout(myShowOverlaysFunction, 1);

    }
    else {
        mySubReport = new GISP_Report({ Parameters: { IDs: myReport.Parameters["IDs"]} });
        mySubReport.Properties["ParentReportID"] = myReport.UniqueID;
        mySubReport.Type = myType;
        _SSR._Reports.push(mySubReport);
        myReport.SubReports[myType] = mySubReport.UniqueID;
        myLink += "&UniqueID=" + mySubReport.UniqueID;
        TVAGoogle.common.services.DocumentLoader.GetReportAsHTML(myLink, mySubReport.UniqueID, LoadSubReportResult);
    }
};


function LoadSubReportResult(pReport) {
    //create a dom element that used to pares the results
    var myTempDOMElement = document.createElement("div");
    myTempDOMElement.innerHTML = pReport.Value;
    var myForm = myTempDOMElement.getElementsByTagName("form")[0];


    var myReportDiv = document.createElement("div");
    myReportDiv.innerHTML = myForm.innerHTML;

    //set the report content in the global report collection
    var myReport = _SSR.GetReportByUniqueID(pReport.Key);
    myReport.Content = myReportDiv;



    ReplaceView("SUBREPORT", myReport.Content);
    var myScripts = myTempDOMElement.getElementsByTagName("script");
    if (myScripts.length > 0) {
        _ReportScriptToEvalAfterLoadingReport = myScripts[0].innerHTML;
        setTimeout(ExecuteReportScriptToEvalAfterLoadingReport, 1);
    };

    myReport.ZoomBounds();

};

//note: each report needs to overwrite this so that the correct tab controller is called
function ReportSubTabSelected(pWhatTab, pReportUniqueID) {
    var myReport = _SSR.GetReportByUniqueID(pReportUniqueID);
    myReport.TabCollection.SetTab(pWhatTab);
};


var _SiteIDForDocumentRequest
function ViewSiteDocuments(pID) {
    _SiteIDForDocumentRequest = pID.replace("SITES_", "");
    DisplayDocumentViewerWhenLoaded(pID);
}; //end function

function DisplayDocumentViewerWhenLoaded() {
    if (typeof (DocumentViewer) != "undefined") {
        DisplayDocumentViewer();
    }
    else {
        var myScriptLoader = new GISPlanning_MapUtilities_ScriptLoader("/common/scripts/Documents.js", "DocumentViewer", DisplayDocumentViewerWhenLoaded);
        myScriptLoader.Load();
    }
}