/** api: constructor
 *  .. class:: AddLayers(config)
 *
 *    Plugin for removing a selected layer from the map.
 *    TODO Make this plural - selected layers
 */
gxp.plugins.AddLayers = Ext.extend(gxp.plugins.Tool, {
    
    /** api: ptype = gxp_addlayers */
    ptype: "gxp_addlayers",
    
    /** private: method[constructor]
     */
    constructor: function(config) {
        this.addEvents(
            /** api: event[sourceselected]
             *  Fired when a new source is selected.
             *
             *  Listener arguments:
             *
             *  * tool - :class:`gxp.plugins.AddLayers` This tool.
             *  * source - :class:`gxp.plugins.LayerSource` The selected source.
             */
            "sourceselected"
        );
        gxp.plugins.AddLayers.superclass.constructor.apply(this, arguments);        
    },
    
    /** api: method[addActions]
     */
    addActions: function() {
        var selectedLayer;
        var actions = gxp.plugins.AddLayers.superclass.addActions.apply(this, [{
            tooltip : locale.tips.addLayerTip,
            text: locale.labels.addLayers.addLayer,
            menuText: locale.labels.addLayers.addLayer,
            disabled: true,
            iconCls: "gxp-icon-addlayers",
            handler : this.showCapabilitiesGrid,
            scope: this
        }]);
        
        this.target.on("ready", function() {actions[0].enable();});
        return actions;
    },
	
	addLayers: function(records, source, isUpload, options) {
        source = source || this.selectedSource;
		
        var layerStore = this.target.mapPanel.layers,
            extent, record, layer;
        for (var i=0, ii=records.length; i<ii; ++i) {
            record = source.createLayerRecord({
                name: records[i].get("name"),
				styles: records[i].get("rubstyles"),
				rubricatorNode: records[i].get("rubricatorNode"),
				title: records[i].get("title"),
                source: source.id
            });
			try{
				for (var it in layerStore.data.items)
					if (layerStore.data.items[it].data)
						if (record.data.name == layerStore.data.items[it].data.name){
							record = undefined;
							break;
						}
			}catch(e){
				console.log(e.message);
			}	
            if (record) {
                layer = record.getLayer();
				if (options) {
					options.opacity = typeof (options.opacity) == "undefined" ? 1 : options.opacity;
					options.visible = typeof (options.visible) == "undefined" ? true : options.visible;
					layer.setOpacity(options.opacity);
					layer.setVisibility(options.visible);
				}
				//layer.options.singleTile = true;
				if (layer.maxExtent) {
                    if (!extent) {
                        extent = record.getLayer().maxExtent.clone();
                    } else {
                        extent.extend(record.getLayer().maxExtent);
                    }
                }
                if (record.get("group") === "background") {
                    layerStore.insert(0, [record]);
                } else {
                    layerStore.add([record]);
                }
            }
        }
        if (extent) {
            this.target.mapPanel.map.zoomToExtent(extent);
        }
        if (isUpload && this.postUploadAction && records.length === 1 && record) {
            // show LayerProperties dialog if just one layer was added
            this.target.selectLayer(record);
            var outputConfig,
                actionPlugin = this.postUploadAction;
            if (!Ext.isString(actionPlugin)) {
                outputConfig = actionPlugin.outputConfig;
                actionPlugin = actionPlugin.plugin;
            }
            this.target.tools[actionPlugin].addOutput(outputConfig);
        }
		
		if (record) return record.id;
    },
        
    /** api: method[showCapabilitiesGrid]
     * Shows the window with a capabilities grid.
     */
    showCapabilitiesGrid: function() {      
		/*if (!servicesSetting)
			servicesSetting = new gxp.ServicesSetting(); 
		servicesSetting.show();*/
		
		//wmscat start
		var namespace = $(this).attr('id');	
			if (!(namespace))
				namespace = (new Date()).getTime();
			namespace += '-catalog';
			$('#'+namespace+'-dialog').remove();
			$('body').append('<div id="'+namespace+'-dialog" title="Каталог сервисов" style="overflow-y:auto;"></div>');
			$('#'+namespace+'-dialog').dialog({
				autoOpen: true,
				minWidth: 900,
				minHeight: 600,
				modal: false,
				resizable: false,
				open: function(){
					var templateurl = '/portal-ajax/jquery/templates/template_wmscat_noauth.html'; 
					if ((window.JOSSO_USER)&&(window.JOSSO_USER != 'null'))
						templateurl = '/portal-ajax/jquery/templates/template_wmscat.html';
					$.ajax({
					  url: templateurl,
					  data: '',
					  cache: false,
					  success: function(htmlcat){
						$('#'+namespace+'-dialog').html(htmlcat.split('NAMESPACE').join(namespace).split('USERNAMEVALUE').join(window.JOSSO_USER));
						
						var allowedTypesForWMS = ["ln","pt","sf"];
						var loadedprofile  = [];
						var foundResources = [];
						var searchParameters = {
							'latmin':'-90',
							'latmax':'90',
							'lonmin':'-180',
							'lonmax':'180',
							'datefrom':'',
							'dateto':'',
							'access':'',
							'provider':'',
							'level':'',
							'text':'',
							'type':'',
							'geotype':'',
							'elementsStr':'',
							'searchGeneralisedDates': true,
							'rubricAdvanced':['']
						};
						var searchParametersArray = [];
						var currentSearchIndex = -1;
						
						//пользовательские слои
						$('#'+namespace+'-userlayerspanel').data({
							'originalLeft': $('#'+namespace+'-userlayerspanel').css('left'),
							'origionalTop': $('#'+namespace+'-userlayerspanel').css('top')
						});
						var userlayersopened = false;
						$('#'+namespace+'-userlayersbutton').die().live('click', function(){
							if ($('#'+namespace+'-userlayerspanel').css('display') == 'none'){
								$('#'+namespace+'-userlayerspanel').css({
									'left': $('#'+namespace+'-userlayerspanel').data('originalLeft'),
									'top': $('#'+namespace+'-userlayerspanel').data('origionalTop')
								});
							}	
							if (!(userlayersopened))
								loadUserLayersToSelect(window.JOSSO_USER, ''+namespace+'-userlayersdialog-list');
							$('#'+namespace+'-userlayerspanel').slideToggle({duration:200});	
						});
						$('#'+namespace+'-userlayers-close-button').die().live('click', function(){
							$('#'+namespace+'-userlayerspanel').slideUp({duration:200});	
						});
						$('#'+namespace+'-userlayersdialog-button-savefrominput').click(function(){
							$('#'+namespace+'-userlayersdialog .portlet-msg-error').remove();
							var check = true;
							var name = '';
							var url = '';				
							if ($('#'+namespace+'-userlayersdialog-input-name').val() == ''){
								check = false;
								$('#'+namespace+'-userlayersdialog-input-name').after('<p class="portlet-msg-error">Не указано название сохраняемого геосервиса</p>');
							}else
								name = $('#'+namespace+'-userlayersdialog-input-name').val();
								
							if ($('#'+namespace+'-userlayersdialog-input-url').val() == ''){
								check = false;
								$('#'+namespace+'-userlayersdialog-input-type').after('<p class="portlet-msg-error">Не указан адрес сохраняемого геосервиса</p>');
							}else if ($('#'+namespace+'-userlayersdialog-input-url').val().indexOf('http://') == -1){
								check = false;
								$('#'+namespace+'-userlayersdialog-input-type').after('<p class="portlet-msg-error">Некорректно указан адрес сохраняемого геосервиса</p>');
							}else
								url = $('#'+namespace+'-userlayersdialog-input-url').val()+'||'+$('#'+namespace+'-userlayersdialog-input-type').val();	
							if (check)
								$.ajax({
								  type: 'POST',
								  url: '/restserver/services/requests/add.json',
								  data: {'obj':'gis.userlayers','name':name,'name_en':url,'owner':window.JOSSO_USER},
								  success: function(json){
									loadUserLayersToSelect(window.JOSSO_USER, ''+namespace+'-userlayersdialog-list');
								  },
								  error: function(jqXHR, textStatus, errorThrown){
										alert(textStatus);
								  },
								  dataType: 'json'
								});
						});
						$('#'+namespace+'-userlayersdialog-button-previewsaved').click(function(){
							var url = $('#'+namespace+'-userlayersdialog-list').val();
							if (url.indexOf('||') != -1)
								url = url.split('||')[0];
							if ((url != '')&&(url != undefined))
								window.open(url);
						});
						$('#'+namespace+'-userlayersdialog-button-removefromsaved').click(function(){
							var id = $('#'+namespace+'-userlayersdialog-list').val().split('||')[1];
							if (id)
								$.ajax({
								  type: 'POST',
								  url: '/restserver/services/requests/admin/delete/'+id+'.json',
								  data: {},
								  success: function(json){
									loadUserLayersToSelect(window.JOSSO_USER, ''+namespace+'-userlayersdialog-list');
								  },
								  error: function(jqXHR, textStatus, errorThrown){
										alert(textStatus);
								  },
								  dataType: 'json'
								});				
						});
						$('#'+namespace+'-userlayersdialog-button-addfrominput').click(function(){
								try{
									if ($('#'+namespace+'-userlayersdialog-input-type').val().toLowerCase()=='wms'){
										var url = $('#'+namespace+'-userlayersdialog-input-url').val();
										if (url){
											var wmsurl = url;
											var capabilities = "";
											try{
												if (wmsurl.toLowerCase().indexOf('request=getcapabilities') == -1){
													if(wmsurl.indexOf('?')>0)
														capabilities = '&request=getcapabilities';
													else
														capabilities = '?request=getcapabilities';
												}					
											}catch(e){console.log(e.message);}
											if ((wmsurl.indexOf('gptl.ru') >= 0)||(wmsurl.indexOf('ifremer.fr') >= 0)){
												wmsurl = wmsurl.replace('?','&');
												wmsurl = '/dataview/xmltojson?xmlurl='+wmsurl+capabilities;
											}else
												wmsurl = '/restserver/services/c/convert.json?url='+wmsurl+capabilities;
											var id = 'id'+(new Date()).getTime();
											$('#'+namespace+'-userlayersdialog-layerstab').html('<div class="portlet-font portlet-icon icon-loading-bar-small" style="width:100px;height:15px;margin:0 auto;">Загрузка слоев</div>');
											console.log(wmsurl);
											$.ajax({
												  type: 'GET',
												  url: wmsurl,
												  async: true,
												  dataType: 'json',
												  timeout: 120000,
												  error: function(e){
														if (e.status == '403')
															$('#'+namespace+'-userlayersdialog-layerstab').html('<p class="portlet-msg-error icon-locked">У вас нет разрешения на использование этих данных</p>');
														else
															$('#'+namespace+'-userlayersdialog-layerstab').html('<p class="portlet-msg-error">Ошибка загрузки слоев</p>');
														console.log(wmsurl);
												  },
												  success: function(jsoncapabilities){
														try{
															$('#'+namespace+'-userlayersdialog-layerstab').html('<table id="'+id+'-userlayertable" class="display" ><thead><th>Название слоя</th><th style="width:18px;"></th><th style="width:18px;"></th></thead><tbody></tbody></table><br/>');
															var layersArray = jsoncapabilities.Capability.Layer.Layer;
															if (layersArray.length == undefined)
																layersArray = [layersArray];
															var aoData = [];
															for (var i=0; i<layersArray.length;i++){
																var layername = layersArray[i].Name;
																if ((!(layername))&&(layersArray[i].Layer)){
																	layername = '';
																	for (var l=0; l<layersArray[i].Layer.length; l++){
																		layername = layersArray[i].Layer[l].Name;
																		if(layername)
																			aoData.push({'title':layersArray[i].Title+' '+layersArray[i].Layer[l].Title,'layer':layername, 'id':l});
																	}
																}
																else
																	aoData.push({'title':layersArray[i].Title,'layer':layername, 'id':i});
															}
															$('#'+id+'-userlayertable').dataTable({
																"aaData": aoData,
																'sDom':'pifrt',
																"sPaginationType": "full_numbers",
																"oLanguage": {
																	"sUrl": "/portal-ajax/jquery/lang.json"
																},
																"aoColumns": [
																	{"bSortable": true, "mDataProp": "titleCleaned",
																	"fnRender": function ( oObj ) {
																		if (oObj.aData["title"])
																			return oObj.aData["title"].split(',,,').join(',').split(',,').join(',');
																		else
																			return oObj.aData["layer"];
																	}},
																	{"bSortable": false, "mDataProp": "buttonPreviewLayer",
																	"fnRender": function ( oObj ) {
																		if (oObj.aData["layer"]){
																			return '<div title="Предпросмотр слоя" class="portlet-form-button portlet-icon-notext icon-map clickable-preview" style="margin:0 auto;" esimo-wmsurl="'+url+'" esimo-layer="'+oObj.aData["layer"]+'"></div>'; ; 
																		}else
																			return '';
																	}},
																	{"bSortable": false, "mDataProp": "buttonAddLayer",
																	"fnRender": function ( oObj ) {
																		if (oObj.aData["layer"]){
																			return '<div title="Добавить слой на карту" esimo-gis-url="'+url+'" esimo-gis-layer="'+oObj.aData["layer"]+'" esimo-gis-type="WMS" class="clickable-layer-add open portlet-form-button portlet-icon-notext icon-plus" type="button"></div>'; 
																		}else
																			return '';
																	}}
																]
															});
														}catch(e){
															console.log(e.message);
															$('#'+id).html('<p class="portlet-msg-error">Ошибка чтения списка слоев</p>');
														}
												  }
											});	
										}else{
											$('#'+namespace+'-userlayersdialog-layerstab').html('<p class="portlet-msg-error">Не указан адрес сервиса</p>');
										}
									}
								}catch(e){
									console.log(e.message);
								}
						});
						$('#'+namespace+'-userlayersdialog-button-addfromsaved').click(function(){
								try{
									if (true/*$('#'+namespace+'-userlayersdialog-list').val().toLowerCase()=='wms'*/){
										var url = $('#'+namespace+'-userlayersdialog-list').val().split('||')[0];
										if (url){
											var wmsurl = url;
											var capabilities = "";
											try{
												if (wmsurl.toLowerCase().indexOf('request=getcapabilities') == -1){
													if(wmsurl.indexOf('?')>0)
														capabilities = '&request=getcapabilities';
													else
														capabilities = '?request=getcapabilities';
												}					
											}catch(e){console.log(e.message);}
											if ((wmsurl.indexOf('gptl.ru') >= 0)||(wmsurl.indexOf('ifremer.fr') >= 0)){
												wmsurl = wmsurl.replace('?','&');
												wmsurl = '/dataview/xmltojson?xmlurl='+wmsurl+capabilities;
											}else
												wmsurl = '/restserver/services/c/convert.json?url='+wmsurl+capabilities;											
											var id = 'id'+(new Date()).getTime();
											$('#'+namespace+'-userlayersdialog-listlayerstab').html('<div class="portlet-font portlet-icon icon-loading-bar-small" style="width:100px;height:15px;margin:0 auto;">Загрузка слоев</div>');
											$.ajax({
												  type: 'GET',
												  url: wmsurl,
												  async: true,
												  dataType: 'json',
												  timeout: 120000,
												  error: function(e){
														if (e.status == '403')
															$('#'+namespace+'-userlayersdialog-listlayerstab').html('<p class="portlet-msg-error icon-locked">У вас нет разрешения на использование этих данных</p>');
														else
															$('#'+namespace+'-userlayersdialog-listlayerstab').html('<p class="portlet-msg-error">Ошибка загрузки слоев</p>');
														console.log(wmsurl);	
												  },
												  success: function(jsoncapabilities){
														try{
															$('#'+namespace+'-userlayersdialog-listlayerstab').html('<table id="'+id+'-userlistlayertable" class="display" ><thead><th>Название слоя</th><th style="width:18px;"></th><th style="width:18px;"></th></thead><tbody></tbody></table><br/>');
															var layersArray = jsoncapabilities.Capability.Layer.Layer;
															if (layersArray.length == undefined)
																layersArray = [layersArray];
															var aoData = [];
															for (var i=0; i<layersArray.length;i++){
																var layername = layersArray[i].Name;
																if ((!(layername))&&(layersArray[i].Layer)){
																	layername = '';
																	for (var l=0; l<layersArray[i].Layer.length; l++){
																		layername = layersArray[i].Layer[l].Name;
																		if(layername)
																			aoData.push({'title':layersArray[i].Title+' '+layersArray[i].Layer[l].Title,'layer':layername, 'id':l});
																	}
																}
																else
																	aoData.push({'title':layersArray[i].Title,'layer':layername, 'id':i});
															}
															$('#'+id+'-userlistlayertable').dataTable({
																"aaData": aoData,
																'sDom':'pifrt',
																"sPaginationType": "full_numbers",
																"oLanguage": {
																	"sUrl": "/portal-ajax/jquery/lang.json"
																},
																"aoColumns": [
																	{"bSortable": true, "mDataProp": "titleCleaned",
																	"fnRender": function ( oObj ) {
																		if (oObj.aData["title"])
																			return oObj.aData["title"].split(',,,').join(',').split(',,').join(',');
																		else
																			return oObj.aData["layer"];
																	}},
																	{"bSortable": false, "mDataProp": "buttonPreviewLayer",
																	"fnRender": function ( oObj ) {
																		if (oObj.aData["layer"]){
																			return '<div title="Предпросмотр слоя" class="portlet-form-button portlet-icon-notext icon-map clickable-preview" style="margin:0 auto;" esimo-wmsurl="'+url+'" esimo-layer="'+oObj.aData["layer"]+'"></div>'; ; 
																		}else
																			return '';
																	}},
																	{"bSortable": false, "mDataProp": "buttonAddLayer",
																	"fnRender": function ( oObj ) {
																		if (oObj.aData["layer"]){
																			return '<div title="Добавить слой на карту" esimo-gis-url="'+url+'" esimo-gis-layer="'+oObj.aData["layer"]+'" esimo-gis-type="WMS" class="clickable-layer-add open portlet-form-button portlet-icon-notext icon-plus" type="button"></div>'; 
																		}else
																			return '';
																	}}
																]
															});
														}catch(e){
															console.log(e.message);
															$('#'+id).html('<p class="portlet-msg-error">Ошибка чтения списка слоев</p>');
														}
												  }
											});	
										}else{
											$('#'+namespace+'-userlayersdialog-listlayerstab').html('<p class="portlet-msg-error">Не указан адрес сервиса</p>');
										}
									}
								}catch(e){
									console.log(e.message);
								}
						});
						//профили
						$('#'+namespace+'-dialog .portlet-accordion').tabs(".portlet-accordion div.pane", {tabs: 'h2', effect: 'slide', initialIndex: null});
						var checkedarray = [];
						var checkedNames = {};
						$('#'+namespace+'-catalog-table input:checkbox').live('click',function(){
									var i = checkedarray.indexOf($(this).val());
									if (i==-1){
										checkedarray.push($(this).val());
										$(this).attr('checked','checked');
										checkedNames[$(this).val()] = $(this).parents('tr').first().children('td').first().next().html();
									}
									else {
										delete checkedNames[checkedarray[i]];
										checkedarray.splice(i,1);
										$(this).attr('checked', null);                
									}
						});


						$('#'+namespace+'-catalog-table-checkpage').live( 'click', function () {
									$('#'+namespace+'-catalog-table input:checkbox').each( function() {
											var i = checkedarray.indexOf($(this).val());
											if (i==-1){
												checkedarray.push($(this).val());
												$(this).attr('checked','checked');
																		checkedNames[$(this).val()] = $(this).parents('tr').first().children('td').first().next().html();
											}
									});
						});
						$('#'+namespace+'-catalog-table-checkall').live( 'click', function () {
									checkedarray = [];
									$('input:checkbox', oTableServices.fnGetFilteredNodes()).each(function(){
										checkedarray.push($(this).val());
										$(this).attr('checked', 'true');
										checkedNames[$(this).val()] = $(this).parents('tr').first().children('td').first().next().html();
									});
						});

						$('#'+namespace+'-catalog-table-uncheckpage').live( 'click', function () {
									$('#'+namespace+'-catalog-table input:checkbox').each( function() {
											var i = checkedarray.indexOf($(this).val());
											if (i==-1){
																	;						
											}
											else {
																		delete checkedNames[checkedarray[i]];
												checkedarray.splice(i,1);
												$(this).attr('checked', null);
											}
									});
						});

						$('#'+namespace+'-catalog-table-uncheckall').live( 'click', function () {
									checkedarray = [];
									checkedNames = {};
									$('input:checkbox', oTableServices.fnGetNodes()).attr('checked', false);
						});
						$('#'+namespace+'-profile-save').click( function() {
							if (checkedarray.length == 0){
									$(this).displayTextMessage({
											'text':'Для создания профиля необходимо отметить в каталоге сервисы, которые будут в него входить',
											'type':'help'
									});
								}else{
								$('#'+namespace+'-profile-dialog').remove();
								$('body').append('<div id="'+namespace+'-profile-dialog" class="portlet-dialog-form" title="Создание профиля каталога из отмеченных в таблице">'+
											'<label class="portlet-form-field-label-nowidth">Введите название профиля:</label><br/><input id="'+namespace+'-profile-dialog-profilename" type="text" value=""  class="portlet-form-input-field" style="width:95%;"/><br/><br/>'+
											'<label class="portlet-form-field-label-nowidth">Отмеченные сервисы для добавления в профиль:</label><br/>'+
											'<div id="'+namespace+'-profile-dialog-subs" class="portlet-form-input-field" style="height:250px; width:95%; overflow:auto; text-align:left; background: white;"></div><br/>'+
											'<input id="'+namespace+'-profile-dialog-save" class="portlet-form-button portlet-icon icon-status-success" type="button" value="Сохранить"/><input id="'+namespace+'-profile-dialog-close" class="portlet-form-button portlet-icon icon-status-error" type="button" value="Отменить"/>'+
											'</div>');
										for (var i=0; i<checkedarray.length; i++)
											 $('#'+namespace+'-profile-dialog-subs').append('<span style="width:100%;"><span class="portlet-icon icon-status-error" style="cursor:pointer; float:right; margin-top:4px;" title="Исключить слой из списка добавления"></span><span class="portlet-icon icon-download-text">'+checkedNames[checkedarray[i]]+'</span><br style="clear:both;"/></span>');

										$('#'+namespace+'-profile-dialog').dialog({
											autoOpen: true,
											minHeight: 390,
											minWidth: 550,
											modal: false,
											open: function(){
													$('#'+namespace+'-profile-dialog-close').click(function(){
														$('#'+namespace+'-profile-dialog').dialog( "close" );
													});
													
													$('#'+namespace+'-profile-dialog-subs span.icon-status-error').die().live('click',function(){
														$(this).parent().remove();
													});
													
													$('#'+namespace+'-profile-dialog-save').click(function(){
															var profilename = $('#'+namespace+'-profile-dialog-profilename').val();
															if(profilename==''){
																	$('#'+namespace+'-profile-dialog div.portlet-msg-error').remove();
																	$('#'+namespace+'-profile-dialog-profilename').after('<div class="portlet-msg-error" style="width:90%;">Введите название профиля</div>');
															}else{
																	var values = "";
																	$('#'+namespace+'-profile-dialog-subs span.layerid').each(function(){
																		if (values.indexOf($(this).attr('name')) == -1)
																			values += $(this).attr('name') + ";";
																	});
																	$.ajax({
																			type: 'POST',
																			url: '/restserver/services/profiles/add.json',
																			dataType: 'json',
																			data: {"owner":window.JOSSO_USER,"obj":"GISLAYERS","prop":"layer.id","name":profilename,"ids":values},
																			success: function(){
																				   $('#'+namespace+'-profile-dialog').dialog( "close" );
																				   $('#'+namespace+'-profile-form').displayTextMessage({
																								  'text':'Сохранен профиль '+profilename,
																								  'type':'success'
																				   });                                                           
																			},
																			error: function(){
																				   $('#'+namespace+'-profile-dialog').dialog( "close" );
																				   $('#'+namespace+'-profile-form').displayTextMessage({
																								  'text':'Ошибка сохранения профиля',
																								  'type':'error'
																				   });
																			}
																	});

															}	
													});
											}
										});	

							
							}
						return false;
						} );

						$('#'+namespace+'-profile-import').click( function() {
							$('#'+namespace+'-profile-dialog').remove();
							$('body').append('<div id="'+namespace+'-profile-dialog" class="portlet-dialog-form" title="Создание профиля каталога из текста">'+
							'<label class="portlet-form-field-label-nowidth">Введите название профиля:</label><br/><input id="'+namespace+'-profile-dialog-profilename" type="text" value="" class="portlet-form-input-field" style="width:95%; margin:0px auto;"/><br/><br/>'+
							'<label class="portlet-form-field-label-nowidth">Введите список идентификаторов сервисов для добавления в профиль через разделитель ";"</label><br/>'+
							'<textarea id="'+namespace+'-profile-dialog-subs" class="portlet-form-input-field" style="height:250px; width:95%; margin: 0px auto;"></textarea><br/>'+
							'<input id="'+namespace+'-profile-dialog-save" class="portlet-form-button portlet-icon icon-status-success" type="button" value="Сохранить"/><input id="'+namespace+'-profile-dialog-close" class="portlet-form-button portlet-icon icon-status-error" type="button" value="Отменить"/>'+
							'</div>');	
							$('#'+namespace+'-profile-dialog').dialog({
								minHeight: 380,
								minWidth: 550,
								modal: false,
								open: function(event, ui) {
									$('#'+namespace+'-profile-dialog-close').click(function(){
										$('#'+namespace+'-profile-dialog').dialog( "close" );
									});
									$('#'+namespace+'-profile-dialog-save').click(function(){
										var profilename = $('#'+namespace+'-profile-dialog-profilename').val();
										if (profilename == ""){
																	$('#'+namespace+'-profile-dialog div.portlet-msg-error').remove();
																	$('#'+namespace+'-profile-dialog-profilename').after('<div class="portlet-msg-error" style="width:90%;">Введите название профиля</div>');
														}
														else
															if ($('#'+namespace+'-profile-dialog-subs').val().indexOf(';') == -1){
																	$('#'+namespace+'-profile-dialog div.portlet-msg-error').remove();
																	$('#'+namespace+'-profile-dialog-subs').after('<div class="portlet-msg-error" style="width:90%;">Введите список сервисов для занесения в профиль</div>');
															}
															else{
																	$.ajax({
																			  type: 'POST',
																			  url: '/restserver/services/profiles/add.json',
																			  dataType: 'json',
																			  data: {"owner":window.JOSSO_USER,"obj":"GISLAYERS","prop":"layer.id","name":profilename,"ids":$('#'+namespace+'-profile-dialog-subs').val()},
																			  success: function(){
																					$('#'+namespace+'-profile-dialog').dialog( "close" );
																					$('#'+namespace+'-profile-form').displayTextMessage({
																						'text':'Сохранен профиль '+profilename,
																						'type':'success'
																					});
																			  },
																			  error: function(){
																					 $('#'+namespace+'-profile-dialog').dialog( "close" );
																					 $('#'+namespace+'-profile-form').displayTextMessage({
																									'text':'Ошибка сохранения профиля',
																									'type':'error'
																					 });
																			  }
																	});

															}	
									});			
								}
							});	
						});

						$('#'+namespace+'-profile-load').click( function() {
							$('#'+namespace+'-profile-dialog').remove();
							$('body').append('<div id="'+namespace+'-profile-dialog" class="portlet-dialog-form" title="Загрузка профиля каталога">'+
							'<br/><label class="portlet-form-field-label-nowidth">Выберите профиль для загрузки:</label><br/>'+
							'<select id="'+namespace+'-profile-dialog-profileslist" style="height:250px; width:95%; margin: 0px auto; border:1px solid #A6C9E2; background:#fff; overflow:auto;" size="10"><option value="full">Все слои</option></select><br/>'+
							'<input id="'+namespace+'-profile-dialog-load" class="portlet-form-button portlet-icon icon-profile-load" type="button" value="Загрузить"/>'+
								//'<input id="'+namespace+'-profile-dialog-export" class="portlet-form-button portlet-icon icon-export-html" type="button" value="Просмотреть"/>'+
								'<input id="'+namespace+'-profile-dialog-delete" class="portlet-form-button portlet-icon icon-profile-remove" type="button" value="Удалить"/>'+
								'<input id="'+namespace+'-profile-dialog-close" class="portlet-form-button portlet-icon icon-status-error" type="button" value="Отменить"/>'+
							'</div>');


							$('#'+namespace+'-profile-dialog').dialog({
								autoOpen: false,
								minHeight: 380,
								minWidth: 520,
								modal: false
							});	
							$.ajax({
								  type: 'GET',
								  url: '/restserver/services/profiles/list.json',
								  data: {"owner":window.JOSSO_USER,"obj":"GISLAYERS"},
								  success: function(json){
												   if (json == null) {
													   $('#'+namespace+'-profile-form').displayTextMessage({
															'text':'У вас не сохранено ни одного профиля каталога для загрузки',
															'type':'info'
														});
												   }else{
													var userprofiles = [];
													if (json["userProfile"].length > 1)
														userprofiles = json["userProfile"];                    
													else
														userprofiles.push(json["userProfile"]);
													for (var i=0; i<userprofiles.length ;i++)
															$('#'+namespace+'-profile-dialog-profileslist').append('<option value="'+userprofiles[i].profileId+'">[#'+userprofiles[i].profileId+'] '+userprofiles[i].profileName+' (слоев: '+userprofiles[i].cnt +', создано: '+userprofiles[i].dateCreate+')</option>');			

													$('#'+namespace+'-profile-dialog').dialog( "open" );

													$('#'+namespace+'-profile-dialog-close').click(function(){
														$('#'+namespace+'-profile-dialog').dialog( "close" );
													});

													$('#'+namespace+'-profile-dialog-export').click(function(){
														var selected = $('#'+namespace+'-profile-dialog-profileslist').val();
														var win = window.open('/dataview/profileManager?profileId='+selected, '_blank');
														win.focus();                            
													});

													$('#'+namespace+'-profile-dialog-delete').click(function(){
														var selected = $('#'+namespace+'-profile-dialog-profileslist').val();
														if ((selected != "")&&(selected != "undefined")&&(selected != "full")){
															$.ajax({
																	type: 'POST',
																	url: '/restserver/services/profiles/delete/'+selected+'.json',
																	data: {},
																	dataType: 'json',
																	error: function(request, status, err){
																		$('#'+namespace+'-profile-form').displayTextMessage({
																						'text':'Ошибка: '+err,
																						'type':'error'
																		 });                                                                                
																	},
																	success: function(json){
																		$('#'+namespace+'-profile-dialog-profileslist option[value="'+selected+'"]').remove();
																		$('#'+namespace+'-profile-form').displayTextMessage({
																						'text':'Удален профиль [#'+selected+']'+userprofiles[$('#'+namespace+'-profile-dialog-profileslist').prop("selectedIndex")-1].profileName,
																						'type':'success'
																		});
																	}
															});
														}

													});

													$('#'+namespace+'-profile-dialog-load').click(function(){
														var selected = $('#'+namespace+'-profile-dialog-profileslist').val();
															if ((selected != "")&&(selected != "undefined")&&(selected != "full"))
															{
																	$.ajax({
																	  type: 'GET',
																	  url: '/restserver/services/profiles/get/'+selected+'.json',
																	  data: {},
																	  dataType: 'json',                                          
																	  success: function(json){
																			var profileresources = json.userProfileProp;
																			loadedprofile = [];
																			for (var i=0; i<profileresources.length ;i++)
																					loadedprofile.push(profileresources[i].profileValue);
																			checkedarray = [];
																			$('input:checkbox', oTableServices.fnGetNodes()).attr('checked', false);
																			oTableServices.fnDraw();
																			try{ 
																				$('#'+namespace+'-profile-dialog').dialog("close");  
																				$('#'+namespace+'-profile-msg').html('<p class="portlet-msg-status">Загружен профиль [#'+selected+']'+userprofiles[$('#'+namespace+'-profile-dialog-profileslist').prop("selectedIndex")-1].profileName+'</p>');
																				$('#'+namespace+'-profile-form').displayTextMessage({
																					'text':'Загружен профиль [#'+selected+']'+userprofiles[$('#'+namespace+'-profile-dialog-profileslist').prop("selectedIndex")-1].profileName,
																					'type':'success'
																				});
																			}catch(e){
																				$('#'+namespace+'-profile-dialog').dialog("close");
																				$('#'+namespace+'-profile-form').displayTextMessage({
																					'text':'Ошибка загрузки профиля',
																					'type':'error'
																				});
																				console.log(e.message);
																			}
																	  }
																	});
															}
															else if (selected == "full")
															{
																	loadedprofile = [];
																	$('#'+namespace+'-profile-msg').html('');
																	checkedarray = [];
																	$('input:checkbox', oTableServices.fnGetNodes()).attr('checked', false);
																	$('#'+namespace+'-profile-dialog').dialog("close");
																	oTableServices.fnDraw();
																	$('#'+namespace+'-profile-form').displayTextMessage({
																			'text':'Загружен полный каталог слоев',
																			'type':'success'
																	});
															}			
												  });
											  }
								  },
								  dataType: 'json'
							});
						return true;
						});

						$('#'+namespace+'-profile-reset').click( function() {
							loadedprofile = [];
							$('#'+namespace+'-profile-msg').html('');
							checkedarray = [];
							$('input:checkbox', oTableServices.fnGetNodes()).attr('checked', false);
							oTableServices.fnDraw();
						});
						//поиск
						$('#'+namespace+'-searchpanel').data({
							'originalLeft': $('#'+namespace+'-searchpanel').css('left'),
							'origionalTop': $('#'+namespace+'-searchpanel').css('top')
						});
						$('#'+namespace+'-searchcollapse').die().live('click', function(){
							if ($('#'+namespace+'-searchpanel').css('display') == 'none'){
								$('#'+namespace+'-searchpanel').css({
									'left': $('#'+namespace+'-searchpanel').data('originalLeft'),
									'top': $('#'+namespace+'-searchpanel').data('origionalTop')
								});
							}	
							$('#'+namespace+'-searchpanel').slideToggle({duration:200});	
						});
						$('#'+namespace+'-search-close-button').die().live('click', function(){
							$('#'+namespace+'-searchpanel').slideUp({duration:200});	
						});
						var opened_1 = 0;
						$('#'+namespace+'-collapse-search label.icon-search-plus').die().live('click',function() {
							$(this).next('div:hidden').slideDown('fast');
							$(this).removeClass('icon-search-plus').addClass('icon-search-minus');
							if ((opened_1 == 0)&&($(this).attr('name')=='map')){
									opened_1 = 1;
									setTimeout("makeMap('"+namespace+"',-22,85,-90,128);", 300);									
							}
						});
						$('#'+namespace+'-collapse-search label.icon-search-minus').die().live('click',function() {
							$(this).next('div:visible').slideUp('fast');
							$(this).removeClass('icon-search-minus').addClass('icon-search-plus');
						});
						var aoColumns = [
											{"mDataProp": "rubricShort",
													"fnRender": function ( oObj ) {
														if ((oObj.aData["rubric"])&&(oObj.aData["rubricname"]))
															return '<span class="rubriccolumn-show"><span style="display:none;">'+oObj.aData["rubric"].split(",")[0].replace("(","").replace(")","")+'</span> '+oObj.aData["rubricname"].split(",")[0]+'</span>';
														else
															return '<span class="rubriccolumn-noshow" style="display:none;">10</span>';
											}},
											{"mDataProp": "objectTitleFull",
																	 "fnRender": function ( oObj ) {
																		  if (oObj.aData["resourceid"])
																			return '<span class="layerid clickable-resource-metadata" esimo-gis-url="'+oObj.aData["url"]+'" name="'+oObj.aData["resourceid"]+'">'+oObj.aData["objecttitle"]+'</span> (<span>'+oObj.aData["resourceid"]+'</span>)';
																		  else if (oObj.aData["objecttitle"])
																			return oObj.aData["objecttitle"];
																		  else
																			return '';
											}},
											{"bSortable": true, "mDataProp": "statcountText",
											"fnRender": function ( oObj ) {
																	if (oObj.aData["statcount"] >= 0)
																		return (oObj.aData["statcount"]);
																	else
																		return '';
											}},
											{"bSortable": true, "mDataProp": "typeFull",
											"fnRender": function ( oObj ) {
																	if (oObj.aData["geographicobjecttype"] == 'wms'){
																		oObj.aData["geotype"] = 'WMS';
																		return '<div title="WMS" class="portlet-icon-notext icon-map-layer-wms">WMS</div>';
																	}else if (oObj.aData["geographicobjecttype"] == 'rss'){
																		oObj.aData["geotype"] = 'RSS';
																		return '<div title="RSS" class="portlet-icon-notext icon-rss-geo">RSS</div>';
																	}else if (oObj.aData["geographicobjecttype"] == 'arcgis'){
																		oObj.aData["geotype"] = 'ARCGIS';
																		return '<div title="ARCGIS" class="portlet-icon-notext icon-arcgis">ARCGIS</div>';
																	}else
																		return '';
											}},
											{"mDataProp": "datesFull",
											"fnRender": function ( oObj ) {
																   var datebegin = oObj.aData["begindatetime"];
																   if (datebegin.indexOf('YYYY')==-1){
																	   if (oObj.aData["begindatetime"] == oObj.aData["enddatetime"])
																			return ('<div style="text-align:center;">'+oObj.aData["begindatetime"]+'</div>');
																	   else
																			return ('<div style="text-align:center;">'+oObj.aData["begindatetime"] + ' <br/>' + oObj.aData["enddatetime"]+'</div>');
																   }												
																   else if (datebegin.indexOf('DD')>=0)
																	   return '<div style="text-align:center;"><span style="display:none;">0_</span>Обобщенные за месяц многолетние данные</div>';
																   else if (datebegin.indexOf('DD')==-1)
																	   return '<div style="text-align:center;"><span style="display:none;">0_</span>Обобщенные за месяц и сутки многолетние данные</div>';
																   else
																	   return '';
											}},
											{"bSortable": false, "mDataProp": "buttonAdd",
											"fnRender": function ( oObj ) {
												if (oObj.aData["url"]){
													if (oObj.aData["geotype"] == 'WMS'){
														if ((window.JOSSO_USER)&&(window.JOSSO_USER != 'null'))
															return '<div title="Показать/скрыть слои" esimo-resource="'+oObj.aData["resourceid"]+'" esimo-access="'+oObj.aData["accessconstraints"]+'" esimo-gis-url="'+oObj.aData["url"]+'" esimo-gis-type="WMS" class="clickable-service-add portlet-form-button portlet-icon-notext icon-wms-open" type="button"></div>'; 
														else
															return '<div title="Показать/скрыть слои" esimo-resource="'+oObj.aData["resourceid"]+'" esimo-gis-url="'+oObj.aData["url"]+'" esimo-gis-type="WMS" class="clickable-service-add portlet-form-button portlet-icon-notext icon-wms-open" type="button"></div>'; 
													}else
														return '<div title="Добавить слой на карту" esimo-gis-icon="'+oObj.aData["icon"]+'"  esimo-gis-title="'+oObj.aData["objecttitle"]+'" esimo-gis-url="'+oObj.aData["url"]+'" esimo-gis-type="'+oObj.aData["geotype"]+'" class="clickable-'+oObj.aData["geotype"].toLowerCase()+'-add open portlet-form-button portlet-icon-notext icon-plus" type="button"></div>'; 
												}else
													return '';
											}},
											{"bSortable": true, "mDataProp": "statcount", "bSearchable": false, "bVisible": false}
										];
						/*if ((window.JOSSO_USER)&&(window.JOSSO_USER != 'null'))
							aoColumns.push({"bSortable": false, "mDataProp": "checkbox","fnRender": function ( oObj ) {return '<div style="text-align:center;"><input class="check-action" title="Отметить ресурс для действия" name="sub" value="'+oObj.aData["resourceid"]+'" type="checkbox"/><span style="display:none;">'+oObj.aData["serviceurl"]+'</span></div>';}});*/
						var oTableServices = $('#'+namespace+'-catalog-table').dataTable({
								"sAjaxSource": "/dataview/wmscat?type=published",
								"bProcessing": true,
								"fnServerData": function ( sSource, aoData, fnCallback, oSettings ) {
										 oSettings.jqXHR = $.ajax( {
										 "dataType": 'json', 
										 "type": "GET", 
										 "url": sSource, 
										 "data": aoData, 
										 "timeout": 120000,
										 "success": function(json){
													 var json_mod = {'aaData':[]};
													 if (json.length > 1)
														json_mod.aaData = json;
													 else 
														json_mod.aaData.push(json);
													 fnCallback(json_mod);
										 },
										 "error": function(request, status, err) {
												if(status == "error") {
													alert("Нет соединения с сервисом данных");
												}								
												else if(status == "timeout") {
													alert("Время ожидания данных превысило 120 секунд. Отмена запроса.");
												}else alert(status);
											}
										});
								},
								//"sDom": '<"portlet-table-top"rTCpi>t<"portlet-table-bottom"pi>',
								//"sDom": '<"portlet-table-top"rpiT>t<"portlet-table-bottom">',
								"sDom": '<"portlet-table-top"rpi>t<"portlet-table-bottom">',
								"bAutoWidth": false,
								"bSortClasses": false,
								"sPaginationType": "full_numbers",
								"aLengthMenu": [[10,15,30], [10,15,30]],
								"iDisplayLength": 10,
										"sPaginationType": "full_numbers",
								"oLanguage": {
											"sUrl": "/portal-ajax/jquery/lang_nomax.json"
										}
								/*,"oTableTools":  {	
											  "sSwfPath": "/portal-ajax/jquery/copy_cvs_xls.swf",
											  "aButtons": [ { "sExtends":"collection",
																		"sButtonText":"",
																		"aButtons": [
																		{"sExtends": "xls","sButtonText": '<span class="portlet-icon icon-export-xls">Excel</span>' },
																		{"sExtends": "copy", "sButtonText": '<span class="portlet-icon icon-export-clipboard">Буфер обмена</span>'},
																		{"sExtends": "text", "sButtonText": '<span class="portlet-icon icon-export-image">Рисунок</span>',
																				"fnClick": function ( nButton, oConfig, oFlash ) {
																						exportDivToCanvas(''+namespace+'-catalog-table');
																				}
																		},
																		{"sExtends": "text", "sButtonText": '<span class="portlet-icon icon-export-html">HTML</span>',
																				"fnClick": function ( nButton, oConfig, oFlash ) {
																					try{
																						var aData = oTableServices.fnGetColumnData("resourceId");
																						var profileStr = '';
																						for (var i = 0; i<aData.length; i++){
																							if (profileStr.indexOf(aData[i]) == -1)                                                               
																								profileStr += aData[i]+";";      
																						}    
																						profileStr = profileStr.replace(',');
																						$.ajax({
																								type: 'POST',
																								url: '/restserver/services/profiles/add.json',
																								dataType: 'json',
																								data: {"owner":"<%=userName%>","obj":"SRBD","prop":"srbd.id","name":"Экспортированный список ресурсов","ids":profileStr},
																								success: function(json){
																									   var win=window.open('/dataview/profileManager?profileId='+json.profileId, '_blank');
																									   win.focus();                                                           
																								},
																								error: function(){
																									   $('#'+namespace+'-profile-dialog').dialog( "close" );
																									   $('#'+namespace+'-profile-form').displayTextMessage({
																													  'text':'Ошибка экспорта',
																													  'type':'error'
																									   });
																								}
																						});
																				   }catch(e){console.log(e.message);}    
																				}
																		},    
																		{"sExtends": "text", "sButtonText": '<span class="portlet-icon icon-question">Помощь</span>',
																				"fnClick": function ( nButton, oConfig, oFlash ) {
																						$(this).displayTextMessage({
																								'text':'Кнопка CSV осуществляет экспорт текущей страницы в csv-файл. Требуется наличие плагина flash в браузере.<br/>'+
																								'Кнопка Excel осуществляет экспорт текущей страницы в xls-файл. Требуется наличие плагина flash в браузере.<br/>'+
																								'Кнопка Буфер обмена осуществляет экспорт текущей страницы в буфер обмена. Требуется наличие плагина flash в браузере.<br/>'+
																								'Если у вас не установлен плагин flash, <a href="http://get.adobe.com/ru/flashplayer/" target="_blank">вы можете загрузить его по ссылке</a><br/><br/>'+
																								'Кнопка Рисунок осуществляет экспорт текущей страницы в рисунок.<br/>',
																								'type':'help'
																						});
																				}
																		}
																		]
														}]
								},*/
								,"aoColumns": aoColumns,
								"aaSorting":[[0,'asc']],
								"fnDrawCallback": function(oSettings, json) {
									if (loadedprofile.length != 0){
										$('#'+namespace+'-table-wrapper').find('._filtered').css("display", "none");
									} else {
										$('#'+namespace+'-table-wrapper').find('._filtered').css("display", "inline"); 
									}
								  },
								"oColVis": {
									  "fnLabel": function ( index, title, th ) {
										var aNames = ['Наименование','Тип геометрии','Начало/окончание данных','Добавление','Описание','Отметки'];
										return aNames[(index)];
									  }
									},
								"fnDrawCallback": function(oSettings, json) {
									if (Math.ceil((this.fnSettings().fnRecordsDisplay()) / this.fnSettings()._iDisplayLength) <= 1)  {
										$('#'+namespace+'-table-wrapper').find('.dataTables_paginate').css("display", "none"); 
									} else {
										$('#'+namespace+'-table-wrapper').find('.dataTables_paginate').css("display", "block"); 
									}
									if (oTableServices.fnSettings().fnRecordsDisplay()>0){
											 $('#'+namespace+'-date-from, #'+namespace+'-date-to').datepicker({
												dateFormat:'yy-mm-dd',
												changeMonth:true,
												changeYear:true,
												currentText: 'Сейчас',
												closeText: 'Закрыть',
												prevText: '&#x3c;Пред',
												nextText: 'След&#x3e;',
												monthNames: ['Январь','Февраль','Март','Апрель','Май','Июнь',
												'Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'],
												monthNamesShort: ['Янв','Фев','Мар','Апр','Май','Июн',
												'Июл','Авг','Сен','Окт','Ноя','Дек'],
												dayNames: ['воскресенье','понедельник','вторник','среда','четверг','пятница','суббота'],
												dayNamesShort: ['вск','пнд','втр','срд','чтв','птн','сбт'],
												dayNamesMin: ['Вс','Пн','Вт','Ср','Чт','Пт','Сб'],
												weekHeader: 'Не',
												firstDay: 1,
												isRTL: false,
												showMonthAfterYear: false,
												yearSuffix: ''
											 });
											 $('#'+namespace+'-date-from').each( function () {
												   $('#'+namespace+'-date-to').each( function () {
													 try{
															var aData = oTableServices.fnGetColumnData("begindatetime");
															var iLen = aData.length;
															var dateMin = new Date();
															var yearMin = dateMin.getFullYear(); 
															var monthNum = dateMin.getMonth()+1;
															var month = ''+monthNum;
															if (month.length == 1)
																month = '0'+month;
															var day = ''+dateMin.getDate();
															if (day.length == 1)
																day = '0'+day;

															var dateMinStr = yearMin+'-'+month+'-'+day+'T00:00:00';
															try{
																for ( var i=0 ; i<iLen ; i++ ){
																	if((aData[i]!='')&&(aData[i]>'1800-01-01T00:00:00')&&(aData[i].indexOf('Y') == -1)&&(aData[i].indexOf('MM') == -1)&&(aData[i].indexOf('DD') == -1)){
																		var date1 = new Date(parseInt(aData[i].substr(0,4)),parseInt(aData[i].substr(5,2)),parseInt(aData[i].substr(8,2)));
																		var date2 = new Date(parseInt(dateMinStr.substr(0,4)),parseInt(dateMinStr.substr(5,2)),parseInt(dateMinStr.substr(8,2)));
																		if (date1.getTime() < date2.getTime()){
																			dateMinStr = aData[i];
																		}    
																	}    
																}
															}catch(e){console.log(e.message);}    
															yearMin = dateMinStr.substr(0,4);
															var monthMin = 0; 
															if (dateMinStr.substr(5,2) != 'MM')
																monthMin = parseInt(dateMinStr.substr(5,2))-1;
															var dayMin = 0;
															if (dateMinStr.substr(8,2)!='DD')
																dayMin = parseInt(dateMinStr.substr(8,2));

															var dateMax = new Date();
															var yearMax = ''+dateMin.getFullYear(); 

															$('#'+namespace+'-date-from').datepicker( 'option', {yearRange : yearMin+':'+yearMax} );
															$('#'+namespace+'-date-from').datepicker('setDate',new Date(parseInt(yearMin),monthMin,dayMin));

															$('#'+namespace+'-date-to').datepicker( 'option', {yearRange : yearMin+':'+yearMax} );
															$('#'+namespace+'-date-to').datepicker('setDate',dateMax);
													  }catch(e){console.log(e.message);}
												   }); 
											});
											
											
											$('#'+namespace+'-search-geotype').each(function(){
												try{
													var selected = $('#'+namespace+'-search-geotype').val();
													var aData = oTableServices.fnGetColumnData("geotype");
													var selectobject = [];
													for (var i=0; i<aData.length; i++){
														var tmp = aData[i];
														if (aData[i] == 'ln')
															tmp = 'Изолинии';
														else if (aData[i] == 'sf')
															tmp = 'Поверхность';
														selectobject.push({"name":tmp,"value":aData[i]});
													}	

													selectobject.sort(compareobj);
													var selectHtml = '<option value=""></option>';
													for ( var i=0 ; i<aData.length ; i++ ){
														if ((selectobject[i].value!='undefined')&&(selectobject[i].value!=undefined)){
															selectHtml += '<option value="'+selectobject[i].value+'">'+selectobject[i].name+'</option>';
														}    
													}							
													
													$('#'+namespace+'-search-geotype').html(selectHtml);
													if((selected != '')&&(selected != undefined))
														  $('#'+namespace+'-search-geotype').val(selected);
													$('#'+namespace+'-search-geotype').trigger("liszt:updated");
													$('#'+namespace+'-search-geotype-num').html(aData.length);
												}catch(e){
													console.log(e.message);
												}
											});
											   
											$('#'+namespace+'-search-element').each( function () {
												 try{
												  var selected = $('#'+namespace+'-search-element').val();
												  var provobject = [];
												  
												  var aData = [];
												  var paramStr = '';
												  var aDataRaw = oTableServices.fnGetColumnData("element");
												  for (var i=0; i<aDataRaw.length; i++){
													  var tempArray = aDataRaw[i].toLowerCase().split('esimo:').join('').split('e2edm:').join('').split(',');
													  for (var j=0; j<tempArray.length; j++)
														if (tempArray[j][0] != 'm')
														if (aData.indexOf(tempArray[j]) == -1){								
															aData.push(tempArray[j]);
															paramStr += ','+tempArray[j];
														}	
												  }
													$.post(
													"/dataview/getcodes",
													{"codesId":paramStr.replace(',','')},
													function(json){
														for (var i=0 ; i<aData.length; i++ ){
															var name = findCodeById(json,aData[i]).name;
															if ((name== undefined)||(name == ''))
																name = aData[i];
															provobject.push({"name":name,"value":aData[i]});
														}
														provobject.sort(compareobj);
														var html = '<option value=""></option>';
														for ( var i=0 ; i<provobject.length; i++ ){
														  html += '<option value="'+provobject[i].value+'">'+provobject[i].name+'</option>';
														}
														$('#'+namespace+'-search-element').html(html);
														
														if((selected != '')&&(selected != undefined))
														  $('#'+namespace+'-search-element').val(selected);
														$('#'+namespace+'-search-element').trigger("liszt:updated");
														$('#'+namespace+'-search-element-num').html(aData.length);
													},
													'json'
													);						  
												 }catch(e){console.log(e.message);} 
										   });
											
											$('#'+namespace+'-search-provider').each( function () {
													 try{
													  var selected = $('#'+namespace+'-search-provider').val();
													  var provobject = [];
													  var aData = oTableServices.fnGetColumnData("datasourceid");
													  var iLen=aData.length;
													  for ( var i=0 ; i<iLen ; i++ ){
														  provobject.push({"name":getprovider(aData[i]),"value":aData[i]});
													  }
													  provobject.sort(compareobj);
													  var selectProviderHtml = '<option value=""></option>';
													  for ( var i=0 ; i<iLen ; i++ ){
														   selectProviderHtml += '<option value="'+provobject[i].value+'">'+provobject[i].name+'</option>';
													  }
													  this.innerHTML = selectProviderHtml;

													  if((selected != '')&&(selected != undefined))
														  $('#'+namespace+'-search-provider').val(selected);
													  $('#'+namespace+'-search-provider').trigger("liszt:updated");
													  $('#'+namespace+'-search-provider-num').html(aData.length);
													 }catch(e){console.log(e.message);} 
											   });                   
											   $('#'+namespace+'-search-level').each( function () {
													 try{
													  var selected = $('#'+namespace+'-search-level').val();
													  var namesObject = {"observations":"Наблюдения","forecast":"Прогноз","diagnosis":"Диагноз","climate":"Климат","statistic":"Статистика","summary":"Обобщение"};
													  var selectobject = [];
													  var aData = oTableServices.fnGetColumnData("processingleveltype");
													  var iLen=aData.length;
														  for ( var i=0 ; i<iLen ; i++ ){
															  selectobject.push({"name":aData[i],"value":aData[i]});
														  }
														  selectobject.sort(compareobj);
														  var selectHtml = '<option value=""></option>';
														  for ( var i=0 ; i<iLen ; i++ ){
															  if ((selectobject[i].value!='undefined')&&(selectobject[i].value!=undefined)){
																  selectHtml += '<option value="'+selectobject[i].value+'">'+namesObject[selectobject[i].value]+'</option>';
															  }    
														  }
														  this.innerHTML = selectHtml;

														  if((selected != '')&&(selected != undefined))
															  $('#'+namespace+'-search-level').val(selected);
														  $('#'+namespace+'-search-level').trigger("liszt:updated");
														  $('#'+namespace+'-search-level-num').html(iLen-1);
													  }catch(e){console.log(e.message);}    
											   });
								   }
								   $("#"+namespace+"-catalog-table tbody td.tree-rubricdir").die().live('click',function(){
										if ( oSettings._iDisplayLength == -1 ){
											if ($(this).hasClass('icon-tree-open')){
												$(this).removeClass('icon-tree-open').addClass('icon-tree-closed');
												$(this).parent().nextUntil("tr:has(td.tree-rubricdir)").each(function(){
													$(this).slideUp({duration:0});
												});
											}else if ($(this).hasClass('icon-tree-closed')){
												$(this).removeClass('icon-tree-closed').addClass('icon-tree-open');
												$(this).parent().nextUntil("tr:has(td.tree-rubricdir)").each(function(){
													$(this).slideDown({duration:0});
												});
											}
										}
								   });
								   if ( oSettings._iDisplayLength == -1 ){
										$("#"+namespace+"-catalog-table tbody td span.rubriccolumn-show").css('visibility','visible');
										var nTrs = $('#'+namespace+'-catalog-table tbody tr');
										var iColspan = nTrs[0].getElementsByTagName('td').length;
										var sLastGroup = "";
										var groupCount = 0;
										for ( var i=0; i<nTrs.length; i++ ){
											groupCount++;
											var iDisplayIndex = oSettings._iDisplayStart + i;
											var sGroup = oSettings.aoData[oSettings.aiDisplay[iDisplayIndex]]._aData["rubricShort"];
											if ( sGroup != sLastGroup )
											{
												var nGroup = document.createElement( 'tr' );
												var nCell = document.createElement( 'td' );
												nCell.colSpan = iColspan;
												nCell.className = "portlet-icon icon-tree-closed tree-rubricdir";
												nCell.style = "height:32px;padding-left:32px;cursor:pointer;";
												nCell.innerHTML = sGroup.replace('rubriccolumn-show','rubriccolumn-group');
												nCell.setAttribute('esimo-rubric',sGroup.replace('rubriccolumn-show','rubriccolumn-group'));
												nGroup.className = "odd";
												nGroup.appendChild( nCell );
												nTrs[i].parentNode.insertBefore( nGroup, nTrs[i] );
												$("#"+namespace+"-catalog-table tbody td.tree-rubricdir").each(function(){
													if ($(this).attr('esimo-rubric') == sLastGroup.replace('rubriccolumn-show','rubriccolumn-group'))
													if ($(this).html().indexOf('(') == -1)
														$(this).html($(this).html() + ' ('+groupCount+')');
												});
												sLastGroup = sGroup;
												groupCount = 0;
											}
										}
										$("#"+namespace+"-catalog-table tbody td span.rubriccolumn-show").css('visibility','hidden');
										$('#'+namespace+'-catalog-table_paginate').css('visibility','hidden');
										$("#"+namespace+"-catalog-table tbody td span.rubriccolumn-show").parent().parent().slideUp({duration:0});
								   }else{
										$('#'+namespace+'-catalog-table_paginate').css('visibility','visible');
										$("#"+namespace+"-catalog-table tbody td span.rubriccolumn-show").css('visibility','visible');
										$("#"+namespace+"-catalog-table tbody td span.rubriccolumn-show").parent().parent().slideDown({duration:0});
								   }
								},
								"fnInitComplete": function(oSettings, json) {
									$('#'+namespace+'-catalog-table_wrapper .portlet-table-top').first().append('<div class="portlet-font" style="float:left;width:120px;padding-top:7px;padding-left:2px;"><b>Упорядочить по:</b></div>'+
									'<input type="button" class="portlet-form-button clickable-order-date" style="float:left;width:110px;margin-top:5px;" value="оперативности"/>'+
									'<input type="button" class="portlet-form-button clickable-order-stat" style="float:left;width:110px;margin-top:5px;" value="популярности"/>'+
									'<input type="button" class="portlet-form-button clickable-order-rubric" style="float:left;width:70px;margin-top:5px;" value="рубрике"/>');
									//'<input type="button" class="portlet-form-button clickable-order-name" style="float:left;width:80px;margin-top:5px;" value="названию"/>'
									$('#'+namespace+'-catalog-table_wrapper .portlet-table-top input.clickable-order-date').die().live('click',function(){
										oTableServices.fnSort([[4,'desc']]);
										$('#'+namespace+'-catalog-table_wrapper .portlet-form-button-active').removeClass('portlet-form-button-active');
										$(this).addClass('portlet-form-button-active');
									});
									$('#'+namespace+'-catalog-table_wrapper .portlet-table-top input.clickable-order-rubric').die().live('click',function(){
										oTableServices.fnSort([[0,'asc']]);
										$('#'+namespace+'-catalog-table_wrapper .portlet-form-button-active').removeClass('portlet-form-button-active');
										$(this).addClass('portlet-form-button-active');
									});
									$('#'+namespace+'-catalog-table_wrapper .portlet-table-top input.clickable-order-name').die().live('click',function(){
										oTableServices.fnSort([[1,'asc']]);
										$('#'+namespace+'-catalog-table_wrapper .portlet-form-button-active').removeClass('portlet-form-button-active');
										$(this).addClass('portlet-form-button-active');
									});
									$('#'+namespace+'-catalog-table_wrapper .portlet-table-top input.clickable-order-stat').die().live('click',function(){
										oTableServices.fnSort([[2,'desc']]);
										$('#'+namespace+'-catalog-table_wrapper .portlet-form-button-active').removeClass('portlet-form-button-active');
										$(this).addClass('portlet-form-button-active');
									});
									$('th.sorting').die().live('click',function(){
										$('#'+namespace+'-catalog-table_wrapper .portlet-form-button-active').removeClass('portlet-form-button-active');
									});
									$('th.sorting_asc').die().live('click',function(){
										$('#'+namespace+'-catalog-table_wrapper .portlet-form-button-active').removeClass('portlet-form-button-active');
									});
									$('th.sorting_desc').die().live('click',function(){
										$('#'+namespace+'-catalog-table_wrapper .portlet-form-button-active').removeClass('portlet-form-button-active');
									});
								
									$('#'+namespace+'-search-rubric').rubricPicker();
									$('#'+namespace+'-search-geotype').each( function () {
										$(this).attr("multiple","mupltiple");
										$(this).attr("data-placeholder","...");
										$(this).css("width","200px");
										$(this).chosen({no_results_text: "Нет совпадений"});
									});
									$('#'+namespace+'-search-element').each( function () {
										$(this).attr("multiple","mupltiple");
										$(this).attr("data-placeholder","...");
										$(this).css("width","200px");
										$(this).chosen({no_results_text: "Нет совпадений"});
									});
									$('#'+namespace+'-search-level').each( function () {
													$(this).attr("multiple","mupltiple");
													$(this).attr("data-placeholder","...");
													$(this).css("width","200px");
													$(this).chosen({no_results_text: "Нет совпадений"});
									});
									$('#'+namespace+'-search-provider').each( function () {
											$(this).attr("multiple","mupltiple");
											$(this).attr("data-placeholder","...");
											$(this).css("width","200px");
											$(this).chosen({no_results_text: "Нет совпадений"});
									});
									//дерево
									$('#'+namespace+'-catalog-table input.tree-full').die().live('click',function(){
										$(this).removeClass('tree-full').addClass('tree-table').removeClass('icon-tree-closed').addClass('icon-table');
										oTableServices.fnSettings()._iDisplayLength = -1;
										oTableServices.fnSort([[0,'asc']]);
									});
									$('#'+namespace+'-catalog-table input.tree-table').die().live('click',function(){
										$(this).removeClass('tree-table').addClass('tree-full').removeClass('icon-table').addClass('icon-tree-closed');
										oTableServices.fnSettings()._iDisplayLength = 10;
										oTableServices.fnDraw();
									});
								}		
							});
							$('#'+namespace+'-search-button-advanced').click( function() {
								advanced = "true";
								searchParameters = {
									'latmin':'-90',
									'latmax':'90',
									'lonmin':'-180',
									'lonmax':'180',
									'datefrom':'',
									'dateto':'',
									'access':'',
									'provider':'',
									'level':'',
									'text':'',
									'type':'',
									'geotype':'',
									'rubricAdvanced':[''],
									'elementsStr':'',
									'searchGeneralisedDates': true
								};
								searchParameters.text =$('#'+namespace+'-word').val();
								searchParameters.geotype = ''+$('#'+namespace+'-search-geotype').val();
								searchParameters.elementsStr = ''+$('#'+namespace+'-search-element').val();
								searchParameters.rubricAdvanced = $('#'+namespace+'-search-rubric').val().replace(',','').split(')').join('').split(',');
								if ($('#'+namespace+'-collapse-map div').is(':visible')){
									searchParameters.datefrom = $('#'+namespace+'-date-from').val();
									searchParameters.dateto = $('#'+namespace+'-date-to').val();    
									searchParameters.latmin = $('#'+namespace+'-lat-min').val();
									searchParameters.latmax = $('#'+namespace+'-lat-max').val();
									searchParameters.lonmin = $('#'+namespace+'-lon-min').val();
									searchParameters.lonmax = $('#'+namespace+'-lon-max').val();
								}
								if ($('#'+namespace+'-collapse-content div').is(':visible')){
									searchParameters.access = $('#'+namespace+'-search-access').val();
									searchParameters.provider = "";
									searchParameters.provider =  searchParameters.provider + $('#'+namespace+'-search-provider').val();
									searchParameters.level = "";
									searchParameters.level = searchParameters.level + $('#'+namespace+'-search-level').val();
								}
								if ($('#'+namespace+'-search-inresults').prop('checked'))
									foundResources = oTableServices.fnGetColumnData("resourceid");
								else
									foundResources = [];
								//searchParameters.searchGeneralisedDates = $('#'+namespace+'-search-climate').prop('checked');
								searchParametersArray.push(searchParameters);
								if (searchParametersArray.length == 6){
									for (var i = 0; i<searchParametersArray.length-1; i++)
										searchParametersArray[i]=searchParametersArray[i+1];
									searchParametersArray.splice(5,1);
								}
								currentSearchIndex = searchParametersArray.length;
								$('#'+namespace+'-search-navigation').css('display','block');
								$('#'+namespace+'-search-button-previous').css('visibility', 'visible');
								$('#'+namespace+'-search-button-next').css('visibility', 'hidden');
								oTableServices.fnDraw();
								return true;
							});
							$('#'+namespace+'-search-reset-advanced').click( function() {
								advanced = "true";
								document.getElementById(namespace+'-search-form').reset();
								searchParameters = {
									'latmin':'-90',
									'latmax':'90',
									'lonmin':'-180',
									'lonmax':'180',
									'datefrom':'',
									'dateto':'',
									'access':'',
									'provider':'',
									'level':'',
									'text':'',
									'type':'',
									'geotype':'',
									'elementsStr':'',
									'keywordsStr':'',
									'rubricAdvanced':[''],
									'searchGeneralisedDates': true,
									'updatetype':'',
									'updatefrom':'',
									'updateto':'',
									'loaded':''
								}
								$('#'+namespace+'-search-provider').trigger("liszt:updated");
								$('#'+namespace+'-search-level').trigger("liszt:updated");
								$('#'+namespace+'-search-geotype').trigger("liszt:updated");
								$('#'+namespace+'-search-element').trigger("liszt:updated");
								$('#'+namespace+'-search-rubric-rubric-list .search-choice').remove();
								$('#'+namespace+'-search-rubric').change();
								foundResources = [];
								currentSearchIndex = searchParametersArray.length;
								$('#'+namespace+'-search-button-previous').css('visibility', 'visible');
								$('#'+namespace+'-search-button-next').css('visibility', 'hidden');
								oTableServices.fnDraw();
								return false;
							});
							$('#'+namespace+'-search-button-previous').die().live('click',function(){
								if (searchParametersArray.length != 0){
									currentSearchIndex -= 1;
									if (currentSearchIndex == searchParametersArray.length-1)
										currentSearchIndex -=1;
									if (currentSearchIndex <= 0 ){
										currentSearchIndex = 0;  
										$(this).css('visibility', 'hidden');
									} 
									$('#'+namespace+'-search-button-next').css('visibility', 'visible');
									searchParameters = searchParametersArray[currentSearchIndex];
									$('#'+namespace+'-word').val(searchParameters.text);
									$('#'+namespace+'-lat-min').val(searchParameters.latmin);
									$('#'+namespace+'-lat-max').val(searchParameters.latmax);
									$('#'+namespace+'-lon-min').val(searchParameters.lonmin);
									$('#'+namespace+'-lon-max').val(searchParameters.lonmax);
									$('#'+namespace+'-search-access').val('');
									$('#'+namespace+'-search-provider').val('');
									$('#'+namespace+'-search-level').val('');
									$('#'+namespace+'-search-geotype').val('');
									$('#'+namespace+'-search-element').val('');
									$('#'+namespace+'-search-rubric-rubric-list .search-choice').remove();
									$('#'+namespace+'-search-rubric').change();
									$('#'+namespace+'-search-provider').trigger("liszt:updated");
									$('#'+namespace+'-search-level').trigger("liszt:updated");
									$('#'+namespace+'-search-geotype').trigger("liszt:updated");
									$('#'+namespace+'-search-element').trigger("liszt:updated");                                   
									$('#'+namespace+'-search-inresults').attr('checked',false);
									foundResources = [];
									oTableServices.fnDraw();  
							   }     
							});
							$('#'+namespace+'-search-button-next').die().live('click',function(){
								if (searchParametersArray.length != 0){
									currentSearchIndex += 1;
									if (currentSearchIndex >= searchParametersArray.length-1){
										currentSearchIndex = searchParametersArray.length-1;
										$(this).css('visibility', 'hidden');
									}
									$('#'+namespace+'-search-button-previous').css('visibility', 'visible');
									searchParameters = searchParametersArray[currentSearchIndex];
									$('#'+namespace+'-word').val(searchParameters.text);
									$('#'+namespace+'-lat-min').val(searchParameters.latmin);
									$('#'+namespace+'-lat-max').val(searchParameters.latmax);
									$('#'+namespace+'-lon-min').val(searchParameters.lonmin);
									$('#'+namespace+'-lon-max').val(searchParameters.lonmax);
									$('#'+namespace+'-search-access').val('');
									$('#'+namespace+'-search-provider').val('');
									$('#'+namespace+'-search-level').val('');
									$('#'+namespace+'-search-geotype').val('');
									$('#'+namespace+'-search-element').val('');
									$('#'+namespace+'-search-rubric-rubric-list .search-choice').remove();
									$('#'+namespace+'-search-rubric').change();
									$('#'+namespace+'-search-keywordsadvanced').trigger("liszt:updated");
									$('#'+namespace+'-search-provider').trigger("liszt:updated");
									$('#'+namespace+'-search-level').trigger("liszt:updated");
									$('#'+namespace+'-search-geotype').trigger("liszt:updated");
									$('#'+namespace+'-search-element').trigger("liszt:updated");                                   
									$('#'+namespace+'-search-inresults').attr('checked',false);
									foundResources = [];
									oTableServices.fnDraw();  
								}  
							});
							$.fn.dataTableExt.afnFiltering.push(
							function( oSettings, aData, iDataIndex ) {
								if (oSettings.sAjaxSource != '/dataview/wmscat?type=published')
									return true;
								else 
									try{
												var alonmin = oTableServices.fnGetData(iDataIndex)["westboundlongitude"];
												var alonmax = oTableServices.fnGetData(iDataIndex)["eastboundlongitude"];
												var alatmin = oTableServices.fnGetData(iDataIndex)["southboundlatitude"];
												var alatmax = oTableServices.fnGetData(iDataIndex)["northboundlatitude"];
												var ageotype = oTableServices.fnGetData(iDataIndex)["geotype"];
												var aelements = oTableServices.fnGetData(iDataIndex)["element"];
												var arubric = oTableServices.fnGetData(iDataIndex)["rubric"];
												var title = oTableServices.fnGetData(iDataIndex)["objecttitle"];
												var systemid = oTableServices.fnGetData(iDataIndex)["resourceid"];
												var lock = oTableServices.fnGetData(iDataIndex)["accessconstraints"];
												var alevel = oTableServices.fnGetData(iDataIndex)["processingleveltype"];
												var adateupdate = oTableServices.fnGetData(iDataIndex)["revisionDate"];
												var adatecreate = oTableServices.fnGetData(iDataIndex)["creationDate"];
												if (alevel == null)
													alevel = "";
												else
													alevel = alevel.toLowerCase();
												var aprovider = oTableServices.fnGetData(iDataIndex)["datasourceid"];
												if (aprovider == "")
													aprovider = oTableServices.fnGetData(iDataIndex)["datasourcename"];
												if (aprovider == null)
													aprovider = "";
												else
													aprovider = aprovider.toLowerCase();  
												var datebegin = oTableServices.fnGetData(iDataIndex)["begindatetime"];
												var dateend = oTableServices.fnGetData(iDataIndex)["enddatetime"];
												var latmin = searchParameters.latmin;
												var latmax = searchParameters.latmax;
												var lonmin = searchParameters.lonmin;
												var lonmax = searchParameters.lonmax;
												var datefrom = searchParameters.datefrom;
												var dateto = searchParameters.dateto;
												var access = searchParameters.access;
												var provider = searchParameters.provider.toLowerCase();
												var level = searchParameters.level;
												var text = searchParameters.text;
												var elementsStr = searchParameters.elementsStr;
												var geotypeStr = searchParameters.geotype;
												var checkprovider = false;
												
												if (!(aprovider))
													checkprovider = true;
												else if (aprovider)
													if ((provider.indexOf(aprovider)>=0)||(provider=="null")||(provider=="")||(provider==","))
														checkprovider = true;
												var checklevel = false;
												if ((level.indexOf(alevel)>=0)||(level=="null")||(level=="")||(level==","))
													checklevel = true;
												var checkword = false;
												if (text == ''){
													checkword = true;
												}    
												else if (text.indexOf(',')>=0){
													var words = text.split(",");
													var i = 0;
													while ((i<words.length)&&(checkword==false)){
														var word = words[i].toLowerCase();
														if (word!='')
														if ((title.toLowerCase().indexOf(word) >= 0)||(systemid.toLowerCase().indexOf(word) >= 0)) 
															checkword = true;
														i=i+1;                            
													}
												}
												else {
													var word = text.toLowerCase();
													if ((title.toLowerCase().indexOf(word) >= 0)||(systemid.toLowerCase().indexOf(word) >= 0))
														checkword = true;
												}
												var inprofile = true;
												if (inprofile == true)
												if (loadedprofile.length != 0)
														if (loadedprofile.indexOf(systemid) == -1)
																inprofile = false;
												var checkgeotype = true;
												if ((geotypeStr!='')&&(geotypeStr!='null')){
													checkgeotype = false;
													var geotypes = geotypeStr.split(",");
													for (var i=0; i<geotypes.length; i++)
														if (geotypes[i] != '')
														if (ageotype != undefined)
														if (ageotype.toLowerCase().indexOf(geotypes[i].toLowerCase()) != -1){
															checkgeotype = true; 
															break;
														}
												}
												var checkelement = true;
												if ((elementsStr!='')&&(elementsStr!='null')){
													checkelement = false;
													var elements = elementsStr.split(",");
													for (var i=0; i<elements.length; i++)
														if (elements[i] != '')
														if (aelements != null)
														if (aelements.toLowerCase().indexOf(elements[i].toLowerCase())>=0){
															checkelement = true; 
															break;
														}
												}
												var checkrubric = true;
												if (searchParameters.rubricAdvanced[0]!=''){
													checkrubric = false;
													for (var i = 0;i<searchParameters.rubricAdvanced.length;i++)
														if (arubric.indexOf(searchParameters.rubricAdvanced[i])>=0){
															checkrubric = true; break;
														}
												}																					
												var inresults = true;
												if (foundResources.length != 0)
														if (foundResources.indexOf(systemid) == -1)
																inresults = false;
												var allowed = true;
												if ((access)&&(lock != access))
													allowed = false;
												
												if (inprofile)
												if (inresults)
												if (checkrubric)
												if (checkgeotype)
												if (checkelement)
												if (checkprovider)
												if (checkword)
												if (checklevel)
												if (allowed)
												if (((datebegin.indexOf('YYYY')>=0)&&(searchParameters.searchGeneralisedDates))||((datefrom <= datebegin)&&(dateto == ""))||((datebegin <= dateto)&&(datefrom == ""))||((datefrom <= datebegin)&&(datebegin <= dateto)))                                    
												if ((latmin=='-90')&&(latmax=='90')&&(lonmin=='-180')&&(lonmax=='180'))
													return true;                        
												else if ((latmin<=alatmin)&&(alatmax<=latmax)&&(lonmin<=alonmin)&&(alonmax<=lonmax))
													return true;
									}catch(e){
										//console.log(e.message);
										return true;
									}
								return false;
							}
						);
							
							//добавление
							//rss
							$('div.clickable-rss-add').die().live('click', function(){
								try{
									var layer = $(this).attr('esimo-gis-url');
									var title = $(this).attr('esimo-gis-title');
									var icon = $(this).attr('esimo-gis-icon');
									if (icon == 'undefined')
										icon = 'script/images/marker-red.png';
									var url = '/dataview/mapproxy?url='+$(this).attr('esimo-gis-url');
									if ((layer)&&(url)){
										var source = app.layerSources['rss'];
										if (!source)
											source = new gxp.plugins.RssSource();
										var config = {
											url: url,
											title: title,
											name: layer,
											icon: icon
										};
										var record = source.createLayerRecord(config);
										var rssStore = source.getLayersStore();
										record.get("layer").setOpacity(1);
										record.get("layer").setVisibility(true);
										rssStore.add([record]);														
										app.mapPanel.layers.add([record]);
									}
								}catch(e){console.log(e.message);}
							});
							//arcgis
							$('div.clickable-arcgis-add').die().live('click', function(){
								try{
									var source = app.layerSources['arcgis93']; 
									if (!source)
										source = new gxp.plugins.ArcGIS93Source();
									var id = $(this).attr('esimo-gis-url');
									var title = $(this).attr('esimo-gis-title');
									var url = $(this).attr('esimo-gis-url');
									var layerStore = app.mapPanel.layers;

									var layer = source.createLayer(title, url);
									layer.setOpacity(1);
									layer.setVisibility(true);
									record = source.createRecord(id, layer);
									if (record)
										layerStore.add([record]);
								}catch(e){console.log(e.message);}
							});
							//wms
							$('div.clickable-service-add.icon-wms-open').die().live('click', function(){
								try{
									if ($(this).attr('esimo-gis-type').toLowerCase()=='wms'){
										$(this).removeClass('icon-wms-open').addClass('icon-wms-close');
										var url = $(this).attr('esimo-gis-url');
										var type = $(this).attr('esimo-gis-type');
										var access = $(this).attr('esimo-access');
										var resourceid = $(this).attr('esimo-resource');
										if (url)
										if (type.toLowerCase() == 'wms'){
											var wmsurl = url;
											var capabilities = "";
											try{
												if (wmsurl.toLowerCase().indexOf('request=getcapabilities') == -1){
													if(wmsurl.indexOf('?')>0)
														capabilities = '&request=getcapabilities';
													else
														capabilities = '?request=getcapabilities';
												}					
											}catch(e){console.log(e.message);}
											
											if ((wmsurl.indexOf('gptl.ru') >= 0)||(wmsurl.indexOf('ifremer.fr') >= 0)){
													wmsurl = wmsurl.replace('?','&');
													wmsurl = '/dataview/xmltojson?xmlurl='+wmsurl+capabilities;
											}else if (access == 'confidential')
												wmsurl = PROXY_URL.replace('&amp;','&')+'&convertjson=true&urltoproxify='+wmsurl+capabilities;//'/restserver/services/resources/convert.json?url='+wmsurl+capabilities;
											else{
												wmsurl = '/restserver/services/c/convert.json?url='+wmsurl+capabilities;
											}
											var nTr = this.parentNode.parentNode;
											var id = 'id'+(new Date()).getTime();
											var sOut = '<div id="'+id+'" style="width:90%;margin:0 auto;" ></div>';
											oTableServices.fnOpen( nTr, sOut, 'details' );
											$('#'+id).append('<div class="portlet-font portlet-icon icon-loading-bar-small" style="width:100px;height:15px;margin:0 auto;">Загрузка слоев</div>');
											$.ajax({
												  type: 'GET',
												  url: wmsurl,
												  async: true,
												  dataType: 'json',
												  timeout: 120000,
												  error: function(e){
														if (e.status == '403'){
															if ((window.JOSSO_USER)&&(window.JOSSO_USER != 'null')){
																$('#'+id).html('<p class="portlet-msg-error icon-locked">У вас нет разрешения на использование этих данных'+
																' <input id="'+id+'-role-order-button" class="portlet-form-button portlet-icon icon-request-accept clickable-roleorder" name="'+window.JOSSO_USER+'" value="Подать заявку" style="width:200px;" type="button">'+
																'</p>');
															}else{
																$('#'+id).html('<p class="portlet-msg-error icon-locked">Сервис доступен только для зарегистрированных пользователей, у которых есть разрешение на его использование.</p>');
															}
														}else if (e.status == '0'){
																$('#'+id).html('<p class="portlet-msg-error icon-locked">Ошибка загрузки слоев</p>');
																console.log(wmsurl);
														}else{
															$('#'+id).html('<p class="portlet-msg-error">Ошибка загрузки слоев</p>');
															console.log(wmsurl);
														}
												  },
												  success: function(jsoncapabilities){
														if (jsoncapabilities.errorcode == '403')
															$('#'+id).html('<p class="portlet-msg-error icon-locked">У вас нет разрешения на использование этих данных'+
																' <input id="'+id+'-role-order-button" class="portlet-form-button portlet-icon icon-request-accept clickable-roleorder" esimo-resource="'+resourceid+'" name="'+window.JOSSO_USER+'" value="Подать заявку" style="width:200px;" type="button">'+
																'</p>');
														else
															try{
																$('#'+id).html('<table id="'+id+'-layertable" class="display" ><thead><th>Название слоя</th><th style="width:18px;"></th><th style="width:18px;"></th></thead><tbody></tbody></table><br/>');
																var layersArray = jsoncapabilities.Capability.Layer.Layer;
																if (layersArray.length == undefined)
																	layersArray = [layersArray];
																var aoData = [];
																for (var i=0; i<layersArray.length;i++){
																	var boundingBox = "";
																	try{
																		try{
																		for (var b=0; b<layersArray[i].BoundingBox.length;b++)
																			if (layersArray[i].BoundingBox[b]['@CRS']){
																				if (layersArray[i].BoundingBox[b]['@CRS'].toUpperCase() == 'EPSG:4326')
																					boundingBox = layersArray[i].BoundingBox[b]['@miny']+','+layersArray[i].BoundingBox[b]['@minx']+','+layersArray[i].BoundingBox[b]['@maxx']+','+layersArray[i].BoundingBox[b]['@maxy'];																				
																			}else if (layersArray[i].BoundingBox[b]['@SRS'])		
																				if (layersArray[i].BoundingBox[b]['@SRS'].toUpperCase() == 'EPSG:4326')
																					boundingBox = layersArray[i].BoundingBox[b]['@miny']+','+layersArray[i].BoundingBox[b]['@minx']+','+layersArray[i].BoundingBox[b]['@maxx']+','+layersArray[i].BoundingBox[b]['@maxy'];																				
																		}catch(e){console.log(e.message);}
																		if (boundingBox == '')																		
																			if (layersArray[i].LatLonBoundingBox) 
																				boundingBox = layersArray[i].LatLonBoundingBox['@miny']+','+layersArray[i].LatLonBoundingBox['@minx']+','+layersArray[i].LatLonBoundingBox['@maxx']+','+layersArray[i].LatLonBoundingBox['@maxy'];;
																	}catch(e){
																		console.log(e.message);
																	}
																	var layername = layersArray[i].Name;
																	if ((!(layername))&&(layersArray[i].Layer)){
																		layername = '';
																		for (var l=0; l<layersArray[i].Layer.length; l++){
																			layername = layersArray[i].Layer[l].Name;
																			if(layername)
																				aoData.push({'title':layersArray[i].Title+' '+layersArray[i].Layer[l].Title,'layer':layername, 'id':l, 'bbox':boundingBox});
																		}
																	}
																	else{
																		if (!(layersArray[i].Title))
																			layersArray[i].Title = layersArray[i].Name;
																		aoData.push({'title':layersArray[i].Title,'layer':layername, 'id':i, 'bbox':boundingBox});
																	}
																}
																$('#'+id+'-layertable').dataTable({
																	"aaData": aoData,
																	'sDom':'pifrt',
																	"sPaginationType": "full_numbers",
																	"oLanguage": {
																		"sUrl": "/portal-ajax/jquery/lang.json"
																	},
																	"aoColumns": [
																		{"bSortable": true, "mDataProp": "titleCleaned",
																		"fnRender": function ( oObj ) {
																			if (oObj.aData["title"])
																				return oObj.aData["title"].split(',,,').join(',').split(',,').join(',');
																			else
																				return oObj.aData["layer"];
																		}},
																		{"bSortable": false, "mDataProp": "buttonPreviewLayer",
																		"fnRender": function ( oObj ) {
																			if (oObj.aData["layer"]){
																				return '<div title="Предпросмотр слоя" class="portlet-form-button portlet-icon-notext icon-map clickable-preview" style="margin:0 auto;" esimo-wmsurl="'+url+'" esimo-layer="'+oObj.aData["layer"]+'" esimo-bbox="'+oObj.aData["bbox"]+'"></div>'; ; 
																			}else
																				return '';
																		}},
																		{"bSortable": false, "mDataProp": "buttonAddLayer",
																		"fnRender": function ( oObj ) {
																			if (oObj.aData["layer"]){
																				return '<div title="Добавить слой на карту" esimo-gis-url="'+url+'" esimo-gis-layer="'+oObj.aData["layer"]+'" esimo-gis-type="WMS" class="clickable-layer-add open portlet-form-button portlet-icon-notext icon-plus" type="button"></div>'; 
																			}else
																				return '';
																		}}
																	]
																});
															}catch(e){
																console.log(e.message);
																console.log(jsoncapabilities);
																$('#'+id).html('<p class="portlet-msg-error">Ошибка чтения списка слоев</p>');
															}
												  }
											});	
										}
									}
								}catch(e){
									console.log(e.message);
								}
							});
							$('div.clickable-service-add.icon-wms-close').die().live('click', function(){
								$(this).removeClass('icon-wms-close').addClass('icon-wms-open');
								var nTr = this.parentNode.parentNode;
								oTableServices.fnClose(nTr);
							});
							$('div.clickable-layer-add').die().live('click', function(){
								var layer = $(this).attr('esimo-gis-layer');
								var url = $(this).attr('esimo-gis-url');
								if ((layer)&&(url)){
									var sourceId = url;
									if (!app.layerSources[sourceId]){
										var conf = {
											url: url, 
											//restUrl: url,
											title: layer,
											version: '1.1.1'//'1.3.0'
										};
										app.addLayerSource({                
											id : sourceId,
											config: conf,
											callback: function(id) {
												var addLayersPlugin = app.tools.gxp_addlayers_ctl;
												var name = layer;
												var records = [];											
												app.layerSources[sourceId].store.each(function(record, index) {
													if (record.get("name") == name) {
														record.data.title = isAlreadyInUse(record.get('title'));
														records.push(record);
													}
												});
												console.log('records 1');
												console.log(records);
												if (records.length==0) {
													console.log('error adding layer');
												}
												else 
													addLayersPlugin.addLayers(records,app.layerSources[sourceId],false);												
											},
											fallback: function(source, msg) {
												console.log('error adding layer: '+msg);													
											},
											scope: this
										});
									}else{
										var addLayersPlugin = app.tools.gxp_addlayers_ctl;
										var name = layer;
										var records = [];											
										app.layerSources[sourceId].store.each(function(record, index) {
											if (record.get("name") == name) {
												record.data.title = isAlreadyInUse(record.get('title'));
												records.push(record);
											}
										});
										console.log('records 2');
										console.log(records);
										if (records.length==0) {
											console.log('error adding layer');
										}
										else 
											addLayersPlugin.addLayers(records,app.layerSources[sourceId],false);
									}
								}									
							});						
					  }
					});
				}
			});
		//wmscat end
		
    }

});

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