var Agency = (function() {

    var bindEvents = function() {
        bindCollectionsEvents();

        var submitHandler = FormValidation.prototype.submitHandler;

        FormValidation.prototype.submitHandler = function () {
            var isValid = validate();

            if (isValid) {
                submitHandler();
            }
        };

        return validate();
    };

    var bindCollectionsEvents = function() {

        var options = {
            'addElement' : '[data-add="collection"]',
            'deleteElement' : '[data-delete="collection"]'
        };

        options[SimpleFormCollection.AFTER_ADD] = function(element) {

            if (!$(element).data("persisted")) {
                initCheckBox(element);
                initSelect2(element);
            }

            popover(element);
            bindUrlCheck(element);
        };

        options[SimpleFormCollection.REMOVE] = function(element) {
            checkRemove(element, this);
        };

        $('[data-collection="collection"]').SimpleFormCollection(options);

    };

    /**
     * Remove group of collection callback.
     *
     * @param {jQuery} element
     * @param {SimpleFormCollection|MultiplePrototypeFormCollection}collection
     */
    var checkRemove = function (element, collection) {
        if($('[data-collection="collection"]').children().length > 1) {
            collection.removeElement(element);
        } else {
            showToastrNotification('error', Translator.trans('agency.form.errors.one_required'));
        }
    };

    var initCheckBox = function(element) {
        $(element).find(('input[type="checkbox"]')).each(function(){
            $(this).bootstrapSwitch();
        });
    };

    var initSelect2 = function(element) {
        $(element).find('select').each(function(){
            $(this).select2();
        });
    };

    var popover = function(element) {
        $(element).find('[data-toggle="popover"]').each(function(){
            $(this).popover({
                "trigger": "hover"
            });
        });
    };

    var bindUrlCheck = function(element) {
        $('[id $="_url"]', element).on("change", function(){
            var _this = $(this);
            var url = $(this).val();
            $.ajax({
                url: Routing.generate("admin_rss_validate_standard"),
                dataType: "json",
                method: "post",
                data: {
                    url: url
                },
                beforeSend: function() {
                    ComitiumUtils.showSpinner();
                },
                complete: function() {
                    ComitiumUtils.hideSpinner();
                },
                success: function(response) {
                    var message = "rss.messages.error.valid_rss";
                    var status  = "warning";

                    if (response.valid) {
                        message = "rss.messages.success.valid_rss";
                        status  = "success";
                        removeError(_this);
                    } else {
                        addUrlError(_this);
                    }

                    showToastrNotification(status, Translator.trans(message));
                }
            });
        });
    };

    var addUrlError = function(element){
        var container = element.parents(".form-group");
        container.addClass("has-error");
        element.data("is-valid", false);
    };

    var removeError = function(element){
        var container = element.parents(".form-group");
        container.removeClass("has-error");
        element.data("is-valid", true);
    };

    var validate = function() {

        var isValid = true;

        $('[id$="_url"]').each(function(){
            if ($(this).data("is-valid") == false) {
                isValid = false;
                addUrlError($(this));
                showToastrNotification('error', Translator.trans('agency.form.errors.invalid_rss'));
            }
        });

        return isValid;
    };

    return {
        initForm: function() {
            bindEvents();
        }
    };
})();
