(function($) {

    Dropzone.autoDiscover = false;

    $(function() {
        
        // Create Dropzone for file uplload
        // -----------------------------------------------------
        var dropzone = $('#filesystem_dropzone');
        var filesystemDropzone = new Dropzone('#filesystem_dropzone', {
            dictDefaultMessage : dropzone.data('dropzone-default-message'),
            dictFallbackMessage : dropzone.data('dropzone-fallback-message'),
            dictInvalidFileType : dropzone.data('dropzone-invalid-file-type-message'),
            dictFileTooBig : dropzone.data('dropzone-file-to-big-message'),
            dictResponseError : dropzone.data('dropzone-response-error-message'),
            dictCancelUpload : dropzone.data('dropzone-cancel-upload-message'),
            uploadMultiple : false,
            forceFallback : false, // Set this to true to test "old style"
            init: function() {
                this.on("success", function(file, response) {
                    
                    try {
                        var data = $.parseJSON(response);
                        if (data === null) {
                            alert('Unkown error uploading file');
                            return;
                        }
                    } catch(e) {
                        alert('Unkown error uploading file');
                        return;
                    }
                    
                    if (data.success !== true) {
                        filesystemDropzone.removeFile(file);
                        alert(data.message);
                        return;
                    }
                    
                    var item = $(data.html);
                    item.hide();
                    item.popover({html: true, content: '', placement: 'bottom', trigger: 'manual'});
                    $('.folder-item-container').prepend(item);
                    item.delay(250).fadeIn('slow');
                    item.addClass('selected');
                    $('body').trigger('filesystem.selectionchanged');
                    
                });
            }
        });
        
        // Add Folder Modal
        // -----------------------------------------------------
        $('.js-filesystem-add-folder-modal')
            .modal({backdrop: true, keyboard: true, show: false})            
            .on('hidden.bs.modal', function() {
                $('.js-filesystem-add-folder-modal input[type="text"]').val('');
                $('.js-add-folder-error').addClass('hide').text('');            
            })            
            .on('shown.bs.modal', function() {
                $('.js-filesystem-add-folder-modal input[type="text"]')
                    .focus()
                    .on('keypress',function (event){
                        if (event.keyCode === 13){
                            $('.js-action-add-folder-ok').trigger('click');
                            event.preventDefault();
                        }                        
                    });
            });
        
        // Upload File Modal
        // -----------------------------------------------------
        $('.js-filesystem-upload-modal')
            .modal({backdrop: true, keyboard: true, show: false})
            .on('hidden.bs.modal', function() {
                filesystemDropzone.removeAllFiles();
            });
            
            
        // Modal for selection item delete
        // -----------------------------------------------------
        $('.js-filesystem-delete-selection-modal')
            .modal({backdrop: true, keyboard: true, show: false})
            .on('hidden.bs.modal', function() {
                $('.js-filesystem-delete-selection-modal .modal-footer').removeClass('hide');
                $('.js-delete-selection-busy').addClass('hide');
                $('.js-delete-selection-error').addClass('hide').text('');            
            });
        

        // User clicks on add folder button
        // -----------------------------------------------------
        $('.js-filesystem-add-folder').on('click', function() {               
            var add_folder_modal = $('.js-filesystem-add-folder-modal');
            add_folder_modal.find('input[type="text"]').val('');
            add_folder_modal.modal('show');
        });
        
        // User clicks on upload button
        // -----------------------------------------------------
        $('.js-filesystem-upload').on('click', function() {               
            var upload_modal = $('.js-filesystem-upload-modal');
            upload_modal.modal('show');
        });
        
        // User clicks on delete selection button
        // -----------------------------------------------------
        $('.js-filesystem-delete-selected').on('click', function() {               
            var delete_sel_modal = $('.js-filesystem-delete-selection-modal');
            delete_sel_modal.modal('show');
        });
        
        // User clicks insert multiple item insert
        $('.js-filesystem-insert-selected').on('click', function() {
            var $this = $(this),
                callback = $this.attr('data-callback'),
                extra_args = $.parseJSON($this.attr('data-extra-args')),
                files = [];
                
            $('.filesystem-item.selected').each(function() {
                files.push($(this).attr('data-filesystem-webpath'));
            });
            
            window.opener[callback](files,extra_args);
            window.close();
        });
        
        // User clicks on add folder confirm button
        // -----------------------------------------------------
        $('.js-action-add-folder-ok').on('click', function() {   
            
            $('.js-action-add-folder-ok').find('i').prop('disabled', true);
            
            var new_name = $('.js-filesystem-add-folder-modal input[type="text"]').val();
            
            var xhr = $.post($('.js-filesystem-add-folder-modal').data('action-url'), {
                new_name : new_name
            }, null, 'json');

            xhr.fail(function() {
                $('.js-action-add-folder-ok').find('i').prop('disabled', false);
                $('.js-add-folder-error').removeClass('hide').text('Unkown error adding folder');
            });
            
            xhr.done(function(data) {
               $('.js-action-add-folder-ok').find('i').prop('disabled', false);
               if (data.success) {
                   
                   $('.js-filesystem-add-folder-modal').modal('hide');
                   var item = $(data.html);
                   item.hide();
                   
                   item.popover({html: true, content: '', placement: 'bottom', trigger: 'manual'});
                   $('.folder-item-container').prepend(item);
                   item.delay(250).fadeIn('slow');
                   
               } else {
                   $('.js-add-folder-error').removeClass('hide').text(data.error);
               }
            });

        });
        
        // User presses the confirm button on the delete selection dialog
        // -----------------------------------------------------
        $('.js-action-delete-selection-ok').on('click', function() {   

            $('.js-delete-selection-busy').removeClass('hide');
            $('.js-filesystem-delete-selection-modal .modal-footer').addClass('hide');

            $('.filesystem-item.selected').each(function() {
                
                var item = $(this),
                    path = item.data('filesystem-rel-path');
                    
                    
                var xhr = $.post(
                    $('.js-filesystem-delete-selection-modal').data('action-url'), 
                    { path : path }, 
                    null, 
                    'json'
                );
        
                xhr.fail(function() {
                    $('.js-delete-selection-error').removeClass('hide').text('Unkown error deleting file/folder');
                });
                
                xhr.done(function(data) {
                    $('.js-action-delete-ok').find('i').prop('disabled', false);
                    if (data.success) {                        
                        item.fadeOut('slow', function() {
                            item.remove();
                            $('body').trigger('filesystem.selectionchanged');
                            if ($('.filesystem-item.selected').length == 0) {
                                $('.js-filesystem-delete-selection-modal').modal('hide');
                            }                            
                        });
                    } else {
                        $('.js-delete-selection-error').removeClass('hide').text(data.error);
                    }
                });
            
            
            });

        });
        
        // Selection has changed
        // -----------------------------------------------------
        $('body').on('filesystem.selectionchanged', function() {

            // Some actions are only available on files
            if ($('.filesystem-folder.selected').length > 0) {
                $('.js-has-only-file-selection').addClass('hide');
            } else {
                $('.js-has-only-file-selection').removeClass('hide');
            }
            
            // Only show selection actions if there is something selected
            if ($('.filesystem-item.selected').length > 0) {
                $('.js-has-selection').removeClass('hide');
            } else {
                $('.js-has-selection').addClass('hide');
            }
            
        });

    });

})(jQuery);