Ext.namespace('CW', 'CW.config', 'CW.data', 'CW.util');
        
CW = function() {
	
    return {
        init : function() {
            
            if(CW.config.Modules.length == 0) {
                throw 'Fout: Er zijn geen modules ingeschakeld.';
            }
            var modules = [];
            Ext.each(CW.config.Modules, function(module) {
                modules.push({xtype: module.classname, module : module, module_id : module.id});
            });
            
            this.viewport = new Ext.Viewport({
                layout : 'border',
                items : [{
                        region : 'center',
                        baseCls : 'cw-main-panel',
                        xtype : 'tabpanel',
                        id : 'cw-main-panel',
                        body : false,
                        bodyStyle : {border: 0},
                        margins : '0 0 5 0',
                        items : modules,
                        activeItem : 0,
                        listeners : {
                            render : function(panel) {
                                panel.header.addClass('cw-main-panel-header');
                            }
                        }
                    }
                ]
            });

            // Sessie live houden
            setInterval(function() {
                
                Ext.Ajax.request({
                    url: CW.config.Base + '/checkSession',
                    callback: function() {
                    }
                });
                
            }, 60000);           
        }
    }
}();

CW.isActive = function(name) {
    return CW.config.Fields[name] === undefined ? false : (CW.config.Fields[name] === true);
}
CW.isActiveTab = function(name) {
    return CW.config.Fields[name] === undefined ? true : (CW.config.Fields[name] === false);
}
CW.isActiveGrid = function(name) {
    return CW.config.Fields[name] === undefined ? true : (CW.config.Fields[name] === false);
}
CW.Toolbar = function(config) {
    config = config || {}
    config.items = config.items || []
    
    config.style = {zoom:1}
    config.items = config.items.concat([
        '->', {
            xtype: 'combo',
            ctClass: 'languages',
            ctCls: 'languages',
            mode: 'local',
            store: new Ext.data.JsonStore({
                data: CW.data.languages,
                fields: ['lang', 'name']
            }),
            valueField: 'lang',
            displayField: 'name',
            value: CW.config.language,
            triggerAction: 'all',
            editable: false,
            width: 150,
            listeners: {
                select: function(combo, record, i) {
                    if(record.data.lang == CW.config.language) return false;
                    
                    window.location.href = CW.config.Base + '/changeLanguage/' + record.data.lang;
                }
            }
        }, '-', {
            text : 'Contact',
            iconCls : 'contact',
            handler : function(button) {
                var contact = new CW.ContactWindow();
                contact.show(button);
            }
        }, '-',
        {
            text : 'Uitloggen',
            iconCls : 'logout',
            handler : function() {
                window.location.href = '/users/logout';
            }
        }
    ]);
    
    CW.Toolbar.superclass.constructor.call(this, config);
}

Ext.extend(CW.Toolbar, Ext.Toolbar, {


});

/**
 *  ContactWindow
 */
CW.ContactWindow = Ext.extend(Ext.Window, {
    width : 500,
    layout : 'fit',
    closeAction : 'close',
    layout : 'fit',
    title : 'Contact gegevens',
    height : 300,
    modal : true,
    border : false,
    id : 'cw-contact',
    initComponent : function() {
        Ext.apply(this, {
            items : [{
                bodyStyle : {padding : '10px'},
                autoLoad : CW.config.Base + '/contact'
            }]
        });
        
        CW.ContactWindow.superclass.initComponent.call(this);
        
    }
}); 
/**
 *  PlayerWindow
 */
CW.PlayerWindow = Ext.extend(Ext.Window, {
    width : 500,
    layout : 'fit',
    closeAction : 'close',
    layout : 'fit',
    title : 'Film afspelen',
    height : 300,
    modal : true,
    border : false,
    id : 'cw-swfplayer',
    initComponent : function(iets) {
        Ext.apply(this, {
            items : [{
                bodyStyle : {padding : '10px'},
                autoLoad : CW.config.Base + '/swfplayer'
                
            }]
        });
        
        CW.PlayerWindow.superclass.initComponent.call(this);
        
    }
});


/**
 *  TagsPanel
*/

Ext.namespace('Ext.tag');

	

