(function($) {

    $(function() {
        
        // Create empty popup for filesystem items
        $('.filesystem-item').popover({html: true, content: '', placement: 'bottom', trigger: 'manual'});
        
        
        // Detect CTRL-click to handle selection
        $('body').on('click', '.filesystem-item', function(event) {
            var $this = $(this);
            if (event.ctrlKey) {
                $this.toggleClass('selected');
                $('body').trigger('filesystem.selectionchanged');                
                event.preventDefault();
            }
        });

        // Modal for single item delete
        // -----------------------------------------------------
        $('.js-filesystem-delete-modal')
            .modal({backdrop: true, keyboard: true, show: false})
            .on('hidden.bs.modal', function() {
                $('.js-delete-error').addClass('hide').text('');            
            });
        
        
        // Modal for single item rename
        // -----------------------------------------------------
        $('.js-filesystem-rename-modal')
            .modal({backdrop: true, keyboard: true, show: false})
            .on('hidden.bs.modal', function() {
                $('.js-filesystem-rename-modal input[type="text"]').val('');
                $('.js-rename-error').addClass('hide').text('');            
            })
            .on('shown.bs.modal', function() {
                $('.js-filesystem-rename-modal input[type="text"]')
                    .focus()
                    .on('keypress',function (event){
                        if (event.keyCode === 13){
                            $('.js-action-rename-ok').trigger('click');
                            event.preventDefault();
                        }                        
                    });
            });


        // User presses the confirm button on the rename dialog
        // -----------------------------------------------------
        $('.js-action-rename-ok').on('click', function() {   
            
            $('.js-action-rename-ok').find('i').prop('disabled', true);
            
            var item = $('#' + $('.js-filesystem-rename-modal').data('item-ref')),
                new_name = $('.js-filesystem-rename-modal input[type="text"]').val(),
                path = item.data('filesystem-rel-path');
            
            var xhr = $.post($('.js-filesystem-rename-modal').data('action-url'), {
                new_name : new_name,
                path : path
            }, null, 'json');

            xhr.fail(function() {
                $('.js-action-rename-ok').find('i').prop('disabled', false);
                $('.js-rename-error').removeClass('hide').text('Unkown error renaming file/folder');
            });
            
            xhr.done(function(data) {
               $('.js-action-rename-ok').find('i').prop('disabled', false);
               if (data.success) {                   
                   $('.js-filesystem-rename-modal').modal('hide');                   
                   var n_item = $(data.html);
                   n_item.popover({html: true, content: '', placement: 'bottom', trigger: 'manual'});
                   
                   if (item.hasClass('selected')) {
                       n_item.addClass('selected');
                   }
                
                
                   
                   item.replaceWith(n_item);          
                   
               } else {
                   $('.js-rename-error').removeClass('hide').text(data.error);
                   
               }
            });

        });
        
        // User presses the confirm button on the delete dialog
        // -----------------------------------------------------
        $('.js-action-delete-ok').on('click', function() {   
            
            $('.js-action-delete-ok').find('i').prop('disabled', true);
            
            var item = $('#' + $('.js-filesystem-delete-modal').data('item-ref')),
                path = item.data('filesystem-rel-path');
            
            var xhr = $.post($('.js-filesystem-delete-modal').data('action-url'), {
                path : path
            }, null, 'json');

            xhr.fail(function() {
                $('.js-action-delete-ok').find('i').prop('disabled', false);
                $('.js-delete-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) {
                   $('.js-filesystem-delete-modal').modal('hide');
                   item.fadeOut('slow', function() {
                       item.remove();
                       $('body').trigger('filesystem.selectionchanged');
                   });
               } else {
                   $('.js-delete-error').removeClass('hide').text(data.error);
               }
            });

        });

        // User presses on of  the action button for an item
        // -----------------------------------------------------
        $('body').on('click', 'button[data-filesystem-action]', function(e) {
            var $this = $(this),
                    action = $(this).attr('data-filesystem-action'),
                    item = $($(this).attr('data-filesystem-ref'));

            // Hide popover
            item.removeClass('highlight').popover('hide');

            if (action == 'select') {
                item.toggleClass('selected');
                $('body').trigger('filesystem.selectionchanged');

            } else if (action == 'delete') {
                var delete_modal = $('.js-filesystem-delete-modal');
                delete_modal.find('.js-filesystem-item-name').text(item.find('.filesystem-filename').text());
                delete_modal.data('item-ref', item.attr('id'));
                delete_modal.modal('show');

            } else if (action == 'rename') {
                var rename_modal = $('.js-filesystem-rename-modal');
                rename_modal.find('.js-filesystem-item-name').text(item.find('.filesystem-filename').text());
                rename_modal.find('input[type="text"]').val(item.find('.filesystem-filename').text());
                rename_modal.data('item-ref', item.attr('id'));
                rename_modal.modal('show');
            }


            e.preventDefault();
        });

        
        // User right clicks on an item
        // -----------------------------------------------------
        $('.folder-item-container').on('contextmenu', '.filesystem-item', function(e) {

            var $this = $(this),
                    popover = $this.data('bs.popover'),
                    tip = popover.tip(),
                    visible = popover && tip && tip.is(':visible');

            if (visible) {
                $(this).removeClass('highlight');
                popover.hide();
                
            } else {
                
                $('.filesystem-item').not($this)
                    .removeClass('highlight')
                    .popover('hide');

                $this.addClass('highlight');
                
                var data = $('.js-filesystem-action-popover').clone();

                // Set reference to the corresponding filesystem item. DONT USE data()
                // function, becouse item is copied as html, and data, event handlers, etc are lost
                data.find('button[data-filesystem-action]').attr('data-filesystem-ref', '#' + $this.attr('id'));

                if ($this.data('filesystem-editable') == 0) {
                    data.find('button[data-filesystem-action="rename"]').prop('disabled', true);
                    data.find('button[data-filesystem-action="edit"]').prop('disabled', true);
                }

                if ($this.data('filesystem-deletable') == 0) {
                    data.find('button[data-filesystem-action="delete"]').prop('disabled', true);
                }

                popover.options.content = data.html();
                popover.show();
            }

            e.preventDefault();
        });

    });

})(jQuery);