/* getanddisplaySplashbanner.js is used to display for both Splash and banner message in UI.
   1. displayBannerMsg used to diplay the banner messages.
-----------------------------------------------------------------------------------------------------
    6/2025 - SN: Recurring Task#16: Updated various sections of the code to be compliant with best coding practices according to SonarQube scans.
    3/2024 - SN: Recurring Task#16: Updated various sections of the code to be compliant with best coding practices according to SonarQube scans.
    5/2023 - SN, Dev&Task#476: Reverted the Message1, Message2, Message3 setup back to where all they use for FIRST site.
    8/2022 -  SP, Dev&Task#412: Added ProdUrl variable to retrieve the value from $("#hdnURL") attribute.
              PV: Dev&Task 428 - Moved banner message code from homepagemaintaince.js,gettimeframe.js
    6/2022 - PV: Dev&Task 406 - Move displaying Popup logic/code out of Timeframe.
----------------------------------------------------------------------------------------------*/
$(function () {
    //  Get the Splash message by ajax call method.       
    const SplashgMsgUrl = 'AppConfig/GetXYTableConfig';
    let SplashSuccessCallBack = function (data) {
        // check the 'data' has data and add the html to Splash div with index.html
        if (data !== undefined && data !== null) {
            $("#dSplashMessage").html(data.PopupMessage);
            messages.push(data.Message1);
            messages.push(data.Message2);
            messages.push(data.Message3);
            startDatesofMessages.push(new Date(data.StartDateandTime1));
            startDatesofMessages.push(new Date(data.StartDateandTime2));
            startDatesofMessages.push(new Date(data.StartDateandTime3));
            endDatesofMessages.push(new Date(data.EndDateandTime1));
            endDatesofMessages.push(new Date(data.EndDateandTime2));
            endDatesofMessages.push(new Date(data.EndDateandTime3));
            // store the Popupmessage.
            localStorage.setItem('popupMessage', data.PopupMessage);
            displayBannerMsg(); //
        }
    }
    // Error trapping: Triggers alert box with message when AJAX request fails
    let SplashErrorCallBack = function (error) {
        alert("System Error Occurred (0410). Please Email NCSARequests@dot.gov");
    }
    common.ajaxGet(SplashgMsgUrl, null, SplashSuccessCallBack, SplashErrorCallBack);
    //} 
    $('#myModal').modal({
        backdrop: 'static',   // This disable for click outside event
        keyboard: true    // This for keyboard event
    })
    $("#myModal").on("show.bs.modal", function (e) {
        $(".modal-dialog").css({
            top: 250,
            left: 0,
            right: 0
        });
    });
});


// assign all the declared messages into messages array.
let messages = [];
// Add the START AND END times for each message with format yyyy-mm-dd hh:mm below.
let startDatesofMessages = []
let endDatesofMessages = [];
const currentTime = new Date();//current date and time
// maintenenaceMsg is used to include the message to be dispalyed at the top of the Homepage.
let maintenenaceMsg = '';
// 1. displayBannerMsg used to diplay the banner messages.
function displayBannerMsg() {
    // for the no of messages to be displayed or removed, update maintenance message based on start and end date of each messages.
    for (let i = messages.length - 1; i >= 0; i--) {
        if ((startDatesofMessages[i] < currentTime) && (endDatesofMessages[i] > currentTime)) {
            if (maintenenaceMsg.length)
            maintenenaceMsg = '<div><p>' + messages[i] + '</p></div> <hr style="margin-left:0%;border-top: 3px solid;margin-bottom: 0px solid;font-weight: bold;color: #FF9933 !important;">' + maintenenaceMsg;
            else
                maintenenaceMsg = '<div><p style = "margin-bottom:0px;">' + messages[i] + '</p></div>' + maintenenaceMsg;
        }
    }
    // display the maintainance messages if maintenanceMessage is not empty
    if (maintenenaceMsg !== '') {
        document.getElementById('maintenanceMessage').innerHTML = maintenenaceMsg;
        document.getElementById('maintenanceMessage').style.display = "block";
    }
    else { // else remove the div of maintenanceMessage if empty
        document.getElementById('maintenanceMessage').style.display = "none";
    }
}

