// Defining Global Variables
const FEEDBACK_API = 'https://docfeedback.int-aws-us.webmethods.io/runflow/run/sync/v2/1vZmfpEiVa'

// ----------------------------------------------------- //
// ----- TOC, Dropdown and Filter related functions ---- //
// ----------------------------------------------------- //

$(window).on('load', () => {
    // Updating the display count
    setTimeout(() => {
        updateCountHandler();

        $('.categories-filter-sm .chosen-single') ? $('.categories-filter-sm .chosen-single').on('click vclick touch touchend', smallFilterSelectHandler) : '';

        $('.categories-filter-sm .chosen-results') ? $('.categories-filter-sm .chosen-results').on('click vclick touch touchend', filterClickHandler) : '';

        $('.toc-item').length ? $('.toc-item').on('click', tocClickHandler) : '';

        $('#reset-filter-btn') ? $('#reset-filter-btn').on('click', resetFilterHandler) : '';

        $('.quickfilter-search-container .dlt-tags__item') ? $('.quickfilter-search-container .dlt-tags__item').on('click', filterTagClickHandler) : '';

        $(".quickfilter-search-container #topic-search") ? $(".quickfilter-search-container #topic-search").on('keyup change', inPageSearchHandler) : '';

        $('.quickfilter-search-container .clear-icon') ? $('.quickfilter-search-container .clear-icon').on('click', inPageSearchClearHandler) : '';

        // - The following line is added to ensure the first option in the category dropdown is marked active 
        //   on page first load / page reload
        // - Required if the user chooses a category, other than the first, and then chooses to reload the page
        // - There is a need to reset the state of the delite rendered category dropdown
        $('.toc-item').length ? $($('.toc-item')[0]).click() : '';


        // Hiding 'TOP' button by default
        $('button.top-btn') ? $('button.top-btn').hide() : '';
        document.querySelector('.main-content') ? document.querySelector('.main-content').addEventListener('scroll', contentScrollHandler) : '';
    }, 150);
});

/*
* * Function to count the number of "valid" topics and update the number on the title
* * A topic is "valid" if it is found via search (search-valid="true") and
* * if it is withing the chosen category (filter-valid="true")
*/
function updateCountHandler() {
    let topicCards = $('.topic-card[search-valid="true"][filter-valid="true"]');
    let topicCountLabel = $('#valid-topic-count');
    let topicList = $('.topics-list');

    let validCount = topicCards ? topicCards.length : 0;
    topicCountLabel ? topicCountLabel.text(`(${validCount})`) : '';
    topicList ? topicList.attr('count', validCount) : '';
}

function applyFilterHandler() {

    let categoryElt = $('.toc-item.active');
    let activeCategory = categoryElt ? categoryElt.attr('id').split('category-option-')[1] : 'all';
    let validProductsCount = 0;
    let recentFilter = $('#recent-filter') ? $('#recent-filter').hasClass('dlt-tags__item--selected') : false;
    let topicCards = $('.topic-card');

    topicCards ? topicCards.attr('filter-valid', 'false') : '';

    topicCards ? topicCards.each((pos, elt) => {
        let isValid = true;
        let categoryId = $(elt).attr('category-id');
        let isRecent = $(elt).find('.topic-card-content').attr('update-date') ? true : false;

        // category selection
        if (activeCategory != 'all' && categoryId != activeCategory) {
            isValid = false;
        }

        // recent selection
        if (recentFilter && !isRecent) {
            isValid = false
        }

        if (isValid) {
            validProductsCount += 1;
        }

        $(elt).attr('filter-valid', isValid);
    }) : '';

    updateCountHandler();
    return;
}