CW.TagsPanel = Ext.extend(Ext.Panel, {
    title : 'Tags',
    initComponent : function() {
	
	var selectionModel = new Ext.grid.CheckboxSelectionModel({
        listeners : {
            'rowselect' : function(sm, index, record) {
                Ext.getCmp('cw-delete-tag').enable();
            },
            'rowdeselect' : function(sm, index, record) {
                if(!sm.hasSelection()) {
                    Ext.getCmp('cw-delete-tag').disable();
                }
            },
            scope: this           
        }
    });
    
    Ext.tag.types = [
        ['H1'],
        ['H2'],
        ['H3'],
        ['H4'],
        ['H5']
	];
   
    var comboGridTagType = new Ext.form.TextField({
        allowBlank: false,
		name: 'value'
        
    });

    var cm = new Ext.grid.ColumnModel([
    	selectionModel, 
    	{id:'id',hidden:true, name : 'id', dataIndex: 'id'},
    	{
        	header: "Soort",
        	name: 'type',
        	dataIndex: 'type',
        	editor: comboGridTagType,
        	width: 60
    	},
    	
        {id:'word',header: "Woord", name : 'word', width: 60, sortable: true, dataIndex: 'word',editor: new Ext.form.TextField({allowBlank: false})},
        {id:'url',header: "URL",  sortable: true, name : 'url', width: 400, dataIndex: 'url',editor: new Ext.form.TextField({allowBlank: false})}
      ]);
    
    var Value = Ext.data.Record.create([
    	{name : 'id', type : 'int'}, 
    	{name : 'type'}, 
        {name : 'word'}, 
        {name : 'url'}
    
    ]);
    
    this.tagsStore = new Ext.data.JsonStore({
        fields: [
            'id',
            'type',
            'word',
            'url'
        ]
    });
    
    this.TagsGrid = new Ext.grid.EditorGridPanel({
        style : {margin : '0 0 0 0'},
        id : 'tags-grid',
        clicksToEdit : 1,
        autoHeight: true,
        enableHdMenu : false,
        enableColumnResize : true,
        border : 1,
        store: this.tagsStore,
        cm : cm,
        sm : selectionModel,
        tbar: [{
            text: 'Tag toevoegen',
            iconCls : 'add',
            handler : function(){
                var value = new Value({
                    type: 'H1',
                    word: '',
                    url: 'http://'
                });
                this.TagsGrid.stopEditing();
                this.tagsStore.insert(this.tagsStore.getCount(), value);
                this.TagsGrid.startEditing(0, 1);
                
            },
            scope : this
        }, {
            text : 'Tag verwijderen',
            iconCls : 'delete',
            id : 'cw-delete-tag',
            disabled : true,
            handler : function() {
            	
            	this.deleteTags();
            	
                
            },
            scope : this
        }],
        listeners : {
            afteredit : function(e) {
                e.grid.getStore().commitChanges();
                
                //save to database
                var ids = [];
                Ext.each(e.grid.getStore().data.items, function(r) {
    		        ids.push(r.data);
    		    }); 
                
    	        Ext.Ajax.request({
    	            url : CW.config.Base + '/tags/save.json',
    	            params : {tags : Ext.encode(ids),module_id : Ext.getCmp('cw-pages').module.id,foreign_id : Ext.getCmp('page-id').getValue()},
    	            success : function() {
    	                 
    	            },
    	            scope : this
    	        }); 
                
            }
        }
    });                
    
        Ext.apply(this, {
            items : [this.TagsGrid]
        });
    
        CW.TagsPanel.superclass.initComponent.apply(this);
    },
    load : function(data) {
        if(!data || data.length == 0) return false;
        
        this.tagsStore.loadData(data);
        if(data.types) {
            this.typeStore.loadData(data.types);
        }
        
        this.expand();
        
    },
    deleteTags : function() {
        var tags = this.TagsGrid.getSelectionModel().getSelections();
        
        var ids = [];
        
        Ext.each(tags, function(r) {
            ids.push(r.get('id'));
        }); 
        
        if(ids.length > 0) {
            this.TagsGrid.getEl().mask('Bezig met verwijderen van tags...');
            Ext.Ajax.request({
                url : CW.config.Base + '/tags/delete.json',
                params : {tags : Ext.encode(ids)},
                success : function() {
                     
                     Ext.each(tags, function(tag) {
    		            this.TagsGrid.getStore().remove(tag);
    		            this.TagsGrid.getEl().unmask();
    		        }, this);
                     
                },
                scope : this
            });
        }
    }
});
Ext.reg('cw-tags', CW.TagsPanel);



/**
 *  ImagesPanel
*/
 
