var fb = function($var){if(typeof console!='undefined')console.log($var); else alert($var)};

/**
 * JavaScript bootstrapper
 * 
 */
$(document).ready(function() {

    App.Navigation.init();
    App.TypeAhead.init();
    App.Message.init();
    App.DateTimePicker.init();
    App.FlashMessenger.init(); 
    
    $("#user_menu").click( function() {
    	
    	if ( $("#user_menu_nav").is( ':hidden' ) ) {
    		$("#user_menu_nav").slideDown();
    	} else {
    		$("#user_menu_nav").slideUp();
    	}
    });
    
});

/**
 * Application namespace
 */
var App = {};


/**
 * Application FlashMessenger
 * @author ???
 */
App.FlashMessenger = {

    /**
     * Add close action to the FlashMessenger
     * @author ???
     */
    init: function() {
        
        $(".flashMessangerClose").click(function () { 
        
            $(this).parent().hide('slow', function() {

                $(this).remove();
            }); 
        });
    }
};


/**
 * Application ExtJS
 * @author Andreas Linden <al@i22.de>
 */
App.Ext = {

    /**
     * Initialize the Ext state manager
     * @author Andreas Linden <al@i22.de>
     */
    enableStatefulBehaviour: function() {

        Ext.state.Manager.setProvider(new Ext.state.CookieProvider({

            expires: new Date(new Date().getTime() + (1000*60*60*24*30)) // valid for 30 days
        }));
    }
};


/**
 * Main navigation handling
 * @author Andreas Linden <al@i22.de>
 */
App.Navigation = {

    init: function() {

        $('ul.nav li').hover(function() {
    
            $(this).css('background-color', '#e20074');
            
        }, function() {
    
            $(this).css('background-color', 'transparent');
        
        }).click(function() {

            window.location = $(this).find('a').attr('href');
        });
    }
};


/**
 * Ajax-load indicator
 * @author ???
 */
App.Message = {

     set: function(message) {
         $("#appMessage").text(message);
     },

     init: function() {

         $appMessage = $("#appMessage");
         $appMessage.ajaxStart(function() {
             $(this).show();
         });

         $appMessage.ajaxStop(function() {
             $(this).hide();
         });
     }
 };


/**
 * Type ahead function for search field in layout
 * @author Andreas Linden <al@i22.de>
 */
App.TypeAhead = {

    timeout: null,
    $source: null,
    
    /**
     * Add required events
     * @author Andreas Linden <al@i22.de>
     */
    init: function() {

        $('#textsearch .query')
            .keypress(App.TypeAhead.keypress)
            .focus(App.TypeAhead.focus);
    },
    
    /**
     * When hovering a suggested item
     * @author Andreas Linden <al@i22.de>
     */
    mouseover: function() {

        $('#typeahead .list .item').removeClass('active');
        $(this).addClass('active');
    },
    
    /**
     * When typing in the search field
     * @param {Object} $event
     * @author Andreas Linden <al@i22.de>
     */
    keypress: function($event) {

        var $typeahead = $('#typeahead');
        
        var $selectedItem = null;
        if ($typeahead.is(':visible')) {

            $('.item', $typeahead).each(function() {

                if ($(this).hasClass('active')) {
    
                   $selectedItem = $(this);
                }
            });
             
             if ($event.keyCode == 13) {

                window.location.href = $('#typeahead .item.active').attr('rel');
                return false;

             } else if ($event.keyCode == 38) {
                
                if (!$selectedItem) {

                    $selectedItem = $('.item:last', $typeahead);
                    
                } else {
    
                    if (!$selectedItem.prev().length) {
                        
                        $selectedItem = $selectedItem.parent().parent().prev().find('.item:last');
                    
                    } else {
                    
                       $selectedItem = $selectedItem.prev();
                    }
                }
                
                $('.item', $typeahead).removeClass('active');
                $selectedItem.addClass('active');
                return;
    
            } else if ($event.keyCode == 40) {
    
                if (!$selectedItem) {

                    $selectedItem = $('.item:first', $typeahead);
                    
                } else {
    
                    if (!$selectedItem.next().length) {
                        
                        $selectedItem = $selectedItem.parent().parent().next().find('.item:first');
                    
                    } else {
                    
                       $selectedItem = $selectedItem.next();
                    }
                }
                
                $('.item', $typeahead).removeClass('active');
                $selectedItem.addClass('active');
                return;
                
            } else {

                // $typeahead.slideUp();
            }
        }
        
        App.TypeAhead.$source = $(this);
        if (App.TypeAhead.timeout) {

            clearTimeout(App.TypeAhead.timeout);
        }
        
        App.TypeAhead.timeout = window.setTimeout(App.TypeAhead.trigger, 500);
    },
    
    /**
     * Trigger the ajax request to fetch matching items
     * @author Andreas Linden <al@i22.de>
     */
    trigger: function() {

        var query = App.TypeAhead.$source.val();
        
        if (query.length < 3) return;
        
        $.ajax({
            type: 'post',
            dataType: 'json',
            url: '/default/search/typeahead/',
            data: 'query='+ query,
            success: App.TypeAhead.callback
        });
    },
    
    /**
     * Receives the matched data and assigns it to the dom
     * @param {Object} result
     * @author Andreas Linden <al@i22.de>
     */
    callback: function(result) {

        if (!(result.events.length || result.users.length)) {

            return;
        }
        
        var $typeahead = $('#typeahead');
        
        App.TypeAhead.$source.blur(App.TypeAhead.blur);
        
        $typeahead.find('.users .list').empty().end().find('.events .list').empty().end();
        
        for (n in result.events) {

            if ( result.events[n].id ) {

                var $item = $('<div class="item event" rel="/event/view/id/'+ result.events[n].id +'"><div class="title">'+ result.events[n].name +'</div></div>');
                $item.click(App.TypeAhead.goto);
                $typeahead.find('.events .list').append($item).end();
            }
        }
        
        for (n in result.users) {

            if ( result.users[n].id ) {

                var $item = $('<div class="item user" rel="/profile/view/id/'+ result.users[n].id +'">'+ result.users[n].firstname +' '+ result.users[n].lastname +' &lt;'+ result.users[n].email +'&gt;</div>');
                $item.click(App.TypeAhead.goto);
                $typeahead.find('.users .list').append($item).end();
           }
        }
        
        if (!result.events.length) {

            $typeahead.find('.events').hide().end();
            
        } else {

            $typeahead.find('.events').show().end();
        }
        
        if (!result.users.length) {

            $typeahead.find('.users').hide().end();
            
        } else {

            $typeahead.find('.users').show().end();
        }
        
        $typeahead.slideDown();
        
        $('.list .item', $typeahead).mouseover(App.TypeAhead.mouseover);
    },
    
    /**
     * Goto HREF
     * @author Andreas Linden <al@i22.de>
     */
    goto: function() {

        window.location.href = $(this).attr('rel');
    },
    
    /**
     * When focussing the search field
     * @author Andreas Linden <al@i22.de> 
     */
    focus: function() {

        if (App.TypeAhead.timeout) {

            clearTimeout(App.TypeAhead.timeout);
        }
    },
    
    /**
     * When leaving the search field
     * @author Andreas Linden <al@i22.de>
     */
    blur: function() {

        App.TypeAhead.timeout = window.setTimeout(App.TypeAhead.hide, 1000);
    },
    
    /**
     * Hide the suggest list
     * @author Andreas Linden <al@i22.de>
     */
    hide: function() {

        $('#textsearch .query').val('');
        
        $('#typeahead').slideUp('medium', function() {
            
            $(this).find('.users .list').empty().end().find('.events .list').empty().end();
        });
    }
};


