var Contest = (function() {

    var _initForm = function() {
        bindCollectionsEvents();
        preSubmitActions();
    };

    var bindCollectionsEvents = function() {

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

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

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

            initCollapseEvents(element);
            initInlineEditableFields(element);
            bindQuestionItemsCollection(element);
            bindDisplayOptions(element);
        };

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

    };

    var bindQuestionItemsCollection = function(element) {

        var options = {
            'addElement' : '[data-add="questions-items"]',
            'deleteElement' : '[data-delete="questions-items"]',
            'context' : element,
            'prototypeFieldName' : '__NAME_OPTION__'
        };

        options[SimpleFormCollection.AFTER_ADD] = function(element) {
            initCheckbox(element);
            checkOption(element, this);
        };

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

        $('[data-collection="content-questions-items"]', element).SimpleFormCollection(options);
    };

    /**
     * Bind pre-submit actions.
     */
    var preSubmitActions = function(){
        $('form').on('submit', function(e) {

            var success = true;//validateFields();

            if (success) {
                $('[id$="position"][data-type="question-position"]', $(this)).each(function(k){
                    $(this).val(k+1);
                });
            }

            return success;
        });
    };

    var initCollapseEvents = function(element) {
        $(element).find('i[data-toggle="collapse"]').on("click", function(){
            $(this).parents(".item").toggleClass("portlet-sortable portlet-sortable-empty");
        });
    };

    var initInlineEditableFields = function(element) {
        $(element)
            .find('.groupname, .fieldname').editable({
                validate: function (value) {
                    if ($.trim(value) == '') {
                        return Translator.trans('cs_common_base.form.messages.errors.required');
                    }
                    else{
                        $('#'+$(this).data('for')).val(value);
                    }
                },
                mode: 'inline'
            })
            .on('click', function(){
                $('.editable-input :first-child').select().addClass('form-control');
            })
        ;
    };

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

    var initAssets = function(element) {
        AssetsHelper.initWidget(element);
    };

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

    var removeOption = function(element, collection) {

        var options = getOptionsByElement(element);

        if(options.length > 1) {
            collection.removeElement(element);
        } else {
            showToastrNotification('error', Translator.trans('contest.messages.error.questions_options_remove'));
        }
    };

    var checkOption = function(element, collection) {

        var container = $(element).parents('.item');
        var select = container.find('[data-action="display-options"]');
        var allowedOptionsStr = String(select.data("allowed-single-options"));
        var allowedOptions = allowedOptionsStr.split(",");

        if ($.inArray(select.val(), allowedOptions) !== -1) {

            var options = getOptionsByElement(element);

            //$(element).find('[id$="_correct"]').bootstrapSwitch("disabled",true);
            $(element).find('[id$="_correct"]').on('switchChange.bootstrapSwitch', function(event, state) {

                var _this = $(event.target);

                if (state === true) {
                    container.find('[id$="_correct"]').each(function(){

                        var _el = $(this);

                        if (_el.attr("id") !== _this.attr("id")) {
                            _el.bootstrapSwitch('state', false, true);
                        }
                    });
                }

                //console.log(this); // DOM element
                //console.log(event); // jQuery event
                //console.log(state); // true | false
            });

            //if(options.length > 1) {
            //    collection.removeElement(element);
            //    showToastrNotification('error', Translator.trans('contest.messages.error.questions_options_add'));
            //}
        }
    };

    var bindDisplayOptions = function(element) {
        var _this = $('[data-action="display-options"]', element);
        var allowedOptionsStr = String(_this.data("allowed-options"));
        var allowedOptions = allowedOptionsStr.split(",");
        var optionsContainer = $('.answers', element);

        _this.select2()
            .on("change", function(e) {
                if ($.inArray(e.val, allowedOptions) !== -1) {
                    optionsContainer.show();
                    optionsContainer.find('[data-type="option"]').remove();
                    $('[data-add="questions-items"]', element).trigger("click");
                } else {
                    optionsContainer.hide();
                    optionsContainer.find('[data-type="option"]').remove();
                }
            });
    };

    //var validateFields = function() {
    //    var success = true;
    //
    //    $('[data-collection="content-questions"]').find('[data-required]').each(function(){
    //        if ($(this).val() == '' && success === true) {
    //            showToastrNotification('error',Translator.trans('contest.messages.error.questions_form'));
    //            success = false;
    //        }
    //    });
    //
    //    return success;
    //};

    var getOptionsByElement = function(element) {
        return $(element).parent('[data-collection="content-questions-items"]').find('[data-type="option"]');
    };


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