/*
* * Function to handle left toc click
* * Updates the "filter-valid" property of a topic card 
* * based on the selected left toc topic
*/
function tocClickHandler(event) {
    let elt = $(event.target);

    // Un-highlighting the currrently selected toc element
    $('.toc-item.active').length ? $('.toc-item.active').removeClass('active') : '';
    // Highlighting the clicked element
    elt.addClass('active');

    let categoryId = elt.prop('id').split('category-option-')[1];

    // Updating the title
    let rightSectionTitle = $('#active-category-title');
    rightSectionTitle ? rightSectionTitle.text(elt.prop('title')) : '';

    // Updating selected attribute for dropdown filter
    let dropdownOptionContainer = $('.categories-filter-sm .chosen-container')
    dropdownOptionContainer ? dropdownOptionContainer.attr('chosen-category', `category-option-${categoryId}`) : '';

    // Changing filter dropdown label for smaller resolutions
    let filterDropdownSelected = $(`.categories-filter-sm .chosen-single span`);
    filterDropdownSelected ? filterDropdownSelected.html(elt.html()) : '';

    applyFilterHandler();
}

/*
Function to handle search input
* * Updates the "search-valid" property of a topic card 
*   based the value of the searchbox
* * "data-tag" attribute on a topic card defines what keywords 
*   the map to the card
* * "data-tag" attribute constructed by joining (1) topic name, 
*   (2) category name and (3) description on the html
*/
function inPageSearchHandler(event) {
    let elt = $(event.target);
    let searchInput = elt.prop('value').trim().toLowerCase();
    let topicCards = $('.topic-card');

    if (searchInput) {
        // Setting all topic-cards's initial search validity to false
        topicCards ? topicCards.attr('search-valid', 'false') : '';

        // Searching for the input value with the search input present as a whole word (~=) or part of a word (*=) on the data-tag attribute
        // Setting the search validity to true for the cards that match
        let matchedTopicCards = $(`.topic-card[data-tag~='${searchInput}'], .topic-card[data-tag*='${searchInput}']`);
        matchedTopicCards ? matchedTopicCards.each((pos, topicElt) => {
            $(topicElt).attr('search-valid', 'true');
        }) : '';
    }
    else {
        // Resetting search validity
        topicCards ? topicCards.attr('search-valid', 'true') : '';
    }

    // Updating the valid count display
    updateCountHandler();
}

/*
* * Function to clear the search bar when the clear button is clicked
* * Resets the 'search-valid' attribute to 'true' for all topic cards
*/
function inPageSearchClearHandler() {
    // Setting the 'search-valid' attribute to 'true' for all topic-cards
    $('.topic-card') ? $('.topic-card').attr('search-valid', 'true') : '';

    // Updating label for dropdown filter
    $('.categories-filter-sm .chosen-container') ? $('.categories-filter-sm .chosen-container').attr('chosen-category', `category-option-all`) : '';

    // Updating the 
    updateCountHandler();
}

// Function to toggle the state of the selectable filter tags
// Used for recently updated tag
// Toggles the CSS and calls the applyFilterHandler function tp apply the changes
function filterTagClickHandler(event) {
    let elt = event.currentTarget;

    $(elt).toggleClass('dlt-tags__item--selected');

    applyFilterHandler();
}

// Reset filter functionality
// Called when the "Reset" button is clicked
// "Reset" button shows up when no search results are found for the inpage search
function resetFilterHandler() {
    // Resetting to all topics guides
    $('.toc-item.active') ? $('.toc-item.active').removeClass('active') : '';
    $('.toc-item#category-option-all') ? $('.toc-item#category-option-all').addClass('active') : '';

    // Resetting search
    $("#topic-search") ? $("#topic-search").prop('value', '') : '';

    // Resetting quickfilter
    $('.quickfilter-search-container .dlt-tags__item') ? $('.quickfilter-search-container .dlt-tags__item').removeClass('dlt-tags__item--selected') : '';

    // Resetting card display
    let topicCards = $('.topic-card');
    topicCards ? topicCards.attr('search-valid', 'true') : '';
    topicCards ? topicCards.attr('filter-valid', 'true') : '';

    // Resetting categories dropdown filter for smaller resolutions
    // changing filter dropdown value for smaller resolutions
    let smDropdownChosen = $(`.categories-filter-sm .chosen-single span`);
    smDropdownChosen ? smDropdownChosen.html($('.toc-item#category-option-all').html()) : '';

    let smDropdownOptions = $('.categories-filter-sm .chosen-container');
    smDropdownOptions ? smDropdownOptions.attr('chosen-category', 'category-option-all') : '';

    // Resetting the title
    let quickfilterTitle = $('.quickfilter-search-container #title');
    quickfilterTitle ? quickfilterTitle.html('All Products') : '';

    // updating count display value
    updateCountHandler();
}

