(function(){
    var Massmailer = function() {

        return {

            init: function() {
                var editor_config = {
                    path_absolute : "/laravel-filemanager/",
                    selector: "textarea.tinyeditor",
                    plugins: [
                        "advlist autolink lists link image charmap print preview hr anchor pagebreak",
                        "searchreplace wordcount visualblocks visualchars code fullscreen",
                        "insertdatetime media nonbreaking save table contextmenu directionality",
                        "emoticons template paste textcolor colorpicker textpattern"
                    ],
                    toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image media",
                    relative_urls: false,
                    file_browser_callback : function(field_name, url, type, win) {
                        var x = window.innerWidth || document.documentElement.clientWidth || document.getElementsByTagName('body')[0].clientWidth;
                        var y = window.innerHeight|| document.documentElement.clientHeight|| document.getElementsByTagName('body')[0].clientHeight;

                        var cmsURL = editor_config.path_absolute + '?field_name=' + field_name;
                        if (type == 'image') {
                            cmsURL = cmsURL + "&type=Images";
                        } else {
                            cmsURL = cmsURL + "&type=Files";
                        }

                        tinyMCE.activeEditor.windowManager.open({
                            file : cmsURL,
                            title : 'Filemanager',
                            width : x * 0.8,
                            height : y * 0.8,
                            resizable : "yes",
                            close_previous : "no"
                        });
                    }
                };

                tinymce.init(editor_config);

                $('select#to').on('change', function(){
                    if( $(this).val() == '7' )
                        $('#specify-list-group').removeClass('hidden');
                    else
                        $('#specify-list-group').addClass('hidden');
                });

                $('a#stored-templates-load').on('click', function (e) {
                    e.preventDefault();

                    var value = $('#stored_templates').val();

                    $.ajax({
                        type: 'POST',
                        url: load_content_ajax_url,
                        data: {
                            id: value
                        },
                        success: function( data ) {
                            tinymce.activeEditor.setContent( data[0], {format : 'raw'} );
                        }
                    });
                });

                $("#user-tagging").select2({
                    tags: true,
                    minimumInputLength: 1,
                    tokenSeparators: [",", " "],
                    formatResult: function (item) { return item.username + ' (' + item.email + ')'; },
                    formatSelection: function (item) { return item.username + ' (' + item.email + ')'; },
                    multiple: true,
                    ajax: {
                        cache: true,
                        type: 'POST',
                        url: user_tagging_ajax_url,
                        dataType: "json",
                        data: function (term, page) { // page is the one-based page number tracked by Select2
                            return {
                                q: term, //search term
                                page_limit: 10, // page size
                                page: page, // page number
                            };
                        },
                        results: function (data, page) {
                            var more = (page * 10) < data.total; // whether or not there are more results available

                            // notice we return the value of more so Select2 knows if more results can be loaded
                            return { results: data.data, more: more };
                        }
                    }
                });

                $('#preview-modal').on('show.bs.modal', function (e) {
                    var content = tinymce.activeEditor.getContent();

                    if(content) {
                        $('#preview-modal .modal-body').empty();
                        $('#preview-modal .modal-body').append(content);
                    }
                })
            }
        };
    }();

    $(document).ready(function() {
        Massmailer.init();
    });
})();