/**
 * Copyright (c) 2008-2011 The Open Planning Project
 * 
 * Published under the BSD license.
 * See https://github.com/opengeo/gxp/raw/master/license.txt for the full text
 * of the license.
 */

/**
 * @requires plugins/Tool.js
 */

/** api: (define)
 *  module = gxp.plugins
 *  class = RubricatorTree
 */

/** api: (extends)
 *  plugins/Tool.js
 */
Ext.namespace("gxp.plugins");

/** api: constructor
 *  .. class:: RubricatorTree(config)
 *
 *    Plugin for adding a tree of layers to a :class:`gxp.Viewer`. Also
 *    provides a context menu on layer nodes.
 */   
gxp.plugins.RubricatorTree = Ext.extend(gxp.plugins.Tool, {
    
    /** api: ptype = gxp_rubricatortree */
    ptype: "gxp_rubricatortree",

    /** api: config[rootNodeText]
     *  ``String``
     *  Text for root node of layer tree (i18n).
     */
    rootNodeText: "Layers",

    /** api: config[overlayNodeText]
     *  ``String``
     *  Text for overlay node of layer tree (i18n).
     */
    overlayNodeText: "Overlays",

    /** api: config[baseNodeText]
     *  ``String``
     *  Text for baselayer node of layer tree (i18n).
     */
    baseNodeText: "Base Layers",
	
	capabilitiesURL: "",
    
    /** api: config[groups]
     *  ``Object`` The groups to show in the layer tree. Keys are group names,
     *  and values are either group titles or an object with ``title`` and
     *  ``exclusive`` properties. ``exclusive`` means that nodes will have
     *  radio buttons instead of checkboxes, so only one layer of the group can
     *  be active at a time. Optional, the default is
     *
     *  .. code-block:: javascript
     *
     *      groups: {
     *          "default": "Overlays", // title can be overridden with overlayNodeText
     *          "background": {
     *              title: "Base Layers", // can be overridden with baseNodeText
     *              exclusive: true
     *          }
     *      }
     */
    groups: null,
    
    /** api: config[defaultGroup]
     *  ``String`` The name of the default group, i.e. the group that will be
     *  used when none is specified. Defaults to ``default``.
     */
    defaultGroup: "default",
	
	errorTitle: "Error",
	
	proxyException: "Can not add this resource. Check authentification and proxy settings",

    denyDefaultTree: false,
	
	title: "Rubrics",
    
    /** private: method[constructor]
     *  :arg config: ``Object``
     */
    constructor: function(config) {
		//console.log('rubricator.constructor');
        gxp.plugins.RubricatorTree.superclass.constructor.apply(this, arguments);
    },

    showProjectionError: function(node,record,projection){
		//console.log('rubricator.showProjectionError');
      var icoEl = node.ui.getEl()
      if(!record.get('srs') || record.get('srs')[projection]){
        node.attributes.iconCls = node.attributes.correctProjectionIconCls
        if( icoEl ) icoEl.firstChild.getElementsByClassName('x-tree-node-icon')[0].setAttribute('class','x-tree-node-icon ' + node.attributes.correctProjectionIconCls)
        node.enable()
      }else{
        node.attributes.iconCls = 'gxp-tree-projectionerror-icon'
        if( icoEl ) icoEl.firstChild.getElementsByClassName('x-tree-node-icon')[0].setAttribute('class','x-tree-node-icon gxp-tree-projectionerror-icon')
        if(record.get('isHardProjection')) node.disable()
      }
    },

    
	treeToArray: function(layers){
		//console.log('rubricator.treeToArray');
		var arr = [];		
		cascade = function(r,f) {f.call(this,r);r.children.every(function(e){cascade(e,f);return true;})};
		cascade(layers,function(e){arr.push(e)});			
		return arr;
	},
	
	filterArray : function(arr,str,field){
		//console.log('rubricator.filterArray');
		return arr.filter(function(el){return el[field].indexOf(str)+1})
	},
	
	getRoot : function(){
		//console.log('rubricator.getRoot');
		return Ext.getCmp(this.outputTarget).items.items[0].root;
	},
	
	expandByNodeId: function(nodeid){
		//console.log('rubricator.expandByNodeId');
		this.collapseAll();
		var ids = nodeid.split('.');
		var r = this.getRoot();
		var cur = "";
		var n, lastParent;
		ids.every(function(el,idx){
			if (idx == ids.length-1) return;
			cur+=el+"."; 
			n = r.findChildBy(function(a){return a.attributes.jsonNode ? a.attributes.jsonNode.nodeid==cur : false},null,true);
			if (n) {
				lastParent = n;
				n.select();
				n.expand();		
				n.renderChildren();
			} else {
				var node = lastParent.childNodes.filter(function(e) {return e.layer.jsonNode.nodeid==nodeid})[0];
				node.select();
			}			
			return true;
		});		
		if (n && n.select) n.select();
	},
	
	collapseAll: function() {
		this.getRoot().cascade(function(n){n.collapseChildNodes();})
	},
	
    /** private: method[addOutput]
     *  :arg config: ``Object``
     */
    addOutput: function(config) {
		//console.log('rubricator.addOutput');
		
		var addChildren = function(node,jsonNode) {
			for (var i = 0; i<jsonNode.children.length;i++) {			
				var n;				
				var getStore = function(jsonNode){
					var store = new Ext.data.Store();//app.mapPanel.layers.constructor();
					if (jsonNode) {
						
						
								
						for (var i=jsonNode.children.length-1; i>=0;i--) {
					
							if (jsonNode.children[i].islayer=="1") {

								var rec = new GeoExt.data.LayerRecord({
									title: jsonNode.children[i].nodename, 
									layerStore: app.mapPanel.layers,
									properties: "gxp_wmslayerpanel",
									resource: jsonNode.children[i].workspace,
									id: 'rubricatorLayer'+jsonNode.children[i].nodeid,
									layer : jsonNode.children[i].servicetype=="wms" ? 
											new GPOpenLayers.Layer.WMS( 
												jsonNode.children[i].nodename, 
												jsonNode.children[i].serverpath+"/"+jsonNode.children[i].workspace+"/wms", 
												{layers: jsonNode.children[i].layername, transparent: true, styles:jsonNode.children[i].stylename},
												{singleTile: true, jsonNode:jsonNode.children[i]}										
											) 
										:
											new GPOpenLayers.Layer.GeoRSS( 
												jsonNode.children[i].nodename, 
												jsonNode.children[i].serverpath,
												{jsonNode: jsonNode.children[i]}												
											)
								});
								store.add(rec);
							}
							
						}	
					}
					return store;
				};
				
				var containsLayers = function(jsonNode){
					if ((jsonNode)&&(jsonNode.children))
					for (var i=0; i<jsonNode.children.length; i++){
						if (jsonNode.children[i].islayer=="1") return true;
					}
				};
				
				var preparedStore = getStore (jsonNode.children[i]);
				
				var isAlreadyInUse = function(t) {
					var k = false;
					app.mapPanel.layers.each(function(record, index) {
						if (record.get("title") == t) {																		
							k = true;
							if (record.get('rubricatorNode')) {
								record.set('title', record.get("title") +" (" +Ext.getCmp('rubricatorTree').items.items[0].getNodeById(record.get('rubricatorNode')).layer.jsonNode.nodename+")");
							}
						}
					});					
					return k;
				}
				
				//if ((jsonNode.children[i].islayer!="1")&&(jsonNode.children[i].children.length>0)&&(containsLayers(jsonNode.children[i]))) {
				if ((jsonNode.children[i].islayer!="1")&&(jsonNode.children[i].children.length>0)&&(jsonNode.children[i].children[0].islayer=="1")) {
				//if (jsonNode.children[i].isservice=="1") {
					var descrLayer = function(server,layername) {
						var format = new GPOpenLayers.Format.WMSCapabilities({
							version: "1.1.1"
						});
						var caplayers = [];
						GPOpenLayers.Request.GET({
							url: server+"?request=getCapabilities",
							async: false,
							params: {
								SERVICE: "WMS",
								VERSION: "1.3.0",
								REQUEST: "GetCapabilities"
							},
							success: function(request) {
								var doc = request.responseXML;
								if (!doc || !doc.documentElement) {
									doc = request.responseText;
								}
								var capabilities = format.read(doc);         
								caplayers.concat(capabilities.capability.layers);																		
							}, 
							failure: function(e) {            
								gxp.plugins.Logger.log(locale.log.rubricatorGetCapsError + server, gxp.plugins.Logger.prototype.LOG_LEVEL_NETWORK_LOCAL_ERRORS);
							}
						});

						
						if (!caplayers) return;
						for (var i=0; i<caplayers.length; i++) {
							if (caplayers[i].name==layername) return caplayers[i];
						}
					};

					n = new GeoExt.tree.LayerContainer({
						text: jsonNode.children[i].nodename,
						group: jsonNode.children[i].nodeid,
						jsonNode: jsonNode.children[i],
						iconCls: jsonNode.children[i].isservice=="1" ? "gxp-isservice" : jsonNode.children[i].islayer=="1" ? "gxp-islayer" : "gxp-folder",
						expanded: false,
						singleClickExpand: true,
						allowDrag: false,
						applyLoader: false,
						layerStore: null,
						isTarget: false,
						id: 'rubricatorLayer'+jsonNode.children[i].nodeid,
						listeners: {
						},
						loader: new GeoExt.tree.LayerLoader({							
							store: preparedStore,
							filter: function(layer) {
								//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
								if (layer)
								{
									//return layer.isChildNode();
									return true;
								}else
								   return false;
								//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
							},
							addLayerNode: function(node, layerRecord, index) {
								//app.mapPanel.layers.add(layerRecord);
								layerRecord.getLayer().setVisibility(false);
								index = index || 0;
								var child = this.createNode({
									//nodeType: 'gx_layer',
									layer: layerRecord.getLayer(),
									iconCls: layerRecord.get('layer').jsonNode.servicetype=="wms" ? "gxp-islayer" 
											 : layerRecord.get('layer').jsonNode.servicetype=="rss" ? "gxp-feed"
											 : layerRecord.get('layer').jsonNode.servicetype=="animation" ? "gxp-control" : "gxp-islayer" , // else: default. may be different
									id: layerRecord.get('id'),
									checked: false,
									listeners: {
										'checkchange' :  function(node, checked){																		
												if (checked) {
													if (window.JOSSO_USER=="null") {
														Ext.Msg.alert(locale.messages.error, locale.messages.accessDeniedText);
														gxp.plugins.Logger.log(locale.log.addLayerSourceAccessError.replace("{0}",conf.url), gxp.plugins.Logger.prototype.LOG_LEVEL_NETWORK_LOCAL_ERRORS);z
														return;
													}
												
													if (!Ext.getCmp('rubricatorTree').loadMask)
															Ext.getCmp('rubricatorTree').loadMask = new Ext.LoadMask(Ext.getCmp('rubricatorTree').getEl(), {msg:locale.labels.rubricator.resourceLoadMask+"..."});
														Ext.getCmp('rubricatorTree').loadMask.show();
													
													// TRUE													
													 var conf = {url: (node.attributes.layer.jsonNode.serverpath+"/"+node.attributes.layer.jsonNode.servicepath).replace(/\/\//g,"/").replace("http:/","http://"), 
																 restUrl: (node.attributes.layer.jsonNode.serverpath+"/rest").replace(/\/\//g,"/").replace("http:/","http://")};
													//var conf = {url: "http://oceanviewer.ru/resources/ru_hydrometcentre_42/wms", restUrl: "http://oceanviewer.ru/resources/rest"};													
													conf.title = node.attributes.layer.jsonNode.nodename;													
													conf.version = '1.3.0'	
													
													if (node.attributes.layer.jsonNode.servicetype=='rss') {
														var rid = "rid"+(new Date()).getTime();
														
														var source = app.layerSources['rss'];
														if (!source)
															source = new gxp.plugins.RssSource();
														var layerStore = app.mapPanel.layers;
														
														var records = [];
														node.attributes.storeId = id;
														app.layerSources['rss'].getLayersStore().each(function(record, index) {
															if (record.get("url") == node.attributes.layer.jsonNode.serverpath+"/"+node.attributes.layer.jsonNode.servicepath) {																		
																record.data.rubricatorNode = node.id;
																record.data.title = record.get('title') + (isAlreadyInUse(record.get('title')) ? " ("+node.attributes.layer.jsonNode.nodename+")" : "");
																record.data.rid = rid;
																//record.data.id = 'rubricatorLayer'+jsonNode.nodeid,
																record.data.id = node.id;
																records.push(record);																
															}
														});
														
														if (records.length==0) {
															var rubConfig = node.attributes.layer.jsonNode;
															var config = {
																url: rubConfig.serverpath + "/" + rubConfig.servicepath,
																title: rubConfig.nodename,
																name: rubConfig.layername,
																icon:  rubConfig.stylename,																
																id: 'rubricatorLayer'+node.attributes.layer.jsonNode.nodeid,
															};
															
															
															
															/*layer = new GPOpenLayers.Layer.GeoRSS (config.name, config.url, {'projection': new GPOpenLayers.Projection("EPSG:4326"), 'icon': new GPOpenLayers.Icon(config.icon)});
															layer.rid = rid;
															*/
															record = source.createLayerRecord(config); 
															record.data.rid = rid;
															record.data.id = 'rubricatorLayer'+node.attributes.layer.jsonNode.nodeid;
															record.data.rubricatorNode = node.id;
															
															//records.push(record);
															var rssStore = source.getLayersStore();
															rssStore.add([record]);														
															layerStore.add([record]);
															node.layerId = record.get('rid');														
														} else {
															var record = source.createRecord(node.attributes.layer.jsonNode.layername); 
															record.data.rid = rid;
															record.data.id = 'rubricatorLayer'+node.attributes.layer.jsonNode.nodeid;
															record.data.rubricatorNode = node.id;
															if (record)
																layerStore.add([record]);	
														}														
														
														
													/*	for (var i=0, ii = records.length; i<ii; ++i) 
														{															
															layerStore.add([record]);
															node.layerId = record.get('rid');
														}
													*/
														Ext.getCmp('rubricatorTree').loadMask.hide();
													}
													
													else
													
													if (!app.layerSources[node.attributes.layer.jsonNode.resourceid]) {
														var rid = "rid"+(new Date()).getTime();
													
														app.addLayerSource({                
															id : node.attributes.layer.jsonNode.resourceid || "source"+(new Date()).getTime() ,
															config: conf, // assumes default of gx_wmssource
															callback: function(id) {											 				
																var addLayersPlugin = app.tools.gxp_addlayers_ctl;
																// TRUE
																 var name = node.attributes.layer.jsonNode.layername;
																 var ws = node.attributes.layer.jsonNode.workspace;
																 var style = node.attributes.layer.jsonNode.stylename;
																//var name = "ru_hydrometcentre_42_1";
																var records = [];
																node.attributes.storeId = id;
																app.layerSources[id].store.each(function(record, index) {
																	if ((record.get("name") == ws+":"+name) ||  (record.get("name") == name)) {																		
																		record.data.rubstyles = style;
																		record.data.rubricatorNode = node.id;
																		record.data.title = record.get('title') + (isAlreadyInUse(record.get('title')) ? " ("+node.attributes.layer.jsonNode.nodename+")" : "");
																		record.data.rid = rid;
																		records.push(record);
																		
																	}
																});
																if (records.length==0) {
																	Ext.Msg.alert(locale.messages.error, locale.messages.noRecordsFound);
																	gxp.plugins.Logger.log(locale.log.addLayerSourceError.replace("{0}",locale.messages.noRecordsFound).replace("{1}", conf.url), gxp.plugins.Logger.prototype.LOG_LEVEL_NETWORK_LOCAL_ERRORS);
																	node.ui.checkbox.checked = false;
																}
																addLayersPlugin.addLayers(records,app.layerSources[id],false);															
																node.layerId = rid;
																Ext.getCmp('rubricatorTree').loadMask.hide();
															},
															fallback: function(source, msg) {
																Ext.Msg.alert(locale.messages.error, locale.messages.proxyException);
																gxp.plugins.Logger.log(locale.messages.proxyException.replace("{0}",conf.url), gxp.plugins.Logger.prototype.LOG_LEVEL_NETWORK_LOCAL_ERRORS);
																node.ui.checkbox.checked = false;
																Ext.getCmp('rubricatorTree').loadMask.hide();
															},
															scope: this
														});
													} else {
														
														var id = node.attributes.layer.jsonNode.resourceid;
														var addLayersPlugin = app.tools.gxp_addlayers_ctl;
														// TRUE
														var name = node.attributes.layer.jsonNode.layername;
														var ws = node.attributes.layer.jsonNode.workspace;
														var style = node.attributes.layer.jsonNode.stylename;
														//var name = "ru_hydrometcentre_42_1";
														var records = [];
														node.attributes.storeId = id;														
														app.layerSources[id].store.each(function(record, index) {
															if (record.get("name") == ws+":"+name || record.get("name") == name ) {
																record.data.rubstyles = style;
																record.data.rubricatorNode = node.id;
																record.data.rid = rid;
																record.data.title = record.get('title') + (isAlreadyInUse(record.get('title')) ? " ("+node.attributes.layer.jsonNode.nodename+")" : "");
																records.push(record);
															}
														});
														if (records.length==0) {
															Ext.Msg.alert(locale.messages.error, locale.messages.noRecordsFound);
															gxp.plugins.Logger.log(locale.log.addLayerSourceError.replace("{0}",locale.messages.noRecordsFound).replace("{1}", conf.url), gxp.plugins.Logger.prototype.LOG_LEVEL_NETWORK_LOCAL_ERRORS);
															node.ui.checkbox.checked = false;
														}
														else 
															addLayersPlugin.addLayers(records,app.layerSources[id],false);
														node.layerId = rid;                                                                                                                
        													Ext.getCmp('rubricatorTree').loadMask.hide();
													}
																																	
												}
												else 
													app.mapPanel.layers.data.each(function(record, index) {
														if (record.get("rubricatorNode") && record.get("rubricatorNode")== node.attributes.id) {															
															//remove found
															app.fireEvent("layerselectionchange", record);
															if (app.tools.gxp_removelayer_ctl.selectedLayer) {
																app.tools.gxp_removelayer_ctl.tryRemoveCurrent();
															}
															if(record)
															{
																var title = record.data['title'];

																app.mapPanel.layers.remove(record);

																for (var i = 0; i < rssVar.rssVectors.length; i++)
																{
																	if (rssVar.rssVectors[i].name === title)
																	{
																		rssVar.rssVectors.splice(i,1);
																		break;
																	}
																}
																for (var i = (app.mapPanel.layers.data.items.length - 1); i >= 0 ; i--)
																{
																	if (app.mapPanel.layers.data.items[i].data['title'] === title)
																	{
																		app.mapPanel.layers.data.items[i].visibility = false;
																		app.mapPanel.layers.remove(app.mapPanel.layers.data.items[i]);
																		break;
																	}
																}
																
																var deleted = false;
																for (var i = (app.mapPanel.map.layers.length - 1); i >= 0; i--)
																{
																	if (app.mapPanel.map.layers[i].name === title)
																	{
																		app.mapPanel.map.removeLayer(app.mapPanel.map.layers[i], false);
																		deleted = true;
																	}
																	if (!deleted && app.mapPanel.map.layers[i].CLASS_NAME === 'GPOpenLayers.Layer.Vector.RootContainer')
																	{
																		app.mapPanel.map.removeLayer(app.mapPanel.map.layers[i], false);
																		deleted = false;
																	}
																}
															}
														}
													});
										}
									},
								});
								var sibling = node.item(index);
								if(sibling) {
									node.insertBefore(child, sibling);
								} else {
									node.appendChild(child);									
								}								
							}
						}),
					});
				} else {	
					//if (jsonNode.children[i].servicetype!='animation'){
						n = new Ext.tree.TreeNode({
							text: jsonNode.children[i].nodename,
							iconCls: jsonNode.children[i].isservice=="1" ? "gxp-isservice" : jsonNode.children[i].islayer=="1" ? 
													jsonNode.children[i].servicetype=="wms" ? "gxp-islayer" 
												 : jsonNode.children[i].servicetype=="rss" ? "gxp-feed"
												 : jsonNode.children[i].servicetype=="animation" ? "gxp-control" : "gxp-islayer" 
									: "gxp-folder",
							expanded: false,
							singleClickExpand: true,
							isTarget: false,
							id: 'rubricatorLayer'+jsonNode.children[i].nodeid,
							jsonNode: jsonNode.children[i]
						});
						addChildren(n,jsonNode.children[i]);
					//}
				}
				
				//if (jsonNode.children[i].servicetype!='animation') 
				node.appendChild(n);
			}	
		}
		
		var treeRoot = new Ext.tree.TreeNode({
            text: locale.labels.rubricator.title,
            expanded: true,
            isTarget: true,
			layout: 'fit',
			id: 'rubricatorLayerRoot',
            allowDrop: false
        });
	
	
		var layers;
		var me = this;
		GPOpenLayers.Request.issue({
			method: "GET",
//			url: OVROOT+"maps",
			url: OVROOT + "services",
			async: true,
			params:{
				service: "rubricator",
				action: "getTree",
				//action: "getLayers"
			},
			callback: function(request) 
			{					
				try {
					gxp.plugins.Logger.log(locale.log.rubricatorGetTreeSuccess, gxp.plugins.Logger.prototype.LOG_LEVEL_INFO);
					layers = JSON.parse(request.responseText);										
					if (!layers) return;
					addChildren(treeRoot, layers);
					Ext.getCmp('rubricatorFilterCombo').getStore().removeAll();
					Ext.getCmp('rubricatorFilterCombo').getStore().add(new Ext.data.ArrayStore ({
						fields: [
						   {name: 'nodename', mapping: 'nodename'},
						   {name: 'nodeid', mapping: 'nodeid'},
						   {name: 'resourceid', mapping: 'resourceid'},
						   {name: 'serverpath', mapping: 'serverpath'}
						],
						data: app.tools.gxp_rubricatortree_ctl.treeToArray(layers)							
					}).getRange());					
					gxp.plugins.Logger.log(locale.log.rubricatorHandleTreeSuccess, gxp.plugins.Logger.prototype.LOG_LEVEL_INFO);
				}
				catch(e) {
					gxp.plugins.Logger.log(locale.logrubricatorHandleTreeError + ": " + e.toString() , gxp.plugins.Logger.prototype.LOG_LEVEL_NETWORK_LOCAL_ERRORS);
				}
			},
			failure: function(request){
				gxp.plugins.Logger.log(locale.logrubricatorGetTreeError + ": " + JSON.parse(request.responseText).error , gxp.plugins.Logger.prototype.LOG_LEVEL_NETWORK_LOCAL_ERRORS);
			}
		});
	 

		var filterStore = new Ext.data.ArrayStore ({
			fields: [
				{name: 'nodename', mapping: 'nodename'},
				{name: 'resourceid', mapping: 'resourceid'},
				{name: 'serverpath', mapping: 'serverpath'}
			],
			data: [/*{nodename:'nodename',nodeid:'1',serverpath:'http' },
				{nodename:'nodename2',nodeid:'2',serverpath:'http2' },
				{nodename:'nodename3',nodeid:'3',serverpath:'http3' },
				{nodename:'nodename4',nodeid:'4',serverpath:'http4' },
				{nodename:'nodename5',nodeid:'5',serverpath:'http5' }*/
			]
		});
		
        config = Ext.apply({
            xtype: "treepanel",
			id:'rubricator',
			tbar : {
				layout: 'column',
				items: [
					{
						xtype: 'combo',
						columnWidth: .90,
						id: 'rubricatorFilterCombo',
						valueField: 'nodeid',
						displayField: 'nodename',
						enableKeyEvents : true,
						store : filterStore,
						doQuery: function (c,b){c=Ext.isEmpty(c)?"":c;var a={query:c,forceAll:b,combo:this,cancel:false};if(this.fireEvent("beforequery",a)===false||a.cancel){return false}c=a.query;b=a.forceAll;if(b===true||(c.length>=this.minChars)){if(this.lastQuery!==c){this.lastQuery=c;if(this.mode=="local"){this.selectedIndex=-1;if(b){this.store.clearFilter()}else{this.store.filter(this.displayField,c,true,false)}this.onLoad()}else{this.store.baseParams[this.queryParam]=c;this.store.load({params:this.getParams(c)});this.expand()}}else{this.selectedIndex=-1;this.onLoad()}}},
						typeAhead: false,
						emptyText: locale.labels.rubricator.filter + '...',
						triggerAction: "all",						
						mode: "local",			
						listeners :{
							select: function(ui,el) {
								app.tools.gxp_rubricatortree_ctl.expandByNodeId(el.json.nodeid);
							}						
						}						
					},
					{
						xtype: 'tbspacer',
						columnWidth: .05,
					},
					{
						text: locale.labels.rubricator.parameter,
						menu: {
							id : 'rubricatorFilterParamMenu',
							items: [{
								xtype: 'radiogroup',									
								itemCls: 'x-check-group-alt',
								columns: 1,
								style: 'margin-left:6px',
								vertical: true,
								listeners : {
									change: function(radiogroup, radio) {										
										var combo = Ext.getCmp('rubricatorFilterCombo');
										combo.clearValue();
										combo.displayField = radio.inputValue;
										Ext.getCmp('rubricatorFilterParamMenu').hide();
										if (!combo.view) return;
										combo.view.tpl = new Ext.XTemplate('<tpl for="."><div class="x-combo-list-item">{'+radio.inputValue+'}</div></tpl>');
										combo.view.refresh();											
									}
								},
								items: [
									{
										boxLabel: locale.labels.rubricator.nodename,
										name: 'rb',
										inputValue: 'nodename',
										checked: true
										
									},
									{
										boxLabel: locale.labels.rubricator.serverpath,
										name: 'rb',
										inputValue: 'serverpath'
									},
									{
										boxLabel: locale.labels.rubricator.resourceid,
										name: 'rb',
										inputValue: 'resourceid'
									}
								]
							}]
						}
					}
				]
			},					
			cls: 'customTree',
            root: treeRoot,
            rootVisible: true,
			flex: 1,
			autoScroll:true,			
            border: false,
            enableDD: true,
            selModel: new Ext.tree.DefaultSelectionModel({               
            }),
            listeners: {				
                contextmenu: function(node, e) {
                    //f(node && node.layer) {
                        if (node.isRoot) return;
						node.select();
                        var tree = node.getOwnerTree();
                        if (tree.getSelectionModel().getSelectedNode() === node) {
                            var c = tree.contextMenu;
                            c.contextNode = node;
                            c.items.getCount() > 0 && c.showAt(e.getXY());							
                        }
                   // }
                },
                beforemovenode: function(tree, node, oldParent, newParent, i) {
                    // change the group when moving to a new container
                    if(oldParent !== newParent) {
                        var store = newParent.loader.store;
                        var index = store.findBy(function(r) {
                            return r.getLayer() === node.layer;
                        });
                        var record = store.getAt(index);
                        record.set("group", newParent.attributes.group);
                    }
                },                
                scope: this
            },
            contextMenu: new Ext.menu.Menu({
                items: [
					{
						text: locale.labels.rubricator.metadata,
						handler: function(e) {
							var rec = e.ownerCt.contextNode.layer ? e.ownerCt.contextNode.layer.jsonNode: e.ownerCt.contextNode.attributes.jsonNode;
							var w = new Ext.Window({
								title: locale.labels.rubricator.metadata,
								width: 500,								
								heigth: 600,
								resizable: false,
								id: 'rubricatorMetadataWindow'+(new Date()).getTime(),
								items: [
									{
										xtype: 'tabpanel',
										id: 'rubricatorMetadataWindowTabpanel',
										activeTab: 0,
										items: [
											{
												title: locale.labels.rubricator.geoserviceMetadata,
												id: 'geoserviceMetadata',
												defaults: {
													border: false
												},
												items: [{
													layout: "form",
													width: "99%",
													style: {"padding": "5px"},
													labelWidth: 150,
													items: [													
														{
															xtype: "textfield",
															fieldLabel: locale.labels.rubricator.nodeid,
															anchor: "99%",
															value: rec.nodeid || locale.labels.rubricator.defaultValue,
															readOnly: true
														},{
															xtype: "textfield",
															fieldLabel: locale.labels.rubricator.nodename,
															anchor: "99%",
															value: rec.nodename|| locale.labels.rubricator.defaultValue,
															readOnly: true
														},{
															xtype: "textfield",
															fieldLabel: locale.labels.rubricator.layername,
															anchor: "99%",
															value: rec.layername|| locale.labels.rubricator.defaultValue,
															readOnly: true
														},{
															xtype: "textfield",
															fieldLabel: locale.labels.rubricator.resourceid,
															anchor: "99%",
															value: rec.resourceid|| locale.labels.rubricator.defaultValue,
															readOnly: true
														},{
															xtype: "textfield",
															fieldLabel: locale.labels.rubricator.workspace,
															anchor: "99%",
															value: rec.workspace|| glocale.labels.rubricator.defaultValue,
															readOnly: true
														},{
															xtype: "textfield",
															fieldLabel: locale.labels.rubricator.parentnode,
															anchor: "99%",
															value: rec.parentnode|| locale.labels.rubricator.defaultValue,
															readOnly: true
														},{
															xtype: "textfield",
															fieldLabel: locale.labels.rubricator.serverpath,
															anchor: "99%",
															value: rec.serverpath|| locale.labels.rubricator.defaultValue,
															readOnly: true
														},{
															xtype: "textfield",
															fieldLabel: locale.labels.rubricator.servicepath,
															anchor: "99%",
															value: rec.servicepath|| locale.labels.rubricator.defaultValue,
															readOnly: true
														},{
															xtype: "textfield",
															fieldLabel: locale.labels.rubricator.servicetype,
															anchor: "99%",
															value: rec.servicetype|| locale.labels.rubricator.defaultValue,
															readOnly: true
														},{
															xtype: "textfield",
															fieldLabel: locale.labels.rubricator.stylename,
															anchor: "99%",
															value: rec.stylename|| locale.labels.rubricator.defaultValue,
															readOnly: true
														},
													]
												}]
											},
											{
												title: locale.labels.rubricator.resourceMetadata,
												id: 'resourceMetadata',
												defaults: {
													border: false
												},
												items: [{
													xtype: 'panel',
													style: {"padding": "5px"},
													autoWidth: true,
													html: "<iframe width=\"100%\" height=\"300\" src=\""+app.metadataUrl+rec.workspace+"\"/>"
												 }]												
											},
										]
									}
								]
							});
							w.show();
						}
					}
				]
            })
        }, config || {});
		
        var rubricatorTree = gxp.plugins.RubricatorTree.superclass.addOutput.call(this, config);

        return rubricatorTree;
    }
});

Ext.preg(gxp.plugins.RubricatorTree.prototype.ptype, gxp.plugins.RubricatorTree);