// Updating active option for capabilities dropdown
// Triggered when the dropdown is clicked to open it
function smallFilterSelectHandler(event) {
    let elt = $(event.target);
    let chosenCategoryId = elt.closest('.chosen-container').attr('chosen-category');

    // Ensuring the selected category is highlighted when the dropdown is opened
    // Making this update only if the currently selected (.result-selected) dropdown option is different from the chosen one (indicated by category id)
    // If they are different, removing the 'result-selected highlighted' classes from the current option and adding them to the new selection
    // Situation only occurs if the left toc was used to choose a category and the window was then resized to show the dropdown filter
    if (chosenCategoryId) {
        let chosenCategory = $(`.categories-filter-sm .active-result.result-selected:not(#sm-${chosenCategoryId})`);
        chosenCategory ? chosenCategory.removeClass('result-selected highlighted') : '';
    }

    let newSeletion = $(`.categories-filter-sm .active-result#sm-${chosenCategoryId}`);
    newSeletion ? newSeletion.addClass('result-selected highlighted') : '';
}

// Filter functionality for capabilities dropdown
// Triggered when any one of the dropdown options are clicked
function filterClickHandler(event) {
    elt = $(event.target);

    if (elt.hasClass('active-result')) {
        let categoryId = elt.prop('id').split('-').slice(-1)[0];

        // Updating the left toc to highlight the same selected option
        $('.toc-item.active') ? $('.toc-item.active').removeClass('active') : '';

        leftTocElt = $(`.toc-item#category-option-${categoryId}`);
        leftTocElt ? leftTocElt.addClass('active') : '';

        let rightSectionTitle = $('#active-category-title');
        rightSectionTitle ? rightSectionTitle.text(leftTocElt.attr('title')) : '';

        // Updating label
        let smDropdownChosen = $('.categories-filter-sm .chosen-container');
        smDropdownChosen ? smDropdownChosen.attr('chosen-category', `category-option-${categoryId}`) : '';

        applyFilterHandler();
    }
}

// ----------------------------------------------------- //
// ----------- Larger Feedback Form functions ---------- //
// ----------- for PC and larger screens --------------- //
// ----------------------------------------------------- //