/* commonpropandevents.js contains commonly used functions that runs in the application which includes Ajax calls that run independently, generic Ajax GET and POST calls, 
   function for resetting values on changing Topics, and show/hide progress indicator on clicking Expand All/Collapse All buttons under Filter Your Selection panel.
   Ajax Request:
    1. Disables the Submit button any time an Ajax call is called.
    2. Enable the Submit button any time all Ajax calls are stopped.
   Common functions:
    3. Check/Uncheck Row Percentage and Column Percentage, clicking Submit and Save buttons, generic Ajax Get and Post calls, open/close panels, retrieve Application Settings data.
   Reset Current Criteria section:
    4. Reset/Remove State, County, City, Region, Make, and Model selected values in Current Criteria section on changing Topic tabs and metric type.
   Show/Hide Progess Indicator:
    5. Show/Hide progress indicator on clicking Expand All/Collapse All button in Filter Your Selection panels.
    6. Changed REPORT A PROBLEM to NCSA problem reporting: ReportingLinks function to display domainname on the subject of the Email.
    7. To remove highlighted Sample Query after retrival is made and there are changes to the original query.
    -------------------------------------------------------------------------------------------------------------------------------------
    6/2025 - SN: Recurring Task#16: Updated various sections of the code to be compliant with best coding practices according to SonarQube scans.
    9/2024 - PV: Dev&task#567 - Removed the code which is using for hiding Data visualization Panel.
    9/2024 - SN: Dev&task#560 - Added hide/show Interactive Data Visualization Panel.
    3/2024 - SN: Recurring Task#16: Updated various sections of the code to be compliant with best coding practices according to SonarQube scans.
    11/23 - Removed relative URL
    10/23 - SN: O&M#121: Added the function to remove highlighted Sample Query after retrieval is made and there are changes to the original query.
    3/23 SN: Dev&task#440: Changed broken problem reporting email format and updated zip code 20590 in prod to match all OTRA sites.
    10/22 SP: Dev&task#440: Changed Search to Search CDAN, when searched search only CDAN.dot.gov site with search results.
    - Changed REPORT A PROBLEM to NCSA problem reporting
    3/2021 - DB: Reviewed and added additional comments as part of code documentation.
    4/2020 - SP: Edited to insert/complete comments.
    ------------------------------------------------------------------------------------------------------------------------------------- */

// Declare Global variables -- START
let inputData = {}; //  object to capture all selected values and append same to sas url
let statesdata = []; //  new array to hold States data
window.regionsDesc = []; //  new array to hold Regions data
window.BuildRows = "";  //  variable to hold selected values in rows section of Build Your Reports panel
window.BuildColumns = "";//  variable to hold selected values in columns section of Build Your Reports panel
window.defaultRowsandColumns = {}; //  object to hold default values for rows and columns section in Build Your Reports panel
let selections = { 'HighestBac': false, 'PersonBac': false, selectionCount: 0, HighestCount: 0, PersonCount: 0 }; //used to show/hide Highest BAC or Person BAC data elements based on selection
let typePrefix = ""; //  variable to hold the report type selection in Current Criteria section
window.jsonObject = {};
inputData.Type = 1; // Store global inputData variable by Report Type (Table)
let retriveflag = true; // variable to check whether it is initial selection or retrieve
let orderId1 = "";
// Declare Global variables -- END
// 1. Disables the Submit button any time an Ajax call is called.
$(document).ajaxStart(function () {
    $('#btnsubmit').prop('disabled', true);
});

// 2. Enable the Submit button any time all Ajax calls are stopped.
$(document).ajaxStop(function () {
    $('#btnsubmit').prop('disabled', false); // Enable Submit button
    // Reset the below values to default values.
    window.jsonObject = {};
    defaultYears.min = 0;
    defaultYears.max = 0;
    defaultYears.timeFrameType = "Y";
    window.sasDataObj = { type0: [], type1: [], type2: [], type3: [], type4: [], type5: [], type6: [], type7: [] };
    // on mouse over show tooltip for plus icon when panel is closed
    $('a[data-toggle = "collapse"]').mouseover(function () {
        // show tooltip for plus icon when panel is closed
        if ($(this).parent().children().hasClass('collapsed')) {
            $(this).attr('title', 'Open panel');
        }
        // otherwise show tooltip for minus icon
        else {
            $(this).attr('title', "Close panel");
        }
    });
});