CW.ImagesPanel = Ext.extend(function(config) {
    var thumbPath = '/';
    
    if(config.module) {
        if(CW.config.Site.testdefault == 1) {
            thumbPath = 'http://'+CW.config.Site.url_test + '/files/uploads/' + config.module.name + '/thumbs';
            normalPath = 'http://'+CW.config.Site.url_test + '/files/uploads/' + config.module.name;
        } else {
            thumbPath = 'http://'+CW.config.Site.url + '/files/uploads/' + config.module.name + '/thumbs';
            normalPath = 'http://'+CW.config.Site.url + '/files/uploads/' + config.module.name;
        }
    }
	
	
	
    CW.ImagesPanel.superclass.constructor.call(this, Ext.apply({
        baseUrl : CW.config.Base + '/images',
        baseParams : {},
        thumbPath : thumbPath,
        normalPath : normalPath,
        sortable : false
    }, config));
}, Ext.Panel, {
    title : 'Afbeeldingen',
    initComponent : function() {
        this.store = new Ext.data.JsonStore({
            fields : [
                'id',
                'filename',
                'name',
                'primary'
            ]
        });
        
        var plugins = [new Ext.DataView.LabelEditor({
            dataIndex : 'name',
            listeners : {
                'complete' : function(ed, value) {
                    Ext.Ajax.request({
                        url : CW.config.Base + '/images/update.json',
                        params : {id : this.activeRecord.get('id'), name : value}
                    });
                }
            }
        }),
        new Ext.ux.DataView.LightBox({
			nextImage : '/images/lightbox/arrow_right.png',
			prevImage : '/images/lightbox/arrow_left.png',
			img_path : this.normalPath,
			event : 'click'
		})]
        
        if(this.sortable) {
            plugins.push(new CW.SortableDataView({
                listeners : {
                    drop : function(oldindex, newindex, record) {
                        Ext.Ajax.request({
                            url : CW.config.Base + '/images/order.json',
                            params : {
                                id : record.data.id,
                                index : newindex
                            }
                        });
                    }
                }
            }));
        }
        
        this.view = new Ext.DataView({
            cls : 'cw-images-view',
            id: 'cw-images-view',
            store : this.store,
            itemSelector : 'div.thumb-wrap',
            overClass : 'x-view-over',
            multiSelect : true,
            style : 'overflow:auto;',
            height: 250,
            autoScroll : true,       
            tpl : new Ext.XTemplate(
                    '<tpl for=".">',
                    '<div id="thumb-{id}" class="thumb-wrap{[values.primary == 1 ? " primary" : ""]}" unselectable="on">',
                    '<div class="thumb">',
                    '<img src="'
                            + this.thumbPath
                            + '/{filename}" />',
                    '</div>',
                    '<div class="info">',
                    '<span title="{name}" class="x-editable">{shortName}</span>',
                    '</div>', '</div>', '</tpl>'),
            prepareData : function(data) {
           		
            	if(data.name == '') {
            		
            		data.shortName = Ext.util.Format.ellipsis('&nbsp;', 12);
            		
            	} else {
            	
            		data.shortName = Ext.util.Format.ellipsis(data.name, 12);
            	
            	}
                
                return data;
            },
            contextmenu : new Ext.menu.Menu({
                items : [{
                    text : 'Instellen als hoofd afbeelding',
                    iconCls : 'primary-image',
                    handler : function() {
                        this.setPrimaryImage();
                    },
                    scope : this
                },'-',{
                    text : 'Carousel instellingen',
                    iconCls : 'carousel-image',
                    handler : function() {
						if(Ext.getCmp('cw-main-panel').getActiveTab().module_id == 4) {
	                        this.carouselSettings.show();
						}
                    },
                    scope : this
                }, '-', {
                    text : 'Verwijderen',
                    iconCls : 'delete-image',
                    handler : function() {
                        Ext.Msg.confirm(
                            'Afbeelding(en) verwijderen', 
                            'Weet u zeker dat u de geselecteerd afbeelding(en) wilt verwijderen?', 
                            function(btn) {
                                if(btn == 'yes') { 
                                    this.deleteImages();
                                }
                            },
                            this
                        );
                    },
                    scope : this
                }]
            }),
            plugins : plugins
        });
        
		this.carouselForm = new Ext.form.FormPanel({
		    bodyStyle: 'padding:15px',
			url : CW.config.Base + '/images/saveCarouselSettings.json',
		    width: 500,
		    
		    defaultType: 'textfield',
		    defaults: {
		        width: 230
		    },
		    items: [{
		            fieldLabel: 'Titel',
		            name: 'carousel_title'
		        },{
		            fieldLabel: 'Link text',
		            name: 'carousel_title_link'
		        },{
		            fieldLabel: 'URL',
		            name: 'carousel_url',
		            value: 'http://'
		        }, {
		            xtype: 'textarea',
		            fieldLabel: 'Omschrijving',
		            name: 'carousel_description',
		            width: 300,
		            height: 100
		        },{
                    fieldLabel: 'Actief',
                    name: 'carousel_active',
                    inputValue: '1',
                    xtype: 'checkbox',
                    checked: true,
                    allowBlank:true
                }
		    ],
		    tbar : [{
	            text : 'Opslaan',
	            iconCls : 'save',
	            handler : function() {
	            	
	            	var s = Ext.getCmp('cw-images-view').getSelectedNodes();
	            	var node = s[0];
	            	var id = Ext.getCmp('cw-images-view').getRecord(node).get('id');
	            	
	                this.carouselForm.form.submit({
	                    waitMsg : 'Instellingen worden opgeslagen',
	                    params : {image_id:id},
	                    success : function(form, action) {
	                        this.fireEvent('save', this, action.result.data);
	                    },
	                    scope : this
	                });
	            },
	            scope : this
	        }, '-',{
	            text : 'Opslaan & sluiten',
	            iconCls : 'closesave',
	            handler : function() {
	            
	            	var s = Ext.getCmp('cw-images-view').getSelectedNodes();
	            	var node = s[0];
	            	var id = Ext.getCmp('cw-images-view').getRecord(node).get('id');
	            	
					this.carouselForm.form.submit({
	                    waitMsg : 'Instellingen worden opgeslagen',
	                    params : {image_id:id}, 
	                    success : function(form, action) {
	                        this.fireEvent('save', this, action.result.data);
	                        this.carouselSettings.hide();
	                    },
	                    scope : this
	                });
	            },
	            scope : this
	        }, '-', {
	            text : 'Sluiten',
	            iconCls : 'close',
	            handler : function() {
	            	//Ext.getCmp('cw-pages-carouselwindow').hide();
	               this.carouselSettings.hide();
	            },
	            scope : this
	        }]
		});

        this.carouselSettings = new Ext.Window({
            layout : 'fit',
            width: 600,
            id: 'cw-pages-carouselwindow',
            height: 300,
            modal : true,
            closeAction : 'hide',
            title : 'Carousel(header) instellingen',
            items : [
				this.carouselForm
            ],
            listeners : {
            	
            	show : function() {
            		
            		var s = Ext.getCmp('cw-images-view').getSelectedNodes();
			        var node = s[0];
			        var id = Ext.getCmp('cw-images-view').getRecord(node).get('id');
            		          		
            		this.carouselForm.form.load({url: CW.config.Base + '/images/loadCarouselSettings.json', params: {image_id: id || 0}, waitMsg : 'Instellingen worden geladen'});
            		
            	},
				scope: this
            	
            }
        });
		
        this.uploadPanel = new Ext.ux.SwfUploadPanel({
            remove_completed : true,
            border : false,
            // Uploader Params				
            upload_url: this.baseUrl + '/upload/' + CW.config.SessionId + '.json',
            debug : false
        });
		
        this.uploadDialog = new Ext.Window({
            layout : 'fit',
            width: 500,
            height: 300,
            modal : true,
            closeAction : 'hide',
            title : 'Afbeelding(en) toevoegen',
            items : [this.uploadPanel],
            post_params : this.baseParams
        });
        
	
	    this.imageLibraryPanel = new Ext.Panel({
	        frame:true,
	        autoWidt:true,
	        autoHeight:true,
	        collapsible:true,
	        layout:'fit',
	        title:false,
	
	        items:
	         new Ext.DataView({
	        	id: 'cw-select-images-view',
	        	cls : 'cw-select-images-view',
	            store: new Ext.data.JsonStore({
			        url : CW.config.Base + '/images/index.json',
                    params : {},
			        root: 'data',
			        fields: ['name', 'thumb_url','normal_url','count']
			    }),
	            tpl: new Ext.XTemplate(
                    '<tpl for=".">',
                    '<div id="thumb-{count}" class="thumb-wrap" unselectable="on">',
                    '<div class="thumb">',
                    '<img src="'
                            + '{thumb_url}" />',
                    '</div>',
                    '<div class="info">',
                    '<span title="{name}">{shortName}</span>',
                    '<span title="preview"><img src="/img/icons/zoom.png"><a href="#" onClick="showPhoto(\'{normal_url}\',\'{name}\');" title="{name}">Vergoot foto</a></span>',
                    '</div>', '</div>', '</tpl>'),
	            autoHeight:true,
	            overClass:'x-view-over',
	            itemSelector:'div.thumb-wrap',
	            emptyText: 'Er zijn nog geen afbeeldingen ge-upload',

	            prepareData: function(data){
	                data.shortName = Ext.util.Format.ellipsis(data.name, 15);
	                
	                return data;
	            },

	            listeners: {
	            	dblclick: function(dv,index,nodes){
            			var image = dv.store.getAt(index);
            			image.data.filename = image.data.name;
            			
            			Ext.Ajax.request({
			                url : CW.config.Base + '/images/save.json',
			                params : {foreign_id : this.baseParams.foreign_id ,module_id : this.baseParams.module_id, filename: image.data.name,name: image.data.name},
			                success : function(data) {
			                    this.imageLibraryWindow.hide();
			                    var response = Ext.decode(data.responseText);
			                    
			                    image.data.id = response.data[0].id;
			                    
			                    Ext.getCmp('cw-images-view').getStore().add(image);
			                    
			                },
			                callback : function() {
			                    
			                },
			                scope : this
			            });
            			
            			
            		},
            		scope: this
	            }
	        })
	    });
		
		
		
        this.imageLibraryWindow = new Ext.Window({
            layout : 'fit',
            width: 800,
            height: 400,
            autoScroll : true,
            modal : true,
            closeAction : 'hide',
            title : 'Selecteer uw afbeelding',
            items : [this.imageLibraryPanel],
            post_params : this.baseParams,
            tbar : [{
                xtype :'button',
                id : 'cw-upload-images',
                text : 'Afbeelding(en) uploaden',
                iconCls : 'add-image',
                handler : function() {
                    this.fireEvent('beforeOpenDialog', this);
                    
                    this.uploadDialog.show();
                    
                },
                scope: this
            }]
        });
        
        Ext.apply(this, {
            tbar : [{
                xtype :'button',
                id : 'cw-upload-images',
                text : 'Afbeelding(en) toevoegen',
                iconCls : 'add-image',
                handler : function() {
                    this.fireEvent('beforeOpenDialog', this);
                    
                    this.imageLibraryWindow.show();
                    Ext.getCmp('cw-select-images-view').store.load();
                },
                scope: this
            }],
            items : [this.view]
        });

        CW.ImagesPanel.superclass.initComponent.apply(this);
    },
    initEvents : function() {
        CW.ImagesPanel.superclass.initEvents.call(this);
        
        if(Ext.getCmp('cw-main-panel').getActiveTab().module_id == 4) {
            	
        	//Ext.getCmp('carousel-open-link').enable();
        	
        
        } 
        
        this.uploadPanel.on({
            'fileUploadSuccess' : function(suo, file, response) {
                if (response.success) {
                    var record = new Ext.data.Record(response.file);
                                       
                    this.store.addSorted(record);

                    if(this.store.getCount() == 1) {
                        this.setPrimaryImage(record);
                    }
                    
                    this.fireEvent('imageUploaded', this, record);
                } else {
                    return false;
                }
            },
            'queueUploadComplete' : function(suo) {
                this.uploadDialog.hide();
                this.imageLibraryWindow.hide();
            },
             scope : this
        });
        
        this.view.on('contextmenu', function(view, i, node, e) {
            e.preventDefault();
            var add = false;
            if(e.ctrlKey) {
                add = true;
            }
            view.select(node, add);
            view.contextmenu.showAt(e.getXY());
           
        });
    },
    load : function(data) {
        if(!data || data.length == 0) return false;
        
        this.store.loadData(data);
        if(data.types) {
            this.typeStore.loadData(data.types);
        }
        
        this.expand();
    },
    deleteImages : function() {
        var records = this.view.getRecords(this.view.getSelectedNodes());
        
        var ids = [];
        
        Ext.each(records, function(r) {
            ids.push(r.get('id'));
        }); 
        
        if(ids.length > 0) {
            this.view.getEl().mask('Bezig met verwijderen van afbeeldingen...');
            Ext.Ajax.request({
                url : this.baseUrl + '/delete.json',
                params : {images : Ext.encode(ids),module_id : this.module.id},
                success : function() {
                    Ext.each(records, function(r) {
                        this.view.store.remove(r);
                    }, this); 
                    this.fireEvent('imagesDeleted', this, records);
                },
                callback : function() {
                    this.view.getEl().unmask();
                },
                scope : this
            });
        }
    },
    setPrimaryImage : function(record) {
        if(!record) {
            var s = this.view.getSelectedNodes();
            var node = s[0];
            var id = this.view.getRecord(node).get('id');
        } else {           
            var node = this.view.getNodes()[0];
            var id = record.get('id');
        }

        var nodes = this.view.getNodes();
        // make sure only one node is selected :)
        this.view.select(node);
        
        Ext.Ajax.request({
            url : this.baseUrl + '/set_primary.json',
            params : Ext.apply(this.baseParams, {id:id}),
            success : function() {
                Ext.each(nodes, function(n) {
                    Ext.get(n).removeClass('primary');
                });
                
                Ext.get(node).addClass('primary'); 
            }
        });
       
    },
    setBaseParams : function(params) {
        this.baseParams = params || {}
        
        this.uploadPanel.addPostParams(this.baseParams);
    },

	onDestroy: function() {
		this.carouselSettings.destroy();
		this.purgeListeners();
	}
});
Ext.reg('cw-images', CW.ImagesPanel);

