﻿const parser = new DOMParser();

window.addEventListener('DOMContentLoaded', (event) => {

    // Alternate color on sections
    alternateSectionBackgroundColor();

    // Check if back to webpage div exists.
    if (document.querySelector("#BackToWebpage") == null) {
        var node = parser.parseFromString('<div id="BackToWebpage" style="visibility:hidden;display:block;Font-family:Open Sans, Sans-serif, Arial;Font-size:11px;width: 100%;background-color: #111;color: white;z-index:9999;text-align: center;padding-top: 6px;padding-bottom: 6px;position: fixed;left: 0;top: 0;cursor:pointer;" onclick="CloseAppView();">LÄMNA BESTÄLLNINGSLÄGE</div>', 'text/html');
        document.querySelector("body").appendChild(node.firstChild.childNodes[1].firstChild);
    }

    let vh = window.innerHeight - document.querySelector("#BackToWebpage").clientHeight;

    // Check if iframe exists otherwise crate in background.
    if (document.querySelector("#FullcreenIframe") == null) {
        var html = '<iframe id="FullcreenIframe" class="built-in-iframe" onload="ifrmLoadedFn(this)" style="display:none;position:fixed; height:' + vh + 'px;top:' + document.querySelector("#BackToWebpage").clientHeight + 'px;left:0px; right:0px; width:100%;border:none; margin:0; padding:0; overflow:hidden; z-index:999999;"></iframe>';
        var node = parser.parseFromString(html, 'text/html');
        document.querySelector("body").appendChild(node.firstChild.childNodes[1].firstChild);
    }

    const body = document.querySelector("html,body");
    body.style.webkitOverflowScrolling = 'touch !important';

    // Open app event
    if (document.querySelector('.ft-click') != null) { 
        var nodeList = document.querySelectorAll('.ft-click');

        for (let i = 0; i < nodeList.length; i++) {
            nodeList[i].addEventListener("click", function (e) {

                //if (this.querySelector('.ft-spinner') == null) {    // Wait for previous click
                    //disableButton(this);
                    OpenAppView();
                //}
            });
        }
    }

    // Send mail event
    if (document.querySelector('.ft-send-mail') != null) {
        document.querySelector('.ft-send-mail').addEventListener("click", function (e) {

            if (this.querySelector('.ft-spinner') == null) {    // Wait for previous click
                disableButton(this);
                sendMail(this);
            }
        });
    }

    window.onresize = onWindowSize;
});

function onWindowSize() {

    if (document.querySelector("#BackToWebpage").style.display == 'block') {
        let vh = window.innerHeight - document.querySelector("#BackToWebpage").clientHeight;

        document.querySelector("#FullcreenIframe").style.height = vh + "px";
    }
}



function alternateSectionBackgroundColor() {

    let alternateColor = false; // Start blank
    let arrayOfSections = document.querySelectorAll('.alternate-background');

    arrayOfSections.forEach(function (section) {
        if (alternateColor) {
            section.classList.add("section-alternate-bg");
            section.classList.remove("section-bg");
            alternateColor = false;
        }
        else {
            section.classList.add("section-bg");
            section.classList.remove("section-alternate-bg");
            alternateColor = true;
        }
    });

    // background-color: var(--bg_opacity_2);

}

function ifrmLoadedFn() { 

    // Do stuff when iframe done loading here..

    // Activate disabled buttons
    enableAllDisabledButtons();
    
}

function sendMail(sendEmailButton) {

    let contactContainer = sendEmailButton.closest('.ft-mail-container');
    if (contactContainer != null) {

        var elName = contactContainer.querySelector('#contactName');
        var elFromAddress = contactContainer.querySelector('#contactAddress');
        var elPhone = contactContainer.querySelector('#contactPhone');
        var elDdlSubject = contactContainer.querySelector('#ddlContactSubject');
        var elDate = contactContainer.querySelector('#bt-date');
        var elTime = contactContainer.querySelector('#bt-time');
        var elSeats = contactContainer.querySelector('#bt-seats');
        var elMessage = contactContainer.querySelector('#contactMessage');

        // Validate

        let contactElements = contactContainer.querySelectorAll("input, select, textarea");
        [].forEach.call(contactElements, function (el) {
            el.classList.remove("element-has-error");
            el.addEventListener('focus', function() {
                el.classList.remove("element-has-error");
                enableButton(sendEmailButton);
            });
        });

        let validation = true;
        if (elName == null || elName.value == "") {
            elName.classList.add("element-has-error");
            validation = false;
        }
        if (elPhone == null || elPhone.value == "") {
            elPhone.classList.add("element-has-error");
            validation = false;
        }
        if (elDdlSubject == null || elDdlSubject.value == "") {
            elDdlSubject.classList.add("element-has-error");
            validation = false;
        }
        if (elMessage == null || elMessage.value == "") {
            elMessage.classList.add("element-has-error");
            validation = false;
        }
        if (elFromAddress == null || !ftValidate.email(elFromAddress.value)) {
            elFromAddress.classList.add("element-has-error");
            validation = false;
        }

        if (validation) {
            let body;

            // Get data

            if (elDdlSubject.value == 1) {
                body = {
                    action: 'sendEmail',
                    name: elName.value,
                    fromAddress: elFromAddress.value,
                    phone: elPhone.value,
                    subject: elDdlSubject.value,
                    date: elDate.value,
                    time: elTime.value,
                    seats: elSeats.value,
                    message: elMessage.value
                }
            }
            else {
                body = {
                    action: 'sendEmail',
                    name: elName.value,
                    phone: elPhone.value,
                    subject: elDdlSubject.value,
                    message: elMessage.value,
                    fromAddress: elFromAddress.value
                }
            }

            // Post
            ftAjax(body, '/data/contact.ashx', sendEmailButton);
        }
        else {
            enableButton(sendEmailButton);
            alert('Du måste fylla i alla fält!');
        }
    }
    else {
        enableButton(sendEmailButton);
        // Deal with no mail-container
    }
}

 

