var Roles = (function () {
    var bindFunction = function(){

        window.options = [];
        var error = $('.alert-danger', FormEditValidation.form);
        var success = $('.alert-success', FormEditValidation.form);
        $("[name=comitiumsuite_bundle_cscommon_csuserbundle_csrole]").validate({
            onfocusout: false,
            doNotHideMessage: true, //this option enables to show the error/success messages on tab switch.
            errorElement: 'span', //default input error message container
            errorClass: 'help-block help-block-error', // default input error message class
            focusInvalid: false, // do not focus the last invalid input
            errorPlacement: function (error, element) { // render error placement for each input type
                if (element.attr("name") == "gender") { // for uniform radio buttons, insert the after the given container
                    error.insertAfter("#form_gender_error");
                } else if (element.attr("name") == "payment[]") { // for uniform radio buttons, insert the after the given container
                    error.insertAfter("#form_payment_error");
                } else {
                    error.insertAfter(element); // for other inputs, just perform default behavior
                }
            },

            invalidHandler: function (event, validator) { //display error alert on form submit
                success.hide();
                error.show();
                Metronic.scrollTo(error, -200);
            },

            highlight: function (element) { // hightlight error inputs
                $(element)
                    .closest('.form-group').removeClass('has-success').addClass('has-error'); // set error class to the control group
            },

            unhighlight: function (element) { // revert the change done by hightlight
                $(element)
                    .closest('.form-group').removeClass('has-error'); // set error class to the control group
            },

            success: function (label) {
                if (label.attr("for") == "gender" || label.attr("for") == "payment[]") { // for checkboxes and radio buttons, no need to show OK icon
                    label
                        .closest('.form-group').removeClass('has-error').addClass('has-success');
                    label.remove(); // remove error label here
                } else { // display success icon for other inputs
                    label
                        .addClass('valid') // mark the current input as valid and display OK icon
                        .closest('.form-group').removeClass('has-error').addClass('has-success'); // set success class to the control group
                }
            }
        });

        $("body")
            .on("click", "tbody tr.warning td a span.fa", function (e) {
                e.preventDefault();

                var element = $(this);
                var event = 'slideUp';

                if (element.hasClass('fa-minus-square-o')) {
                    element.removeClass('fa-minus-square-o');
                    element.addClass("fa-plus-square-o");
                } else if (element.hasClass("fa-plus-square-o")) {
                    event = 'slideDown';
                    element.addClass('fa-minus-square-o');
                    element.removeClass("fa-plus-square-o");
                }

                element.closest('tbody').next()[event]("slow");
            })
        ;

        $("input[id$='_all'], input[id$='permissions_all']").on('switchChange.bootstrapSwitch', function (event, state) {
            $(this).closest("tr").find("td:not(:last-child) input").bootstrapSwitch('state', state);
            if ($(this).attr("id").indexOf("permissions_all") > -1) {
                var current_td = $(this).closest("td");
                var col = current_td.parent().children().index(current_td);
                var current_tbody = $(this).closest("tbody");
                setCheckboxesStatus(current_tbody, state, col);
            }
        });

        $("input[id$='_read'], input[id$='_new'], input[id$='_update'], input[id$='_delete']").on('switchChange.bootstrapSwitch', function (event, state) {
            var current_tr = $(this).closest("tr");
            var current_td = $(this).closest("td");
            var col = current_td.parent().children().index(current_td);
            var view_all_select = current_tr.find("td:last-child input");
            var final_state = current_tr.find("td:not(:last-child) input").bootstrapSwitch('state');
            var current_tbody = $(this).closest("tbody");

            view_all_select.bootstrapSwitch("state", final_state, true);

            if ($(this).attr("id").indexOf("permissions") == -1) {
                findPreviousModuleTr(current_tbody, true, col);
            } else {
                setCheckboxesStatus(current_tbody, state, col);
            }

        });

        $("table > tbody").each(function (k, v) {

            if (!$(v).find(".warning").length) {
                for (var i = 1; i <= 4; i++) {
                    findPreviousModuleTr($(v), false, i);
                }
            }
        });
    };

    var setCheckboxesStatus = function(tbody, state, column) {

        tbody.next().children().each(function (k, v) {
            $(v).children().eq(column).find("input").bootstrapSwitch('state', state);
        });
    };

    var findPreviousModuleTr = function(tbody, exec, column) {

        var final_state = true;
        tbody.children().each(function (k, v) {
            var current_state = $(v).children().eq(column).find("input").bootstrapSwitch('state');
            if (current_state == false) {
                final_state = false;
            }
        });

        var current_tr = tbody.prev().find("tr");
        var view_all_select = current_tr.find("td:last-child input");
        current_tr.children().eq(column).find("input").bootstrapSwitch('state', final_state, true);
        var check_all_state = current_tr.find("td:not(:last-child) input").bootstrapSwitch('state');
        view_all_select.bootstrapSwitch("state", check_all_state, exec);
    };

    return {
        init: function() {
            bindFunction();
        },
        paginationInit: function(){
            var paginator = createPagination($);
            paginator.setUrl(Routing.generate('cs_common_cs_user_profile_page'));
            paginator.setDomSelector('.profiles_content ul.pagination li a');
            paginator.init();
        }
    };
})();