/**
 *  VideosPanel
*/
 
CW.VideosPanel = Ext.extend(function(config) {
    var thumbPath = '/';
    var moduleName = config.module.name;
    if(config.module) {
        if(CW.config.Site.testdefault == 1) {
            thumbPath = 'http://'+CW.config.Site.url_test + '/files/uploads/' + config.module.name + '';
        } else {
            thumbPath = 'http://'+CW.config.Site.url + '/files/uploads/' + config.module.name + '';
        }
    }

    CW.VideosPanel.superclass.constructor.call(this, Ext.apply({
        baseUrl : CW.config.Base + '/videos',
        baseParams : {},
        thumbPath : thumbPath,
        moduleName : moduleName,
        sortable : false
    }, config));
}, Ext.Panel, {
    title : 'Videos',
    initComponent : function() {
        this.store = new Ext.data.JsonStore({
            fields : [
                'id',
                'youtube_code',
                'name',
                'thumbnail'
            ]
        });
        
        var plugins = [new Ext.DataView.LabelEditor({
            dataIndex : 'name',
            listeners : {
                'complete' : function(ed, value) {
                    Ext.Ajax.request({
                        url : CW.config.Base + '/videos/save.json',
                        params : {id : this.activeRecord.get('id'), name : value,youtube_code : this.activeRecord.get('youtube_code')}
                    });
                }
            }
        })]
        
        if(this.sortable) {
            plugins.push(new CW.SortableDataView({
                listeners : {
                    drop : function(oldindex, newindex, record) {
                        Ext.Ajax.request({
                            url : CW.config.Base + '/videos/order.json',
                            params : {
                                id : record.data.id,
                                index : newindex
                            }
                        });
                    }
                }
            }));
        }
        
        this.view = new Ext.DataView({
            cls : 'cw-videos-view',
            store : this.store,
            itemSelector : 'div.thumb-wrap',
            overClass : 'x-view-over',
            multiSelect : true,
            style : 'overflow:auto',
            autoHeight: true,       
            tpl : new Ext.XTemplate(
                    '<tpl for=".">',
                    '<div id="thumb-{id}" class="thumb-wrap" unselectable="on">',
                    '<div class="thumb">',
                    '<img src="'
                            + this.thumbPath
                            + '/{thumbnail}" />',
                    '</div>',
                    '<div class="info">',
                    '<span title="{name}" class="x-editable">{shortName}</span>',
                    '<hr>',
                    '<strong>Duur</strong>:{duration}s<br />',
                    '<strong>Views</strong>:{view_count}',
                    '</div>', '</div>', '</tpl>'),
            prepareData : function(data) {
            	if(data.name == '') {
            		
            		data.shortName = Ext.util.Format.ellipsis('&nbsp;', 12);
            		
            	} else {
            	
            		data.shortName = Ext.util.Format.ellipsis(data.name, 12);
            	
            	}
                
                return data;
            },
            listeners : {
                dblclick : function(vid,index) {
                	var video = this.store.getAt(index);
                	
					var win = new Ext.Window({
		                layout      : 'fit',
		                width       : 500,
		                height      : 420,
		                closeAction :'close',
		                plain       : true,
		                title		: 'Video afspelen',
		                items : [{
			                html : '<object width="480" height="385"><param name="movie" value="http://www.youtube.com/v/'+video.data.youtube_code+'&hl=nl_NL&fs=1&"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/'+video.data.youtube_code+'&hl=nl_NL&fs=1&" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed></object>'
			                
			            }]
		            }); 
		            win.show();
									
					
                	
                },
                scope : this
            },
            contextmenu : new Ext.menu.Menu({
                items : [{
                    text : 'Verwijderen',
                    iconCls : 'delete-video',
                    handler : function() {
                        Ext.Msg.confirm(
                            'Afbeelding(en) verwijderen', 
                            'Weet u zeker dat u de geselecteerd video wilt verwijderen?', 
                            function(btn) {
                                if(btn == 'yes') { 
                                    this.deleteVideos();
                                }
                            },
                            this
                        );
                    },
                    scope : this
                }]
            }),
            plugins : plugins
        });
		
        this.uploadPanel = new Ext.ux.SwfUploadPanel({
            remove_completed : true,
            border : false,
            file_size_limit: 204800,
            // Uploader Params				
            upload_url: this.baseUrl + '/upload/' + CW.config.SessionId + '.json',
            debug : false
        });

        this.uploadDialog = new Ext.Window({
            layout : 'fit',
            width: 500,
            height: 330,
            modal : true,
            closeAction : 'hide',
            title : 'Video(s) toevoegen (Maximaal 100MB per video)',
            items : [this.uploadPanel],
            post_params : this.baseParams
        });
        
        Ext.apply(this, {
            tbar : [{
                xtype :'button',
                id : 'cw-upload-videos',
                text : 'Video(s) toevoegen',
                iconCls : 'add-scene',
                handler : function() {
                    this.fireEvent('beforeOpenDialog', this);
                    
                    this.uploadDialog.show('cw-upload-videos');
                },
                scope: this
            }],
            items : [this.view]
        });

        CW.VideosPanel.superclass.initComponent.apply(this);
    },
    initEvents : function() {
        CW.VideosPanel.superclass.initEvents.call(this);
        
        this.uploadPanel.on({
            'fileUploadSuccess' : function(suo, file, response) {
                
                if (response.success) {
                    var record = new Ext.data.Record(response);
                                        
                    this.store.addSorted(record);
                    

                } else {
                    return false;
                }
            },
            'queueUploadComplete' : function(suo) {
                this.uploadDialog.hide();
                this.store.load();
            },
             scope : this
        });
        
        this.view.on('contextmenu', function(view, i, node, e) {
            e.preventDefault();
            var add = false;
            if(e.ctrlKey) {
                add = true;
            }
            view.select(node, add);
            view.contextmenu.showAt(e.getXY());            
        });
    },
    load : function(data) {
        if(!data || data.length == 0) return false;
        
        this.store.loadData(data);
        if(data.types) {
            this.typeStore.loadData(data.types);
        }
        
        this.expand();
    },
    deleteVideos : function() {
        var records = this.view.getRecords(this.view.getSelectedNodes());
        
        var codes = [];
        
        Ext.each(records, function(r) {
            codes.push(r.get('youtube_code'));
        }); 
        
        if(codes.length > 0) {
            this.view.getEl().mask('Bezig met verwijderen van afbeeldingen...');
            Ext.Ajax.request({
                url : this.baseUrl + '/delete.json',
                params : {codes : Ext.encode(codes),module_id : this.module.id},
                success : function() {
                    Ext.each(records, function(r) {
                        this.view.store.remove(r);
                    }, this); 
                },
                callback : function() {
                    this.view.getEl().unmask();
                },
                scope : this
            });
        }
    },
    setBaseParams : function(params) {
        this.baseParams = params || {}
        
        this.uploadPanel.addPostParams(this.baseParams);
    }
});
Ext.reg('cw-videos', CW.VideosPanel);


