﻿function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function () {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}

function currentObjectWithInEvent(THIS) {
    if (!THIS.tagName) {
        return window.event.srcElement;
    } else {
        return THIS;
    }
}

function AddEventObject(Object, eventType, fn) {
    if (Object) {
        if (Object.addEventListener) {
            Object.addEventListener(eventType, fn, false);
        } else {
            Object.attachEvent('on' + eventType, fn);
        }
    }
}

function debug(text) {
    var debug = document.getElementById("DEBUG");
    if (debug) {
        debug.innerHTML = text + "<br />" + debug.innerHTML;
    } else {
        alert(text);
    }
}

function focus(objectName, tryHarder) {
    var element = document.getElementById(objectName);
    if (element) {
        betterFocus(element);
    }
    if (tryHarder)
        focusElement(element, 100);
}

function betterFocus(element) {
    if (/iPhone|iPod|iPad/.test(navigator.platform)) {
        element.setAttribute("aria-hidden", true);
        setTimeout(function () {
            element.blur();
            element.setAttribute("aria-hidden", false);
            element.focus();
        }, 500);
    } else {
        element.setAttribute("aria-hidden", false);
    }
    element.focus();
}

function focusElement(element, delay) {
    setTimeout(function () {
        if (element && element != document.activeElement) {
            element.focus();
            focusElement(element, delay);
        }
    }, delay);
}
// Fix iOS problem not selection top element
function focusTopElement() {
    let middleChildren = document.querySelectorAll('#middle *');
    let found = null;
    let elements = [];
    if (middleChildren.length) {
        for (let i = 0; i < middleChildren.length; i++) {
            if (!found && middleChildren[i].textContent && middleChildren[i].textContent.trim() != '' && !middleChildren[i].classList.contains("hidden") && (middleChildren[i].tagName == "H2" || middleChildren[i].tagName == "H3" || middleChildren[i].tagName == "LEGEND" || middleChildren[i].tagName == "P")) {
                found = middleChildren[i];
                if (found.tagName == "H2" || found.tagName == "H3")
                    found.setAttribute("role", "alert");
            }
            else if (!middleChildren[i].getAttribute("aria-hidden")) {
                if (middleChildren[i].tagName !== "SPAN")
                {
                    elements.push(middleChildren[i]);
                }
                
            }
        }
    }
    if (found) {
        popParent(elements, found);
        popChildren(elements, found);
        setAriaHidden(elements, true);
        betterFocus(found);
        setTimeout(function () { setAriaHidden(elements, false) }, 1000);
    }
    return found;
}
function popParent(elements, element) {
    if (element) {
        popElement(elements, element);
        popParent(elements, element.parentNode);
    }
}
function popChildren(elements, element) {
    if (element) {
        popElement(elements, element);
        if (element.childNodes) {
            for (let i = 0; i < element.childNodes.length; i++) {
                popChildren(elements, element.childNodes[i]);
            }
        }
    }
}
function popElement(elements, element) {
    var index = elements.indexOf(element);
    if (index !== -1) {
        elements.splice(index, 1);
    }
}
function setAriaHidden(elements, hidden) {
    for (let i = 0; i < elements.length; i++) {
        elements[i].setAttribute("aria-hidden", hidden);
    }
}

function updateBackButtonAttributes() {
    var backButton = document.getElementById("BackButton");
    if (!backButton) {
        return;
    }

    backButton.addEventListener("click", function () { history.go(-1) })
}

function updateErrorMessageCount() {
    var errorMessageOnTopOfThePageLabels = document.getElementsByName("ErrorMessageOnTopOfThePage");
    if (!errorMessageOnTopOfThePageLabels.length) {
        return;
    }

    var errorMessagesCount = document.getElementsByClassName("ErrorSign").length - 1;
    if (errorMessagesCount < 1) {
        return;
    }

    // horizontal radio buttons have own error message under their block
    errorMessagesCount -= document.querySelectorAll("caption > .Error > .ErrorSign").length;
    var errorMessageTemplateElement = errorMessagesCount > 1
        ? document.getElementsByName("MoreQuestionsLeftUnansweredErrorMessageTemplate")[0]
        : document.getElementsByName("OneQuestionLeftUnansweredErrorMessageTemplate")[0];

    // do not change message on the top if template was not found
    if (!errorMessageTemplateElement) {
        return;
    }

    errorMessageOnTopOfThePageLabels[0].textContent = errorMessageTemplateElement.value.replace(/{.*}/, errorMessagesCount);
}

function updateInputErrorDescription() {
    var inputsWithErrors = document.querySelectorAll(".ErrorBorder  input[aria-describedby]");
    if (!inputsWithErrors.length) {
        return;
    }

    inputsWithErrors.forEach(function (element) {
        var errorId = element.getAttribute('aria-describedby')
        var errorMessage = document.querySelector('#' + errorId)
        if (errorMessage == null) {
            var prevElement = element.closest('.ErrorBorder').previousSibling;
            if (prevElement == null) {
                element.removeAttribute('aria-describedby');
                return;
            }
            var elementWithError = element.closest('.ErrorBorder').previousSibling.querySelector('input[aria-describedby]')
            if (elementWithError) {
                element.setAttribute('aria-describedby', elementWithError.getAttribute('aria-describedby'))

            } else {
                element.removeAttribute('aria-describedby')
            }
        }
    });
}