$(document).ready(() => {

    // add downloadable
    // let $downloadParent = document.getElementById("deliverable-download");
    // let $downloadLink = [`<a href="${deliverable}" alt="Download the complete documentation">`];
    // $downloadLink.push('<img src="images/doc-download.svg" alt="Download the documentation" class="as-icon no-zoom"/>');
    // $downloadLink.push('</a>');
    // $downloadParent.innerHTML = $downloadLink.join("");
    
    //error: Commenting out the above lines as they're added in the html.
    //note: 'deliverable' is not defined in the above code. This causes an error preventing the lines below from being executed.


    
    // Top Button Functionality
    let topBtn = $('#top-btn');
    topBtn ? topBtn.on('click', () => { $('.main-content').animate({ scrollTop: 0 }, 500, 'swing') }) : '';

    clearFormData();
    hideFeedbackHandler();

    mobileResetForm();
    mobileHideFeedbackHandler();

    //  Following function adds 'click' functionality to the feedback icon
    // Actions performed:
    // 1. Toggle (alternate b/w i.e. hide/show) the feedback form
    // 2. Toggle (alternate b/w adding & removing) the 'down-arrow' class for the feedback icon
    let feedbackTab = $('#feedback-tab');
    feedbackTab ? feedbackTab.click(() => {
        $('#feedback-form').fadeToggle('fast', () => $('#feedback-tab').toggleClass('down-arrow'));
        feedback_status();
    }) : '';

    let mobFeedbackTab = $('#mob_feedback-tab');
    mobFeedbackTab ? mobFeedbackTab.click(() => {
        $('#mob_feedbackform').fadeToggle('fast', () => $('#mob_feedback-tab').toggleClass('down-arrow'));

    }) : '';

    // Code to hide the feedback-form on scroll
    let mainContent = $('.main-content');
    mainContent ? mainContent.on('scroll', () => {
        if (!$("#feedback-form").is(':hidden')) {
            $("#feedback-form").hide();
            $("#feedback-tab").removeClass('down-arrow');
            feedback_status();
        }
    }) : '';

    //  Configure form behaviour when "Specific content" radio is selected
    let specificRadio = $('input[type="radio"]#specific');
    specificRadio ? specificRadio.on('change', (e) => {
        if (e.target.checked) {
            // clear any existing selection, reset seltected text and reset comments section
            let copiedTextElt = document.getElementById("copiedText");
            copiedTextElt ? copiedTextElt.value = '' : '';

            let guideTextElt = document.getElementById("guidetext");
            guideTextElt.innerHTML = 'Please select the text of concern to enter your comments';

            let commentsElt = $("textarea#comments");
            let commnetsContainer = $(".comments-container");
            commentsElt ? commentsElt.prop('disabled', true) : '';
            commnetsContainer ? commnetsContainer.attr('disabled', 'disabled') : '';

            // Indicate form state using class 'specific'
            let feedbackFormElt = $('#feedback-form');
            feedbackFormElt ? feedbackFormElt.removeClass('article') : '';
            feedbackFormElt ? feedbackFormElt.addClass('specific') : '';

            // Hide feedback when selection starts
            let contentElt = $(".product-details-wrapper");
            contentElt ? contentElt.on('mousedown', hideFeedbackHandler) : '';

            feedback_status();
            // Show feedback when selection ends
            document.addEventListener('mouseup', copySelectedText);

            // Prevent selection of form content
            let feedbackTabElt = $("#feedback-tab");
            feedbackFormElt.on('mousedown', stopPropagationHandler);
            feedbackTabElt ? feedbackTabElt.on('mousedown', stopPropagationHandler) : '';

            // Validate form post change
            formChangeHandler()
        }
    }) : '';

    // Configure form behaviour when "This site or page" radio is selected
    let pageRadio = $('input[type="radio"]#article');
    pageRadio ? pageRadio.on('change', (e) => {
        if (e.target.checked) {

            let copiedTextElt = document.getElementById("copiedText");
            let guideTextElt = document.getElementById("guidetext")
            let commentsElt = $("textarea#comments");
            let commnetsContainer = $(".comments-container");
            let feedbackFormElt = $('#feedback-form');
            let feedbackTabElt = $("#feedback-tab");
            let contentElt = $(".product-details-wrapper");

            // clear any existing selection, reset seltected text and reset comments section
            copiedTextElt ? copiedTextElt.value = '' : '';
            guideTextElt ? guideTextElt.innerHTML = 'Please select the text of concern to enter your comments' : '';

            commentsElt ? commentsElt.prop('disabled', false) : '';
            commnetsContainer ? commnetsContainer.removeAttr('disabled') : '';

            // Indicate form state using class 'article'
            feedbackFormElt ? feedbackFormElt.addClass('article') : '';
            feedbackFormElt ? feedbackFormElt.removeClass('specific') : '';

            // Clear event listeners
            contentElt ? contentElt.off('mousedown', hideFeedbackHandler) : '';
            document.removeEventListener('mouseup', copySelectedText);
            feedbackFormElt ? feedbackFormElt.off('mousedown', stopPropagationHandler) : '';
            feedbackTabElt ? feedbackTabElt.off('mousedown', stopPropagationHandler) : '';

            // Validate form post change
            formChangeHandler();
        }
    }) : '';

});

/**
 * 
 * Function to handle page scrolls
 * Responsible for:
 * - Showing/hiding the 'TOP' button.
 * - Moving the feedback tab and form up/down to make space for the 'TOP' button.
 */