// 3. Combine relative base URL with relative path.
//function relativeUrl(url) {
//    return url;
//}

// 4. Check/Uncheck Row Percentage and Column Percentage, clicking Submit and Save buttons, generic Ajax Get and Post calls, open/close panels, retrieve Application Settings data.
let common = (function () {
    // public methods will get added to this object
    let publicMethods = {};
    // publicMethods props 
    publicMethods.props = {
        enableLog: true,
        retriveflag: false
    };
    // initialize the properties and events
    publicMethods.init = function () {
        $("#modelyearicon").hide();
        /* Build Your Table has an option to select Row Percentage and Column Percentage
           selecting/unselecting Row Percentage checkbox will show/hide the selection value in Current Criteria section. */
        $('#RowPer').change(function () {
            let ischecked = $(this).is(':checked'); // checkbox is checked
            // If Row Percentage checkbox is checked, then display 'RowPer=1' in Current Criteria section.
            if (ischecked) {
                $('#RowPerspan').css('display', '');
                $('#RowPerstrong').html('Row Percentage = On');
                $("#RowPerstrong").attr("data-rowPer", "RowPer=1");
            }
            // If Row Percentage checkbox is unchecked, then remove 'RowPer=1' in Current Criteria section.
            else {
                $('#RowPerspan').css('display', 'none');
                $('#RowPerstrong').html('');
            }
        });
        // selecting/unselecting Column Percentage checkbox will show/hide the selection value in Current Criteria section.
        $('#ColPer').change(function () {
            let ischecked = $(this).is(':checked'); // checkbox is checked
            // If Column Percentage checkbox is checked, then display 'ColPer=1' in Current Criteria section.
            if (ischecked) {
                $('#ColPerspan').css('display', '');
                $('#ColPerstrong').html('Column Percentage = On');
                $("#ColPerstrong").attr("data-colPer", "ColPer=1");

            }
            // If Column Percentage checkbox is unchecked, then remove 'ColPer=1' in Current Criteria section.
            else {
                $('#ColPerspan').css('display', 'none');
                $('#ColPerstrong').html('');
            }
        });
        // get the topic Id of topic selected
        const topicid = localStorage.getItem("topicId");
        // hide/show Related Publications panel and Interactive Data Visualization Panel.

        $(".topicpanel").hide();
        $(".topicinfo_" + topicid).show();
        $(".topicinfo_" + topicid).find("[href='#Panel_" + topicid + "']").click();

    };
    // Generic Ajax based which is used in all other JS files. 
    publicMethods.ajaxCall = function (url, params, type, successCallback, errorCallback, headers) {
        params = params || {};
        $.ajax({
            // properties of the Ajax call
            url: url,
            data: params,
            cache: false,
            type: type,
            contentType: "application/json; charset=utf-8",
            headers: headers || {},
            // when the call is success, then pass the data to successCallback.
            success: function (data) {
                successCallback(data);
            },
            // when the call fails, then pass the error to errorCallback.
            error: function (err) {
                errorCallback(err);
            }
        });
    };
    // Generic Ajax GET call. Uses ajaxCall function.
    publicMethods.ajaxGet = function (url, params, successCallback, errorCallback) {
        common.ajaxCall(url, params, "GET", successCallback, errorCallback);
    };
    // Generic Ajax POST call. Uses ajaxCall function.
    publicMethods.ajaxPost = function (url, params, headers, successCallback, errorCallback) {
        common.ajaxCall(url, params, "POST", successCallback, errorCallback, headers);
    };

    // Toggle between open and close of the panel based on panel Id	
    publicMethods.toggleshowHide = function (elementId) {
        const panelObj = $("#" + elementId);
        const panelHeaderObj = $("." + elementId);
        const anchorObj = panelHeaderObj.find("a");

        panelObj.toggle();
        const isPanelOpen = panelObj.css("display") === "block";

        updatePanelIcon(anchorObj, isPanelOpen);

        const datatblnames = ($("#datatablesview").val() || "").split(",").filter(Boolean);
        const sasTableIds = datatblnames.map(item => 'collapse_' + item);
        const isSasDataViewPanel = elementId === "collapsedivsasdataviewPanel" || sasTableIds.includes(elementId);

        if (isPanelOpen) {
            handlePanelOpen(elementId, isSasDataViewPanel, datatblnames);
        } else {
            handlePanelClose(elementId, isSasDataViewPanel, datatblnames);
        }
    };

    // ------------------- Helper Functions -------------------

    function updatePanelIcon(anchorObj, isPanelOpen) {

        if (isPanelOpen) {
            anchorObj.find("em").removeClass("fa-plus").addClass("fa-minus").attr("title", "Close panel");
            anchorObj.removeClass("collapsed");
        } else {
            anchorObj.find("em").removeClass("fa-minus").addClass("fa-plus").attr("title", "Open panel");
            anchorObj.addClass("collapsed");
        }
    }

    function handlePanelOpen(elementId, isSasDataViewPanel, datatblnames) {
        if (elementId === "collapsedivsasdataviewPanel") {
            $("#openalltables").show();
            $("#closealltables").hide();
        }

        if (isSasDataViewPanel) {
            datatblnames.forEach(tableId => {
                const tableObj = $('#collapse_' + tableId);
                if (tableObj.is(':visible')) {
                    toggleTableButtons(tableId, true);
                }
            });
        }

        if (elementId === "SampleQueriesSection") {
            setupSampleQueriesPanel();
        }
    }

    function handlePanelClose(elementId, isSasDataViewPanel, datatblnames) {
        if (isSasDataViewPanel) {
            datatblnames.forEach(tableId => {
                if ($('#collapse_' + tableId).is(':hidden')) {
                    $("#openalltables").show();
                    $("#closealltables").hide();
                }
            });
        }

        if (elementId === "SampleQueriesSection") {
            teardownSampleQueriesPanel();
        }
    }

    function toggleTableButtons(tableId, isOpen) {
        $("#collapsebutton_" + tableId).toggleClass("hidePanel", isOpen).toggleClass("showPanel", !isOpen);
        $("#expandbutton_" + tableId).toggleClass("showPanel", isOpen).toggleClass("hidePanel", !isOpen);
        $("#openalltables").toggle(!isOpen);
        $("#closealltables").toggle(isOpen);
    }

    function setupSampleQueriesPanel() {
        $("#expandQueries").show();
        $("#collapseQueries").hide();
        $(".local").show();
        $("#Searchqueries, #Searchallqueries").val('');
        $("#sampleQuieries").addClass('scroll').show().empty();
        $(".not-found").hide();
        $("#allsampleQuieries").hide();

        $("#expandQueries").off("click").on("click", () => {
            $("#expandQueries").hide();
            $("#collapseQueries").show();
            $("#sampleQuieries").removeClass('scroll');
        });

        $("#collapseQueries").off("click").on("click", () => {
            $("#collapseQueries").hide();
            $("#expandQueries").show();
            $("#sampleQuieries").addClass('scroll');
        });
    }

    function teardownSampleQueriesPanel() {
        $("#expandQueries, #collapseQueries").hide();
        $("#Searchqueries, #Searchallqueries").val('');
        $("#sampleQuieries").addClass('scroll').empty().show();
        $(".not-found").hide();

        const sampleData = $("#sampleQuieries").data("sampleQuieries");
        sampleData?.forEach(item => {
            $("#sampleQuieries").append(bindsamplequery(item, "local"));
        });
    }



    // Open panel based on elementId
    publicMethods.showElement = function (elementId) {
        $("#" + elementId).show();
        const panelHeaderObj = $("." + elementId); // declare a variable and concatenate . to elementId
        $.each(elementId.split(","), function () {
            const anchorObj = panelHeaderObj.find("a"); // find the panel
            anchorObj.removeClass("collapsed");
            anchorObj.find("em").removeClass("fa-plus").addClass("fa-minus").attr("title", "Close panel"); //show minus symbol and change the tooltip
        });
    };

    // Show  panel based on elementIds
    publicMethods.showElements = function (elementIds) {
        // split the panels separated by comma and then join by ,#.
        const pIds = elementIds.split(",").join(",#");
        $("#" + pIds).show();
        // for each panel separated by comma, find the panel and then open the panel.
        $.each(elementIds.split(","), function () {
            const anchorObj = $(this).find("a");
            anchorObj.removeClass("collapsed");
            anchorObj.find("em").removeClass("fa-plus").addClass("fa-minus").attr("title", "Close panel"); //show minus symbol and change the tooltip
        });
    };
    // Close panel based on elementId
    publicMethods.hideElement = function (elementId) {
        $("#" + elementId).hide();
    };
    // Close panel based on elementIds
    publicMethods.hideElements = function (elementIds) {
        // split the panels separated by comma and then join by ,#.
        const pIds = elementIds.split(",").join(",#");
        $("#" + pIds).hide();
        const elementIdsList = elementIds.split(",");
        // for each panel separated by comma, find the panel and then close the panel.
        $.each(elementIdsList, function (i, item) {
            const panelHeaderObj = $("." + item);
            const anchorObj = panelHeaderObj.find("a");
            anchorObj.addClass("collapsed");
            anchorObj.find("em").removeClass("fa-minus").addClass("fa-plus").attr("title", "Open panel"); //show plus symbol and change the tooltip
        });
    };

    /* Retrieve Application Settings data
       If setting data is avilable in localstorage then get from localStorage.getItem("settings")
       otherwise get data using ajax call */
    publicMethods.getSettings = function () {
        let defer = $.Deferred();
        let settings = {};
        let sData = localStorage.getItem("settings");
        // if the data is not empty
        if (sData !== undefined && sData !== null) {
            settings = JSON.parse(sData);
            defer.resolve(settings);
        } else {
            // URL to retrieve Application Settings values
            const appSettingsUrl = 'AppConfig/GetXYTableConfig';
            // on success get the Years data from Application Settings
            let appSettingsSuccessCallBack = function (yearsdata) {
                // check the yearsdata has data and update setting variable
                if (yearsdata !== undefined && yearsdata !== null) {
                    localStorage.setItem("settings", JSON.stringify(yearsdata));
                    settings = yearsdata;
                }
                // resolve with result
                defer.resolve(settings);
            }
            // display error alert message when the ajax request fails.
            let appSettingsErrorCallBack = function (error) {
                alert("System Error Occurred (0410). Please Email NCSARequests@dot.gov");
            }
            // uses ajaxGet function from commonpropandevents.js file for ajax get request
            common.ajaxGet(appSettingsUrl, null, appSettingsSuccessCallBack, appSettingsErrorCallBack);
        }
        return defer.promise();
    };
    // Show alert message on retrieving the query.
    publicMethods.alertMsgShowOnce = function () {
        let invalidMsgCount = localStorage.getItem("invalidMsgCount");
        invalidMsgCount = invalidMsgCount ? Number(invalidMsgCount) : 0;
        //check the invalidMsgCount count
        if (invalidMsgCount <= 1) {
            alert("Your saved queries may not work due to system and data upgrades. Please review the retrieved queries for accuracy before running them. By resaving the corrected query, if needed, this message will disappear.");
        }
    };
    // update message count  
    publicMethods.setinvalidMsgCount = function (val) {
        let invalidMsgCount = localStorage.getItem("invalidMsgCount");
        //if count  is not null update count
        if (val) {
            invalidMsgCount = val;
        } else { // otherwise update the count
            invalidMsgCount = invalidMsgCount ? Number(invalidMsgCount) : 0;
            invalidMsgCount = invalidMsgCount + 1;
        }
        localStorage.setItem("invalidMsgCount", invalidMsgCount);
    };
    return publicMethods;
})();