CW.SortableDataView = function(config) {
	Ext.apply(this, config || {}, {
		dragCls : 'x-view-sortable-drag',
		viewDragCls : 'x-view-sortable-dragging'
	});
	CW.SortableDataView.superclass.constructor.call(this);
};

Ext.extend(CW.SortableDataView, Ext.util.Observable, {

	events : {
		'drop' : true
	},

	init : function(view) {
		//window.sdv = this;
		this.view = view;
		view.on('render', this.onRender, this);
		view.on('destroy', this.onDestroy, this);
	},

	onRender : function() {

		var self        = this,
		    v           = this.view,
		    ds          = v.store,
		    dd          = new Ext.dd.DragDrop(v.el),
		    dragCls     = this.dragCls
		    viewDragCls = this.viewDragCls;

		// onMouseDown : if found an element, record it for future startDrag
		dd.onMouseDown = function(e) {

			var t,idx,record;
			this.dragData = null;

			try {
				t = e.getTarget(v.itemSelector);
				idx = v.indexOf(t);
				record = ds.getAt(idx);

				// Found a record to move
				if (t && record) {
					this.dragData = {
						origIdx : idx,
						lastIdx : idx,
						record  : record
					};
					return true;
				}
			} catch (ex) { this.dragData = null; }
			return false;
		};

		// startDrag: add dragCls to the element
		dd.startDrag = function(x, y) {
			if (!this.dragData) { return false; }
			Ext.fly(v.getNode(this.dragData.origIdx)).addClass(dragCls);
			v.el.addClass(viewDragCls);
		};

		// endDrag : remove dragCls and fire "drop" event
		dd.endDrag = function(e) {
			if (!this.dragData) { return true; }
			Ext.fly(v.getNode(this.dragData.lastIdx)).removeClass(dragCls);
			v.el.removeClass(viewDragCls);
			self.fireEvent('drop', this.dragData.origIdx,
				this.dragData.lastIdx, this.dragData.record);
            this.dragData = false;
			return true;
		};

		// onDrag : if correct position, move record
		dd.onDrag = function(e) {

			var t,idx,record,data = this.dragData;
			if (!data) { return false; }

			try {
				t = e.getTarget(v.itemSelector);
				idx = v.indexOf(t);
				record = ds.getAt(idx);

				if (idx === data.lastIdx) { return true; }

				// found new position : move record and re-add dragCls
				if (t && record) {
					data.lastIdx = idx;
					ds.remove(data.record);
					ds.insert(idx, [data.record]);
					Ext.fly(v.getNode(idx)).addClass(dragCls);
					return true;
				}
			} catch (ex) { return false; }
			return false;
		};

		this.dd = dd;

	},
	
	onDestroy : function() {
	   this.purgeListeners();
	}
});



