/*
*
 * LIFESTYLE SSO-WEB-SP / Navigation
 * Author: LifeStyle Webconsulting GmbH, Sebastian Gronauer, www.life-style.de
*/

var formevents = function() {

    var form,
        inputFields,
        submitButton,
        submitIcon,
        isGoogleChromeBrowser = /chrom(e|ium)/.test(navigator.userAgent.toLowerCase());

    function isFieldEmpty(inputField)
    {
        var inputEmpty = 0 === inputField.val().length,
            googleChromeAutofill = inputField.css("backgroundColor") === "rgb(250, 255, 189)";
        return inputEmpty && !googleChromeAutofill;
    }

    function formIsValid()
    {
        if (form.data("bootstrapValidator").isValid()) {
            return true;
        }

        // Validate manually for google chrome autofill @see http://stackoverflow.com/a/35783761/6067705
        if (isGoogleChromeBrowser) {
            if (form.hasClass("form-mfa-js")) {
                return !isFieldEmpty($("#mfa_token"));
            }
            if (form.hasClass("form-login-js")) {
                return !isFieldEmpty($("#username")) && !isFieldEmpty($("#password"));
            }
        }

        return false;
    }

    function disableSubmitButton()
    {
        submitButton.attr("disabled", "disabled");
        submitIcon.removeClass("icon-unlock");
        submitIcon.addClass("icon-lock");
    }

    function enableSubmitButton()
    {
        submitButton.removeAttr("disabled");
        submitIcon.removeClass("icon-lock");
        submitIcon.addClass("icon-unlock");
    }

    function setSubmitButton()
    {
        if(form.length !== 0) {
            if (formIsValid()) {
                enableSubmitButton();
            } else {
                disableSubmitButton();
            }
        }
    }

    function initForm()
    {
        if (window.loginForm === undefined) {
            window.setTimeout(initForm.bind(this), 250);
            return;
        }

        /* Receive login form from global scope */
        form = window.loginForm;
        inputFields = form.find('input[type="text"]').add(form.find('input[type="password"]'));
        submitButton = form.find("button.btn-submit-js");
        submitIcon = submitButton.find(".icons");

        inputFields.on("keyup select focus blur change", setSubmitButton);
        submitButton.on("click", disableSubmitButton);

        /** Detect browser autofill - set input field style */
        var timer = window.setInterval(setSubmitButton, 100);
        window.setTimeout(function() {
            window.clearTimeout(timer);
        }, 1500);
    }

    function init() {
        if ($("#login").length > 0) {
            initForm();
        }
    }

    return {
        init: init
    };
}();

module.exports = formevents;
