/* Minification failed. Returning unminified contents.
(11,1): run-time error CSS1019: Unexpected token, found '$'
(11,2): run-time error CSS1019: Unexpected token, found '('
(11,11): run-time error CSS1031: Expected selector, found ')'
(11,11): run-time error CSS1025: Expected comma or open brace, found ')'
(438,116): Scanner error CSS1002: Unterminated string: 's Downloads section</b> to monitor the progress of your download.</p>
(446,2): run-time error CSS1019: Unexpected token, found ')'
 */
/*
  !!!! ---------------------------- IMPORTANT ---------------------------- !!!!
  This script file includes functionality for locked components, which may be required in the future.
  The commented-out code is not unused or trash; it contains functionality for these locked components.
  Please retain these comments, as they may be useful for future development.
  **The view mode values in the code may need to be adjusted for proper functionality because this site doesn't contain double action buttons like Kaz.**
*/



$(document).ready(() => {
    //var areaID = document.querySelector('.bookPageContent')?.getAttribute("data-areaid");
    //if (areaID) {
    //    const popover = document.querySelector('#popoverButton');
    //        if (popover) {
    //            if (areaID == 13) { // teacher's area
    //                popover.setAttribute('data-bs-content', 'Please contact your methodologist to obtain the code');
    //            }
    //            else { //  student's area
    //                popover.setAttribute('data-bs-content', 'Please contact your teacher to obtain the code.');
    //            }
    //        }
    //}
 

    //=====================================================General Handlers starts here=========================================
    $(document).on("click", function (event) {
        //if (!$(event.target).closest(".pin-input").length) { //for locked components
        //    if ($(".popupInfoContainer").is(":visible")) {
        //        toggleErrorArea();
        //    }
        //}

        if (!$(event.target).closest(".actionButton").length && !$(event.target).closest(".popup-content").length) {
            if ($("#popup").is(":visible")) {
                $("#popup").fadeOut();
            }
        }

        if (event.target.id === "popupActionButton" || event.target.id === "viewButton") {
            $("#popup").fadeOut();

        }
    });
    //=====================================================General Handlers ends here =========================================







    //=====================================================Handlers for input _ start here=====================================================
    //const inputs = document.querySelectorAll('.pin-segment');

    //const focusInput = (input, position) => {
    //    input.focus();
    //    input.setSelectionRange(position, position); //cursor must be on next pos.
    //};

    //const handleArrowKeys = (event, index) => {
    //    const { key, target: { selectionStart, value } } = event;
    //    if (key === 'ArrowLeft' && selectionStart === 0 && index > 0) {
    //        focusInput(inputs[index - 1], inputs[index - 1].value.length);
    //        event.preventDefault();
    //    } else if (key === 'ArrowRight' && selectionStart === value.length && index < inputs.length - 1) {
    //        focusInput(inputs[index + 1], 0);
    //        event.preventDefault();
    //    } else if (event.keyCode == 46 && selectionStart === value.length && index < inputs.length - 1) {
    //        focusInput(inputs[index + 1], 0);
    //        event.preventDefault();
    //    }
    //};

    //const handleInput = (event, index) => {
    //    event.target.value = event.target.value.replace(/[\s-]/g, ''); // Remove white space and "-"

    //    if (event.target.value.length >= event.target.maxLength && index < inputs.length - 1) {
    //        inputs[index + 1].focus();
    //    }
    //};


    //const handleBackspace = (event, index) => {
    //    const input = event.target;
    //    const selectionEnd = input.selectionEnd;
    //    if (event.key === 'Backspace' && event.target.selectionStart === 0 && index > 0) {
    //        if (selectionEnd > 0) {
    //            input.value = '';
    //        }
    //        focusInput(inputs[index - 1], inputs[index - 1].value.length);
    //        event.preventDefault();

    //    }
    //};


    //const handlePaste = (event) => {
    //    event.preventDefault();
    //    let paste = (event.clipboardData || window.clipboardData).getData('text').replace(/[\s-]/g, ''); //exclude spaces and - 
    //    const focusedInput = document.activeElement; //get focusedinput
    //    const focusedIndex = Array.from(inputs).indexOf(focusedInput); //get the index of fcsInpt.

    //    if (focusedIndex === -1) return;

    //    let index = 0;
    //    for (let i = 0; i < inputs.length && index < paste.length; i++) {
    //        const maxLength = parseInt($(inputs[i]).attr("maxlength")); // Get the maxlength attribute of the input
    //        inputs[i].value = paste.slice(index, index + maxLength); // Set value based on maxlength
    //        index += maxLength;
    //    }


    //    if (index > 0) {
    //        const lastIndex = Math.min(Math.floor(paste.length / 4), inputs.length - 1);
    //        const lastInput = inputs[lastIndex];
    //        lastInput.focus();
    //    }
    //};





    //const fields = document.querySelector('.fields');
    //if (fields) {
    //    fields.addEventListener('keydown', (event) => {
    //        if (event.ctrlKey && event.key === 'z') { //Maybe we dont need it
    //            event.preventDefault();
    //        }
    //        const index = Array.from(inputs).indexOf(event.target);
    //        handleArrowKeys(event, index);
    //        handleBackspace(event, index);
    //    });
    //    fields.addEventListener('input', (event) => {
    //        const index = Array.from(inputs).indexOf(event.target);
    //        handleInput(event, index);
    //    });

    //    inputs.forEach(segment => {
    //        segment.addEventListener('paste', handlePaste);
    //    });


    //}
    //=====================================================Handlers for input _ ends here=====================================================



    //=====================================================Subscription starts here=========================================

    //const displayAccessPopUp = () => {
    //    $('.accessKeyContainer').fadeIn();
    //};


    //function isSubscriptionValid(subscriptionValue) {

    //    return new Promise(function (resolve, reject) {
    //        $.ajax({
    //            url: "/Subscriptions",
    //            type: 'POST',
    //            dataType: 'json',
    //            contentType: 'application/json',
    //            data: JSON.stringify({
    //                subscription: subscriptionValue,
    //                productTypeId: areaID
    //            }),
    //            success: function (response) {
    //                if (!response.success) {
    //                    resolve(false);
    //                } else {
    //                    resolve(true);
    //                }
    //            },
    //            error: function (xhr, status, error) {
    //                console.error('Error:', error);
    //                reject(error);
    //            }
    //        });
    //    });
    //}

    //const toggleErrorArea = () => { //when code is wrong the add this style.
    //    $('.popupInfoContainer').fadeToggle();
    //    $('#wrongAccessKey').fadeToggle();
    //    $('.fields').toggleClass('error');
    //}

    //const handleAccessKeySubmit = async () => {
    //    const inputs = document.querySelectorAll('.pin-segment');
    //    const hasCorrectData = Array.from(inputs).every(input => input.value.length === parseInt($(input).attr("maxlength")));

    //    if (hasCorrectData) {
    //        const accessKey = Array.from(inputs).map(input => input.value).join('-');

    //        try {
    //            const isValid = await isSubscriptionValid(accessKey);

    //            if (isValid) {
    //                if ($(".popupInfoContainer").is(":visible")) {
    //                    toggleErrorArea();
    //                }
    //                unlockContent('.isLockedContent');
    //            } else {
    //                if (!$(".popupInfoContainer").is(":visible")) {
    //                    toggleErrorArea();
    //                }
    //            }
    //        } catch (error) {
    //            console.error('Error occurred:', error);
    //        }
    //    }
    //    else {
    //        if (!$(".popupInfoContainer").is(":visible")) {
    //            toggleErrorArea();
    //        }

    //    }
    //};

    //const pinSumbit = document.querySelector('.pinSubmit');
    //if (pinSumbit) {
    //    pinSumbit.addEventListener('click', handleAccessKeySubmit);
    //}

    ////=====================================================Subscriptions ends here=========================================






    ////===================================================== ADD NEW BUTTON (AFTER UNLOCK) =====================================================
    //const addButton = (parent, compTitle, viewMode, compID, compID2) => { // Once the component is unlocked, add the button to the interface
    //    let buttonHtml='';
    //    if (viewMode == 1) { // Redirection Button (New page).
    //        buttonHtml = `
    //        <p class="woohoooo">You have unlocked the ${compTitle}! 🎉</p>
    //        <button  
    //            class="actionButton accessKeyBtn unlockedBtn" 
    //            data-isWebResource="true"
    //            arialLabel = "View material in a new browser tab";
    //        >
    //            <span class="actionButtonText">${compTitle}</span>
    //            <div class="actionIconContainer">
    //                <div class="actionIcon"> 
    //                    <img src="/Ukraine/Content/css/images/eyeIcon.svg" alt="An eye icon to view the material on a different page tab on your browser">
    //                </div>
    //            </div>
    //        </button>
    //        `
    //    }
    //    else if (viewMode == 2) { // Flash download button
    //        buttonHtml = `
    //        <p class="woohoooo">You have unlocked the ${compTitle}! 🎉</p>
    //        <button
    //            class="actionButton accessKeyBtn unlockedBtn"
    //            data-isFlash="true"
    //            data-compID="${compID}"
    //            arialLabel = "Download material to your device";
    //        >
    //            <span class="actionButtonText">${compTitle}</span>
    //            <div class="actionIconContainer">
    //                <div class="actionIcon">  
    //                    <img src="/Ukraine/Content/css/images/downloadIcon.svg" alt="An arrow icon to download the material on your device">
    //                </div>
    //            </div>
    //        </button
    //        `
    //    }
    //    else if (viewMode == 5) { //Audio download button
    //        buttonHtml = `
    //        <p class="woohoooo">You have unlocked the ${compTitle}! 🎉</p>
    //        <button
    //            class="actionButton accessKeyBtn unlockedBtn"
    //            data-isdownloadable="true"
    //            data-compID="${compID}"
    //            arialLabel = "Download material to your device";
    //        >
    //            <span class="actionButtonText">${compTitle}</span>
    //            <div class="actionIconContainer">
    //                <div class="actionIcon">  
    //                    <img src="/Ukraine/Content/css/images/downloadIcon.svg" alt="An arrow icon to download the material on your device">
    //                </div>
    //            </div>
    //        </button
    //        `
    //    }
    //    else {
    //        buttonHtml = `
    //        <p class="woohoooo">You have unlocked the ${compTitle}! 🎉</p>
    //        <button 
    //            class="actionButton unlockedBtn accessKeyBtn"
    //            data-viewmode="${viewMode}" 
    //            data-compid="${compID}" 
    //            data-compid2="${compID2}"
    //            arialLabel = "Open the options menu of this material";
    //            data-is_double_action="true"
    //        >
    //                <span class="actionButtonText">IWB Material</span>
    //                <div class="actionIconContainer">
    //                    <div class="actionIcon">    
    //                        <img src=/Ukraine/Content/css/images/ellipsisIcon.svg" alt="An arrow icon to download the material on your device">
    //                    </div>
    //                </span>
    //        </button>
    //            `

    //    }
    //    $(parent).replaceWith(buttonHtml);
    //    document.querySelector('.unlockedBtn').addEventListener('click', handleActionButtons);
    //};




    ////===================================================== UNLOCK BUTTON =====================================================
    //const unlockContent = (parent) => {
    //    const viewMode = document.querySelector('.isLockedContent .accessKeyBtn').getAttribute("data-viewmode");
    //    const compTitle = document.querySelector(".isLockedContent .actionButtonText").textContent;
    //    const compID = document.querySelector('.isLockedContent .accessKeyBtn').getAttribute('data-compID');
    //    const compID2 = document.querySelector('.isLockedContent .accessKeyBtn').getAttribute('data-compID2');

    //    addButton(parent, compTitle, viewMode, compID, compID2);
    //};




    //================================================== TYPE HANDLERS =======================================================
    function handlePopUpActions(target) {
        let actionButton = target.closest(".actionButton");
        if (actionButton) {
            let compID = actionButton.getAttribute('data-compID');
 
            $("#popupTitle").text("As of 31 December 2020, Flash Player is no longer supported by browsers.");
            $("#popupMsg").css("display", "block");
            $(".popupButtonList").empty();
            $(".popupButtonList").append(`
                <button class="buttonStyle" id="popupActionButton">Download</button>
            `)
           
            //-----------POP UP ACTIONS---------------
            $("#popup").fadeIn();
            $("#popupActionButton").off("click").on("click", function () {    
                displayDownloadMessage();
                window.open(`/Ukraine/DownloadFile/${compID}`);
            });
        }
    }

    function handleActionButtons(event) {
        //info
        const urlPart = document.querySelector('.bookContainer').getAttribute('data-urlpart');
        const isUnlockedBtn = this.classList.contains('unlockedBtn');
        const isLockedContent = this.closest('.isLockedContent');

        //what is it(flash/audio downloadable/redirect/flipbook/doubleAction): -- doubleAction does not exists on this site.
        const isWebResource = this.hasAttribute('data-isWebResource');
        const isFlash = this.hasAttribute('data-isFlash');
        const isFlipBook = this.hasAttribute('data-isflipbook');
        const isDownloadable = this.hasAttribute('data-isdownloadable');
        const type = this.innerText.replace(/\s+/g, '-');//Type Name of button

        // Handle Unlocked components(Subscription Code added)
        if (isUnlockedBtn) {
            if (isWebResource) { //opens to iframe comp page.
                window.open(`${type}/${urlPart}`, '_blank');
            }
            else if (isFlipBook) { //redirect to new page (without iframe)
                window.open(`https://www.mmpublications.com/flipbooks`, '_blank');
            }
            else if (isFlash) {// is flash
                handlePopUpActions(event.target);
            }
            else if (isDownloadable) { // is simple download file
                handleDownload(event.target, type);
            }
            return;
        }

        if (!isLockedContent) { //free to use components.
            if (isWebResource) {
                window.open(`${type}/${urlPart}`, '_blank');
            } else if (isFlipBook) {
                window.open(`https://www.mmpublications.com/flipbooks`, '_blank');
            } else if (isFlash) {// || isDoubleAction) {
                handlePopUpActions(event.target);
            }
            else if (isDownloadable) {
                handleDownload(event.target, type);
            }
            return;
        }

        // Display access popup
        displayAccessPopUp();

        /*Pop Over  - If we have locked componenets we need this.*/
        //var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'));
        //var popoverList = popoverTriggerList.map(function (popoverTriggerEl) {
        //    return new bootstrap.Popover(popoverTriggerEl, {
        //        customClass: 'myPopOver'
        //    });
        //});

    }



    const handleDownload = (target) => {
        let actionButton = target.closest(".actionButton");
        let compID = actionButton.getAttribute('data-compID');
        displayDownloadMessage();
        window.open(`/Ukraine/DownloadFile/${compID}`);

    }


    // Handlers for act button
    const actionButtons = document.querySelectorAll('.accessKeyBtn');
    if (actionButtons) {
        actionButtons.forEach(button => {
            button.addEventListener('click', handleActionButtons);
        });

    }

    const displayDownloadMessage = () => {
        if ($(".digitalMaterial .downloadMsg").length === 0) {

            $(".digitalMaterial").append(`
              <div class="downloadMsg">
                <div class="downloadMsgIcon">
                    <img src="/Ukraine/Content/css/images/downloadIcon.svg" alt="An arrow icon to download the material on your device">
                </div>
                <p>Please open your <b>browser's Downloads section</b> to monitor the progress of your download.</p>
             </div>

            `);
        }
    }


});


