var Wick = Wick || {};

Wick.ShoppingList = {
    bindAll : function () {
        Wick.ShoppingList.bindButtons();
    },

    bindButtons : function () {
        $('.btn-share-confirmation .btn-primary').on('click', function (e) {
            e.preventDefault();
            $('#share-via-email').prop('required', false);
            Wick.ShoppingList.submitSharingShoppingList();
        });
    },

    submitSharingShoppingList : function () {
        var forms = Wick.ShoppingList.getRecipientEmailsForms();

        if (Wick.ShoppingList.isFormsValid(forms)) {
            Wick.ShoppingList.onSuccessSharingShoppingList();
        }
    },

    onSuccessSharingShoppingList : function () {
        Wick.ShoppingList.resetFormErrors();
    },

    getRecipientEmailsForms : function () {
        var forms = new Array();

        forms.push($('#share-via-email'));
        $('.share-via-email-box').each(function () {
            forms.push($(this).find('[type="email"]'));
        });

        return forms;
    },

    isFormsValid : function (forms) {
        var oneFieldFilledIn = false;

        forms.forEach(function(form) {
            if ($(form).val() !== '') {
                oneFieldFilledIn = true;
            }
        });

        if (!oneFieldFilledIn) {
            Wick.ShoppingList.showEmptyFormsWarning(forms[0]);
            return false;
        }

        var isFormsValid = true;

        forms.forEach(function(form) {
            console.log(form[0]);
            if (!form[0].checkValidity()) {
                Wick.ShoppingList.showInvalidEmailWarning(form);
                isFormsValid = false;
            }
        });

        return isFormsValid;
    },

    showEmptyFormsWarning : function (form) {
        form.prop('required', true);

        try {
            form.get(0).reportValidity();
        } catch (e) {
            Wick.ShoppingList.resetFormErrors();

            form.closest('.form-row').addClass('form-row_validation-error');
            form.closest('.form-row__field').append('<div class="form-row__error">Please fill in the field</div>');
        }
    },

    showInvalidEmailWarning : function (form) {
        try {
            form.get(0).reportValidity();
        } catch (e) {
            Wick.ShoppingList.resetFormErrors();

            form.closest('.form-row').addClass('form-row_validation-error');
            form.closest('.form-row__field').append('<div class="form-row__error">Please fill in the field</div>');
        }
    },

    resetFormErrors: function () {
        $('#share-list-form .form-row').each(function() {
            $(this).removeClass('form-row_validation-error');
            $(this).find('.form-row__error').remove();
        });
    }
};



$(document).ready(function() {
    Wick.ShoppingList.bindAll();
});