// 5. Reset/Remove State, County, City, Region, Make, and Model selected values in Current Criteria section.
function resetStates() {
    /* To reset the State, City, County, and Regions in Select State/Region panel and Make and model in Select Vehicle Make and Model panel.
       Empty State, County, City, Region, Make, and Model inputData objects */
    inputData.State = [];
    inputData.County = "";
    inputData.City = "";
    inputData.Region = [];
    inputData.Make = [];
    inputData.Model = "";
    // Reset State and Region radio button.
    $("#radiostate").prop("checked", false);
    $("#radioregion").prop("checked", false);
    // Reset States, Counities, Cities, and Regions on changing Topic tabs and on changing Metric types.
    $("#divregions,#divstates,#opregions,#divcounties,#countiesseparator,#trainglecities, #divcities,#divregiondisc,#trainglestateregion,#trainglecounties,#trainglestateregion,#opstates,#opregions").css("display", "none");
    $(".statesregionpanelbodyspan").show(); // To display informative messages under NHTSA region after reset.
    // Reset Select TimeFrame, Select State and/or Region, and Build Your Reports panels.
    common.hideElements("collapsedivXYtablePanel,collapsedivTimeFramePanel,collapsedivstateregionPanel");
    // Remove Counties, Cities and region text from Current Criteria section on changing Topics.
    $("#strcounties,#strcities,#txt,#region").html("");
    // Remove States, Regions, Counties, Cities options from dropdown.
    $("#opstates option").remove();
    $("#opregions option").remove();
    $("#opcounties option").remove();
    $("#opcities option").remove();
    $("#opregions").unbind('change');
}