/**
 * Datepicker for event-editing
 * @author Andreas Linden <al@i22.de>
 */
App.DateTimePicker = {

    /**
     * Datepicker for event-editing
     * @author Andreas Linden <al@i22.de>
     */
    init: function() {

        $('input.time_hours, input.time_minutes').keyup(App.DateTimePicker.filterTime);
    },

    filterTime: function() {

        $(this).val($(this).val().replace(/[^\d]/, ''));
        if ($(this).val().length == 2 && $(this).is('.time_hours')) {

            $(this).parent().find('input.time_minutes').focus();
            
        } else {

            $(this).val($(this).val().substr(0,2));
        }
    },

    onSelect: function() {

        $(this).parent().find('.time_hours').focus().val('');
    }
}


/**
 * Event FileManager
 * 
 * @author Andreas Linden <al@i22.de>
 * @version 0.1
 * @uses ExtJS
 * @uses jQuery
 */
App.FileManager = {

    /**
     * View config for Ext grid
     */
    gridViewConfig: {
        forceFit: false,
        enableRowBody: true,
        headersDisabled: false,
        sortAscText: 'Aufsteigend sortieren',
        sortDescText: 'Absteigend sortieren',
        columnsText: 'Anzuzeigende Spalten'
    },
    
    /**
     * Initialize
     * 
     * @param {integer} eventId
     * @author Andreas Linden <al@i22.de>
     */
    init: function(newsId) {

        App.Ext.enableStatefulBehaviour();
        
        this.uploader        = this.createUploader(newsId);
        this.dataProxy       = this.createDataProxy(newsId);
        this.dataReader      = this.createDataReader();
        this.dataWriter      = this.createDataWriter();
        this.dataStore       = this.createDataStore();
        this.columnModel     = this.createColumnModel();
        this.loadMask        = this.createLoadMask();
        this.pagingToolbar   = this.createPaginator();
        this.grid            = this.createGrid();
        
        //Ext.EventManager.onWindowResize(this.windowResize);
        this.dataStore.load();
        this.grid.render();
    },
    
    
    /**
     * Create the AjaxUplaoder
     * @param {Integer} eventId
     * @return {AjaxUplaoder}
     * @author Andreas Linden <al@i22.de>
     */
    createUploader: function(newsId) {

        return new AjaxUpload('upload_button', {
            name: 'news',
            action: '/admin/news/upload/id/'+ newsId +'/',
            autoSubmit: false,
            responseType: 'json',
            onChange: this.onUploadChange,
            onSubmit: this.onUploadSubmit,
            onComplete: this.onUploadComplete
        });
    },
    
    /**
     * Create the data proxy
     * @param {Integer} eventId
     * @return {Ext.data.HttpProxy}
     * @author Andreas Linden <al@i22.de>
     */
    createDataProxy: function(newsId) {
    
       return new Ext.data.HttpProxy({
            method: 'POST',
            api: {
                read : basepath + 'admin/news/files/id/'+ newsId,
                update: basepath + 'admin/news/updatefile'
            }
        });
    },
    
    /**
     * Create the data reader
     * @return {Ext.data.JsonReader}
     * @author Andreas Linden <al@i22.de>
     */
    createDataReader: function() {

        return new Ext.data.JsonReader({
            root: 'images',
            totalProperty: 'totalCount',
            id: 'id'
        }, [
            {name: 'id'},
            {name: 'filename'},
            {name: 'description'},
        ]);
    },
    
    /**
     * Create the data writer
     * @return {Ext.data.JsonWriter}
     * @author Andreas Linden <al@i22.de>
     */
    createDataWriter: function() {
    
       return new Ext.data.JsonWriter({
            returnJson: true,
            writeAllFields: false
        });
    },
    
    /**
     * Create the data store
     * @return {Ext.data.Store}
     * @author Andreas Linden <al@i22.de>
     */
    createDataStore: function() {

        return new Ext.data.Store({
            proxy: this.dataProxy,
            reader: this.dataReader,
            writer: this.dataWriter,
            autoLoad: false,
            remoteSort: false
        });
    },
    
    /**
     * Create the grid
     * @return {Ext.grid.EditorGridPanel}
     * @author Andreas Linden <al@i22.de>
     */
    createGrid: function()  {

        return new Ext.grid.EditorGridPanel({
            el:'grid',
            stateful: true,
            stateId: 'App.FileManager.grid',
            height: 410,
            width: 640,
            clicksToEdit: 1,
            trackMouseOver:true,
            enableCtxMenu: false,
            enableColumnMove: false,
            store: this.dataStore,
            loadMask: this.loadMask,
            cm: this.columnModel,
            bbar: this.pagingToolbar,
            viewConfig: this.gridViewConfig,
            listeners: {    
                rowcontextmenu: this.rowContextListener,
                rowdblclick: this.offerDownload
            }
        });
    },
    
    /**
     * Create the column model for the grid
     * @return {Ext.grid.ColumnModel}
     * @author Andreas Linden <al@i22.de>
     */
    createColumnModel: function() {

        return new Ext.grid.ColumnModel([{
                header: 'ID',
                dataIndex: 'id',
                width: 30,
                sortable: true
            },{
                header: 'Dateiname',
                dataIndex: 'filename',
                width: 300,
                sortable: true
            },{
                header: 'Beschreibung',
                dataIndex: 'description',
                width: 300,
                sortable: true,
                editor: new Ext.form.TextField()
        }]);
    },
    
    /**
     * Create the load mask for the grid
     * @return {Ext.LoadMask}
     * @author Andreas Linden <al@i22.de>
     */
    createLoadMask: function() {

        return new Ext.LoadMask(Ext.get('grid'), {

            msg: "Dateien werden geladen"
        });
    },
    
    /**
     * Create the "show current items"-button for the grid
     * @return {Ext.Button}
     * @author Andreas Linden <al@i22.de>
     */
    createCurrentButton: function() {

        return new Ext.Button({
            text: 'Aktuelle Dateien anzeigen',
            handler: function() {
                this.hide();
                App.FileManager.dataStore.load({
                    params: {
                        deleted: 0
                    },
                    callback: function() {
                        App.FileManager.showDeleted.show();
                    }
                });
            }
        });
    },
    
    /**
     * Create the "show deleted items"-button for the grid
     * @return {Ext.Button}
     * @author Andreas Linden <al@i22.de>
     */
    createDeletedButton: function() {

        return new Ext.Button({
            text: 'Gelöschte Dateien anzeigen',
            handler: function(a, b) {
                this.hide();
                App.FileManager.dataStore.load({
                    params: {
                        deleted: 1
                    },
                    callback: function() {
                        App.FileManager.showCurrent.show();
                    }
                });
            }
        });
    },
    
    /**
     * Create the paging toolbar for the grid
     * @return {Ext.PagingToolbar}
     * @author Andreas Linden <al@i22.de>
     */
    createPaginator: function() {
    
       return new Ext.PagingToolbar({

            pageSize: 15,
            store: this.dataStore,
            displayInfo: true,
            displayMsg: 'Datei {0} - {1} von {2}',
            refreshText: 'Aktualisieren',
            prevText: 'Vorherige Seite',
            nextText: 'Nächste Seite',
            emptyMsg: "Keine Dateien gefunden",
            beforePageText: "Seite",
            afterPageText: "von {0}",
        });
    },
    
    
    /**
     * Event handler: after selecting a file to upload
     * 
     * @param {String} file
     * @param {String} extension
     * @author Andreas Linden <al@i22.de>
     */
    onUploadChange: function(file, extension) {

        $('#source').val(file);
    },
    
    /**
     * Ecent handler: before uploading begins
     * 
     * @param {String} file
     * @param {String} extension
     * @author Andreas Linden <al@i22.de>
     */
    onUploadSubmit: function(file, extension) {

        var descr = $('#description').val();
        $('#submit').attr('disabled', 'disabled');
        
        this.setData({
            description: descr
        });
    },
    
    /**
     * Event handler: when upload has finished
     * 
     * @param {String} file
     * @param {Object} response
     * @author Andreas Linden <al@i22.de>
     */
    onUploadComplete: function(file, response) {

        var dialog = new Ext.Window({
            title: 'Datei hinzufügen',
            html: response.message,
            layout: 'auto',
            width: 400,
            height: 150,
            plain: false,
            resizable: false,
            shadow: true,
            minimizable: false,
            draggable: true,
            buttons: [{
                text: 'OK',
                handler: function() {
                    dialog.destroy();
                }
            }]
        });
        
        dialog.show();
        
        $('#submit').removeAttr('disabled');
        $('#description').val('');
        $('#source').val('');
        
        App.FileManager.dataStore.reload();
    },
    
    /**
     * Submit the upload
     * @author Andreas Linden <al@i22.de>
     */
    submit: function() {

        try {
          this.uploader.submit();
        } catch (e) {}
    },
    
    /**
     * Ask to delete a file
     * 
     * @param {Ext.grid.Column} row
     * @author Andreas Linden <al@i22.de>
     */
    deleteFileDialog: function(row) {

        var dialog = new Ext.Window({
            title: 'Datei löschen',
            html: 'Sind Sie sicher, das Sie die Datei "' + row.get('filename') + '" wirklich löschen möchten?',
            layout: 'auto',
            width: 400,
            height: 150,
            plain: false,
            resizable: false,
            shadow: true,
            minimizable: false,
            draggable: true,
            buttons: [{
                text: 'Datei löschen',
                handler: function() {
                    dialog.destroy();
                    App.FileManager.deleteFile(row);
                }
            },{
                text: 'Abbrechen',
                handler: function() {
                    dialog.destroy();
                }
            }]
        }).show();
    },
    
    /**
     * Delete a file
     * 
     * @param {Ext.grid.Column} row
     * @author Andreas Linden <al@i22.de>
     */
    deleteFile: function(row) {

        $.ajax({
            type: "POST",
            url: basepath + 'admin/news/deletefile/id/' + row.get('id'),
            dataType: "json",
            success: this.deleteFileCallback
        });
    },
    
    /**
     * Notify about file deletion result
     * 
     * @param {Object} result
     * @author Andreas Linden <al@i22.de>
     */
    deleteFileCallback: function(result) {

        if(result.success == true) {

            var dialog = new Ext.Window({
                title: 'Datei löschen',
                html: 'Die Datei wurde erfolgreich gelöscht!',
                layout: 'auto',
                width: 400,
                height: 150,
                plain: false,
                resizable: false,
                shadow: true,
                minimizable: false,
                draggable: true,
                buttons: [{
                    text: 'OK',
                    handler: function() {
                        dialog.destroy();
                    }
                }]
            }).show();
            
            App.FileManager.dataStore.reload();
            
        } else {
            
             var dialog = new Ext.Window({
                title: 'Datei löschen',
                html: 'Die Datei '+ name +' konnte nicht glöscht werden!',
                layout: 'auto',
                width: 400,
                height: 150,
                plain: false,
                resizable: false,
                shadow: true,
                minimizable: false,
                draggable: true,
                buttons: [{
                    text: 'OK',
                    handler: function() {
                        dialog.destroy();
                    }
                }]
            }).show();
        }
    },
    
    /**
     * Show the history of a file
     * 
     * @param {Ext.grid.Column} row
     * @author Andreas Linden <al@i22.de>
     */
    showFileHistory: function(row) {

        $.ajax({
            type: 'post',
            url: '/admin/news/filehistory/',
            data: {
                id: row.get('id')
            },
            dataType: 'json',
            success: function(result) {

                var dialog = new Ext.Window({
            
                    header: true,
                    layout: 'auto',
                    width: 600,
                    height: 300,
                    plain: false,
                    resizable: true,
                    shadow: true,
                    minimizable: false,
                    draggable: true,
                    buttons: [{
                        text: 'OK',
                        handler: function() {
                            dialog.destroy();
                        }
                    }]
                });
                
                dialog.setTitle('Verlauf für '+ result.file.filename);
                dialog.html = '<div style="overflow: auto; height: 100%;"><table border="0" width="100%"><tr style="font-weight: bold;"><td>Datum</td><td>Aktion</td><td>Kategorie</td><td>Beschreibung</td></tr>';
                for (n in result.versions) {

                    if (typeof result.versions[n] == 'object') {
                        
                        dialog.html += '<tr><td>'+ result.versions[n].created +'</td><td>'+ result.versions[n].action +'</td><td>'+ result.versions[n].category +'</td><td>' + result.versions[n].description +'</td></tr>';
                    }
                }
                
                dialog.html += '</table></div>';
                dialog.show();
            }
        });
    },
    
    /**
     * Listener for row contextmnue
     * 
     * @param {Ext.grid} grid
     * @param {Integer} rowIndex
     * @param {Object} e
     * @author Andreas Linden <al@i22.de>
     */
    rowContextListener: function(grid, rowIndex, e) {
            
        e.stopEvent();
        var row = grid.getStore().getAt(rowIndex);
        var items = [];

        

        items.push({
             text: 'Datei herunterladen',
             handler: function() {
               App.FileManager.offerDownload(grid, rowIndex, e);
             }
        });   
         
        items.push({
             text: 'Datei löschen',
             handler: function() {
               App.FileManager.deleteFileDialog(row);
             }
        });    
        
        new Ext.menu.Menu({items: items}).showAt(e.getXY());         
    },
    
    /**
     * Offer the selected file for download
     * @author Andreas Linden <al@i22.de>
     */
    offerDownload: function(grid, rowIndex, e) {

        var row = grid.getStore().getAt(rowIndex);
        window.location.href = '/admin/news/filedownload/id/'+ row.get('id');
    }
};


