var Pages = (function() {

    var bindFunction = function() {
        $('.cs_pages .entity-container').each(function(i,e) {
            var $tag = $(e);
            $('span.status', $tag).on('click', function() {
                var $el = $(this);
                var id = $el.parents('.entity-container:first').data('id');
                if(!$el.data('lock')) {
                    $el.data('lock', true);
                    var action = ('enabled' === $el.data('status')) ? 'disable' : 'enable';
                    $.ajax({
                        url: Routing.generate('pages_set_status', { id: id }),
                        method: 'POST',
                        data: { action: action },
                        complete: function() {
                            $el.data('lock', false);
                        },
                        success: function() {
                            $el
                                .data('status', (action == 'enable') ? 'enabled' : 'disabled')
                                .find('i')
                                .removeClass('fa-dot-circle-o fa-times')
                                .addClass((action == 'enable') ? 'fa-dot-circle-o' : 'fa-times');

                            showToastrNotification('success',Translator.trans( $el.data('status') == 'enabled' ? 'cs_pages.messages.enabled' : 'cs_pages.messages.disabled'));
                        }
                    });
                }
            });

            $('span.info', $tag).on('click', function() {
                var $el = $(this);
                var id = $el.parents('.entity-container:first').data('id');
                if(!$el.data('lock')) {
                    $el.data('lock', true);
                    var privacy = ('public' === $el.data('privacy')) ? 'private' : 'public';
                    $.ajax({
                        url: Routing.generate('pages_set_privacy', { id: id }),
                        method: 'POST',
                        data: { privacy: privacy },
                        complete: function() {
                            $el.data('lock', false);
                        },
                        success: function() {
                            $el
                                .data('privacy', privacy)
                                .find('i')
                                .removeClass('fa-circle-o fa-ban')
                                .addClass((privacy == 'public') ? 'fa-circle-o' : 'fa-ban');

                            showToastrNotification('success',Translator.trans( $el.data('privacy') == 'private' ? 'cs_pages.messages.private' : 'cs_pages.messages.public'));
                        }
                    });
                }
            });

            $('.checkboxes', $tag).uniform();
            $('.checkboxes', $tag).on('change', function() {
                if($('.cs_pages .checkboxes:checked').length) {
                    $('#page-action-menu button')
                        .attr('disabled', false);


                    if(false === Pages.validateDeletion()) {
                        $('#btn-delete')
                            .addClass('btn-disabled')
                            .attr('disabled', true);
                    } else {
                        $('#btn-delete')
                            .removeClass('btn-disabled')
                            .attr('disabled', false);
                    }

                } else {
                    $('#page-action-menu')
                        .removeClass('open')
                        .find('button')
                        .attr('disabled', true);
                }
            });

        });

        var list = $('#nestable_list_1');

        $('.dd3-item', list).each(function(i,e) {
            $(e).data('position', $(e).index());
        });

        var setParent = function(el, parentEl, callback) {
            var id = $(el).data('id');
            var parentId = $(parentEl).data('id');
            $.ajax({
                url: Routing.generate('pages_set_hierarchy_position', { id: id }),
                data: (function() {
                    var data = {
                        position: $(el).index()
                    };

                    if(parentId)
                        data.parent = parentId;

                    return data;

                })(),
                method: 'POST',
                complete: (typeof callback == 'function') ? callback : function() {}
            });
        };

        list.nestable({
            dropCallback: function(e) {
                var sources = $(e.sourceEl);
                var parent = $(e.destParent);

                setParent(sources, parent, function() {
                    $(e).data('position', $(e).index());
                });

                // Only its brothers
                $('> ol > .dd-item', parent).each(function(i,e) {

                    if($(e).data('position') !== $(e).index()) {
                        setParent(e, parent, function() {
                            $(e).data('position', $(e).index());
                        });
                    }

                });

            }});
    };

    var bindFormFunctions = function(formId) {
        var form = $('[name="' + formId + '"]');
        var templateField = $("#"+formId+"_template");
        var selector = '[data-action="choice-page-template"]';
        var redirectSelector = $("#"+formId+"_defaultLang_redirect");
        var redirectToSelector = $("#"+formId+"_defaultLang_redirectTo");


        form.find(selector).each(function(){

            $(this).on('click', function(e){
                e.preventDefault();

                var value = $(this).data('value');

                $(selector, form).removeClass("active");

                $(this).toggleClass('active');

                templateField.val(value);
            });
        });

        redirectSelector.on("click", function(){
            if (redirectToSelector.attr("required")) {
                redirectToSelector.attr("required", false);
            } else {
                redirectToSelector.attr("required", true);
            }
        });
    };

    return {
        init: function() {
            bindFunction();
        },
        initForm: function(formId, callBack) {
            bindFormFunctions(formId);

            if (typeof callBack === "function") {
                callBack.call(this);
            }
        },
        disableActionsButton: function() {
            $('#page-action-menu')
                .removeClass('open')
                .find('button')
                .attr('disabled', true)
            ;
        },
        enableActionsButton: function() {
            $('#page-action-menu')
                .removeClass('open')
                .find('button')
                .attr('disabled', false)
            ;
        },
        validateDeletion: function() {
            var selected = $('input:checked', $('#nestable_list_1')).toArray();

            for(index in selected) {
                var el = $(selected[index]).parents('.dd3-item:first');

                if(el.find('input').length !== el.find('input:checked').length) {
                    return false;
                }

            }

            return true;
        }
    };
})();