function contentScrollHandler(event) {
    let scrollContainer = $(event.target);
    let topBtnElement = $('button.top-btn');
    let feedbackTabElement = $('#feedback-tab');
    let feedbackFormElement = $('#feedback-form');
    let mobileFeedbackTabElement = $('#mob_feedback-tab');
    let mobileFeedbackFormElement = $('#mob_feedbackform');

    // Return if any element is not found
    if (!(scrollContainer && topBtnElement && feedbackTabElement && feedbackFormElement && mobileFeedbackTabElement && mobileFeedbackFormElement)) {
        return;
    }

    if (scrollContainer.scrollTop() <= 80 && !topBtnElement.is(":hidden")) {
        topBtnElement.hide(0, () => {
            feedbackTabElement.stop().animate({ bottom: "24px" });
            feedbackFormElement.stop().animate({ bottom: "-=34px" });

            mobileFeedbackTabElement.stop().animate({ bottom: "24px" });
            mobileFeedbackFormElement.stop().animate({ bottom: "-=34px" });
        });
    }
    else if (scrollContainer.scrollTop() > 80 && topBtnElement.is(":hidden")) {
        feedbackTabElement.stop().animate({ bottom: "60px" }, 50, () => {
            topBtnElement.show();
            feedbackFormElement.stop().animate({ bottom: "+=34px" });
        });

        mobileFeedbackTabElement.stop().animate({ bottom: "60px" }, 50, () => {
            topBtnElement.show();
            mobileFeedbackFormElement.stop().animate({ bottom: "+=34px" });
        });
    }
};

function stopPropagationHandler(e) {
    e.stopPropagation();
}

// For larger screens
function hideFeedbackHandler() {
    $("#feedback-form") ? $("#feedback-form").hide() : '';
    $("#feedback-tab") ? $("#feedback-tab").removeClass('down-arrow') : '';
    feedback_status();
}

function showFeedbackHandler() {
    $("#feedback-form") ? $("#feedback-form").show() : '';
    $('#feedback-tab') ? $('#feedback-tab').addClass('down-arrow') : '';
}

function copySelectedText() {
    //  console.log("entered event listener");
    let thetext = getTextSelectionHandler();
    if (thetext.length >= 1) {
        // console.log(thetext);
        let copiedTextElt = document.getElementById("copiedText");
        copiedTextElt ? copiedTextElt.value = thetext : '';

        let guideTextElt = document.getElementById("guidetext");
        guideTextElt ? guideTextElt.innerHTML = thetext : '';

        $("textarea#comments") ? $("textarea#comments").prop('disabled', false) : '';
        $(".comments-container") ? $(".comments-container").removeAttr('disabled') : '';
        showFeedbackHandler();
    }

    // update form validity
    formChangeHandler();
}

function getTextSelectionHandler() {
    let selectedText = "";
    if (window.getSelection().containsNode(document.body, true)) {
        selectedText = window.getSelection().toString();
    }
    return selectedText;
}

function clearText(event) {
    event.preventDefault();
    let copiedTextElt = document.getElementById("copiedText");
    copiedTextElt ? copiedTextElt.value = '' : '';

    let guideTextElt = document.getElementById("guidetext");
    guideTextElt ? guideTextElt.innerHTML = 'Please select the text of concern to enter your comments' : '';

    $("textarea#comments") ? $("textarea#comments").prop('disabled', true) : '';
    $(".comments-container") ? $(".comments-container").attr('disabled', 'disabled') : '';
    formChangeHandler();
}

// Function to reset form data
function clearFormData() {

    let feedbackFormElt = document.getElementById("feedback-form");
    feedbackFormElt ? feedbackFormElt.reset() : '';

    let feedbackResponseRadio = $('[name="response"]:checked');
    feedbackResponseRadio ? feedbackResponseRadio.each((pos, ele) => ele.checked = false) : '';

    let feedbackTypeRadio = $('[name="feedbackoption"]:checked');
    feedbackTypeRadio ? feedbackTypeRadio.each((pos, ele) => ele.checked = false) : '';

    let copiedTextElt = document.getElementById('copiedText');
    copiedTextElt ? copiedTextElt.value = '' : '';

    let guideTextElt = document.getElementById("guidetext");
    guideTextElt ? guideTextElt.innerHTML = 'Please select the text of concern to enter your comments' : '';

    let commentsElt = document.getElementById('comments');
    commentsElt ? commentsElt.value = '' : '';

    let userEmailElt = document.getElementById('userEmail');
    userEmailElt ? userEmailElt.value = '' : '';

    let contentElt = $(".product-details-wrapper");
    contentElt ? contentElt.off('mousedown', hideFeedbackHandler) : '';

    document.removeEventListener('mouseup', copySelectedText);


    let feedbackTabElt = $("#feedback-tab");
    feedbackTabElt ? feedbackTabElt.off('mousedown', stopPropagationHandler) : '';
    feedbackFormElt ? $(feedbackFormElt).off('mousedown', stopPropagationHandler) : '';
    feedbackFormElt ? $(feedbackFormElt).removeClass('yes-response no-response partly-response specific article') : '';

    let loadingElt = document.getElementById('loading');
    loadingElt ? loadingElt.innerHTML = "" : '';

    let submitBtnElt = $('#submit');
    $('#comments') ? $('#comments').prop('disabled', true) : '';
    $('.comments-container') ? $('.comments-container').attr('disabled', 'disabled') : '';

    submitBtnElt ? submitBtnElt.attr('disabled', true) : '';
    feedback_status();
}

