
{% if programmode == 'true' %}

<a id="saveButton" class="btn btn-warning hidden-print" onclick="viewPageHelp();">Create Page Walkthrough</a>
{% else %}
<a  id="viewpage" class="btn btn-info hidden-print" onclick="viewPageHelp();">View Page Walkthrough</a>
{% endif %}
<div id="confirm" class="rock-modal"
    style="position:fixed; background-color:rgba(0,0,0,.4); inset:0px; display:none; z-index:200;">
    <div style="psition:relative; height:500px;">
        <div class="modal-content" style="position:absolute; top:50%; left:50%; width:400px; transform:translate(-50%,-50%); ">
            <div class="modal-header">
                <a href="#" class="close" onclick="refreshPage()">×</a>
                <h3 class="modal-title">
                    Save Changes?</h3>
            </div>
            <div class="modal-body" style="position: relative;min-height:0px;height: 175px;">
                <h2>Save Changes</h2>
                <p>Would you like to save your changes.</p>
                <div>
                    <button class="btn btn-primary" onclick="saveDictionary()"> Yes </button>
                    <button class="btn btn-default" onclick="refreshPage()"> No </button>
                </div>
            </div>
        </div>
    </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/driver.js@1.0.1/dist/driver.js.iife.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/driver.js@1.0.1/dist/driver.css"/>
<style>
.driver-popover {
    width:600px;
    max-width:600px !important;
    }
</style>
<script>
    const driver = window.driver.js.driver;
    let dictionary = {{ 'Global' | Attribute:'WalkthroughDictionary' | FromJSON | ToJSON }};


          function viewPageHelp() {
        event.preventDefault();
      // Example usage:


{% if programmode and programmode == 'false' %}
let elements = [];
let walkthroughElements = Array.from(document.getElementsByClassName('walkthrough'))
        walkthroughElements.forEach((el) => {

            let element = {};
            element.popover = {};

            element.element = el;
            element.popover.title = el.getAttribute('data-walkthrough-title')

            element.popover.description = el.getAttribute('data-walkthrough-description');
            elements.push(element);

        })

{% if includetooltips and includetooltips == "true" %}
    let tooltips = Array.from(document.getElementsByClassName('help'))
    tooltips.forEach((el) => {

        let element = {};
        element.popover = {};

        element.element = el.parentElement.parentElement;
        element.popover.title = el.parentElement.innerText;

        element.popover.description = el.getAttribute('data-original-title')
        elements.push(element);
    })
{% endif %}

{% if includelabelitems and includelabelitems == 'true' %}


  let pageLabels = document.querySelectorAll('label:not(:has(a.help)):not(div.modal label):not(.walkthrough label)')

  for(label in pageLabels ) {

    let element = {};
    element.popover = {};

    let labelText = pageLabels[label].innerText;
    let match = findMatch(dictionary, labelText, "{{identifier}}");

    if(match)
    {
        element.element = pageLabels[label].parentElement;
        element.popover.title = match.text;
        element.popover.description = match.description;
        elements.push(element);

    }

}


    function findMatch(array, text, identifier) {
        // Use the Array.prototype.find() method to search for a match
        return array.find(item => item.text === text && item.identifier === identifier);
      }

{% endif %}
sortedElements = elements.sort(function(a,b) {
    if( a === b) return 0;
    if( !a.element.compareDocumentPosition) {
        // support for IE8 and below
        return a.element.sourceIndex - b.element.sourceIndex;
    }
    if( a.element.compareDocumentPosition(b.element) & 2) {
        // b comes before a
        return 1;
    }
    return -1;
});


            const driverObj = driver({
              showProgress: true,
              steps: sortedElements,
            });



        driverObj.drive();
    }
{% else %}
let pageLabels = document.querySelectorAll('label:not(:has(a.help)):not(div.modal label)');
let labelObjects = [];
let newItems = []
let currentIndex = 0;
let itemsToDelete = [];

for(label of pageLabels)
    {
        let labelObject = {};
        let labelText = label.innerText;

        let match = findMatch(dictionary, labelText, "{{identifier}}");
        let matchIndex = findIndex(dictionary, labelText, "{{identifier}}");


            let element = {};
            element.popover = {};
            element.element = label.parentElement;
            element.popover.title = `Enter Popover Content For ${labelText}`;

            element.popover.description = `
            <p>Enter Descrition for Item with Label: ${ labelText }. Leave blank to Skip this Item in the Walkthrough.</p>
            <textarea rows="10" style="width:100%;" type='text' id="label-text-${ labelText.replace(/ /g, '-') }" data-index="${ matchIndex }" data-label="${ labelText }">${match? match.description : '' }</textarea>`
            element.popover.onNextClick = () => {
                let newItem = {};
                const labelElement = document.getElementById('label-text-'+ labelText.replace(/ /g, '-') ); // Remove the '#' symbol

                if (labelElement) {
                let indexId = labelElement.getAttribute('data-index');
                newItem.text = labelElement.getAttribute('data-label');
                newItem.description = labelElement.value;
                newItem.identifier = "{{identifier}}";

                if(indexId == -1 ) {
                    if(newItem.description) {
                        dictionary.push(newItem);

                    }

                    }
                else {

                    if(newItem.description.length > 0){

                        dictionary[indexId].description = newItem.description;

                    } else {
                        itemsToDelete.push(dictionary[indexId]);

                        dictionary.splice(indexId, 1);

                        document.getElementById('label-text-' + labelText.replace(/ /g, '-') ).value = '';
                        }

                }

                }
                driverObj.moveNext();
                },
                element.popover.onPrevClick = () => {

                }

            labelObjects.push(element);

    }





  const driverObj = driver({
    showButtons: [
        'next',
        'close'
      ],
              showProgress: true,
              steps: labelObjects,
        onDestroyStarted: () => {

                document.getElementById('confirm').style.display = 'block';
                driverObj.destroy();


            },
        });


        driverObj.drive();
function findIndex(array, text, identifier){
    // Use the Array.prototype.find() method to search for a match
    return array.findIndex(item => item.text === text && item.identifier === identifier);
    }
function findMatch(array, text, identifier) {
    // Use the Array.prototype.find() method to search for a match
    return array.find(item => item.text === text && item.identifier === identifier);
  }




}
{% endif %}

function saveDictionary(){
    event.preventDefault();

    // write a function that takes the dictionary and saves it to the clip board, then shows an alert that it is in the clipboard.

    {% attributevalue expression:'Attribute.Key == "WalkthroughDictionary" && Attribute.EntityTypeId == ""' securityenabled:'false' %}
        {% assign Id =  attributevalueItems | First | Property:'Id' %}

        {% endattributevalue %}
    let value = {
            Value: JSON.stringify(dictionary)
        }



    fetch('{{'Global' | Attribute:'InternalApplicationRoot'}}/api/AttributeValues/{{ Id }}',{
        method:'PATCH',
        headers:{'Content-type':'application/json'},
        body: JSON.stringify(value)

        })
        .then( () => {
            document.getElementById('confirm').style.display = 'none';
            })


    }

function refreshPage() {
    location.reload();
    }

</script>