/**
 * ???
 * 
 * @author ts@i22.de ???
 */
App.EventSetup = {
    role: null,
    locked: null,
    match_found: null,
    field: null,

    init: function() {
        // setup authorized
        $editButton = new Array();
        $searchForm = new Array();
        $submitButton = new Array();
        $dropDown = new Array();
        $textLabel = new Array();
        $resultSheet = new Array();


        var elements = new Array('unit_manager','project_leader','editor');

        // Close button
        $(".toggleClose").click( function() {
            $dropDown[App.EventSetup.field].slideUp('slow');
            $(".editImageButton").fadeIn('slow');
        });

        for( n in elements ) {

            var element = elements[n];

            if (element.length > 1) {

                // Formularelemente
                $editButton[element] = $("#"+element);
                $searchForm[element] = $("#setup-authorized-searchForm_"+element);
                $submitButton[element] = $("#setup-authorized-submitButton_"+element);
                $dropDown[element] = $("#dropDown_"+element);
                $textLabel[element] = $("#current_"+element);
                $resultSheet[element] = $("#resultSheet_"+element);



                // Button triggers slideDown for typeahead search field
                $editButton[element].click(function() {
                    App.EventSetup.field = $(this).get(0).id;
                    $submitButton[App.EventSetup.field].attr('disabled', true);
                    $searchForm[App.EventSetup.field].val('');
                    $searchForm[App.EventSetup.field].removeAttr('disabled');
                    $dropDown[App.EventSetup.field].slideDown('slow');
                    $(".editImageButton").fadeOut('slow');
                });

                // typeahead field
                $searchForm[element].keyup(function() {
                    if( $searchForm[App.EventSetup.field].val().length > 2 ) {
                        if (!App.EventSetup.locked) {
                            App.EventSetup.locked = true;
                            window.setTimeout("App.EventSetup.triggerResult()", 500);
                        }
                    }
                });

                // Empty field when match exists and textfield is selected again
                $searchForm[element].focus(function() {
                    if (App.EventSetup.match_found == true) {
                        $searchForm[App.EventSetup.field].val('');
                        $submitButton[App.EventSetup.field].attr('disabled', true);
                    }
                });

                $searchForm[element].blur(function() {
                    $searchForm[App.EventSetup.field].val('');
                    $resultSheet[App.EventSetup.field].slideUp('slow');
                });

                $submitButton[element].click(function() {
                    $(this).attr('disabled', true);

                    $.ajax({
                        type: "POST",
                        url: basepath + "event/setupAuthorized/type/update",
                        data: {'id':App.EventSetup.id, 'role':App.EventSetup.role, 'eventId':eventId},
                        dataType: "json",
                        success: function() {
                            $dropDown[App.EventSetup.field].slideUp('slow');
                            $(".editImageButton").fadeIn('slow');
                            $textLabel[App.EventSetup.field].html(App.EventSetup.name + ', ' + App.EventSetup.email);
                            App.EventSetup.hideNotifier();
                        },
                        error: function() {
                            $(this).removeAttr('disabled');
                        }
                    });
                });
            }
        }
    },

    toggleAuthority: function(role, id, display, name, email)
    {
        App.EventSetup.role = role;
        App.EventSetup.id = id;
        App.EventSetup.name = name;
        App.EventSetup.email = email;

        $searchForm[App.EventSetup.field].val(display);
        App.EventSetup.match_found = true;
        $submitButton[App.EventSetup.field].removeAttr('disabled');
    },

    highlightSearchTerm: function(term, query)
    {
        result = term.match(new RegExp(query,"gi"));
        
        for (n in result) {
            match = result[n];

            if( match.length > 1 ) {

                term = term.replace(match, "<b>"+match+"</b>");
            }
        }
        
        return term;

    },
    
    triggerResult: function()
    {
        if ($searchForm[App.EventSetup.field].val().length > 2) {
            var query = $searchForm[App.EventSetup.field].val();
            url = "event/setupAuthorized/type/find/query/" + query;

            if (App.EventSetup.field == 'unit_manager' ||
                App.EventSetup.field == 'project_leader') {

                url += "/role/" + App.EventSetup.field;
            }

            $.ajax({
                type: "GET",
                url: basepath + url,
                dataType: "json",
                success: function(response) {
                    if(response.success == true) {
                        $resultSheet[App.EventSetup.field].html('');
                        $resultSheet[App.EventSetup.field].append('<div style="width:200px; height:1px; font-size:1px;"></div>');
                        $resultSheet[App.EventSetup.field].append('<ul>');

                        if (typeof(response.matches) == 'object') {

                            for (var i = 0; i < response.matches.length; i += 1) {
                                var userId = response.matches[i].id;
                                var display = response.matches[i].firstname +' '+response.matches[i].lastname+' &lt;'+response.matches[i].email+'&gt';
                                var name = response.matches[i].firstname + ' ' + response.matches[i].lastname;
                                var email = response.matches[i].email;
                                $resultSheet[App.EventSetup.field].append('<li>&raquo; <a href="javascript:App.EventSetup.toggleAuthority(\''+App.EventSetup.field+'\', \''+userId+'\', \''+display+'\', \''+name+'\', \''+email+'\');">'+ App.EventSetup.highlightSearchTerm(display, query) +'</a></li>');
                            }

                        } else {

                            $resultSheet[App.EventSetup.field].append('Keine Treffer');
                        }

                        $resultSheet[App.EventSetup.field].append('</ul>');

                        // ie6 conform hover
                        $entries = $(".setup-resultSheet li");
                        $entries.hover(function() {
                            $(this).addClass('setup-resultSheetSelected');
                        }, function() {
                            $(this).removeClass('setup-resultSheetSelected');
                        });

                        $entries.click(function() {
                           window.location = $(this).find('a').attr('href');
                        });
                        
                        $resultSheet[App.EventSetup.field].slideDown();
                    }
                }
            });

            App.EventSetup.locked = false;
        } else {
            return;
        }
    },

    hideNotifier: function()
    {
        $notifyUnitManager = $("#infoBox_unit_manager");
        $notifyProjectLeader = $("#infoBox_unit_manager");

        if (typeof($notifyUnitManager) == 'object') {

            $notifyUnitManager.hide();
        }

        if (typeof($notifyProjectLeader) == 'object') {

            $notifyProjectLeader.hide();
        }
    },

    defineStatus: function() {

        if (typeof(disable_post_states) != 'undefined' ||
            typeof(disable_pre_states) != 'undefined') {

            var $selectedValue = $("[id=setup-eventstate-status] :selected").val();
            var prependEmpty = false;

            var remove = new Array();
            if (disable_post_states) {
                remove[0] = 'postprocessing';
                remove[1] = 'closed';
            }

            if (disable_pre_states) {
                remove[0] = 'planning_doubtful';
                remove[1] = 'planning_certain';
            }

            if (remove.length > 0) {
                $("[id=setup-eventstate-status] option").each(function() {
                    for (n in remove) {
                        if (remove[n] == $(this).val()) {
                            if ($selectedValue == $(this).val()) {
                                prependEmpty = true;
                            }
                            $(this).remove();
                        }
                    }
                });
            }

            if (prependEmpty == true) {
                $("[id=setup-eventstate-status]").prepend('<option value="">Bitte wählen</option>');
                $("[id=setup-eventstate-status] option").each(function() {
                    if ($(this).val() == '') {
                        $(this).attr('selected', true);
                    }
                });
            }
        }
    }
};