// Function count the remaining characters available for comments section
// Also updates form validity state
function countChars(event) {
    let elt = event.target;
    let maxLength = 2000;
    let strLength = elt.value.length;
    let charCount;

    if (strLength == 0) {
        charCount = 2000;
    }
    else if (strLength < maxLength) {
        charCount = maxLength - strLength;
    } else {
        charCount = 0;
    }

    let commentsContainer = document.querySelector(".comments-container");
    commentsContainer ? commentsContainer.setAttribute('count', charCount) : '';
    formChangeHandler();
}

// Function to change feedback icon depending on state
function feedback_status() {
    let responseInputElt = $("input[name='response']");
    const responseChecked = responseInputElt ? responseInputElt.is(":checked") : false;

    let feedbackOptionRadio = $("input[name='feedbackoption']");
    const feedbackOptionChecked = feedbackOptionRadio ? feedbackOptionRadio.is(":checked") : false;

    let userEmailElt = $("#userEmail");
    const emailValue = userEmailElt && userEmailElt.val() ? userEmailElt.val().trim() !== "" : '';

    let feedbackTabElt = $('#feedback-tab');
    if (responseChecked || feedbackOptionChecked || emailValue) {
        feedbackTabElt ? feedbackTabElt.removeClass('feedback-icon').addClass('feedback-icon-active') : '';
    } else {
        feedbackTabElt ? feedbackTabElt.removeClass('feedback-icon-active').addClass('feedback-icon') : '';
    }
}

// Function to configure form behaviour when "Yes", "No" & "Partly" radios are selected
function responseChangeHandler(event, addClass, removeClass) {
    if (event.target.checked) {
        let feedbackFormElt = $('#feedback-form');
        feedbackFormElt ? feedbackFormElt.removeClass(removeClass) : '';
        feedbackFormElt ? feedbackFormElt.addClass(addClass) : '';
    }
}

//function to find user device type
function deviceType() {
    const ua = navigator.userAgent;
    if (/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(ua)) {
        return "tablet";
    }
    else if (/Mobile|Android|iP(hone|od)|IEMobile|BlackBerry|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(ua)) {
        return "mobile";
    }
    return "desktop";
};


// Function to determin  validity of current form state
function FormUIValidationHandler() {
    let responseRadioElt = $('[name="response"]:checked');
    let feedbackOptionElt = $('[name="feedbackoption"]:checked');
    let copiedTextElt = document.getElementById('copiedText');
    let commentsElt = document.getElementById('comments');
    let userEmailElt = document.getElementById('userEmail');
    let validationState = false;

    let responseValue = responseRadioElt && responseRadioElt.length ? $('[name="response"]:checked')[0].value : '';
    let feedbackScope = feedbackOptionElt && feedbackOptionElt.length ? $('[name="feedbackoption"]:checked')[0].value : '';
    let copiedText = copiedTextElt ? copiedTextElt.value : '';
    let commentsText = commentsElt ? commentsElt.value : '';
    let email = userEmailElt ? userEmailElt.value : '';

    if (responseValue === 'yes') {
        validationState = true;
    }
    else if (responseValue === 'partly' || responseValue === 'no') {
        if (feedbackScope === 'article' && commentsText.length) validationState = true;
        else if (feedbackScope === 'specific' && copiedText.length && commentsText.length) validationState = true;
    }

    // console.log('validity: ',validationState);
    return validationState;
}