/*/
/* category settings */
CW.CategorySettings = function(config) {
    CW.CategorySettings.superclass.constructor.call(this, Ext.apply({
        layout : 'form',
        id : 'category-settings-form',
        url : CW.config.Base + '/categories/save.json',
		defaults : {width : 280},
        bodyStyle : { padding : '10px' },
        /*tbar: [{
            text: 'Opslaan',
            iconCls : 'save',
            handler : function(){
                this.form.submit({
                    waitMsg : 'Gegevens worden opgeslagen',
                    success : function(form, action) {
						this.fireEvent('save', this, action.result.data);
                    },
                    scope : this
                });
                
            },
            scope : this
        },{
            text: 'Opslaan & sluiten',
            iconCls : 'closesave',
            handler : function(){
                this.form.submit({
                    waitMsg : 'Gegevens worden opgeslagen',
                    success : function(form, action) {
						this.fireEvent('save', this, action.result.data);
						Ext.getCmp('category-settings-form').ownerCt.close();
                    },
                    scope : this
                });
                
            },
            scope : this
        }, {
            text : 'Sluiten',
            iconCls : 'close',
            id : 'cw-delete-tag',
            handler : function() {
            	
            	Ext.getCmp('category-settings-form').ownerCt.close();
            	
                
            },
            scope : this
        }],*/
        items :[{
        	xtype: 'hidden',
            name: 'id'
        },{
        	xtype: 'textarea',
        	fieldLabel: 'Categorie omschrijving',
            name: 'description',
			height: 80,
            allowBlank:true
		},{
        	xtype: 'textfield',
        	fieldLabel: 'Meta titel',
            name: 'meta_title',
            allowBlank:true
        },{
        	xtype: 'textarea',
        	fieldLabel: 'Meta omschrijving',
            name: 'meta_description',
            allowBlank:true
        },{
        	xtype: 'textarea',
        	fieldLabel: 'Meta keywords',
            name: 'meta_keywords',
            allowBlank:true
        }]
    }, config || {}));
}

Ext.extend(CW.CategorySettings, Ext.form.FormPanel, {
    render : function(ct, position) {
        CW.CategorySettings.superclass.render.call(this, ct, position);
        
        this.getForm().on('actioncomplete', function(form, action) {
            if(!action.result.success) return false;
        	

        }, this);
        
        this.getForm().load({url: CW.config.Base + '/categories/loadMetaInfo.json', params: {id: this.category_id || 0}, waitMsg : 'Instellingen worden geladen'});
        
    }
});


