var editGroup, prpEditor;

showPropEditor = function(cfg) {
    prpEditor = new propEditor(cfg);
    prpEditor.show();
}

propEditor = function(cfg) {
    Ext.apply(this.startUp, cfg);
    this.editorNS = { Tree: Ext.tree };
    this.editorGrp = { Tree: Ext.tree };
}

propEditor.prototype = {
    map: {
        group: 0,
        namespace: 1
    },
    startUp: {
        tab: 'namespace',
        idNS: 0,
        nameNS: 'Mainspace',
        nameGrp: '*'
    },
    show: function() {
        if(!this.win) {
            // FormItemTemplate
            var tplNS = new Ext.XTemplate(
                '<tpl for=".">',
                '<tpl if="Available == true">',
                '<label class="{Class}"><input class="checkPerm" type="checkbox" name="perms[]" value="{Permission}" checked="checked" /> {Title}</label></tpl>',
                '<tpl if="Available == false">',
                '<label class="{Class}"><input class="checkPerm" type="checkbox" name="perms[]" value="{Permission}" /> {Title}</label></tpl>',
                '<br /></tpl>'
            );
            // End FormItemTemplate

            // Store
            this.store = new Ext.data.Store({
                proxy: new Ext.data.HttpProxy({
                    method: 'POST',
                    url: 'index.php?action=ajax&rs=hwaGroupmanager&mode=getGroupPermissions'
                }),
                reader: new Ext.data.JsonReader({
                    root: 'permissions',
                    id: 'perm'
                }, [
                    {name: 'Permission', mapping: 'perm'},
                    {name: 'Title', mapping: 'title'},
                    {name: 'Class', mapping: 'cls'},
                    {name: 'Available', mapping: 'avail'}
                ]),
                listeners: {
                    'load': {fn:function() {
                        this.tabs.getItem('0').setTitle('Gruppe ' + this.startUp.nameGrp + ' bearbeiten');
                        this.tabs.getItem('1').setTitle('Namespace ' + this.startUp.nameNS + ' bearbeiten');
                        if(this.startUp.idNS != 0) {
                            if(document.getElementById('legendPanel'))
                            document.getElementById('legendPanel').innerHTML =
                                      '<p style="margin-left:5px; margin-right:5px;">Es k&ouml;nnen in einem Namespace nur Rechte vergeben werden, die der entsprechenden Gruppe im Mainspace grunds&auml;tzlich zugewiesen wurden.</p>'
                                    + '<p><span style="margin-left:5px; padding:2px;" class="exclusive" qtip="Recht in exklusivem Gruppenbesitz">exklusiv</span>'
                                    + '<span style="margin-left:5px; padding:2px;" class="nonexcl" qtip="Recht mehreren Gruppen zugewiesen">nicht exklusiv</span>'
                                    + '<span style="margin-left:5px; padding:2px;" class="implicite" qtip="Recht allen Gruppen verfügbar/nicht zugewiesen">implizit</span>'
                                    + '<span style="margin-left:5px; padding:2px;" class="locked" qtip="Recht im Besitz einer anderen Gruppe">vergeben</span></p>';
                            if(document.getElementById('legendPanel2'))
                            document.getElementById('legendPanel2').innerHTML =
                                      '<p style="margin-left:5px; margin-right:5px;">Es k&ouml;nnen in einem Namespace nur Rechte vergeben werden, die der entsprechenden Gruppe im Mainspace grunds&auml;tzlich zugewiesen wurden.</p>'
                                    + '<p><span style="margin-left:5px; padding:2px;" class="exclusive" qtip="Recht in exklusivem Gruppenbesitz">exklusiv</span>'
                                    + '<span style="margin-left:5px; padding:2px;" class="nonexcl" qtip="Recht mehreren Gruppen zugewiesen">nicht exklusiv</span>'
                                    + '<span style="margin-left:5px; padding:2px;" class="implicite" qtip="Recht allen Gruppen verfügbar/nicht zugewiesen">implizit</span>'
                                    + '<span style="margin-left:5px; padding:2px;" class="locked" qtip="Recht im Besitz einer anderen Gruppe">vergeben</span></p>';
                        }
                        else {
                            if(document.getElementById('legendPanel'))
                            document.getElementById('legendPanel').innerHTML = '<p style="margin-left:5px; padding:2px;">Im <b>Mainspace</b> k&ouml;nnen die grunds&auml;tzlichen Rechte f&uuml;r eine Benutzergruppe gesetzt werden.</p>';
                            if(document.getElementById('legendPanel2'))
                            document.getElementById('legendPanel2').innerHTML = '<p style="margin-left:5px; padding:2px;">Im <b>Mainspace</b> k&ouml;nnen die grunds&auml;tzlichen Rechte f&uuml;r eine Benutzergruppe gesetzt werden.</p>';
                        }
                    }, scope:this}
                }
            });
            // End Store

            // Configuration Group-Editor
            // Group-Tree
            this.editorGrp.tree = new this.editorGrp.Tree.TreePanel({
                title: 'Namespaces',
                useArrows:true,
                singleExpand:true,
                rootVisible: true,
                animate:true,
                autoScroll:true,
                loader: new this.editorNS.Tree.TreeLoader({dataUrl:'index.php?action=ajax&rs=hwaGroupmanager&mode=getNamespaces'}),
                enableDD:false,
                containerScroll: true,
                height: 300,
                width:150,
                listeners: {
                    'click': {fn:function(node, ev) {
                        this.startUp.idNS = node.id;
                        this.startUp.nameNS = node.text;
                        this.store.load({params:{idNS:this.startUp.idNS,nameGrp:this.startUp.nameGrp}});
                    }, scope:this},
                    'render': {fn:function() {
                        this.store.load({params:{idNS:this.startUp.idNS,nameGrp:this.startUp.nameGrp}});
                        this.editorGrp.root.expand(true, false);
                    }, scope:this}
                }
            });
            new this.editorGrp.Tree.TreeSorter(this.editorGrp.tree, {folderSort:true});
            this.editorGrp.root = new this.editorGrp.Tree.AsyncTreeNode({
                text: 'Mainspace',
                dragable: false,
                id: '0'
            });
            this.editorGrp.tree.setRootNode(this.editorGrp.root);
            // End Group-Tree
            // FormPanel
            this.editorGrp.legend = new Ext.Panel({
                id: 'legendPanel',
                border: false,
                html: '<p style="margin-left:5px; margin-right:5px;">Es k&ouml;nnen in einem Namespace nur Rechte vergeben werden, die der entsprechenden Gruppe im Mainspace grunds&auml;tzlich zugewiesen wurden.</p>'
                    + '<p><span style="margin-left:5px; padding:2px;" class="exclusive" qtip="Recht in exklusivem Gruppenbesitz">exklusiv</span>'
                    + '<span style="margin-left:5px; padding:2px;" class="nonexcl" qtip="Recht mehreren Gruppen zugewiesen">nicht exklusiv</span>'
                    + '<span style="margin-left:5px; padding:2px;" class="implicite" qtip="Recht allen Gruppen verfügbar/nicht zugewiesen">implizit</span>'
                    + '<span style="margin-left:5px; padding:2px;" class="locked" qtip="Recht im Besitz einer anderen Gruppe">vergeben</span></p>'
            });
            this.editorGrp.form = new Ext.FormPanel({
                title: 'Rechte',
                height: 300,
                autoScroll: true,
                items: [
                    this.editorGrp.legend,
                    new Ext.DataView({
                        tpl: tplNS,
                        store: this.store,
                        itemSelector: 'input.checkPerm'
                    })],
                buttons: [{
					text: 'speichern',
                    handler: function() {
                        this.editorGrp.form.form.submit({
                            url: 'index.php?action=ajax&rs=hwaGroupmanager&mode=setGroupPermissions',
                            params: {idNS:this.startUp.idNS, nameGrp:this.startUp.nameGrp},
                            success: function(form, action) {
                               Ext.Msg.alert("Success", action.result.msg);
                            },
                            failure: function(form, action) {
                                switch (action.failureType) {
                                    case Ext.form.Action.CLIENT_INVALID:
                                        Ext.Msg.alert("Failure", "Form fields may not be submitted with invalid values");
                                        break;
                                    case Ext.form.Action.CONNECT_FAILURE:
                                        Ext.Msg.alert("Failure", "Ajax communication failed");
                                        break;
                                    case Ext.form.Action.SERVER_INVALID:
                                       Ext.Msg.alert("Failure", action.result.msg);
                               }
                            }
                        });
                    },
                    scope: this
				},{
					text: 'abbrechen',
					handler: function(){ this.win.hide(); },
					scope: this
				}]
            });
            // End FormPanel
            // End Configuration Group-Editor

            // Configuration Namespace-Editor
            // Namespace-Tree
            this.editorNS.tree = new this.editorNS.Tree.TreePanel({
                title: 'Gruppen',
                id: 'treeGroups',
                useArrows:true,
                singleExpand:true,
                rootVisible: false,
                animate:true,
                autoScroll:true,
                loader: new this.editorNS.Tree.TreeLoader({dataUrl:'index.php?action=ajax&rs=hwaNamespaceManager&mode=getGroups'}),
                enableDD:false,
                containerScroll: true,
                height: 300,
                width:150,
                listeners: {
                    'click': {fn:function(node, ev) {
                        this.startUp.nameGrp = node.id;
                        this.store.load({params:{idNS:this.startUp.idNS,nameGrp:this.startUp.nameGrp}});
                    }, scope:this},
                    'render': {fn:function() {
                        this.store.load({params:{idNS:this.startUp.idNS,nameGrp:this.startUp.nameGrp}});
                        this.editorNS.root.expand(true,  false);
                    }, scope:this}
                }
            });
            new this.editorNS.Tree.TreeSorter(this.editorNS.tree, {folderSort:true});
            this.editorNS.root = new this.editorNS.Tree.AsyncTreeNode({
                text: 'Gruppen',
                draggable: false,
                id:'root'
            });
            this.editorNS.tree.setRootNode(this.editorNS.root);
            // End Namespace-Tree
            // FormPanel
            this.editorNS.legend = new Ext.Panel({
                id: 'legendPanel2',
                border: false,
                html: '<p style="margin-left:5px; padding:2px;">Im <b>Mainspace</b> k&ouml;nnen die grunds&auml;tzlichen Rechte f&uuml;r eine Benutzergruppe gesetzt werden.</p>'
            });
            this.editorNS.form = new Ext.FormPanel({
                title: 'Rechte',
                height: 300,
                autoScroll: true,
                items: [
                    this.editorNS.legend,
                    new Ext.DataView({
                        tpl: tplNS,
                        store: this.store,
                        itemSelector: 'input.checkNS'
                    })],
                buttons: [{
					text: 'speichern',
                    handler: function() {
                        this.editorNS.form.form.submit({
                            url: 'index.php?action=ajax&rs=hwaNamespaceManager&mode=setNamespacePermissions',
                            params: {idNS:this.startUp.idNS, nameGrp:this.startUp.nameGrp},
                            success: function(form, action) {
                               Ext.Msg.alert("Success", action.result.msg);
                            },
                            failure: function(form, action) {
                                switch (action.failureType) {
                                    case Ext.form.Action.CLIENT_INVALID:
                                        Ext.Msg.alert("Failure", "Form fields may not be submitted with invalid values");
                                        break;
                                    case Ext.form.Action.CONNECT_FAILURE:
                                        Ext.Msg.alert("Failure", "Ajax communication failed");
                                        break;
                                    case Ext.form.Action.SERVER_INVALID:
                                       Ext.Msg.alert("Failure", action.result.msg);
                               }
                            }
                        });
                    },
                    scope: this
				},{
					text: 'abbrechen',
					handler: function(){ this.win.hide(); },
					scope: this
				}]
            });
            // End FormPanel
            // End Configuration Namespace-Editor

            // TabPanel
            this.tabs = new Ext.TabPanel({
                activeTab: this.map[this.startUp.tab],
                layoutOnTabChange: true,
                items: [{
                    title: 'Gruppe bearbeiten',
                    layout: 'border',
                    height: 300,
                    items: [{
                        region: 'west',
                        width: 150,
                        items: this.editorGrp.tree
                    }, {
                        region: 'center',
                        items: this.editorGrp.form
                    }]
                }, {
                    title: 'Namespace bearbeiten',
                    layout: 'border',
                    height: 300,
                    items: [{
                        region: 'west',
                        width: 150,
                        items: this.editorNS.tree
                    }, {
                        region: 'center',
                        items: this.editorNS.form
                    }]
                }]
            });
            // End TabPanel

            var cfg = {
                title: 'Zugriffs-Editor',
                width: 600,
                modal: true,
                items: this.tabs,
                keys: {
					key: 27,
					handler: function() { this.win.close(); },
					scope: this
				}
            };
            this.win = new Ext.Window(cfg);
        }
        this.store.load({params:{idNS:this.startUp.idNS,nameGrp:this.startUp.nameGrp}});
        this.win.show();
    }
}