// Function to change "submit" btn state based on validity
function formChangeHandler(event) {
    event ? event.stopPropagation() : '';
    let validityState = FormUIValidationHandler();

    let submitBtnElt = $('#submit');
    if (validityState) submitBtnElt ? submitBtnElt.prop('disabled', false) : '';
    else submitBtnElt ? submitBtnElt.prop('disabled', true) : '';

    let loadingElt = document.querySelector('#loading');
    loadingElt ? loadingElt.innerHTML = '' : '';
}

function getPageURL() {
    return window.location.href;
}

function feedbackSubmitHandler(e) {
    e.preventDefault();
    sendResponse();
}

function sendResponse() {

    let loadingElt = document.querySelector('#loading');
    let validationState = FormUIValidationHandler();

    if (!validationState) {
        loadingElt ? loadingElt.innerHTML = '<span style="color: #D22D3D;">Invalid input, please check your responses and try again</span>' : '';
    }
    else {
        loadingElt ? loadingElt.innerHTML = '' : '';
    }

    let responsevalue = $('[name="response"]:checked').length ? $('[name="response"]:checked')[0].value : '';
    let feedbackoption = $('[name="feedbackoption"]:checked').length ? $('[name="feedbackoption"]:checked')[0].value : '';
    let feedback_on = '';
    if (feedbackoption == "specific") {
        feedback_on = "Specific content in this article.";
    } else if (feedbackoption == "article") {
        feedback_on = "This article or documentation in general.";
    }

    let copiedtext = document.getElementById('copiedText') ? document.getElementById('copiedText').value : '';
    let comments = document.getElementById('comments') ? document.getElementById('comments').value : '';
    var article_title = 'docs.webmethods.io landing page';
    var email = document.getElementById('userEmail') ? document.getElementById('userEmail').value : '';
    var product = "landingPage";
    var pageURL = getPageURL();
    var device = deviceType();

    $.ajax({
        type: "POST",
        url: FEEDBACK_API,
        data: {
            article_title: article_title,
            responsevalue: responsevalue,
            feedbackoption: feedback_on,
            copiedtext: copiedtext || "N/A",
            comments: comments,
            device: device,
            email: email,
            product: product,
            pageURL: pageURL
        },
        success: function (res) {
            // console.log('success', res);
            clearFormData();
            $('#loading') ? $('#loading').html("<span class='container alert alert-success'>Thank you! We value your feedback.</span>") : '';
            setTimeout(function () {
                document.getElementById('loading') ? document.getElementById('loading').innerHTML = "" : '';
                hideFeedbackHandler();
            }, 2000);
        }
    });
}

// ----------------------------------------------------- //
// ----------- Small Feedback Form functions ----------- //
// ---------- for mobile and smaller screens ----------- //
// ----------------------------------------------------- //

// Hiding the feedback form on clicking the down-carrot button
function mobileHideFeedbackHandler(event = null) {
    if (event) event.preventDefault();
    $("#mob_feedbackform") ? $("#mob_feedbackform").hide() : '';
    $("#mob_feedback-tab") ? $("#mob_feedback-tab").removeClass('down-arrow') : '';
    let messageElt = document.getElementById("message");

    messageElt ? messageElt.classList.remove('alert-error') : '';
    messageElt ? messageElt.classList.remove('alert-success') : '';
    messageElt ? messageElt.innerHTML = "" : '';
    mobfeedback_status();
}

function mobileOnChangeHandler(event) {
    let messageElt = document.getElementById("message");
    messageElt ? messageElt.classList.remove('alert-error') : '';
    messageElt ? messageElt.classList.remove('alert-success') : '';
    messageElt ? messageElt.innerHTML = "" : '';
}

// Reset the fields of the feedback by clearing it
// Hide the feedback form
function mobileResetForm() {
    //$("button[type='button']").removeClass("mob_clicked_btn");
    document.getElementById("mob_comments") ? document.getElementById("mob_comments").value = "" : '';

    let messageElt = document.getElementById("message");
    messageElt ? messageElt.classList.remove('alert-error') : '';
    messageElt ? messageElt.classList.remove('alert-success') : '';
    messageElt ? messageElt.innerHTML = "" : '';

    document.querySelectorAll('input[name="mob_responseValue"]').forEach(e => e.checked = false);
    $("#mob_feedbackform") ? $("#mob_feedbackform").hide() : '';
    $("#mob_feedback-tab") ? $("#mob_feedback-tab").removeClass('down-arrow') : '';
    mobfeedback_status();
}