/**
 * Searchresults Grid
 * 
 * @author Andreas Linden <al@i22.de>
 * @uses ExtJS
 */
App.SearchResults = {

    /**
     * Rows for the grid
     */
    data: [],

    /**
     * View config for Ext grid
     */
    gridViewConfig: {
        forceFit: false,
        enableRowBody: true,
        headersDisabled: false,
        sortAscText: 'Aufsteigend sortieren',
        sortDescText: 'Absteigend sortieren',
        columnsText: 'Anzuzeigende Spalten'
    },

    /**
     * Initialize the searchresults grid
     *
     * @author Andreas Linden <al@i22.de>
     */
    init: function() {
    
        App.Ext.enableStatefulBehaviour();
    
        App.SearchResults.dataStore = new Ext.data.ArrayStore({
            fields: [
               {name: 'id'},
               {name: 'event_ident'},
               {name: 'name'},
               {name: 'city'},
               {name: 'project_description'},
               {name: 'score'},
            ]
        });
    
        // manually load local data
        App.SearchResults.dataStore.loadData(App.SearchResults.data);
    
        // create the Grid
        App.SearchResults.grid = new Ext.grid.GridPanel({
            stateful: true,
            stateId: 'App.SearchResults.Grid',
            store: App.SearchResults.dataStore,
            columns: [
                {header: 'Name', width: 200, sortable: true, dataIndex: 'name'},
                {header: 'Ident', width: 75, sortable: true, dataIndex: 'event_ident'},
                {header: 'Stadt', width: 100, sortable: true, dataIndex: 'city'},
                {header: 'Projektbeschreibung', width: 400, sortable: true, dataIndex: 'project_description'},
                {header: 'Übereinstimmung', width: 100, sortable: true, dataIndex: 'score'}
            ],
            height: 410,
            layout: 'fit',
            title: 'Suchergebnisse',
            listeners: {    
                rowcontextmenu: App.SearchResults.rowContextListener,
                rowdblclick: App.SearchResults.gotoSearchResult
            }
        });
        
        App.SearchResults.grid.render('search_results');
        
        Ext.EventManager.onWindowResize(function() {
            
            var width = $(window).width() - 10;
            App.SearchResults.grid.setWidth(width);
        });
    },
    
    /**
     * Method to add a row to the grid
     * 
     * @param {Object} row
     * @author Andreas Linden <al@i22.de>
     */
    addSearchResult: function(row) {

        App.SearchResults.data.push(row);
    },
    
    /**
     * Listener for row contextmnue
     * 
     * @param {Ext.grid} grid
     * @param {Integer} rowIndex
     * @param {Object}
     * @author Andreas Linden <al@i22.de>
     */
    rowContextListener: function(grid, rowIndex, e) {
            
        e.stopEvent();
        var row = grid.getStore().getAt(rowIndex);
        var items = [{
             text: 'Zum Event',
             handler: function() {
                App.SearchResults.gotoSearchResult(grid, rowIndex, e);
             }
        }];
        
        new Ext.menu.Menu({items: items}).showAt(e.getXY());         
    },
    
    /**
     * Action for rows
     * 
     * @param {Ext.grid} grid
     * @param {Integer} rowIndex
     * @param {Object}
     * @author Andreas Linden <al@i22.de>
     */
    gotoSearchResult: function(grid, rowIndex, e) {
    
       e.stopEvent();
       var row = grid.getStore().getAt(rowIndex);
       window.location.href= "/event/view/id/" + row.get('id');
    }
};