function ftAjax(body, url, sendEmailButton) {

    // POST request using fetch with error handling
    const element = document.querySelector('#post-request-error-handling .article-id');
    const requestOptions = {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body)
    };
    fetch(url, requestOptions)
        .then(async response => {
            const isJson = response.headers.get('content-type')?.includes('application/json');
            const data = isJson && await response.json();

            // check for error response
            if (!response.ok) {
                // get error message from body or default to response status
                const error = (data && data.message) || response.status;
                enableButton(sendEmailButton);
                return Promise.reject(error);
            }

            // All well, proceed with
            //console.log('Email sent');
            clearContactFields();
            enableButton(sendEmailButton);

            ftModal.open({
                height: '50px',
                width: '400px',
                success: {
                    content: 'Epost skickat!'
                }
            })
        })
        .catch(error => {
            enableButton(sendEmailButton);
            ftModal.open({
                height: '50px',
                width: '400px',
                error: {
                    content: 'Något gick fel..'
                }
            })
            console.error('There was an error!', error);
        });

}

function clearContactFields() {
    let containers = document.getElementsByClassName('ft-mail-container');
    for (i = 0; i < containers.length; ++i) {

        inputs = containers[i].getElementsByTagName('input');
        for (j = 0; j < inputs.length; ++j) {
            if (inputs[j].type == "text" || inputs[j].type == "email")
                inputs[j].value = '';
        }

        textareas = containers[i].getElementsByTagName('textarea');
        for (j = 0; j < textareas.length; ++j) {
            textareas[j].value = '';  
        }
    }
}

function OpenAppView() {
    // Check to see if we should use popup or mobile design.
    if (window.innerWidth < 768) {
        //window.scrollTo(0, 0);

        document.querySelector("body,html").style.overflowY = "hidden";
        document.querySelector("body,html").style.height = "100vh";
        document.querySelector("body,html").style.padding = "0 !Important";
        document.querySelector("body,html").style.margin = "0 !Important";

        document.querySelector("#FullcreenIframe").style.display = '';

        document.querySelector('#FullcreenIframe').src = appUrl + '?BuiltIn=True&BuiltInType=App';

        document.querySelector("#BackToWebpage").style.visibility = '';

    } else {
        document.querySelector("body,html").style.overflowY = "hidden";
        document.querySelector("body,html").style.height = "100vh";
        //jQuery.fancybox.open({
        //    src: UrlToUse + '?BuiltIn=True&BuiltInType=Fancybox',
        //    type: 'iframe',
        //    iframe: {
        //        css: {
        //            height: '90vh',
        //            width: '700px'
        //        }
        //    }
        //});


        ftModal.open({
            height: '90vh',
            width: '700px',
            iframe: {
                src: appUrl + '?BuiltIn=True&BuiltInType=modal'
            }
        })
    }
}

function CloseAppView() {
    document.querySelector("#FullcreenIframe").style.display = 'none';
    document.querySelector("#BackToWebpage").style.visibility = 'hidden';
    document.querySelector("body,html").style.overflowY = "";
    document.querySelector("body,html").style.height = "";
    document.querySelector("body,html").style.padding = "";
    document.querySelector("body,html").style.margin = "";

    enableAllDisabledButtons();
}

function disableAllButtons() {

    let buttons = document.querySelector(".btn");
    buttons.forEach((userItem) => {
        disableButton(this);
    });
}

function enableAllButtons() {
    let buttons = document.querySelectorAll(".btn");
    buttons.forEach(() => {
        enableButton(this)
    });
}

function enableAllDisabledButtons() {
    let spinnersList = document.querySelectorAll('.ft-spinner');
    let spinnersArray = [...spinnersList]; // converts NodeList to Array
    spinnersArray.forEach(spinner => {
        let btn = spinner.parentElement;
        enableButton(btn);
    });
}

function disableButton(btn) {
    btn.setAttribute("disabled", "disabled");
    let loadingSpan = "<span class='ft-spinner'></span";

    let currentHtml = btn.innerHTML;
    btn.innerHTML = currentHtml + loadingSpan;
}

function enableButton(btn) {
    btn.removeAttribute("disabled");
    btn.querySelector(".ft-spinner").remove();
}