function updateShowAsRequiredInstructionText(isSinglePageSurvey = false) {
    // do not show instruction text if error message exists on surveys different than single page survey
    if (!isSinglePageSurvey) {
        var errorMessagesCount = document.getElementsByClassName("ErrorSign").length - 1;
        if (errorMessagesCount > 0) {
            return;
        }
    }

    var showAsRequiredLabel = $("#showAsRequiredInstructionText");
    if (!showAsRequiredLabel) {
        return;
    }

    var showAsRequiredElements = $("[data-showAsRequired='True']");

    if (showAsRequiredElements.length > 0) {
        showAsRequiredLabel.removeClass('hidden');
        return;
    } 

    showAsRequiredLabel.addClass('hidden');
    return;
}

function addHiddenInputWithRadioButtonNamesToTheFormOnIndexPage() {
    if (!document.body.classList.contains("IndexPage")) {
        return;
    }

    var surveyEntryForm = document.getElementById("surveyEntryForm");
    if (!surveyEntryForm) {
        return;
    }

    var radioButtonNames = [];
    surveyEntryForm.querySelectorAll("input[type='radio']").forEach(input => {
        if (!radioButtonNames.includes(input.name)) {
            radioButtonNames.push(input.name);
        }
    });

    if (radioButtonNames.length < 1) {
        return;
    }

    // create an hidden input here, set it to the form and set the value of radio button names
    var radioButtonNamesInput = document.createElement("input");
    radioButtonNamesInput.setAttribute("type", "hidden");
    radioButtonNamesInput.setAttribute("name", "RadioButtonNames");
    radioButtonNamesInput.setAttribute("value", radioButtonNames.join("|"));

    surveyEntryForm.appendChild(radioButtonNamesInput);
}

document.addEventListener('DOMContentLoaded', function () {
    showJsRequired();

    if (window.NodeList && !NodeList.prototype.forEach) {
        NodeList.prototype.forEach = Array.prototype.forEach;
    }

    addOtherOptionEvents(document)

    document.querySelectorAll('textarea').forEach(function (element) {
        if (element.hasAttribute("maxlength")) {
            TextAreaCounter(element.id, element.getAttribute("maxlength"))
            element.addEventListener("keyup", function (event) { TextAreaCounter(element.id, element.getAttribute("maxlength")) });
        }
    }); 

    document.querySelectorAll('[id*="CN"], [id*="AmountSpent"]').forEach(function (element) {
        if (element.hasAttribute('autotab')) {
            element.addEventListener("keyup", function (event) { autoTab(element, element.getAttribute("maxlength"), event) });
        }
    });

    if (document.getElementById("JavaScriptEnabled")) { document.getElementById("JavaScriptEnabled").value ="1"; }

    var errorLink = document.querySelector("#FNSErrorFocus")
    if (errorLink) {
        var linkId = errorLink.getAttribute("href").replace("#", "");
        errorLink.addEventListener("click", function () { focus(linkId, true); })
        focus("FNSErrorFocus");
    } else {
        if (!focusTopElement())
            focus("surveyQuestions", true);
    }

    updateShowAsRequiredInstructionText();
    updateErrorMessageCount();
    updateInputErrorDescription();
    updateBackButtonAttributes();
    addHiddenInputWithRadioButtonNamesToTheFormOnIndexPage();

    AddWaitIfNeeded();
    AddRecaptchaArias();
});

function addOtherOptionEvents(ele) {
    ele.querySelectorAll("[othertextbox]").forEach(function (element) {
        if (element.getAttribute("type") === "checkbox") {
            addCheckboxOtherOptionEvent(element);
        }
        if (element.getAttribute("type") === "radio") {
            addRadioOtherOptionEvent(element);
        }
        if (element.tagName === "SELECT") {
            addSelectOtherOptionEvent(element);
        }
    });
}

function addCheckboxOtherOptionEvent(element) {
    element.addEventListener("click", function (event) {
        const otherTextbox = document.getElementById(element.id + 'Other');
        if (!element.checked) {
            otherTextbox.parentElement.parentElement.classList.add('not-visible');
            otherTextbox.classList.add('not-visible');
            otherTextbox.value = '';
        } else {
            otherTextbox.parentElement.parentElement.classList.remove('not-visible');
            otherTextbox.classList.remove('not-visible');
            otherTextbox.focus();
        }
    });
}

function addRadioOtherOptionEvent(element) {
    element.parentElement.parentElement.parentElement.addEventListener("change", function (event) {
        const otherTextbox = document.getElementById(element.name + 'Other');
        if (!element.checked) {
            otherTextbox.parentElement.parentElement.classList.add('not-visible');
            otherTextbox.classList.add('not-visible');
            otherTextbox.value = '';
        } else {
            otherTextbox.parentElement.parentElement.classList.remove('not-visible');
            otherTextbox.classList.remove('not-visible');
            otherTextbox.focus();
        }
    });
}