showEditGroup = function(group) {
	loadExt();
	editGroup = new prtEditGroup(group);
	editGroup.show();
}

prtEditGroup = function(group) {
	if(typeof(group) == 'undefined') {
		this.group = 0;
	}
	else {
		this.group = group;
	}
}

prtEditGroup.prototype = {
	show: function() {
		if(!this.win) {
            this.ARStore = new Ext.data.JsonStore({
                url: 'index.php?action=ajax&rs=hwaGroupmanager&mode=getPerms',
                root: 'Perms',
                fields: ['Label', 'Value']
            });

            this.SRStore = new Ext.data.JsonStore({
                url: 'index.php?action=ajax&rs=hwaGroupmanager&mode=getPerms',
                root: 'Perms',
                fields: ['Label', 'Value']
            });

			this.baseStore = new Ext.data.JsonStore({
			    url: 'index.php?action=ajax&rs=hwaGroupmanager&mode=getGroupDetails',
			    root: 'Groups',
			    totalProperty: 'totalGroups',
			    fields: ['GroupName', 'GroupValue'],
				listeners: {
					'load': {fn:function() {
                        var rec = this.baseStore.getAt(0);
						this.form.getForm().loadRecord(rec);
                        this.NSStore.load({params:{method:'POST',group:rec.data.GroupValue}});
                        this.ARStore.load({params:{method:'POST',group:rec.data.GroupValue,ns:0,perms:'available'}});
                        this.SRStore.load({params:{method:'POST',group:rec.data.GroupValue,ns:0,perms:'set'}});
						Ext.getCmp('NSCombo').setValue('Main');
					}, scope:this},
					'reload': {fn:function() {
						var rec = this.baseStore.getAt(0);
						this.form.getForm().loadRecord(rec);
                        this.NSStore.load({params:{method:'POST',group:rec.data.GroupValue}});
                        this.ARStore.load({params:{method:'POST',group:rec.data.GroupValue,ns:0,perms:'available'}});
                        this.SRStore.load({params:{method:'POST',group:rec.data.GroupValue,ns:0,perms:'set'}});
						Ext.getCmp('NSCombo').setValue('Main');
					}, scope:this}
				}
			});
			this.baseStore.load({params:{method:'POST',start:this.group, limit:1}});
			
			this.NSStore = new Ext.data.JsonStore({
			    url: 'index.php?action=ajax&rs=hwaGroupmanager&mode=getNamespaces',
			    root: 'NameSpaces',
				fields: ['Label', 'Value']
			});

			this.pbar = new Ext.PagingToolbar({
				pageSize: 1,
				store: this.baseStore,
				displayInfo: true,
				displayMsg: '',
				emptyMsg: "No groups to display",
                beforePageText: "Gruppe",
                afterPageText: "von {0}"
			});

            this.NS = 0;

			this.DragPanel = new Ext.Panel({
				autoWidth: true,
				tbar: [{
					xtype: 'tbtext',
					text: 'Namespace: '
				}, {
					xtype: 'combo',
					id: 'NSCombo',
					name: 'NSCombo',
					store: this.NSStore,
					displayField: 'Label',
					valueField: 'Value',
					editable: false,
					mode: 'local',
					forceSelection: true,
					triggerAction: 'all',
					emptyText:'Select a namespace ...',
					selectOnFocus:true,
					allowBlank: false,
					listeners: {
						'render': {fn:function() {
							Ext.getCmp('NSCombo').setValue('Main');
						}, scope:this},
                        'select': {fn:function(box, rec, id) {
                            var grprec = this.baseStore.getAt(0);
                            this.NS = rec.data.Value;
                            this.ARStore.load({params:{method:'POST',group:grprec.data.GroupValue,ns:rec.data.Value,perms:'available'}});
                            this.SRStore.load({params:{method:'POST',group:grprec.data.GroupValue,ns:rec.data.Value,perms:'set'}});
                        }, scope:this}
					}
				}, {
                    xtype: 'button',
					text: 'Speichern',
					handler: function() {
						var grprec = this.baseStore.getAt(0);
                        var data = new Object;
                        data.__group = grprec.data.GroupValue;
                        data.__ns = this.NS;
                        var i = 0;
                        this.SRStore.each(function(record) {
                            data[i] = record.data.Value;
                            i++;
                            return true;
                        });
                        var req = new Ext.data.Connection();
                        req.request({
                            url:'index.php?action=ajax&rs=hwaGroupmanager&mode=setPerms',
                            params:data,
                            method:'POST',
                            success:function() {
                                alert('gespeichert');
                            }
                        });
                    },
					scope: this
                }],
				items: [{
		            xtype:"itemselector",
		            name:"itemselector",
		            fieldLabel:"ItemSelector",
		            dataFields:["Label", "Value"],
                    width:526,
		            msWidth:250,
		            msHeight:200,
		            valueField:"Value",
		            displayField:"Label",
		            imagePath:"hallowelt/js/ext/examples/multiselect/images/",
		            toLegend:"Erteilte Rechte",
		            fromLegend:"Verfügbare Rechte",
		            fromStore:this.ARStore,
		            toStore:this.SRStore
		        }, {
                    xtype: 'tbtext',
                    text: ' * diese Rechte können nicht entzogen werden<br />'
                }, {
                    xtype: 'tbtext',
                    text: ' ** einige Rechte dieses Namespaces werden schon von anderen Gruppen genutzt'
                }]
			});

			this.form = new Ext.form.FormPanel({
				labelWidth: 85,
				labelAlign: 'left',
				bodyStyle:'padding:10px',
				items: [{
					xtype: 'textfield',
					fieldLabel: 'Gruppenname',
					name: 'GroupName',
                    readOnly: true,
					width:175,
            		allowBlank:false
				}, this.DragPanel],
				buttons: [{
					text: 'Schließen',
					handler: function() { this.win.close(); },
					scope: this
				}]
			});

			var cfg = {
				title: 'Gruppen bearbeiten',
				autoWidth: true,
				autoHeight:true,
				tbar: this.pbar,
				items: this.form,
				modal: true,
				constrain: true,
				keys: {
					key: 27,
					handler: function() { this.win.close(); },
					scope: this
				}
			};

			this.win = new Ext.Window(cfg);
		}
		this.win.show();
        //this.load();
	},
	load: function() {
        if(this.group) {
            this.pbar.changePage(this.group);
        }
	}
};