/* 6. Show/Hide progress indicator on clicking Expand All/Collapse All button in Filter Your Selection panels.
   clicking Collapse All button will hide the loader */
function hideLoader(id) {
    $("#divfade_" + id).hide();
}
// clicking Expand All button will show the loader
function showLoader(id) {
    $("#divfade_" + id).css("display", "block");
}
// Search code on the Header within the CDAN home page which redirects google doamain
$(document).ready(function () {
    // form id to to submit the domain and inputvalue on search.
    let form = document.getElementById("SearchForm");
    $(form).submit(function () {
        let domainName = "https://www.google.com/search?q=site:https://cdan.dot.gov" + " "; // Domanin name redirecting to google site wihtin the cdan search
        let inputValue = $(this).serialize(); // Inputvlaue entered in the Search box
        let finalURl = inputValue.replace('q=', ""); // Remov q= from the URL.
        window.open(domainName + finalURl, '_blank'); // open new page.
        return false;
    });
});
// 7. Changed REPORT A PROBLEM to NCSA problem reporting: ReportingLinks function to display domainname on the subject of the Email.
function reportingLinks() {
    const domainName = window.location.href;
    let hrefLink = "mailto:NCSARequests@dot.gov ?subject=NCSA Fatality and Injury Reporting System Tool (FIRST) Feedback  " + domainName +
        " &body=Thank you for visiting the National Center for Statistics and Analysis (NCSA), Traffic Records and Analysis Division, an office within the National Highway Traffic Safety Administration (NHTSA.  Feel free to provide your feedback of the site and the information provided with this tool.  You may leave your name and a phone number if you like to be contacted for any clarifications needed or you need a reply from us. %0D%0DThe Subject Line of this email Subject: “NCSA Fatality and Injury Reporting System Tool (FIRST)” must remain unchanged in order for your request to reach our office."
        +
        " %0DSubmit your feedback and comments below :______________________________________________________________________________________________________________________________";
    let a = document.getElementById("reportingLinks");
    a.setAttribute("href", hrefLink); // appends href value
    $("#reportLink").attr("href", hrefLink)
}
// 8. To remove highlighted Sample Query after retrival is made and there are changes to the original query. 
function removeSamplequeryHighlight() {
    if (window.jsonObject["topic_num"] === undefined) {
        localStorage.setItem("selectedQuery", null);
        $("a").removeClass("sampleQueryClickId");
        $('#sampleQuieries').animate({ scrollTop: 0 });
    }
}