function addSelectOtherOptionEvent(element) {
    element.addEventListener("change", function (event) {
        const otherTextbox = document.getElementById(element.id + 'Other');
        if (element.value !== element.getAttribute('othertextbox')) {
            otherTextbox.parentElement.parentElement.classList.add('not-visible');
            otherTextbox.classList.add('not-visible');
            otherTextbox.value = '';
        } else {
            otherTextbox.parentElement.parentElement.classList.remove('not-visible');
            otherTextbox.classList.remove('not-visible');
            otherTextbox.focus();
        }
    });
}

document.addEventListener('keydown', function (event) {
    if (event.code === 'Space' || event.keyCode === 32 || event.key === ' ') {
        var activeElement = document.activeElement;
        if (activeElement.type == 'radio') {
            activeElement.nextSibling.click();
        }
        if (activeElement.getAttribute('role') == 'radio' || activeElement.getAttribute('role') == 'checkbox') {
            event.preventDefault();
            if (activeElement.querySelector('span[class*=SimpleInputMobile]>label[class*=SimpleInput]')) {
                activeElement.querySelector('span[class*=SimpleInputMobile]>label[class*=SimpleInput]').click();
            }
            else if (activeElement.querySelector('span[class*=SimpleInputMobile]>label[class*=hf]')) {
                activeElement.querySelector('span[class*=SimpleInputMobile]>label[class*=hf]').click();
            }
            else if (activeElement.querySelector('span[class*=SimpleInputMobile]>span[class*=SimpleInput]')) {
                activeElement.querySelector('span[class*=SimpleInputMobile]>span[class*=SimpleInput]').click();
            }
            else if (activeElement.querySelector('label.radioBranded')) {
                activeElement.querySelector('label.radioBranded').click();
            }
            else if (activeElement.querySelector('span.radioBranded')) {
                activeElement.querySelector('span.radioBranded').click();
            }
            else if (activeElement.querySelector('label.checkboxBranded')) {
                activeElement.querySelector('label.checkboxBranded').click();
            }
            else if (activeElement.querySelector('span.checkboxBranded')) {
                activeElement.querySelector('span.checkboxBranded').click();
            }
            else if (activeElement.querySelector('label[class*=SimpleInput]')) {
                activeElement.querySelector('label[class*=SimpleInput]').click();
            }
            else if (activeElement.querySelector('span[class*=SimpleInput]')) {
                activeElement.querySelector('span[class*=SimpleInput]').click();
            }
            else if (activeElement.querySelector('span[class*=scale-image]')) {
                activeElement.querySelector('span[class*=scale-image]').click();
            }
            else if (activeElement.querySelector('span[class*=radio-scale]')) {
                activeElement.querySelector('span[class*=radio-scale]').click();
            }
            else if (activeElement.querySelector('label[class*=radio-scale]')) {
                activeElement.querySelector('label[class*=radio-scale]').click();
            }
            else if (activeElement.querySelector('label[class*=hf]')) {
                activeElement.querySelector('label[class*=hf]').click();
            }
            else {
                activeElement.click();
            }

            if (!activeElement.querySelector('div[class*=Inputtypeother]')) {
                activeElement.focus()
            }
        }
    }
})

function showJsRequired() {
    const hasMap = document.getElementById('wseSMGMap');
    const hasPicklist = document.getElementsByTagName('app-picklist').length > 0

    if (hasMap || hasPicklist) {
        const matched = navigator.userAgent.match('MSIE ([0-9]{1,})');
        if (matched) {
            var ie9OrBelow = matched[0].replace("MSIE ", "") <= 9
            if (ie9OrBelow) {
                document.getElementById('javascript-required').style.display = 'block';
                if (hasMap) {
                    document.getElementById('locationSelectionGroup').style.display = 'none';
                }
                return;
            }
        }
        document.getElementById('javascript-required').style.display = 'none';
        if (hasMap) {
            document.getElementById('locationSelectionGroup').style.display = 'block';
        }
    }
}

function isIE() {
    const ua = window.navigator.userAgent; //Check the userAgent property of the window.navigator object
    const msie = ua.indexOf('MSIE '); // IE 10 or older
    const trident = ua.indexOf('Trident/'); //IE 11

    return (msie > 0 || trident > 0);
}

function AddRecaptchaArias() {
     (document.querySelectorAll('[name="g-recaptcha-response"]')).forEach(function (element) {
         element.setAttribute('aria-hidden', true);
         element.setAttribute('aria-label', 'g-recaptcha-response');
         element.setAttribute("aria-readonly", true);
    })
}

function AddWaitIfNeeded() {
    (document.querySelectorAll('[UseWaitScreen="true"]')).forEach(function (element) {
        element.onclick = function () { return waitifneeded(); };
    });
}