// Validate the fields of the feedback form
// If invalid, display error message
// If valid, call 'mobileSendResponse' function
function mobileValidateForm(e) {
    e.preventDefault();

    let feedbackFormElt = document.getElementById("mob_feedbackform");
    if (!feedbackFormElt) return;

    let mobForm = new FormData(feedbackFormElt);
    let mobComments = mobForm.get("mob_comments");
    let mobResponseValue = mobForm.get("mob_responseValue");
    let messageBox = document.getElementById('message');

    let noResponse = !Boolean(mobResponseValue); // "true" if no response (between 'yes' & 'no' is given), else "false"
    let noComment = !Boolean(mobComments ? mobComments.trim().length : false); // "true" if no comment / blank comment was given, else false.

    if (noResponse || (mobResponseValue === 'no' && noComment)) {
        // Results in 'true' if:
        // The user has either not given a response (irrespective of comment value)
        // Or, the user has chosen 'no' but not given a comment.

        messageBox ? messageBox.classList.add('alert-error') : '';
        messageBox ? messageBox.classList.remove('alert-success') : '';
        messageBox ? messageBox.innerHTML = "Invalid input, please check your responses and try again" : '';
    }
    else {
        messageBox ? messageBox.innerHTML = "" : '';
        //console.log('Feedback accepted!');
        mobileSendResponse();
    }
}

//Function to check feedback status
function mobfeedback_status() {
    const mobResponseChecked = $("input[name='mob_responseValue']") ? $("input[name='mob_responseValue']").is(":checked") : false;
    const mobCommentsFilled = $("#mob_comments") && $("#mob_comments").val() ? $("#mob_comments").val().trim() !== "" : '';

    if (mobResponseChecked || mobCommentsFilled) {
        $('#mob_feedback-tab') ? $('#mob_feedback-tab').removeClass('feedback-icon').addClass('feedback-icon-active') : '';
    } else {
        $('#mob_feedback-tab') ? $('#mob_feedback-tab').removeClass('feedback-icon-active').addClass('feedback-icon') : '';
    }
}

// Function to send the mobile feedback form
function mobileSendResponse() {
    let product = "landingPage";
    let mobForm = new FormData(document.getElementById("mob_feedbackform"));
    let mob_comments = mobForm.get("mob_comments") || '';
    let mob_responseValue = mobForm.get("mob_responseValue") || '';

    let article_title = 'Product Landing Page';
    let pageURL = getPageURL();
    let device = deviceType()
    let messageElt = document.getElementById("message");

    $.ajax({
        type: "POST",
        url: FEEDBACK_API,
        data: {
            article_title: article_title,
            responsevalue: mob_responseValue,
            feedbackoption: "N/A",
            copiedtext: "N/A",
            comments: mob_comments,
            device: device,
            email: "N/A",
            product: product,
            pageURL: pageURL
        },
        success: function (res) {
            // Resetting the form
            document.getElementById("mob_comments") ? document.getElementById("mob_comments").value = "" : '';

            messageElt ? messageElt.classList.remove('alert-error') : '';
            messageElt ? messageElt.classList.remove('alert-success') : '';
            messageElt ? messageElt.innerHTML = "" : '';
            document.querySelectorAll('input[name="mob_responseValue"]').forEach(e => e.checked = false);

            messageElt ? messageElt.classList.add('alert-success') : '';
            messageElt ? messageElt.classList.remove('alert-error') : '';
            messageElt ? messageElt.innerHTML = "Thank you! We value your feedback." : '';

            setTimeout(function () {
                messageElt ? messageElt.classList.remove('alert-error') : '';
                messageElt ? messageElt.classList.remove('alert-success') : '';
                messageElt ? messageElt.innerHTML = "" : '';
                mobileHideFeedbackHandler();
            }, 3000);
        }
    });
}

// ------------------------ END: Mobile Feedback form ------------------------
