$(document).ready(function () {
    let inputs = $('[input]').toArray();

    $(window).click(function () {
        blur();
    });

    $.each(inputs, function (index, input) {
        $(input).click(function (event) {
            focus(input, index);
            event.stopPropagation();
        });

        isActive(input);
    });

    function isActive(input) {
        let textField = getTextField(input);
        let wrapper = getWrapper(input);
        if(textField.val().length > 0) {
            if (wrapper) {
                wrapper.addClass('active');
            }
        }
        textField.on('input', function() {
            if($(this).val().length > 0) {
                wrapper.addClass('active');
            } else {
                wrapper.removeClass('active');
            }
        })
    }

    /**
     * Focus current input and blur all the others in this page.
     * */
    function focus(input, index) {
        let textField = getTextField(input);
        if(textField) {
            textField.focus();
            let wrapper = getWrapper(input);
            if (wrapper) {
                wrapper.addClass('focused');
            }
        }
        blur(index);
    }

    /**
     * Blurs all inputs except of the given index;
     * */
    function blur(index = -1) {
        $.each(inputs, function (j, input) {
            let textField = getTextField(input);
            if(textField && index !== j) {
                textField.blur();
                let wrapper = getWrapper(input);
                if(wrapper) {
                    wrapper.removeClass('focused');
                }
            }
        });
    }
});

function getWrapper(input) {
    return  $(input).find('.input-wrapper');
}


/**
 *  Get the current textField
 *  Currently works for input and textarea
 * */
function getTextField(input) {
    let textField = $(input).find('input');
    if(!textField) {
        textField = $(input).find('textarea');
    }
    return textField;
}