/**
 * Event FileManager
 * 
 * @author Andreas Linden <al@i22.de>
 * @version 0.1
 * @uses ExtJS
 * @uses jQuery
 */
App.AboutusFileManager = {

    /**
     * View config for Ext grid
     */
    gridViewConfig: {
        forceFit: false,
        enableRowBody: true,
        headersDisabled: false,
        sortAscText: 'Aufsteigend sortieren',
        sortDescText: 'Absteigend sortieren',
        columnsText: 'Anzuzeigende Spalten'
    },
    
    /**
     * Initialize
     * 
     * @param {integer} eventId
     * @author Andreas Linden <al@i22.de>
     */
    init: function(newsId) {

        App.Ext.enableStatefulBehaviour();
        
        this.uploader        = this.createUploader(newsId);
        this.dataProxy       = this.createDataProxy(newsId);
        this.dataReader      = this.createDataReader();
        this.dataWriter      = this.createDataWriter();
        this.dataStore       = this.createDataStore();
        this.columnModel     = this.createColumnModel();
        this.loadMask        = this.createLoadMask();
        this.pagingToolbar   = this.createPaginator();
        this.grid            = this.createGrid();
        
        //Ext.EventManager.onWindowResize(this.windowResize);
        this.dataStore.load();
        this.grid.render();
    },
    
    
    /**
     * Create the AjaxUplaoder
     * @param {Integer} eventId
     * @return {AjaxUplaoder}
     * @author Andreas Linden <al@i22.de>
     */
    createUploader: function(newsId) {

        return new AjaxUpload('upload_button', {
            name: 'news',
            action: '/admin/aboutuscontent/upload/id/'+ newsId +'/',
            autoSubmit: false,
            responseType: 'json',
            onChange: this.onUploadChange,
            onSubmit: this.onUploadSubmit,
            onComplete: this.onUploadComplete
        });
    },
    
    /**
     * Create the data proxy
     * @param {Integer} eventId
     * @return {Ext.data.HttpProxy}
     * @author Andreas Linden <al@i22.de>
     */
    createDataProxy: function(newsId) {
    
       return new Ext.data.HttpProxy({
            method: 'POST',
            api: {
                read : basepath + 'admin/aboutuscontent/files/id/'+ newsId,
                update: basepath + 'admin/aboutuscontent/updatefile'
            }
        });
    },
    
    /**
     * Create the data reader
     * @return {Ext.data.JsonReader}
     * @author Andreas Linden <al@i22.de>
     */
    createDataReader: function() {

        return new Ext.data.JsonReader({
            root: 'images',
            totalProperty: 'totalCount',
            id: 'id'
        }, [
            {name: 'id'},
            {name: 'filename'},
            {name: 'description'},
            {name: 'position'}
        ]);
    },
    
    /**
     * Create the data writer
     * @return {Ext.data.JsonWriter}
     * @author Andreas Linden <al@i22.de>
     */
    createDataWriter: function() {
    
       return new Ext.data.JsonWriter({
            returnJson: true,
            writeAllFields: false
        });
    },
    
    /**
     * Create the data store
     * @return {Ext.data.Store}
     * @author Andreas Linden <al@i22.de>
     */
    createDataStore: function() {

        return new Ext.data.Store({
            proxy: this.dataProxy,
            reader: this.dataReader,
            writer: this.dataWriter,
            autoLoad: false,
            remoteSort: false
        });
    },
    
    /**
     * Create the grid
     * @return {Ext.grid.EditorGridPanel}
     * @author Andreas Linden <al@i22.de>
     */
    createGrid: function()  {

        return new Ext.grid.EditorGridPanel({
            el:'grid',
            stateful: true,
            stateId: 'App.AboutusFileManager.grid',
            height: 410,
            width: 640,
            clicksToEdit: 1,
            trackMouseOver:true,
            enableCtxMenu: false,
            enableColumnMove: false,
            store: this.dataStore,
            loadMask: this.loadMask,
            cm: this.columnModel,
            bbar: this.pagingToolbar,
            viewConfig: this.gridViewConfig,
            listeners: {    
                rowcontextmenu: this.rowContextListener,
                rowdblclick: this.offerDownload
            }
        });
    },
    
    /**
     * Create the column model for the grid
     * @return {Ext.grid.ColumnModel}
     * @author Andreas Linden <al@i22.de>
     */
    createColumnModel: function() {

        return new Ext.grid.ColumnModel([{
                header: 'ID',
                dataIndex: 'id',
                width: 30,
                sortable: true
            },{
                header: 'Dateiname',
                dataIndex: 'filename',
                width: 250,
                sortable: true
            },{
                header: 'Beschreibung',
                dataIndex: 'description',
                width: 280,
                sortable: true,
                editor: new Ext.form.TextField()
	        },{
	        	header: 'Position',
	        	dataIndex: 'position',
	        	width: 70,
	        	sortable: true,
	        	editor: new Ext.form.TextField()
	        }]);
    },
    
    /**
     * Create the load mask for the grid
     * @return {Ext.LoadMask}
     * @author Andreas Linden <al@i22.de>
     */
    createLoadMask: function() {

        return new Ext.LoadMask(Ext.get('grid'), {

            msg: "Dateien werden geladen"
        });
    },
    
    /**
     * Create the "show current items"-button for the grid
     * @return {Ext.Button}
     * @author Andreas Linden <al@i22.de>
     */
    createCurrentButton: function() {

        return new Ext.Button({
            text: 'Aktuelle Dateien anzeigen',
            handler: function() {
                this.hide();
                App.AboutusFileManager.dataStore.load({
                    params: {
                        deleted: 0
                    },
                    callback: function() {
                    	App.AboutusFileManager.showDeleted.show();
                    }
                });
            }
        });
    },
    
    /**
     * Create the "show deleted items"-button for the grid
     * @return {Ext.Button}
     * @author Andreas Linden <al@i22.de>
     */
    createDeletedButton: function() {

        return new Ext.Button({
            text: 'Gelöschte Dateien anzeigen',
            handler: function(a, b) {
                this.hide();
                App.AboutusFileManager.dataStore.load({
                    params: {
                        deleted: 1
                    },
                    callback: function() {
                    	App.AboutusFileManager.showCurrent.show();
                    }
                });
            }
        });
    },
    
    /**
     * Create the paging toolbar for the grid
     * @return {Ext.PagingToolbar}
     * @author Andreas Linden <al@i22.de>
     */
    createPaginator: function() {
    
       return new Ext.PagingToolbar({

            pageSize: 15,
            store: this.dataStore,
            displayInfo: true,
            displayMsg: 'Datei {0} - {1} von {2}',
            refreshText: 'Aktualisieren',
            prevText: 'Vorherige Seite',
            nextText: 'Nächste Seite',
            emptyMsg: "Keine Dateien gefunden",
            beforePageText: "Seite",
            afterPageText: "von {0}"
        });
    },
    
    
    /**
     * Event handler: after selecting a file to upload
     * 
     * @param {String} file
     * @param {String} extension
     * @author Andreas Linden <al@i22.de>
     */
    onUploadChange: function(file, extension) {

        $('#source').val(file);
    },
    
    /**
     * Ecent handler: before uploading begins
     * 
     * @param {String} file
     * @param {String} extension
     * @author Andreas Linden <al@i22.de>
     */
    onUploadSubmit: function(file, extension) {

        var descr = $('#description').val();
        var pos = $('#position').val();
        $('#submit').attr('disabled', 'disabled');
        
        this.setData({
            description: descr,
            position: pos
        });
    },
    
    /**
     * Event handler: when upload has finished
     * 
     * @param {String} file
     * @param {Object} response
     * @author Andreas Linden <al@i22.de>
     */
    onUploadComplete: function(file, response) {

        var dialog = new Ext.Window({
            title: 'Datei hinzufügen',
            html: response.message,
            layout: 'auto',
            width: 400,
            height: 150,
            plain: false,
            resizable: false,
            shadow: true,
            minimizable: false,
            draggable: true,
            buttons: [{
                text: 'OK',
                handler: function() {
                    dialog.destroy();
                }
            }]
        });
        
        dialog.show();
        
        $('#submit').removeAttr('disabled');
        $('#description').val('');
        $('#source').val('');
        
        App.AboutusFileManager.dataStore.reload();
    },
    
    /**
     * Submit the upload
     * @author Andreas Linden <al@i22.de>
     */
    submit: function() {

        try {
          this.uploader.submit();
        } catch (e) {}
    },
    
    /**
     * Ask to delete a file
     * 
     * @param {Ext.grid.Column} row
     * @author Andreas Linden <al@i22.de>
     */
    deleteFileDialog: function(row) {

        var dialog = new Ext.Window({
            title: 'Datei löschen',
            html: 'Sind Sie sicher, das Sie die Datei "' + row.get('filename') + '" wirklich löschen möchten?',
            layout: 'auto',
            width: 400,
            height: 150,
            plain: false,
            resizable: false,
            shadow: true,
            minimizable: false,
            draggable: true,
            buttons: [{
                text: 'Datei löschen',
                handler: function() {
                    dialog.destroy();
                    App.AboutusFileManager.deleteFile(row);
                }
            },{
                text: 'Abbrechen',
                handler: function() {
                    dialog.destroy();
                }
            }]
        }).show();
    },
    
    /**
     * Delete a file
     * 
     * @param {Ext.grid.Column} row
     * @author Andreas Linden <al@i22.de>
     */
    deleteFile: function(row) {

        $.ajax({
            type: "POST",
            url: basepath + 'admin/aboutuscontent/deletefile/id/' + row.get('id'),
            dataType: "json",
            success: this.deleteFileCallback
        });
    },
    
    /**
     * Notify about file deletion result
     * 
     * @param {Object} result
     * @author Andreas Linden <al@i22.de>
     */
    deleteFileCallback: function(result) {

        if(result.success == true) {

            var dialog = new Ext.Window({
                title: 'Datei löschen',
                html: 'Die Datei wurde erfolgreich gelöscht!',
                layout: 'auto',
                width: 400,
                height: 150,
                plain: false,
                resizable: false,
                shadow: true,
                minimizable: false,
                draggable: true,
                buttons: [{
                    text: 'OK',
                    handler: function() {
                        dialog.destroy();
                    }
                }]
            }).show();
            
            App.AboutusFileManager.dataStore.reload();
            
        } else {
            
             var dialog = new Ext.Window({
                title: 'Datei löschen',
                html: 'Die Datei '+ name +' konnte nicht glöscht werden!',
                layout: 'auto',
                width: 400,
                height: 150,
                plain: false,
                resizable: false,
                shadow: true,
                minimizable: false,
                draggable: true,
                buttons: [{
                    text: 'OK',
                    handler: function() {
                        dialog.destroy();
                    }
                }]
            }).show();
        }
    },
    
    /**
     * Show the history of a file
     * 
     * @param {Ext.grid.Column} row
     * @author Andreas Linden <al@i22.de>
     */
    showFileHistory: function(row) {

        $.ajax({
            type: 'post',
            url: '/admin/aboutuscontent/filehistory/',
            data: {
                id: row.get('id')
            },
            dataType: 'json',
            success: function(result) {

                var dialog = new Ext.Window({
            
                    header: true,
                    layout: 'auto',
                    width: 600,
                    height: 300,
                    plain: false,
                    resizable: true,
                    shadow: true,
                    minimizable: false,
                    draggable: true,
                    buttons: [{
                        text: 'OK',
                        handler: function() {
                            dialog.destroy();
                        }
                    }]
                });
                
                dialog.setTitle('Verlauf für '+ result.file.filename);
                dialog.html = '<div style="overflow: auto; height: 100%;"><table border="0" width="100%"><tr style="font-weight: bold;"><td>Datum</td><td>Aktion</td><td>Kategorie</td><td>Beschreibung</td></tr>';
                for (n in result.versions) {

                    if (typeof result.versions[n] == 'object') {
                        
                        dialog.html += '<tr><td>'+ result.versions[n].created +'</td><td>'+ result.versions[n].action +'</td><td>'+ result.versions[n].category +'</td><td>' + result.versions[n].description +'</td></tr>';
                    }
                }
                
                dialog.html += '</table></div>';
                dialog.show();
            }
        });
    },
    
    /**
     * Listener for row contextmnue
     * 
     * @param {Ext.grid} grid
     * @param {Integer} rowIndex
     * @param {Object} e
     * @author Andreas Linden <al@i22.de>
     */
    rowContextListener: function(grid, rowIndex, e) {
            
        e.stopEvent();
        var row = grid.getStore().getAt(rowIndex);
        var items = [];

        

        items.push({
             text: 'Datei herunterladen',
             handler: function() {
        	App.AboutusFileManager.offerDownload(grid, rowIndex, e);
             }
        });   
         
        items.push({
             text: 'Datei löschen',
             handler: function() {
        		App.AboutusFileManager.deleteFileDialog(row);
             }
        });    
        
        new Ext.menu.Menu({items: items}).showAt(e.getXY());         
    },
    
    /**
     * Offer the selected file for download
     * @author Andreas Linden <al@i22.de>
     */
    offerDownload: function(grid, rowIndex, e) {

        var row = grid.getStore().getAt(rowIndex);
        window.location.href = '/admin/aboutuscontent/filedownload/id/'+ row.get('id');
    }
};

