var Diaries = {

    init: function() {
        this.bindFunction();

        var self = this;

        Pagination.onChange.add(function() {
            self.initDomFunctions($('#diary-table-container'));
        });
    },
    bindFunction: function() {
        $(document).on('click', '[data-action="switch-diary"]',  function() {

            var node  = $(this).find('[type="checkbox"]');
            var id    = node.data('id');
            var state = Number(node.is(':checked'));

            $.ajax({
                url: Routing.generate(
                    'cs_cms_diaries_switch_enabled', {
                        id: id,
                        state: state
                    }, true)
                ,
                method: 'POST',
                success: function(response) {
                    if (response.updated) {
                        showToastrNotification('success',Translator.trans( state ? 'cms_diaries.diaries.messages.enabled_success' : 'cms_diaries.diaries.messages.disabled_success'));
                    }
                },
                error: function() {
                    showToastrNotification('error',Translator.trans('cms_diaries.diaries.messages.enabled_disabled_error'));
                }
            });
        });
    },
    initDomFunctions: function(element) {
        $(element).find('[type="checkbox"]').bootstrapSwitch();
    },
    initActivitySearch: function() {
        $('[data-advanced-search]').on('switchChange.bootstrapSwitch', function(event, state) {
            advancedSearch.trigger();
        });
    },
    bindFormActions: function() {

        var organizerSuggest = new CreateSuggest();
        var organizerSelector = $('[name="cms_activity[organizer]"]');

        organizerSuggest.setSelector(organizerSelector);
        organizerSuggest.init();
        organizerSuggest.signals.onLoad.addOnce(function(el, callback) {
            $('.organizer-create .select2-input').on('keyup', function(e) {
                var value = $(this).val();
                if(e.keyCode === KEY_ENTER && $.trim(value) !== "") {
                    el.select2("close");
                    addOrganizer(value, callback);
                }
            });
        });

        $('[data-toggle]').on('switchChange.bootstrapSwitch', function(event, state) {
            var id = $(this).data('toggle').split(',');

            for(var i = 0; id.length > i; i++) {
                var node = $(id[i]).parents('.form-group:first');

                if($(this).is(':checked')) {
                    var input = node.slideUp().find('input');

                    if (input.attr('id') !== 'cms_activity_price') {
                        input.attr('required', false);
                    }
                } else {
                    var input =  node.slideDown().find('input');

                    if (input.attr('id') !== 'cms_activity_price') {
                        input.attr('required', true);
                    }
                }
            }
        });

        $('[data-toggle]').trigger('switchChange.bootstrapSwitch');

        var timeOut;

        $('#cms_activity_dates_startAt').on('change', function() {
           if( $(this).val() !== '' && $('#cms_activity_publishDates_publishedAt').val() === '') {
               $('#cms_activity_publishDates_publishedAt').val($(this).val());
           }
        });


        $('#cms_activity_dates_endAt').on('change', function() {
            if(typeof timeOut !== 'undefined') {
                clearTimeout(timeOut);
            }

            if( $(this).val() !== '' && $('#cms_activity_publishDates_unPublishedAt').val() === '') {
                $('#cms_activity_publishDates_unPublishedAt').val($(this).val());
            }
            else if($(this).val() !== '' ) {
                var self = $(this);
                var expirationDateInput = $('#cms_activity_publishDates_unPublishedAt');
                timeOut = setTimeout(function() {
                    var expiresDate = expirationDateInput.val();
                    var endDate = self.val();

                    if( endDate !== expiresDate ) {
                        var title = Translator.trans('cms_diaries.activities.expiration_date_modal.title');
                        var message = Translator.trans('cms_diaries.activities.messages.expiration_date_info');
                        var button = Translator.trans('cms_diaries.activities.expiration_date_modal.accept');

                        var modal = bootstrap.createModal();
                        modal.struct = '<div data-backdrop="static"  data-keyboard="false" class="modal"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal"><span>&times;</span><span class="sr-only">Close</span></button><h4 class="modal-title"></h4></div><div class="modal-body"></div><div class="modal-footer"><button type="button" class="btn defaultBtn" data-dismiss="modal"></button><button type="button" class="btn mainBtn"></button></div></div></div></div>';
                        modal = modal.show(title, message, button);

                        modal.find('[data-btn-type="save"]').on("click", function () {
                            expirationDateInput.val(self.val());
                            modal.modal('hide');
                            modal.remove();
                        });

                        modal.find('[data-btn-type="cancel"]').on("click", function () {
                            modal.modal('hide');
                            modal.remove();
                        }).html(Translator.trans('cms_diaries.activities.expiration_date_modal.cancel'));
                    }

                }, 200);
            }

        });

        $('[data-create-organizer]').click(function() {
            var modal = bootstrap.createModal();
            var title = Translator.trans('cms_diaries.activities.organizer.add');
            var button = Translator.trans('cms_diaries.activities.organizer.modal.create');

            $.post( Routing.generate('cs_cms_diaries_activities_organizer_add'), {} , function(data) {
                modal = modal.show(title, data.html, button);
                modal.find('[data-btn-type="save"]').on("click", function () {
                    $.post(Routing.generate('cs_cms_diaries_activities_organizer_add'), modal.find('form:first').serialize(), function(data, textStatus, xhr) {
                        if(xhr.status === 200) {
                            modal.find('.modal-body').html(data.html);
                        }
                        else if(xhr.status === 201) {

                            $('[name="cms_activity[organizer]"]').select2("data",{id: data.id, text:data.text })

                            modal.modal('hide');
                            modal.remove();
                        }
                    });

                });
            });
        });

        var addOrganizer = function(name, callback) {

            $.ajax({
                url: Routing.generate('cs_cms_diaries_activities_organizer_add_auto'),
                method: "post",
                data: {
                    name: name
                },
                success: function(data) {
                    data.text = data.name;
                    $('[name="cms_activity[organizer]"]').select2('data', data);
                        //.append($('<option/>')
                        //    .attr('value', data.id)
                        //    .html(data.name))
                        //.val(data.id)
                        //.trigger('change');

                },
                error: function() {
                    showToastrNotification('error',Translator.trans('cms_diaries.diaries.messages.error_create_organizer'));
                }
            });
        };
    }
};