$(document).ready(function(){

    Pages.init();

    $('#btn-clone').on('click', function() {
        var data= (function() {
            return {
                ids: $('.cs_pages .checkboxes:checked').map(function(i, e) {
                    return $(e).parents('.entity-container').data('id');
                }).toArray()
            };
        })();

        var ids = data.ids;

        $.ajax({
            url: Routing.generate('pages_clone'),
            data: data,
            method: 'PUT',
            success: function() {

                showToastrNotification('success',
                    Translator.transChoice('cs_pages.messages.success_cloned', ids.length, { count: ids.length }));

                Pagination.paginate(
                    Routing.generate('pages_page'),
                    1,
                    $('.cs_pages .pagination-container')
                );
            }
        });
    });

    //$('#btn-publish').on('click', function() {
    //    var data= (function() {
    //        return {
    //            ids: $('.cs_pages .checkboxes:checked').map(function(i, e) {
    //                return $(e).parents('.entity-container').data('id');
    //            }).toArray()
    //        };
    //    })();
    //
    //    var ids = data.ids;
    //    $.ajax({
    //        url: Routing.generate('pages_publish'),
    //        data: data,
    //        method: 'POST',
    //        success: function() {
    //            showToastrNotification('success',
    //                Translator.transChoice('cs_pages.messages.success_published', ids.length, { count: ids.length }));
    //            Pagination.paginate(
    //                Routing.generate('pages_page'),
    //                1,
    //                $('.cs_pages .pagination-container')
    //            );
    //        }
    //    });
    //});
    //
    //$('#btn-unpublish').on('click', function() {
    //    var data= (function() {
    //        return {
    //            ids: $('.cs_pages .checkboxes:checked').map(function(i, e) {
    //                return $(e).parents('.entity-container').data('id');
    //            }).toArray()
    //        };
    //    })();
    //
    //    var ids = data.ids;
    //    $.ajax({
    //        url: Routing.generate('pages_unpublish'),
    //        data: data,
    //        method: 'POST',
    //        success: function() {
    //            Pages.disableActionsButton();
    //
    //            showToastrNotification('success',
    //                Translator.transChoice('cs_pages.messages.success_unpublished', ids.length, { count: ids.length }));
    //
    //            Pagination.paginate(
    //                Routing.generate('pages_page'),
    //                1,
    //                $('.cs_pages .pagination-container')
    //            );
    //        }
    //    });
    //});

    $('#btn-delete').on('click', function() {

        if(Pages.validateDeletion()) {
            var data= (function() {
                return {
                    ids: $('.cs_pages .checkboxes:checked').map(function(i, e) {
                        return $(e).parents('.entity-container').data('id');
                    }).toArray()
                };
            })();

            var ids = data.ids;
            $.ajax({
                url: Routing.generate('pages_multi_delete'),
                data: data,
                method: 'POST',
                success: function() {
                    showToastrNotification('success',
                        Translator.transChoice('cs_pages.messages.success_deleted', ids.length, { count: ids.length }));

                    Pagination.paginate(
                        Routing.generate('pages_page'),
                        1,
                        $('.cs_pages .pagination-container')
                    );
                }
            });
        }

    });

    Pagination.onChange.add(function() {
        Pages.init();
    });

});