/**
 * Gallery FileManager
 * 
 * @author Dennis Langen
 * @version 0.1
 * @uses ExtJS
 * @uses jQuery
 */
App.GalleryFileManager = {

    /**
     * View config for Ext grid
     */
    gridViewConfig: {
        forceFit: false,
        enableRowBody: true,
        headersDisabled: false,
        sortAscText: 'Aufsteigend sortieren',
        sortDescText: 'Absteigend sortieren',
        columnsText: 'Anzuzeigende Spalten'
    },
    
    /**
     * Initialize
     * 
     * @param {integer} eventId
     * @author Dennis Langen
     */
    init: function(galleryId) {

        App.Ext.enableStatefulBehaviour();
        
        this.uploader        = this.createUploader(galleryId);
        this.dataProxy       = this.createDataProxy(galleryId);
        this.dataReader      = this.createDataReader();
        this.dataWriter      = this.createDataWriter();
        this.dataStore       = this.createDataStore();
        this.columnModel     = this.createColumnModel();
        this.loadMask        = this.createLoadMask();
        this.pagingToolbar   = this.createPaginator();
        this.grid            = this.createGrid();
        
        //Ext.EventManager.onWindowResize(this.windowResize);
        this.dataStore.load();
        this.grid.render();
    },
    
    
    /**
     * Create the AjaxUplaoder
     * @param {Integer} eventId
     * @return {AjaxUplaoder}
     * @author Dennis Langen
     */
    createUploader: function(galleryId) {

        return new AjaxUpload('upload_button', {
            name: 'news',
            action: '/admin/gallerycontent/upload/id/'+ galleryId +'/',
            autoSubmit: false,
            responseType: 'json',
            onChange: this.onUploadChange,
            onSubmit: this.onUploadSubmit,
            onComplete: this.onUploadComplete
        });
    },
    
    /**
     * Create the data proxy
     * @param {Integer} eventId
     * @return {Ext.data.HttpProxy}
     * @author Dennis Langen
     */
    createDataProxy: function(galleryId) {
    
       return new Ext.data.HttpProxy({
            method: 'POST',
            api: {
                read : basepath + 'admin/gallerycontent/files/id/'+ galleryId,
                update: basepath + 'admin/gallerycontent/updatefile'
            }
        });
    },
    
    /**
     * Create the data reader
     * @return {Ext.data.JsonReader}
     * @author Dennis Langen
     */
    createDataReader: function() {

        return new Ext.data.JsonReader({
            root: 'images',
            totalProperty: 'totalCount',
            id: 'id'
        }, [
            {name: 'id'},
            {name: 'filename'},
            {name: 'description'},
            {name: 'position'}
        ]);
    },
    
    /**
     * Create the data writer
     * @return {Ext.data.JsonWriter}
     * @author Dennis Langen
     */
    createDataWriter: function() {
    
       return new Ext.data.JsonWriter({
            returnJson: true,
            writeAllFields: false
        });
    },
    
    /**
     * Create the data store
     * @return {Ext.data.Store}
     * @author Dennis Langen
     */
    createDataStore: function() {

        return new Ext.data.Store({
            proxy: this.dataProxy,
            reader: this.dataReader,
            writer: this.dataWriter,
            autoLoad: false,
            remoteSort: false
        });
    },
    
    /**
     * Create the grid
     * @return {Ext.grid.EditorGridPanel}
     * @author Dennis Langen
     */
    createGrid: function()  {

        return new Ext.grid.EditorGridPanel({
            el:'grid',
            stateful: true,
            stateId: 'App.GalleryFileManager.grid',
            height: 410,
            width: 640,
            clicksToEdit: 1,
            trackMouseOver:true,
            enableCtxMenu: false,
            enableColumnMove: false,
            store: this.dataStore,
            loadMask: this.loadMask,
            cm: this.columnModel,
            bbar: this.pagingToolbar,
            viewConfig: this.gridViewConfig,
            listeners: {    
                rowcontextmenu: this.rowContextListener,
                rowdblclick: this.offerDownload
            }
        });
    },
    
    /**
     * Create the column model for the grid
     * @return {Ext.grid.ColumnModel}
     * @author Dennis Langen
     */
    createColumnModel: function() {

        return new Ext.grid.ColumnModel([{
                header: 'ID',
                dataIndex: 'id',
                width: 30,
                sortable: true
            },{
                header: 'Dateiname',
                dataIndex: 'filename',
                width: 250,
                sortable: true
            },{
                header: 'Beschreibung',
                dataIndex: 'description',
                width: 280,
                sortable: true,
                editor: new Ext.form.TextField()
	        },{
	        	header: 'Position',
	        	dataIndex: 'position',
	        	width: 70,
	        	sortable: true,
	        	editor: new Ext.form.TextField()
	        }]);
    },
    
    /**
     * Create the load mask for the grid
     * @return {Ext.LoadMask}
     * @author Dennis Langen
     */
    createLoadMask: function() {

        return new Ext.LoadMask(Ext.get('grid'), {

            msg: "Dateien werden geladen"
        });
    },
    
    
    /**
     * Create the paging toolbar for the grid
     * @return {Ext.PagingToolbar}
     * @author Dennis Langen
     */
    createPaginator: function() {
    
       return new Ext.PagingToolbar({

            pageSize: 15,
            store: this.dataStore,
            displayInfo: true,
            displayMsg: 'Datei {0} - {1} von {2}',
            refreshText: 'Aktualisieren',
            prevText: 'Vorherige Seite',
            nextText: 'Nächste Seite',
            emptyMsg: "Keine Dateien gefunden",
            beforePageText: "Seite",
            afterPageText: "von {0}"
        });
    },
    
    
    /**
     * Event handler: after selecting a file to upload
     * 
     * @param {String} file
     * @param {String} extension
     * @author Dennis Langen
     */
    onUploadChange: function(file, extension) {

        $('#source').val(file);
    },
    
    /**
     * Ecent handler: before uploading begins
     * 
     * @param {String} file
     * @param {String} extension
     * @author Dennis Langen
     */
    onUploadSubmit: function(file, extension) {

        var descr = $('#description').val();
        var pos = $('#position').val();
        $('#submit').attr('disabled', 'disabled');
        
        this.setData({
            description: descr,
            position: pos
        });
    },
    
    /**
     * Event handler: when upload has finished
     * 
     * @param {String} file
     * @param {Object} response
     * @author Dennis Langen
     */
    onUploadComplete: function(file, response) {

        var dialog = new Ext.Window({
            title: 'Datei hinzufügen',
            html: response.message,
            layout: 'auto',
            width: 400,
            height: 150,
            plain: false,
            resizable: false,
            shadow: true,
            minimizable: false,
            draggable: true,
            buttons: [{
                text: 'OK',
                handler: function() {
                    dialog.destroy();
                }
            }]
        });
        
        dialog.show();
        
        $('#submit').removeAttr('disabled');
        $('#description').val('');
        $('#source').val('');
        
        App.GalleryFileManager.dataStore.reload();
    },
    
    /**
     * Submit the upload
     * @author Dennis Langen
     */
    submit: function() {

        try {
          this.uploader.submit();
        } catch (e) {}
    },
    
    /**
     * Ask to delete a file
     * 
     * @param {Ext.grid.Column} row
     * @author Dennis Langen
     */
    deleteFileDialog: function(row) {

        var dialog = new Ext.Window({
            title: 'Datei löschen',
            html: 'Sind Sie sicher, das Sie die Datei "' + row.get('filename') + '" wirklich löschen möchten?',
            layout: 'auto',
            width: 400,
            height: 150,
            plain: false,
            resizable: false,
            shadow: true,
            minimizable: false,
            draggable: true,
            buttons: [{
                text: 'Datei löschen',
                handler: function() {
                    dialog.destroy();
                    App.GalleryFileManager.deleteFile(row);
                }
            },{
                text: 'Abbrechen',
                handler: function() {
                    dialog.destroy();
                }
            }]
        }).show();
    },
    
    /**
     * Delete a file
     * 
     * @param {Ext.grid.Column} row
     * @author Dennis Langen
     */
    deleteFile: function(row) {

        $.ajax({
            type: "POST",
            url: basepath + 'admin/gallerycontent/deletefile/id/' + row.get('id'),
            dataType: "json",
            success: this.deleteFileCallback
        });
    },
    
    /**
     * Notify about file deletion result
     * 
     * @param {Object} result
     * @author Dennis Langen
     */
    deleteFileCallback: function(result) {

        if(result.success == true) {

            var dialog = new Ext.Window({
                title: 'Datei löschen',
                html: 'Die Datei wurde erfolgreich gelöscht!',
                layout: 'auto',
                width: 400,
                height: 150,
                plain: false,
                resizable: false,
                shadow: true,
                minimizable: false,
                draggable: true,
                buttons: [{
                    text: 'OK',
                    handler: function() {
                        dialog.destroy();
                    }
                }]
            }).show();
            
            App.GalleryFileManager.dataStore.reload();
            
        } else {
            
             var dialog = new Ext.Window({
                title: 'Datei löschen',
                html: 'Die Datei '+ name +' konnte nicht glöscht werden!',
                layout: 'auto',
                width: 400,
                height: 150,
                plain: false,
                resizable: false,
                shadow: true,
                minimizable: false,
                draggable: true,
                buttons: [{
                    text: 'OK',
                    handler: function() {
                        dialog.destroy();
                    }
                }]
            }).show();
        }
    },
    
    
    
    /**
     * Listener for row contextmnue
     * 
     * @param {Ext.grid} grid
     * @param {Integer} rowIndex
     * @param {Object} e
     * @author Dennis Langen
     */
    rowContextListener: function(grid, rowIndex, e) {
            
        e.stopEvent();
        var row = grid.getStore().getAt(rowIndex);
        var items = [];

        

        items.push({
             text: 'Datei herunterladen',
             handler: function() {
        	App.GalleryFileManager.offerDownload(grid, rowIndex, e);
             }
        });   
         
        items.push({
             text: 'Datei löschen',
             handler: function() {
        		App.GalleryFileManager.deleteFileDialog(row);
             }
        });    
        
        new Ext.menu.Menu({items: items}).showAt(e.getXY());         
    },
    
    /**
     * Offer the selected file for download
     * @author Dennis Langen
     */
    offerDownload: function(grid, rowIndex, e) {

        var row = grid.getStore().getAt(rowIndex);
        window.location.href = '/admin/gallerycontent/filedownload/id/'+ row.get('id');
    }
};
