var globalDangerArr = ['RU_RNDMC_116'];
var globalStationArr = ['RU_RIHMI-WDC_2665','RU_RIHMI-WDC_2666','RU_RIHMI-WDC_2667',"RU_RIHMI-WDC_1293","RU_RIHMI-WDC_2665","RU_RIHMI-WDC_2666","RU_RIHMI-WDC_2667","RU_RIHMI-WDC_1170","RU_RIHMI-WDC_1242","RU_RIHMI-WDC_1325","RU_RIHMI-WDC_1329","RU_RIHMI-WDC_2663","RU_RIHMI-WDC_2658","RU_RIHMI-WDC_2660","RU_RIHMI-WDC_2655","RU_RIHMI-WDC_2656"];

function loadUserLayersToSelect(user, selectid){
	$.ajax({
			  type: 'GET',
			  url: '/restserver/services/requests/list.json',
			  data: {'obj':'gis.userlayers','owner':user},
			  success: function(json){
					var serviceArray = [];
					if (json.description.length > 1)
						serviceArray = json.description;                    
					else
						serviceArray.push(json.description);
					$('#'+selectid).html('');
					for (var i=0; i< serviceArray.length; i++)
						$('#'+selectid).append('<option value="'+serviceArray[i].profileNameEn.split('||')[0]+'||'+serviceArray[i].profileId+'">'+serviceArray[i].profileName+' (тип: '+serviceArray[i].profileNameEn.split('||')[1]+', добавлен: '+serviceArray[i].dateCreate+')</option>');
			  },
			  error: function(jqXHR, textStatus, errorThrown){
					alert(textStatus);
			  },
			  dataType: 'json'
			});
}

function sortByKey(array, key) {
    return array.sort(function(a, b) {
        var x = a[key]; var y = b[key];
        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
    });
}
 
 var globalMapObject = {};
 
 function popup(feature){
	alert(feature.type);
 }

function getWMS(resource){
if (resource=="eko")
//return ({wmsurl:"10.20.135.51:8081/eko?",wmsname:"eko_merge"});
return ({wmsurl:"http://gis.esimo.ru/cache/service/wms?",wmsname:"eko_merge"});
//return ({wmsurl:"http://vmap0.tiles.osgeo.org/wms/vmap0?",wmsname:"basic"});
}

function getCoords(area){
if (area=="world")
return (new OpenLayers.Bounds (-180,-90,180,90));
else if (area=="russia")
return (new OpenLayers.Bounds (27.00,-6.15,179.63,89.30));
else if (area=="yenisei")
return (new OpenLayers.Bounds (54.00,50.00,117.00,75.00));
else if ((area=="azov")||(area=="[Азовское море]"))
return (new OpenLayers.Bounds(34,44,39,47));
else if ((area=="balt")||(area=="[Балтийское море]"))
return (new OpenLayers.Bounds (12,53,29,64));
else if ((area=="barents")||(area=="[Баренцево море]"))
return (new OpenLayers.Bounds (23,67,44,83));
else if ((area=="white")||(area=="[Белое море]"))
return (new OpenLayers.Bounds (31,62,44,68));
else if ((area=="bering")||(area=="[Берингово море]"))
return (new OpenLayers.Bounds (160,50,179,63));
else if ((area=="eastsib")||(area=="[Восточно-Сибирское море]"))
return (new OpenLayers.Bounds (140,67,179,77));
else if ((area=="casp")||(area=="[Каспийское море]"))
return (new OpenLayers.Bounds (44,35,58,48));
else if ((area=="kara")||(area=="[Карское море]"))
return (new OpenLayers.Bounds (54,71,99,82));
else if ((area=="lapt")||(area=="[Море Лаптевых]"))
return (new OpenLayers.Bounds (104,69,144,82));
else if ((area=="okhot")||(area=="[Охотское море]"))
return (new OpenLayers.Bounds (138,49,158,59));
else if ((area=="black")||(area=="[Черное море]"))
return (new OpenLayers.Bounds (31,42,42,50));
else if ((area=="chuk")||(area=="[Чукотское море]"))
return (new OpenLayers.Bounds (-179,66,-157,76));
else if ((area=="japan")||(area=="[Японское море]"))
return (new OpenLayers.Bounds (126,32,144,51));
else if (area=="northwest")
return (new OpenLayers.Bounds (-1,54,74,72));
else if (area=="northnorthwest")
return (new OpenLayers.Bounds (32,64,64,72));
else if (area=="east")
return (new OpenLayers.Bounds (97,36,177,65));
else if ((area=="amur"))
return (new OpenLayers.Bounds(129,42,145,55));
else if ((area=="arctic"))
return (new OpenLayers.Bounds(28,67,180,82));
else if ((area=="port-kgd"))
return (new OpenLayers.Bounds(20.054,54.755,20.854,54.979));
else if ((area=="port-spb"))
return (new OpenLayers.Bounds(29.519,59.879,31.116,60.266));
else if ((area=="port-murm"))
return (new OpenLayers.Bounds(32.731,68.969,33.611,69.070));
else if ((area=="port-arh"))
return (new OpenLayers.Bounds(40.127,64.611,40.928,64.776));
else if ((area=="port-gel"))
return (new OpenLayers.Bounds(37.979,44.726,38.179,44.795));
else if ((area=="port-novoross"))
return (new OpenLayers.Bounds(37.638,44.824,38.039,44.961));
else if ((area=="port-mgd"))
return (new OpenLayers.Bounds(150.599,59.686,150.999,59.784));
else if ((area=="port-petrkam"))
return (new OpenLayers.Bounds(158.333,53.059,159.134,53.292));
else if ((area=="port-kors"))
return (new OpenLayers.Bounds(142.608,46.769,143.007,46.902));
else if ((area=="port-vlad"))
return (new OpenLayers.Bounds(131.645,43.206,132.445,43.489));
else if ((area=="port-astr"))
return (new OpenLayers.Bounds(47.474,46.219,49.074,46.755));
else if ((area=="ocean-atlantic"))
return (new OpenLayers.Bounds(-77,-33,15,51));
else if ((area=="ocean-pacific"))
return (new OpenLayers.Bounds(123,-10,-123,66));
else if ((area=="ocean-indian"))
return (new OpenLayers.Bounds(22.395,-57.164,102.02,23.19));
else if ((area=="cfo"))
return (new OpenLayers.Bounds(20,50,65,60));
else 
return (new OpenLayers.Bounds (-180,-90,180,90));
}

function getGeometry(area){
if (area=="azov")
return (new OpenLayers.Geometry.Polygon(new OpenLayers.Geometry.LinearRing(
													[
													new OpenLayers.Geometry.Point(33,48),
													new OpenLayers.Geometry.Point(40,48),
													new OpenLayers.Geometry.Point(40,44),
													new OpenLayers.Geometry.Point(33,44)
													]
													)));
if (area=="balt")
return (new OpenLayers.Geometry.Polygon(new OpenLayers.Geometry.LinearRing(
													[
													new OpenLayers.Geometry.Point(12,64),
													new OpenLayers.Geometry.Point(29,64),
													new OpenLayers.Geometry.Point(29,53),
													new OpenLayers.Geometry.Point(12,53)
													]
													)));
if (area=="barents")
return (new OpenLayers.Geometry.Polygon(new OpenLayers.Geometry.LinearRing(
													[
													new OpenLayers.Geometry.Point(23,83),
													new OpenLayers.Geometry.Point(44,83),
													new OpenLayers.Geometry.Point(44,67),
													new OpenLayers.Geometry.Point(23,67)
													]
													)));
if (area=="white")
return (new OpenLayers.Geometry.Polygon(new OpenLayers.Geometry.LinearRing(
													[
													new OpenLayers.Geometry.Point(31,68),
													new OpenLayers.Geometry.Point(44,68),
													new OpenLayers.Geometry.Point(44,62),
													new OpenLayers.Geometry.Point(31,62)
													]
													)));
if (area=="bering")
return (new OpenLayers.Geometry.Polygon(new OpenLayers.Geometry.LinearRing(
													[
													new OpenLayers.Geometry.Point(160,63),
													new OpenLayers.Geometry.Point(179,63),
													new OpenLayers.Geometry.Point(179,50),
													new OpenLayers.Geometry.Point(160,50)
													]
													)));
if (area=="eastsib")
return (new OpenLayers.Geometry.Polygon(new OpenLayers.Geometry.LinearRing(
													[
													new OpenLayers.Geometry.Point(140,77),
													new OpenLayers.Geometry.Point(179,77),
													new OpenLayers.Geometry.Point(179,67),
													new OpenLayers.Geometry.Point(140,67)
													]
													)));
if (area=="casp")
return (new OpenLayers.Geometry.Polygon(new OpenLayers.Geometry.LinearRing(
													[
													new OpenLayers.Geometry.Point(44,48),
													new OpenLayers.Geometry.Point(58,48),
													new OpenLayers.Geometry.Point(58,35),
													new OpenLayers.Geometry.Point(44,35)
													]
													)));
if (area=="kara")
return (new OpenLayers.Geometry.Polygon(new OpenLayers.Geometry.LinearRing(
													[
													new OpenLayers.Geometry.Point(54,82),
													new OpenLayers.Geometry.Point(99,82),
													new OpenLayers.Geometry.Point(99,71),
													new OpenLayers.Geometry.Point(54,71)
													]
													)));
if (area=="lapt")
return (new OpenLayers.Geometry.Polygon(new OpenLayers.Geometry.LinearRing(
													[
													new OpenLayers.Geometry.Point(104,82),
													new OpenLayers.Geometry.Point(144,82),
													new OpenLayers.Geometry.Point(144,69),
													new OpenLayers.Geometry.Point(104,69)
													]
													)));
if (area=="okhot")
return (new OpenLayers.Geometry.Polygon(new OpenLayers.Geometry.LinearRing(
													[
													new OpenLayers.Geometry.Point(138,59),
													new OpenLayers.Geometry.Point(158,59),
													new OpenLayers.Geometry.Point(158,49),
													new OpenLayers.Geometry.Point(138,49)
													]
													)));
if (area=="black")
return (new OpenLayers.Geometry.Polygon(new OpenLayers.Geometry.LinearRing(
													[
													new OpenLayers.Geometry.Point(28,47),
													new OpenLayers.Geometry.Point(41,47),
													new OpenLayers.Geometry.Point(41,40),
													new OpenLayers.Geometry.Point(28,40)
													]
													)));
if (area=="chuk")
return (new OpenLayers.Geometry.Polygon(new OpenLayers.Geometry.LinearRing(
													[
													new OpenLayers.Geometry.Point(-179,76),
													new OpenLayers.Geometry.Point(-157,76),
													new OpenLayers.Geometry.Point(-157,66),
													new OpenLayers.Geometry.Point(-179,66)
													]
													)));
if (area=="japan")
return (new OpenLayers.Geometry.Polygon(new OpenLayers.Geometry.LinearRing(
													[
													new OpenLayers.Geometry.Point(126,51),
													new OpenLayers.Geometry.Point(144,51),
													new OpenLayers.Geometry.Point(144,32),
													new OpenLayers.Geometry.Point(126,32)
													]
													)));													
else
return ("");
}

function getControlsMin(map, namespace){
var select_extent = new OpenLayers.Control();
select_extent.displayClass = "olControlSelectExtentBox";
select_extent.autoActivate = true;

OpenLayers.Util.extend(select_extent, {                                                           
                    draw: function () {
                        this.box = new OpenLayers.Handler.Box( select_extent,
                            {"done": this.notice}
							);
                        this.box.activate();
                    },
					notice: function (bounds) {
                        var ll = map.getLonLatFromPixel(new OpenLayers.Pixel(bounds.left, bounds.bottom));
                        var ur = map.getLonLatFromPixel(new OpenLayers.Pixel(bounds.right, bounds.top));
                        
						var latmin = ll.lat.toFixed(2);
						if (latmin == 'NaN')
							latmin = '-90';
						var lonmax = ur.lon.toFixed(2);
						if (lonmax == 'NaN')
							lonmax = '180';
						var latmax = ur.lat.toFixed(2);
						if (latmax == 'NaN')
							latmax = '90';
						var lonmin = ll.lon.toFixed(2);
						if (lonmin == 'NaN')
							lonmin = '-180';
                        document.getElementById(namespace+"-lat-min").value = latmin;
                        document.getElementById(namespace+"-lon-max").value = lonmax;
                        document.getElementById(namespace+"-lat-max").value = latmax;
                        document.getElementById(namespace+"-lon-min").value = lonmin;
						
						map.layers[1].removeAllFeatures();						
						var box = new OpenLayers.Geometry.LinearRing([new OpenLayers.Geometry.Point(ur.lon, ll.lat),
																new OpenLayers.Geometry.Point(ur.lon, ur.lat),
																new OpenLayers.Geometry.Point(ll.lon, ur.lat),
																new OpenLayers.Geometry.Point(ll.lon, ll.lat)]);
						var feature_box = new OpenLayers.Feature.Vector(box);
						map.layers[1].addFeatures([feature_box]);
                    }
					});

 return ([
 select_extent,
 new OpenLayers.Control.Navigation(/*{dragPanOptions: {enableKinetic: true}}*/), 
 new OpenLayers.Control.ZoomBox({alwaysZoom:true}),
 new OpenLayers.Control.ZoomIn(),
 new OpenLayers.Control.ZoomOut(),
 new OpenLayers.Control.ZoomToMaxExtent(),
 new OpenLayers.Control()
 ]);
}

function getControlsView(){
 return ([
 new OpenLayers.Control.Navigation({title:'Навигация. Зажмите левую кнопку мыши на карте для передвижения. Используйте колесико мыши для изменения масштаба'}), 
 //new OpenLayers.Control.ZoomBox({title:'Увеличить масштаб выбранного района на карте',alwaysZoom:true}),
 new OpenLayers.Control.ZoomIn({title:'Увеличить масштаб'}),
 new OpenLayers.Control.ZoomOut({title:'Уменьшить масштаб'}),
 new OpenLayers.Control.ZoomToMaxExtent({title:'Перейти к минимальному масштабу'}),
 new OpenLayers.Control()
 ]);
}

function getControlsFull(namespace){
 return ([
 new OpenLayers.Control.Navigation({title:'Навигация. Зажмите левую кнопку мыши на карте для передвижения. Используйте колесико мыши для изменения масштаба'}),
 //new OpenLayers.Control.ZoomBox({alwaysZoom:true}),
 new OpenLayers.Control.ZoomIn({title:'Увеличить масштаб'}),
 new OpenLayers.Control.ZoomOut({title:'Уменьшить масштаб'}),
 new OpenLayers.Control.ZoomToMaxExtent({title:'Перейти к минимальному масштабу'}),
 new OpenLayers.Control(),
 new OpenLayers.Control.LayerSwitcher({'div':OpenLayers.Util.getElement(namespace+'-layerswitcher')})
 ]);
}

function highlightMapFeatures(map, filter){
	var flatmin = 90;
	var flatmax = -90;
	var flonmin = 180;
	var flonmax = -180;

	var filterObj = {};
	for (var i=0; i<filter.length; i++)
		try{
			if (filter[i].indexOf('between') == -1)
			if (filter[i].indexOf('=') != -1)
				filterObj[filter[i].split('=')[0].toLowerCase()] = filter[i].split('=')[1].split("'").join('');
		}catch(e){console.log(e.message)};	
	var selectFeature = {};
	for (var i=0; i<map.controls.length; i++) 
		if (map.controls[i].displayClass == 'olControlSelectFeature')
			selectFeature = map.controls[i];
	
	var features = map.layers[1].features;
	
	for (var i=0; i<features.length; i++)
		try{
			var nonfiltered = true;
			for (var f in filterObj)
				if (features[i].attributes[f])
				if (features[i].attributes[f] == filterObj[f])
					nonfiltered = false;
			if (!(nonfiltered)){
				selectFeature.select(features[i]);
				try{
					if (features[i].geometry.y < flatmin)
						flatmin = features[i].geometry.y;
					if (features[i].geometry.y > flatmax)
						flatmax = features[i].geometry.y;
					if (features[i].geometry.x < flonmin)
						flonmin = features[i].geometry.x;
					if (features[i].geometry.x > flonmax)
						flonmax = features[i].geometry.x;	
				}catch(e){console.log(e.message);}
			}else
				selectFeature.unselect(features[i]);
		}catch(e){console.log(e.message)};	
	if ((flatmin != 90)&&(flatmax != -90)&&(flonmin != 180)&&(flonmax != -180)){
		if (flatmin == flatmax){
			flatmin -= 2;
			flatmax += 2;
		}
		if (flonmin == flonmax){
			flonmin -= 2;
			flonmax += 2;
		}
		map.zoomToExtent(new OpenLayers.Bounds (flonmin, flatmin, flonmax, flatmax),true);	
	}
}

OpenLayers.Control.WeatherInfo = OpenLayers.Class(OpenLayers.Control, {
	title: 'Метеоусловия в указанной точке',
                
	autoActivate: false,

	defaultHandlerOptions: {
		'single': true,
		'double': false,
		'pixelTolerance': 0,
		'stopSingle': false,
		'stopDouble': false
	},

	initialize: function(options) {
		this.handlerOptions = OpenLayers.Util.extend(
			{}, this.defaultHandlerOptions
		);
		OpenLayers.Control.prototype.initialize.apply(
			this, arguments
		); 
		this.handler = new OpenLayers.Handler.Click(
			this, {
				'click': this.trigger
			}, this.handlerOptions
		);
	}, 

	trigger: function(e) {
		var lonlat = this.map.getLonLatFromPixel(e.xy);
		lonlat.transform(this.map.projection, "EPSG:4326");
		if ((lonlat.lon)&&(lonlat.lat)){
			try{
				for (var i =0; i<this.map.layers.length; i++)
					if (this.map.layers[i].comment == "tempWeather")
						this.map.removeLayer(this.map.layers[i]);
				var styleMap = new OpenLayers.StyleMap({
					"default": new OpenLayers.Style({cursor: "pointer", fillColor:"#3399ff",pointRadius:4, fillOpacity: 0.4,strokeWidth:1}),
					"temporary": new OpenLayers.Style({cursor: "pointer", fillColor:"#0000ff",pointRadius:4,strokeWidth:1}),
					"select": new OpenLayers.Style({cursor: "pointer", fillColor:"#0000ff",pointRadius:6,strokeWidth:1})
				});
				var vector_layer = new OpenLayers.Layer.Vector('point',{styleMap: styleMap});
				vector_layer.comment = "tempWeather";
				this.map.addLayer(vector_layer);
				var point = new OpenLayers.Geometry.Point(lonlat.lon, lonlat.lat);
				var pointFeature = new OpenLayers.Feature.Vector(point);
				vector_layer.addFeatures([
					pointFeature
				]);
			}catch(e){console.log(e.message)}
			$('#dialog-monitor').remove();
			var title = 'Метеоусловия в указанной точке';
			$('body').append('<div id="dialog-monitor" title="'+title+'" style="padding:10px;"></div>');
			var positionX = pageX-670;
			if (pageX < $(window).width()*0.4)
				positionX = pageX+10;
			if (positionX<0)
				positionX = 0;
			var positionY=pageY-255;
			if (positionY<0)
				positionY = 0;
			$('#dialog-monitor').dialog({
				minWidth:650,		
				minHeight: 240,
				position: [positionX,positionY],
				modal:false,
				resizable:false,
				draggable:true,
				open: function(){
					$('#dialog-monitor').html('<div id="dialog-monitor-display" style="width:100%; max-height:600px; overflow:auto;"><div class="portlet-font portlet-icon icon-loading-bar-small" style="width:100px;height:15px;margin:0 auto;">Загрузка информации об объекте</div></div>');
					$('#dialog-monitor-display').makeMonitor({
					  'resourceId':'RU_RIHMI-WDC_1172',												
					  'm4311':lonlat.lat,
					  'm4312':lonlat.lon,
					  'name':title
					});
				}
			});
		}
	}

});

function getControlsWeather(namespace){
 var weatherControl = new OpenLayers.Control.WeatherInfo();
 weatherControl.displayClass = "olControlWeather";
 
 return ([
 new OpenLayers.Control.Navigation({title:'Навигация. Зажмите левую кнопку мыши на карте для передвижения. Используйте колесико мыши для изменения масштаба'}),
 new OpenLayers.Control.ZoomIn({title:'Увеличить масштаб'}),
 new OpenLayers.Control.ZoomOut({title:'Уменьшить масштаб'}),
 new OpenLayers.Control.ZoomToMaxExtent({title:'Перейти к минимальному масштабу'}),
  weatherControl,
 new OpenLayers.Control(),
 new OpenLayers.Control.LayerSwitcher({'div':OpenLayers.Util.getElement(namespace+'-layerswitcher')})
 ]);
}

function makeMap (namespace, latmin, latmax, lonmin, lonmax){
var map = new OpenLayers.Map(namespace+'-map-small', {restrictedExtent: getCoords("world"), controls: getControlsMin()});
var base = new OpenLayers.Layer.WMS( "Рельеф",
                getWMS("eko").wmsurl, 
                    {layers: getWMS("eko").wmsname,  format: 'image/png', WMTVER: '1.1.1', REQUEST: 'GetMap', SRS:'EPSG:4326', EXCEPTIONS: 'INIMAGE'
			        } );
map.addLayer(base);
var BoxLayer = new OpenLayers.Layer.Vector("Select box");
map.addLayer(BoxLayer);
map.zoomToExtent(new OpenLayers.Bounds (lonmin, latmin, lonmax, latmax),true);
var control_panel = new OpenLayers.Control.Panel({
div: document.getElementById(namespace+'-map-controls'),
defaultControl: new OpenLayers.Control.Navigation()
});
control_panel.addControls(getControlsMin(map, namespace));
map.addControl(control_panel);

return (map);
}

function makeMapRss (namespace, rssurl, iconurl, latmin, latmax, lonmin, lonmax){
var map = new OpenLayers.Map(namespace+'-map-small', {restrictedExtent: getCoords("world"), controls: getControlsMin(), fallThrough: true});
var base = new OpenLayers.Layer.WMS( "Эко 3.1",
                getWMS("eko").wmsurl, 
                    {layers: getWMS("eko").wmsname,  format: 'image/png', WMTVER: '1.1.1', REQUEST: 'GetMap', SRS:'EPSG:4326', EXCEPTIONS: 'INIMAGE'
			        } );
map.addLayer(base);

var georss = new OpenLayers.Layer.GeoRSS("", rssurl,
 {'icon':new OpenLayers.Icon(iconurl, new OpenLayers.Size(13,13)),'popupSize':new OpenLayers.Size(180,150)}
 );
map.addLayer(georss);	
	
map.zoomToExtent(new OpenLayers.Bounds (lonmin, latmin, lonmax, latmax),true);
var control_panel = new OpenLayers.Control.Panel({
div: document.getElementById(namespace+'-map-controls'),
defaultControl: new OpenLayers.Control.Navigation()
});
control_panel.addControls(getControlsView());
map.addControl(control_panel);

return (map);
}

function showInfo(evt){
	try{
		var json = jQuery.parseJSON(evt.text);
	}catch(e){console.log(e.message);}
	var text = 'По указанным координатам объект не найден';
	if (json['gml:featureMember'] != undefined){
		if (Object.prototype.toString.call(json['gml:featureMember']) == '[object Array]'){
			var arr = json['gml:featureMember'];
			var paramNamesObj = {};
			var namespace = 'id' + (new Date()).getTime();
			var dataText = '';
			for (var j=0; j < arr.length; j++){
				var i = 0;
				var obj = json['gml:featureMember'][j];
				for (var prop in obj){
					if (i == 0){
						dataText += '<div style="width:100%;">';
						var dataObj = obj[prop];
						for (var param in dataObj)
							try{
								if (((param.indexOf('m') == 0)||(param.indexOf('p') == 0))&&(param != 'm1253')){
									dataText += '<div class="portlet-form-field-label" style="width:40%;"><b class="clickable-element-metadata portlet-icon-right icon-question" name="'+param+'">'+param+': </b></div> <div style="width:50%;float:left; margin-bottom:5px;">'+dataObj[param]+'</div><br style="clear:both;"/>';
									if (paramNamesObj[param] == undefined)
										paramNamesObj[param] = '';
								}else if (param == 'm1253'){
									dataText += '';
								}else if (param.indexOf('@') == 0){
									dataText += '';
								}else if (Object.prototype.toString.call(dataObj[param]) != '[object Object]'){
									dataText += '<div class="portlet-form-field-label" style="width:30%;"><b>'+param+': </b></div> <div style="width:50%;float:left; margin-bottom:5px;">'+dataObj[param]+'</div><br style="clear:both;"/>';
								}	
							}catch(e){console.log(e.message);}
						dataText += '</div>';								
					}
					i++;
				}
			}
			try{
				var paramStr = '';
				for (var param in paramNamesObj) 
					paramStr += ','+param;
				paramStr = paramStr.replace(',','');
				$.ajax({
					  type: 'POST',
					  url: '/dataview/getcodes',
					  data: {'codesId':paramStr},
					  async: false,
					  dataType: 'json',                                          
					  success: function(json){
							paramNamesObj = json;
					  },
					  error: function(jqXHR, textStatus, errorThrown){
							console.log(textStatus);
					  } 
				});
			}catch(e){console.log(e.message);}
			for (var param in paramNamesObj)
				dataText = dataText.split(paramNamesObj[param].code+":").join(paramNamesObj[param].name+":");
				//console.log(paramNamesObj[param].code+":");
				
			
			text= '<div id="'+namespace+'-slider-wrap" class="portlet-slider-wrap">'+
					'<div style="float:right; z-index: 1000;">'+
					'<input type="button" class="portlet-form-button" id="'+namespace+'-slider-prev" value="<" style="float:left;"/>'+
					'<div id="'+namespace+'-slider-nav" class="slider-nav" style="float:left; margin-top:5px;"></div>'+
					'<input type="button" class="portlet-form-button" id="'+namespace+'-slider-next" value=">" style="float:left; margin-left:5px;"/>'+
					'</div><br/>'+
					'<div id="'+namespace+'-slider" class="portlet-slider" style="visibility:hidden; margin:30px auto;">'+dataText+'</div>'+
					'</div>'; 
			$('body').displayTextMessage({
				  'text': text,
				  'type':'none'
			});
			$('#'+namespace+'-slider').cycle({
						fx: 'fade',
						speed: 'slow',
						timeout: 0,
						pager:  '#'+namespace+'-slider-nav',
						next:   '#'+namespace+'-slider-next', 
						prev:   '#'+namespace+'-slider-prev',
						after: function (curr, next, opts) {;}
			}).css("visibility","visible");
			try{
				var maxSlideHeight = 0;
				$('#'+namespace+'-slider div').each(function(){
					if ($(this).height() > maxSlideHeight)
						maxSlideHeight = $(this).height();
				});
				//console.log(maxSlideHeight);
				$('#'+namespace+'-slider div').first().parent().height(maxSlideHeight + 10);
			}catch(e){console.log(e.message);}	
		}else{
			text = '';
			var obj = json['gml:featureMember'];
			var paramNamesObj = {};
			var i = 0;
			for (var prop in obj){
				if (i == 0){
					var dataObj = obj[prop];
					//console.log(dataObj);
					for (var param in dataObj)
						try{
							if (((param.indexOf('m') == 0)||(param.indexOf('p') == 0))&&(param != 'm1253')){
								text += '<div class="portlet-form-field-label" style="width:40%;"><b class="clickable-element-metadata portlet-icon-right icon-question" name="'+param+'">'+param+': </b></div> <div style="width:50%;float:left; margin-bottom:5px;">'+dataObj[param]+'</div><br style="clear:both;"/>';
								if (paramNamesObj[param] == undefined)
									paramNamesObj[param] = '';
							}else if (param == 'm1253'){
								text += '';
							}else if (param.indexOf('@') == 0){
								text += '';
							}else if (Object.prototype.toString.call(dataObj[param]) != '[object Object]'){
								text += '<div class="portlet-form-field-label" style="width:30%;"><b>'+param+': </b></div> <div style="width:50%;float:left; margin-bottom:5px;">'+dataObj[param]+'</div><br style="clear:both;"/>';
							}
						}catch(e){console.log(e.message);}		
				}
				i++;
			}
			try{
				var paramStr = '';
				for (var param in paramNamesObj) 
					paramStr += ','+param;
				paramStr = paramStr.replace(',','');
				$.ajax({
					  type: 'POST',
					  url: '/dataview/getcodes',
					  data: {'codesId':paramStr},
					  async: false,
					  dataType: 'json',                                          
					  success: function(json){
							paramNamesObj = json;
					  },
					  error: function(jqXHR, textStatus, errorThrown){
							console.log(textStatus);
					  } 
				});
			}catch(e){console.log(e.message);}
			for (var param in paramNamesObj)
				text = text.split(paramNamesObj[param].code+":").join(paramNamesObj[param].name+":");
			
			$('body').displayTextMessage({
				  'text': text,
				  'type':'none'
			});
		}
	}else{
		$('body').displayTextMessage({
			  'text': text,
			  'type':'none'
		});
	}
}

function addLayerGeoSearch(namespace,map,wms){
	var servicesUrlArray = [];
	
	try{
		for (var i in wms){
			if (servicesUrlArray.indexOf(wms[i].url) == -1)
				servicesUrlArray.push(wms[i].url);
		}
	}catch(e){console.log(e.message);}
	
	try{
		$('#'+namespace+'-map-controls div.olControlWMSGetFeatureInfoItemInactive').addClass('hidden-map-button-info');
		$('#'+namespace+'-map-controls div.olControlWMSGetFeatureInfoItemActive').addClass('hidden-map-button-info');
		$('#'+namespace+'-map-controls .hidden-map-button-info').css('display','none');
		for (var i in servicesUrlArray){
			var layer_ctrl = new OpenLayers.Control.WMSGetFeatureInfo({
				url: servicesUrlArray[i],
				queryVisible: true,
				maxFeatures: 20,
				infoFormat:"application/vnd.ogc.gml"
			});
			layer_ctrl.events.register('getfeatureinfo', this, showInfo);
			globalMapObject[namespace+'-control-panel'].addControls(layer_ctrl);
		}
		var j = 0;
		$('#'+namespace+'-map-controls div.olControlWMSGetFeatureInfoItemInactive:not(.hidden-map-button-info)').each(function(){
			j++;
			$(this).addClass('portlet-form-button').addClass('portlet-icon').css('padding','5px 5px 0px 26px').css('width','140px').text('Данные по сервису '+j).wrap('<li></li>'); 
		});
		//$('#'+namespace+'-map-controls li').wrapAll('<div class="portlet-form-button portlet-icon-notext icon-info-white"><ul class="portlet-popup-list" style="width:40px;"></ul></div>');*/
		$('#'+namespace+'-map-controls li').wrapAll('<div class="olControlWMSGetFeatureInfoItemInactive portlet-form-button" style="width:20px;height:20px;"><ul class="portlet-popup-list" style="margin-left:-5px; margin-top:15px; z-index:1000;"></ul></div>');
	}catch(e){console.log(e.message);}

	$('#'+namespace+' div.dataLayersDiv label.labelSpan').each(function(){
		var layer = $(this).text();
		if (layer != ''){
			$(this).attr('name',layer)
			var el = $('<span title="Найти слой на карте" class="portlet-icon icon-search clickable-zoomto" style="cursor:pointer; padding:5px 5px 5px 16px;" name="'+layer+'"></span>');
			$(this).before(el);
		}
		$('#'+namespace+' div.dataLayersDiv [name="'+layer+'"]').wrapAll('<li class="map-node jstree-leaf" esimo-geo-layer="'+layer+'"/>');
	});
	$('#'+namespace+' div.dataLayersDiv br').remove();
	$('#'+namespace+' div.dataLayersDiv li').prepend('<ins class="jstree-icon">&nbsp;</ins>').wrapAll('<ul style="list-style-type:none; padding:0px;"/>');
	$('#'+namespace+' div.dataLayersDiv ul').wrapAll('<div class="jstree" id="'+namespace+'-layertree"/>');

	$('#'+namespace+' .clickable-zoomto').click(function(e){
		var layer = $(this).attr('name');
		for (var i=0; i<wms.length; i++)
		if (wms[i].name == layer){
			var centerx = 0;
			var centery = 0;
			if (wms[i].LatLonBoundingBox != undefined){
				var minx = wms[i].LatLonBoundingBox['@minx'];
				var maxx = wms[i].LatLonBoundingBox['@maxx'];
				var miny = wms[i].LatLonBoundingBox['@miny'];
				var maxy = wms[i].LatLonBoundingBox['@maxy'];
				centerx = minx+(maxx-minx)/2;
				centery = miny+(maxy-miny)/2;
			}else if (wms[i].EX_GeographicBoundingBox != undefined){
				var minx = wms[i].EX_GeographicBoundingBox.westBoundLongitude;
				var maxx = wms[i].EX_GeographicBoundingBox.eastBoundLongitude;
				var miny = wms[i].EX_GeographicBoundingBox.southBoundLatitude;
				var maxy = wms[i].EX_GeographicBoundingBox.northBoundLatitude;
				centerx = minx+(maxx-minx)/2;
				centery = miny+(maxy-miny)/2;
			}
			
			var lonlat = new OpenLayers.LonLat(centerx, centery);
			lonlat.transform(map.displayProjection, map.baseLayer.projection);
			map.setCenter(lonlat,5);
		}
	});
	
	if (wms.length <= 1000){
		servicesUrlArray = [];
		for (var i in wms){
			if (servicesUrlArray.indexOf(wms[i].url) == -1)
				servicesUrlArray.push(wms[i].url);
		}
		for (var i in servicesUrlArray){
			for (var j in wms)
				if (wms[j].url == servicesUrlArray[i]){
					if (wms[j].name == undefined)
						$('#'+namespace+' div.dataLayersDiv li[esimo-geo-layer="'+wms[j].layers+'"]').attr('esimo-geo-service',servicesUrlArray[i]);
					else
						$('#'+namespace+' div.dataLayersDiv li[esimo-geo-layer="'+wms[j].name+'"]').attr('esimo-geo-service',servicesUrlArray[i]);
				}	
			$('#'+namespace+' div.dataLayersDiv li[esimo-geo-service="'+servicesUrlArray[i]+'"]').wrapAll('<ul esimo-geo-service="'+servicesUrlArray[i]+'"/>');			
			$('#'+namespace+' div.dataLayersDiv ul[esimo-geo-service="'+servicesUrlArray[i]+'"]').wrapAll('<li class="node-service" style="display:none;" esimo-geo-service="'+servicesUrlArray[i]+'"/>');			
			$('#'+namespace+' div.dataLayersDiv li[esimo-geo-service="'+servicesUrlArray[i]+'"].node-service').before('<li esimo-geo-service="'+servicesUrlArray[i]+'" class="node-service-clickable node-closed" style="cursor:pointer;"><ins class="icon-tree-closed">&nbsp;</ins>Сервис '+(parseInt(i)+1)+'</li>');
			//$('#'+namespace+' div.dataLayersDiv li').first().before('<li style="cursor:pointer;"><ins class="icon-tree-open">&nbsp;</ins>Сервис '+(parseInt(i)+1)+'</li>');
			$('#'+namespace+' div.dataLayersDiv li.node-service-clickable').unbind().click(function(){
					if ($(this).hasClass('node-open')){
						var service = $(this).attr('esimo-geo-service');
						$('#'+namespace+' div.dataLayersDiv li[esimo-geo-service="'+service+'"].node-service').slideUp();
						$(this).removeClass('node-open').addClass('node-closed');
						$(this).find('.icon-tree-open').removeClass('icon-tree-open').addClass('icon-tree-closed');
					}else if($(this).hasClass('node-closed')){
						var service = $(this).attr('esimo-geo-service');
						$('#'+namespace+' div.dataLayersDiv li[esimo-geo-service="'+service+'"].node-service').slideDown();
						$(this).removeClass('node-closed').addClass('node-open');
						$(this).find('.icon-tree-closed').removeClass('icon-tree-closed').addClass('icon-tree-open');
					}
			});
			$('#'+namespace+' div.dataLayersDiv li.node-service-clickable').each(function(){
					var service = $(this).attr('esimo-geo-service');
					if (service == servicesUrlArray[servicesUrlArray.length - 1]){
						$('#'+namespace+' div.dataLayersDiv li[esimo-geo-service="'+service+'"].node-service').slideDown();
						$(this).removeClass('node-closed').addClass('node-open');
						$(this).find('.icon-tree-closed').removeClass('icon-tree-closed').addClass('icon-tree-open');
					}
			});
			
		}
	}
}

function addWMSLayerToMap(namespace,map,wms,newwmsurl){
    var wmsurl = newwmsurl;
    var paramposition = wmsurl.indexOf("?");
    var httpposition = wmsurl.indexOf("http:");
    var userName = "";
    if (wmsurl.indexOf("&username=")>0){
        var temp = wmsurl.substring(wmsurl.indexOf("username="),wmsurl.indexOf("&version="));
        userName = temp;
    }    
    var md5password = "";
    if (wmsurl.indexOf("&md5password=")>0)
        md5password = "";
    
    var timeFrom = "";
    if (wmsurl.indexOf("TIMEFROM=")>=0){
       timeFrom = wmsurl.substring(wmsurl.indexOf("TIMEFROM="),wmsurl.indexOf("TIMEFROM=")+19); 
    }
    var timeTo = "";
    if (wmsurl.indexOf("TIMETO=")>=0){
       timeTo = wmsurl.substring(wmsurl.indexOf("TIMETO="),wmsurl.indexOf("TIMETO=")+17);  
    }
    
    if (paramposition>0){
        if (httpposition > 0)
            wmsurl = wmsurl.substring(httpposition,paramposition);
        else
            wmsurl = wmsurl.substring(0,paramposition);
        if (userName != '')
            wmsurl += "?"+userName;
        if (md5password  != '')
            wmsurl += "&"+md5password;
        if (timeFrom  != '')
            wmsurl += "&"+timeFrom;
        if (timeTo != '')
            wmsurl += "&"+timeTo;
    }


	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);}
	var url = '/restserver/services/c/convert.json?url='+wmsurl+capabilities;
	if (wmsurl.indexOf('gptl.ru') >= 0)
		url = '/dataview/xmltojson?xmlurl='+wmsurl.replace("?","&")+capabilities;
	var serviceUrl = wmsurl.replace('&request=getcapabilities','').replace('?request=getcapabilities','');
	
	$('#'+namespace).displayTextMessage({
		  'text': 'Получение списка слоев из геосервиса',
		  'type':'loading'
	});
	$.ajax({
		  type: 'GET',
		  url: url,
		  async: true,
		  dataType: 'json',
		  timeout: 30000,
		  error: function(e){
				$('.portlet-msg-loading:contains("Получение списка слоев из геосервиса")').parent(".ui-dialog-content").dialog("close");
				$('#'+namespace).displayTextMessage({
								  'text':'Ошибка чтения геосервиса',
								  'type':'error'
				});
		  },
		  success: function(json){
				$('.portlet-msg-loading:contains("Получение списка слоев из геосервиса")').parent(".ui-dialog-content").dialog("close");
				$('#'+namespace).displayTextMessage({
					  'text': 'Добавление слоев на карту',
					  'type':'loading'
				});
				try{
					//alert(json.toSource());
					var layersArray = json.Capability.Layer.Layer;
					var wmsObj = [];
					for (var i = layersArray.length-1;i>=0; i--){
						try{
							if ((layersArray[i].Name != undefined)&&(layersArray[i].Name != '')){
								wmsObj.push({
									 "url":serviceUrl,
									 "layers":layersArray[i].Name,
									 "name":layersArray[i].Title,
									 "LatLonBoundingBox": layersArray[i].LatLonBoundingBox,
									 "EX_GeographicBoundingBox": layersArray[i].EX_GeographicBoundingBox,
									 "visibility": false
								});
							}	
						}catch(e){console.log(e.message);}
					}	
					
					wmsObj = sortByKey(wmsObj, 'name');	

					//console.log(wmsObj);

					for (var i in wmsObj){
						wms.push(wmsObj[i]);
						var layer = new OpenLayers.Layer.WMS(wmsObj[i].name,
							wmsObj[i].url,
							{'layers': wmsObj[i].layers, transparent: "true", format: "image/png"},
							{isBaseLayer: false, visibility: false, opacity: 0.9}
						);
						globalMapObject[namespace].addLayer(layer);
					}
					var c_LayerSwitcher = globalMapObject[namespace].getControlsByClass("OpenLayers.Control.LayerSwitcher")[0]; 
					c_LayerSwitcher.redraw();
					
					addLayerGeoSearch(namespace,globalMapObject[namespace],wms);
					$('.portlet-msg-loading:contains("Добавление слоев на карту")').parent(".ui-dialog-content").dialog("close");
				} catch(e){
					console.log(e.message);
					$('#'+namespace).displayTextMessage({
								  'text':'Ошибка чтения списка слоев из геосервиса',
								  'type':'error'
					});
				}	
		  }
	});
}

function buildWmsCatalogueLocal(namespace){
		var html = '<table id="'+namespace+'-catlocal" class="display">'+
		'<thead><th>Название сервиса</th><th style="width:100px;"></th></thead>'+
		'<tbody></tbody>'
		'</table>';
		$('#'+namespace).html('').html(html);
		$('#'+namespace+'-catlocal').dataTable({
			 "sAjaxSource": '/dataview/wmscat?type=local',
			 "bServerSide": false,
			 "fnServerData": function ( sSource, aoData, fnCallback, oSettings ) {
					$.ajax({
						"url": sSource,
						"type": "GET",
						"data": aoData,
						"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("Время ожидания данных превысило 30 секунд. Отмена запроса.");
								}else alert(status);
						},
						"dataType": "json",
						"cache": false
					});
			  },
			  "aoColumns": [
				  {"bSortable": true, "mDataProp": "titleText",
				   "fnRender": function (oObj){
						var text = oObj.aData["objecttitle"];
						if (oObj.aData["resourceid"].toUpperCase().indexOf('RU_') >= 0)
							text = '<span class="portlet-icon icon-download-text clickable-resource-metadata" name="'+oObj.aData["resourceid"]+'">'+oObj.aData["objecttitle"]+'</span> (<span>'+oObj.aData["resourceid"]+'</span>)';
						return text;
				  }},
				  {"bSortable": false, "mDataProp": null,
				   "fnRender": function (oObj){
						return '<input esimo-geo-service="'+oObj.aData["objectinfourl"]+'" class="portlet-form-button portlet-icon icon-layer-add clickable-layer" value="Добавить слой на карту"/>';
				  }}
			  ],
			  "sDom": '<"portlet-table-top"lpiTfr>t<"portlet-table-bottom"pi>',  
			  "sPaginationType": "full_numbers",
			  "bProcessing": true,
			  "bAutoWidth": false,
			  "bSortClasses": false,
			  "sPaginationType": "full_numbers",
			  "aLengthMenu": [[10, 20, 100, -1], [10, 20, 100, "Все"]],
			  "iDisplayLength": 10,
			  "sPaginationType": "full_numbers",
			  "oLanguage": {
				"sUrl": "/portal-ajax/jquery/lang.json"
			  },
			  "oTableTools":  {	
			  "sSwfPath": "/portal-ajax/jquery/copy_cvs_xls.swf",
			  "aButtons": [ { "sExtends":"collection",
												"sButtonText":"",
												"aButtons": [
												{"sExtends": "csv", "sButtonText": "CSV"},
												{"sExtends": "xls","sButtonText": "Excel" },
												{"sExtends": "copy", "sButtonText": "Буфер обмена"} 
												]
										}]
			  }
		});
}

function buildWmsCatalogueGlobal(namespace){
		var html = '<table id="'+namespace+'-catlocal" class="display">'+
		'<thead><th>Название сервиса</th><th style="width:100px;"></th></thead>'+
		'<tbody></tbody>'
		'</table>';
		$('#'+namespace).html('').html(html);
		$('#'+namespace+'-catlocal').dataTable({
			 "sAjaxSource": '/dataview/wmscat?type=global',
			 "bServerSide": false,
			 "fnServerData": function ( sSource, aoData, fnCallback, oSettings ) {
					$.ajax({
						"url": sSource,
						"type": "GET",
						"data": aoData,
						"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("Время ожидания данных превысило 30 секунд. Отмена запроса.");
								}else alert(status);
						},
						"dataType": "json",
						"cache": false
					});
			  },
			  "aoColumns": [
				  {"bSortable": true, "mDataProp": "titleText",
				   "fnRender": function (oObj){
						var text = oObj.aData["objecttitle"];
						if (oObj.aData["resourceid"].toUpperCase().indexOf('RU_') >= 0)
							text = '<span class="portlet-icon icon-download-text clickable-resource-metadata" name="'+oObj.aData["resourceid"]+'">'+oObj.aData["objecttitle"]+'</span> (<span>'+oObj.aData["resourceid"]+'</span>)';
						return text;
				  }},
				  {"bSortable": false, "mDataProp": null,
				   "fnRender": function (oObj){
						return '<input esimo-geo-service="'+oObj.aData["objectinfourl"]+'" class="portlet-form-button portlet-icon icon-layer-add clickable-layer" value="Добавить слой на карту"/>';
				  }}
			  ],
			  "sDom": '<"portlet-table-top"lpiTfr>t<"portlet-table-bottom"pi>',  
			  "sPaginationType": "full_numbers",
			  "bProcessing": true,
			  "bAutoWidth": false,
			  "bSortClasses": false,
			  "sPaginationType": "full_numbers",
			  "aLengthMenu": [[10, 20, 100, -1], [10, 20, 100, "Все"]],
			  "iDisplayLength": 10,
			  "sPaginationType": "full_numbers",
			  "oLanguage": {
				"sUrl": "/portal-ajax/jquery/lang.json"
			  },
			  "oTableTools":  {	
			  "sSwfPath": "/portal-ajax/jquery/copy_cvs_xls.swf",
			  "aButtons": [ { "sExtends":"collection",
												"sButtonText":"",
												"aButtons": [
												{"sExtends": "csv", "sButtonText": "CSV"},
												{"sExtends": "xls","sButtonText": "Excel" },
												{"sExtends": "copy", "sButtonText": "Буфер обмена"} 
												]
										}]
			  }
		});
}

function showDialogWmsCatalogue(namespace,map,wms){
	$('#dialog-wmscat').remove();
	$('body').append('<div id="dialog-wmscat" title="Добавление геосервиса" class="portlet-dialog-form ui-dialog-content ui-widget-content" style="padding:10px;"></div>');
	var positionX=$(window).width()/2-320;
	if (positionX<0)
		positionX = 0;
	var positionY=$(window).height()/2-200;
	if (positionY<0)
		positionY = 0;
	$('#dialog-wmscat').dialog({
		minHeight: 600,
		minWidth:800,
		modal:false,
		resizable:true,
		draggable:true,
		open: function(){
			var html = '<ul id="dialog-wmscat-selection" class="portlet-tab">'+
			'<li id="dialog-wmscat-source-local" title="Каталог всех геосервисов, зарегистрированных на текущем узле"><a href="#"><b class="portlet-icon icon-map">Каталог текущего узла</b></a></li>'+
			'<li id="dialog-wmscat-source-global" title="Каталог всех геосервисов, зарегистрированных в СРБД ЕСИМО"><a href="#"><b class="portlet-icon icon-map-globe">Общий каталог ЕСИМО</b></a></li>'+
			'<li id="dialog-wmscat-source-direct" title="Каталог всех геосервисов, зарегистрированных на текущем узле"><a href="#"><b class="portlet-icon icon-map-edit">Прямой ввод адреса</b></a></li>'+
			'</ul><br/>'+
			'<div id="dialog-wmscat-display" style="width:100%;height:80%;min-height:445px;"></div>';		
			html = html.split("null").join("");
			$('#dialog-wmscat').html(html);
			$('#dialog-wmscat-selection').tabs("div.panes > div");
			buildWmsCatalogueLocal('dialog-wmscat-display');
			
			$('#dialog-wmscat-source-local').click(function(){
					buildWmsCatalogueLocal('dialog-wmscat-display');
			});
			$('#dialog-wmscat-source-global').click(function(){
					buildWmsCatalogueGlobal('dialog-wmscat-display');
			});
			$('#dialog-wmscat-display .clickable-layer').die().live('click',function(){
							addWMSLayerToMap(namespace,map,wms,$(this).attr('esimo-geo-service'));							
			});
			$('#dialog-wmscat-source-direct').click(function(){
					html = '<input id="display-input-direct" style="width:95%;margin:0 auto;"/><br/>'+
					'<input id="dialog-wmscat-add-direct" class="portlet-form-button portlet-icon icon-status-success" type="button" value="Добавить"/>';	
					$('#dialog-wmscat-display').html('').html(html);
					$('#dialog-wmscat-add-direct').die().live('click',function(){
							$('#dialog-wmscat-display .portlet-msg-error').remove();
							if ($('#display-input-direct').val() == '')
								$('#dialog-wmscat-display').append('<p class="portlet-msg-error">Не введен адрес сервиса для подключения</p>');
							else if ($('#display-input-direct').val() == undefined)
								;
							else if ($('#display-input-direct').val().indexOf('http://') == -1)
								$('#dialog-wmscat-display').append('<p class="portlet-msg-error">Адрес сервиса должен начинаться с http:// например http://geo.ferhri.ru:8080/geoserver/ber/wms</p>');
							else
								addWMSLayerToMap(namespace,map,wms,$('#display-input-direct').val());							
					});					
			});
		}
	});
}

function makeMapFull (namespace, basewmsurl, basewmslayer, wms, featureslayer, posturl, postparam, posticon, rss, latmin, latmax, lonmin, lonmax, layerSelector, projection, criteriaParameter){
//console.log(projection);
var options = {
    projection: new OpenLayers.Projection(projection),
	displayProjection: new OpenLayers.Projection("EPSG:4326"),
	controls: getControlsMin(),
	fallThrough: true								 
};
var map = new OpenLayers.Map(namespace+'-map-small', options);

var base = new OpenLayers.Layer.WMS( "ЭКО", basewmsurl, 
                    {layers: basewmslayer,  format: 'image/png', WMTVER: '1.1.1', REQUEST: 'GetMap', SRS: projection, EXCEPTIONS: 'INIMAGE'},
					{isBaseLayer: true,wrapDateLine: false,transitionEffect: 'resize'});
map.addLayer(base);

if ((wms.length > 0)){
OpenLayers.ProxyHost = "/dataview/xmltojson?xmlurl=";

	for(var i=0; i<wms.length; i++){
		try{
			if (wms[i].visibility == undefined)
				wms[i].visibility = false;
			var title = '';
			if (wms[i].name == undefined)
				title = wms[i].layers;
			else
				title = wms[i].name;
			var singleTile = false;
			if (wms[i].url.indexOf('esimo') != -1)
				singleTile = true;
			var layer = new OpenLayers.Layer.WMS(title,
				wms[i].url,
				{'layers': wms[i].layers, transparent: "true", format: "image/png"},
				{isBaseLayer: false, visibility: wms[i].visibility, opacity: 0.9, singleTile: singleTile}
			);
			map.addLayer(layer);
			console.log('layer');
			console.log(layer);
		}catch(e){		
			console.log(e.message);
		};
	}	
}

var control_panel = new OpenLayers.Control.Panel({
div: document.getElementById(namespace+'-map-controls'),
defaultControl: new OpenLayers.Control.Navigation()
});
var controls = getControlsFull(namespace);
if ((posturl)&&(postparam))
	controls = getControlsWeather(namespace);
control_panel.addControls(controls);
map.addControl(control_panel);

globalMapObject[namespace+'-control-panel'] = control_panel;

if ((wms.length > 0)){
	addLayerGeoSearch(namespace,map,wms);
}


if ((rss.length > 0)){
	for(var i=0; i<rss.length; i++){
		if ((rss[i].icon == '')||(rss[i].icon == undefined))
			rssicon = '/portal-core/themes/esimo-central/images/icons/icon-map-marker.png';
		var georss  = new OpenLayers.Layer.GeoRSS(rss[0].name, rss[0].url,
			{'icon':new OpenLayers.Icon(rssicon, new OpenLayers.Size(13,13)),'popupSize':new OpenLayers.Size(180,150)}
		);
		map.addLayer(georss);
	}
}

if (featureslayer != ''){
	    $.getJSON(featureslayer,
		function(json){
            var featurecollection = json;
		    var geojson_format = new OpenLayers.Format.GeoJSON();
		    var vector_layer = new OpenLayers.Layer.Vector(); 
			var styleMap = new OpenLayers.StyleMap({
				"default": new OpenLayers.Style({cursor: "pointer", fillColor:"#3399ff",pointRadius:4, fillOpacity: 0.4,strokeWidth:1}),
				"temporary": new OpenLayers.Style({cursor: "pointer", fillColor:"#0000ff",pointRadius:4,strokeWidth:1}),
				"select": new OpenLayers.Style({cursor: "pointer", fillColor:"#0000ff",pointRadius:6,strokeWidth:1})
			});
		    var vector_layer = new OpenLayers.Layer.Vector('features',{styleMap: styleMap});
		    map.addLayer(vector_layer);
		    vector_layer.addFeatures(geojson_format.read(featurecollection));
                    
                    var selectControl = new OpenLayers.Control.SelectFeature( vector_layer,
                    {
                        hover: true
                    });
                    map.addControl(selectControl);
                    selectControl.activate();
                    
					var columns = json.codes;
                    vector_layer.events.on({
                        "featureselected": function(e) {
                            var attr = e.feature.attributes;
							var params = "";
                            for(var property in attr)
								if (columns[property] != 'Geometry (точка, поверхность, сетка)')
									params = params + "<b>" + columns[property] + "</b>" + " : " + attr[property] + "<br/>";  
                            var popupX = pageX+15;
							var popupY = pageY-65;
                            $("#"+namespace+"-info").remove();
                            $("body").append("<div id='"+namespace+"-info' class='map-info portlet-font'>"+"<div class='tooltip-close portlet-icon-notext icon-cross-white' style='float:right;'>X</div>"+params+"</div>");
                            $("#"+namespace+"-info").css("top",popupY + "px");
                            $("#"+namespace+"-info").css("left",popupX + "px");
                            $("#"+namespace+"-info .tooltip-close").click(function() {
								$("#"+namespace+"-info").remove();
                            });
                        },
                        "featureunselected": function(e) {
                        }
                    });
                    });
}

if (posturl != '')
if (postparam != ''){
		var resId = '';
		var paramsToPost = {};
		for (var p in postparam){
			paramsToPost[p] = postparam[p];
			if (p == 'resourceId')
				resId = postparam[p];
		}	
		if ((postparam.refreshfilter != '')&&(postparam.refreshfilter != undefined)){
			if (postparam.filter != '')
				paramsToPost.filter += ' and ' + postparam.refreshfilter;
			else
				paramsToPost.filter = postparam.refreshfilter;
		}	
		if (criteriaParameter != '')
			paramsToPost.criteriaparameter = criteriaParameter;

		$.post(posturl,
		paramsToPost,
		function(json){
			//console.log(json);
            var featurecollection = json;
		    var geojson_format = new OpenLayers.Format.GeoJSON();
			var defaultstyle = new OpenLayers.Style({graphicName:"circle", cursor: "pointer", fillColor:"#3399ff",pointRadius:4, fillOpacity: 0.4, strokeWidth:1}, {
				rules: [
					new OpenLayers.Rule({
						minScaleDenominator: 55000000,
						symbolizer: {
							pointRadius: 1,
							strokeColor:"#3399ff",
						}
					}),
					new OpenLayers.Rule({
						maxScaleDenominator: 55000000,
						minScaleDenominator: 20000000,
						symbolizer: {
							pointRadius: 2
						}
					}),
					new OpenLayers.Rule({
						maxScaleDenominator: 20000000,
						minScaleDenominator: 10000000,
						symbolizer: {
							pointRadius: 3							
						}
					}),
					new OpenLayers.Rule({
						maxScaleDenominator: 10000000,
						symbolizer: {
							pointRadius: 4
						}
					})
				]
			});
			if(resId.indexOf('_2886') != -1){
				defaultstyle = new OpenLayers.Style({graphicName:"circle", cursor: "pointer", fillColor:"#3399ff",pointRadius:7, fillOpacity: 0.9, strokeWidth:1});
			}
			var criteria = criteriaParameter.substring(0,5);
			if (criteriaGlobal[criteria] != undefined){
				var property = "max";
				if (criteria == "p0001")
					property = "mod";
				for (var j=0; j<criteriaGlobal[criteria].length; j++){
						var from = parseFloat(criteriaGlobal[criteria][j].from);
						var to = parseFloat(criteriaGlobal[criteria][j].to);
						var rule = new OpenLayers.Rule({
						  filter: new OpenLayers.Filter.Comparison({
							  type: OpenLayers.Filter.Comparison.BETWEEN,
							  property: property,
							  lowerBoundary: from,
							  upperBoundary: to
						  }),
						  symbolizer: {fillOpacity: 1, fillColor:dangerColorsMapArray[criteriaGlobal[criteria][j].danger]}
						});
						defaultstyle.addRules([rule]);
				}
			}
			
			var selectstyle = new OpenLayers.Style({graphicName:"circle", cursor: "pointer", fillColor:"#0000ff",pointRadius: 6,strokeWidth:1});
			var styleMap = new OpenLayers.StyleMap({
				"default": defaultstyle,
				"select": selectstyle
			});
			var styleMapSelected = new OpenLayers.StyleMap({
				"default": selectstyle,
				"select": selectstyle
			});
			
			if (globalDangerArr.indexOf(paramsToPost.resourceId.toUpperCase()) != -1)
				posticon = 'icon-danger';
			if (globalStationArr.indexOf(paramsToPost.resourceId.toUpperCase()) != -1)
				posticon = 'icon-platform-10';
			if ((posticon != undefined)&&(posticon != ''))
				styleMap = new OpenLayers.StyleMap({
					"default": new OpenLayers.Style({cursor: "pointer", externalGraphic:'/portal-core/themes/esimo-central/images/icons/'+posticon+'.png', pointRadius:8, fillOpacity: 0.8}),
					"temporary": new OpenLayers.Style({cursor: "pointer", externalGraphic:'/portal-core/themes/esimo-central/images/icons/'+posticon+'.png', pointRadius:8, fillOpacity: 0.8}),
					"select": new OpenLayers.Style({cursor: "pointer",  externalGraphic:'/portal-core/themes/esimo-central/images/icons/'+posticon+'.png', pointRadius:12, fillOpacity: 1})
				});
			if (resId)
			if (resId.toUpperCase().indexOf('RU_SSRI-CENTR_') != -1)
				styleMap = new OpenLayers.StyleMap({
					"default": new OpenLayers.Style({cursor: "pointer", externalGraphic:'/portal-core/themes/esimo-central/images/icons/icon-factory.png', pointRadius:8, fillOpacity: 0.8}),
					"temporary": new OpenLayers.Style({cursor: "pointer", externalGraphic:'/portal-core/themes/esimo-central/images/icons/icon-factory.png', pointRadius:8, fillOpacity: 0.8}),
					"select": new OpenLayers.Style({cursor: "pointer",  externalGraphic:'/portal-core/themes/esimo-central/images/icons/icon-factory-blue.png', pointRadius:12, fillOpacity: 1})
				});
		    var vector_layer = new OpenLayers.Layer.Vector('features',{styleMap: styleMap}); 
		    map.addLayer(vector_layer);
			
			var columns = json.codes;
			vector_layer.events.on({
				/*"featuresadded": function(e){
					try{
					}catch(e){console.log(e.message);}
				},*/
				"featureover": function(e) {
					$("#"+namespace+"-info").remove();
					var attr = e.feature.attributes;
					var params = '<p><b style="padding:5px 10px 6px 30px;">Сведения об объекте:</b></p>';
					
					params += '<div id="'+namespace+'-info-text">';
					var codesArray = [];
					for(var property in attr)
						codesArray.push(property);
					if (resId)	
					if (resId.toUpperCase() == 'RU_SSRI-CENTR_79')
						codesArray = 'm4091,m4327,m4133,m4130,m4107,m4110,m4102,m4037,m4141,m4142,m4111,m4311,m4312'.split(',');
					for(var i=0; i<codesArray.length; i++){					
						if (i == 0){
							if (codesArray[i].indexOf('p')==0)
								params += '<div class="portlet-msg-values">';
							else
								params += '<div class="portlet-msg-text">';
						}							
						if (i > 0){
							if ((codesArray[i-1].indexOf('m')==0)&&(codesArray[i].indexOf('p')==0))
								params += '</div><br/><div class="portlet-msg-values">';
						}
						if (attr[codesArray[i]])
						if ((codesArray[i] != 'max')&&(codesArray[i] != 'min')&&(codesArray[i] != 'mod'))
							params += "<b>" + columns[codesArray[i]] + "</b>" + " : " + attr[codesArray[i]] + "<br/>";
						if (i == codesArray.length -1){
							params += '</div>';
						}	
					}	
					params += '</div>';
					params += '<input id="'+namespace+'-export-mail-button" class="portlet-form-button portlet-icon-notext icon-export-email button-exportrecord" type="button" title="Отправить по e-mail" style="float:right;" />';
					params += '<input id="'+namespace+'-export-image-button" class="portlet-form-button portlet-icon-notext icon-export-image button-exportrecord" type="button" title="Экспорт в рисунок" style="float:right;" />';
					params += '<input id="'+namespace+'-export-docx-button" class="portlet-form-button portlet-icon-notext icon-export-doc button-exportrecord" type="button" title="Экспорт в docx" style="float:right;" />';

					var popupX = pageX+15;
					var popupY = pageY-65;
					$("#"+namespace+"-info").remove();
					$("body").append("<div id='"+namespace+"-info' class='map-info portlet-font'>"+"<div class='tooltip-close portlet-icon-notext icon-cross-white' style='float:right; cursor:pointer;'></div>"+params+"</div>");
					$("#"+namespace+"-info").css("top",popupY + "px");
					$("#"+namespace+"-info").css("left", popupX + "px");
					$("#"+namespace+"-info .tooltip-close").click(function() {
						$("#"+namespace+"-info").remove();
					});
					
					try{
						$('#'+namespace+'-export-image-button').die().live('click', function(){
							exportDivToCanvas(namespace+'-info-text');
						});
						$('#'+namespace+'-export-mail-button').die().live('click', function(){
							exportDivToMail(namespace+'-info-text');
						});
						$('#'+namespace+'-export-docx-button').die().live('click', function(){
							exportDivToDocx(namespace+'-info-text','doc');
						});
					}catch(e){console.log(e.message);}	
				},
				"featureout": function(e) {
					//$("#"+namespace+"-info").remove();
				}
			});			
		    vector_layer.addFeatures(geojson_format.read(featurecollection));
			if (featurecollection.features.length >= 3000){
				$('#'+namespace).append('<p class="portlet-msg-alert" style="display:block;">Достигнут предел отображения в 3000 точек, уменьшите район отображения и нажмите кнопку "Перестроить по текущему району" для получения более точной информации.</p>');
				$('#'+namespace).animate({paddingBottom: '+=60px'}, 0);
			}
                    
			var selectControl = new OpenLayers.Control.SelectFeature( vector_layer,
			{
				hover: false
			});
			map.addControl(selectControl);
			selectControl.activate();					
		},
		'json'   
		)
} 
map.zoomToExtent(new OpenLayers.Bounds (lonmin, latmin, lonmax, latmax).transform(map.displayProjection, map.baseLayer.projection),true);
map.setOptions({restrictedExtent: getCoords("world").transform(map.displayProjection, map.baseLayer.projection)});

return (map);
}

function makeMapFilterResource(namespace, basewmsurl, basewmslayer, resourceId, filterstr, column, lonmin, latmin, lonmax, latmax, metadataResource,wms,criteriaParameter){
var map = new OpenLayers.Map(namespace+'-map-small', {restrictedExtent: getCoords("world"), controls: getControlsMin(), fallThrough: true});
var base = new OpenLayers.Layer.WMS( "Base layer", basewmsurl, 
                    {layers: basewmslayer,  format: 'image/png', WMTVER: '1.1.1', REQUEST: 'GetMap', SRS:'EPSG:4326', EXCEPTIONS: 'INIMAGE'},
					{isBaseLayer: true,wrapDateLine: true});
map.addLayer(base);

var control_panel = new OpenLayers.Control.Panel({
div: document.getElementById(namespace+'-map-controls'),
defaultControl: new OpenLayers.Control.Navigation()
});
control_panel.addControls(getControlsView(namespace));
map.addControl(control_panel);

if (resourceId != ''){
		$.post('/dataview/viewgeo',
		{'resourceId':resourceId,'distinct':column,'filter':filterstr,'filtermap':'true','criteriaparameter':criteriaParameter},
		function(json){
            var featurecollection = json;
		    var geojson_format = new OpenLayers.Format.GeoJSON();
			var defaultstyle = new OpenLayers.Style({graphicName:"circle", cursor: "pointer", fillColor:"#3399ff",pointRadius:4, fillOpacity: 0.4,strokeWidth:1}, {
				rules: [
					new OpenLayers.Rule({
						minScaleDenominator: 55000000,
						symbolizer: {
							pointRadius: 1,
							strokeColor:"#3399ff",
						}
					}),
					new OpenLayers.Rule({
						maxScaleDenominator: 55000000,
						minScaleDenominator: 20000000,
						symbolizer: {
							pointRadius: 2
						}
					}),
					new OpenLayers.Rule({
						maxScaleDenominator: 20000000,
						minScaleDenominator: 10000000,
						symbolizer: {
							pointRadius: 3							
						}
					}),
					new OpenLayers.Rule({
						maxScaleDenominator: 10000000,
						symbolizer: {
							pointRadius: 4
						}
					})
				]
			});
			var criteria = criteriaParameter.substring(0,5);
			if (criteriaGlobal[criteria] != undefined){
				var property = "max";
				if (criteria == "p0001")
					property = "mod";
				for (var j=0; j<criteriaGlobal[criteria].length; j++){
						var from = parseFloat(criteriaGlobal[criteria][j].from);
						var to = parseFloat(criteriaGlobal[criteria][j].to);
						var rule = new OpenLayers.Rule({
						  filter: new OpenLayers.Filter.Comparison({
							  type: OpenLayers.Filter.Comparison.BETWEEN,
							  property: property,
							  lowerBoundary: from,
							  upperBoundary: to
						  }),
						  symbolizer: {fillOpacity: 1, fillColor:dangerColorsMapArray[criteriaGlobal[criteria][j].danger]}
						});
						defaultstyle.addRules([rule]);
				}
			}
			
			var selectstyle = new OpenLayers.Style({graphicName:"circle", cursor: "pointer", fillColor:"#0000ff",pointRadius: 6,strokeWidth:1});
			var styleMap = new OpenLayers.StyleMap({
				"default": defaultstyle,
				"select": selectstyle
			});
			var styleMapSelected = new OpenLayers.StyleMap({
				"default": selectstyle,
				"select": selectstyle
			});
			/*var posticon = '';
			if (globalStationArr.indexOf(paramsToPost.resourceId.toUpperCase()) != -1)
				posticon = 'icon-platform-10';
			if ((posticon != undefined)&&(posticon != ''))
				styleMap = new OpenLayers.StyleMap({
					"default": new OpenLayers.Style({cursor: "pointer", externalGraphic:'/portal-core/themes/esimo-central/images/icons/'+posticon+'.png', pointRadius:8, fillOpacity: 0.8}),
					"temporary": new OpenLayers.Style({cursor: "pointer", externalGraphic:'/portal-core/themes/esimo-central/images/icons/'+posticon+'.png', pointRadius:8, fillOpacity: 0.8}),
					"select": new OpenLayers.Style({cursor: "pointer",  externalGraphic:'/portal-core/themes/esimo-central/images/icons/'+posticon+'.png', pointRadius:12, fillOpacity: 1})
				});*/
			if (resourceId)
			if (resourceId.toUpperCase().indexOf('RU_SSRI-CENTR_') != -1)
				styleMap = new OpenLayers.StyleMap({
					"default": new OpenLayers.Style({cursor: "pointer", externalGraphic:'/portal-core/themes/esimo-central/images/icons/icon-factory.png', pointRadius:8, fillOpacity: 0.8}),
					"temporary": new OpenLayers.Style({cursor: "pointer", externalGraphic:'/portal-core/themes/esimo-central/images/icons/icon-factory.png', pointRadius:8, fillOpacity: 0.8}),
					"select": new OpenLayers.Style({cursor: "pointer",  externalGraphic:'/portal-core/themes/esimo-central/images/icons/icon-factory-blue.png', pointRadius:12, fillOpacity: 1})
				});	
		    var vector_layer = new OpenLayers.Layer.Vector('features',{styleMap: styleMap}); 
		    map.addLayer(vector_layer);
			
			var codes = json.codes;
			vector_layer.events.on({
				/*"featuresadded": function(e){
					try{
					}catch(e){console.log(e.message);}
				},*/
				"featureover": function(e) {
					var attr = e.feature.attributes;
					var params = "";
					for(var property in attr){
						var name = codes[property];
						if ((name != '')&&(name != undefined)&&(name.indexOf('min') == -1)&&(name.indexOf('max') == -1))
							params += "<b>" + name + "</b>" + " : " + attr[property] + "<br/>";  
					}	
					if (metadataResource.resourceId !='')
					if (metadataResource.codeIn !='')
					if (metadataResource.codeOut !='')
						params += '<br/><b class="portlet-icon icon-question clickable-resourcerecord-metadata" data-resource="'+metadataResource.resourceId+'" data-filter="'+metadataResource.codeOut+'=\''+attr[metadataResource.codeIn]+'\'" style="text-decoration:underline;cursor:pointer;">Сведения об объекте</b>';
					var popupX = pageX+15;
					var popupY = pageY-65;
					$("#"+namespace+"-info").remove();
					$("body").append("<div id='"+namespace+"-info' class='map-info portlet-font'>"+"<div class='tooltip-close portlet-icon-notext icon-cross-white' style='float:right;'>X</div>"+params+"</div>");
					$("#"+namespace+"-info").css("top",popupY + "px");
					$("#"+namespace+"-info").css("left", popupX + "px");
					$("#"+namespace+"-info .tooltip-close").click(function() {
						$("#"+namespace+"-info").remove();
					});
				},
				"featureout": function(e) {
					$("#"+namespace+"-info").remove();
				}
			});			
		    vector_layer.addFeatures(geojson_format.read(featurecollection));
			if (featurecollection.features.length >= 3000){
				$('#'+namespace).append('<p class="portlet-msg-alert" style="display:block;">Достигнут предел отображения в 3000 точек, уменьшите район отображения и нажмите кнопку "Перестроить по текущему району" для получения более точной информации.</p>');
				$('#'+namespace).animate({paddingBottom: '+=60px'}, 0);
			}
                    
			var selectControl = new OpenLayers.Control.SelectFeature( vector_layer,
			{
				hover: false
			});
			map.addControl(selectControl);
			selectControl.activate();
			
			
			if ((wms.length > 0)) 
			{
				for(var i=0; i<wms.length; i++){
					if (wms[i].visibility == undefined)
						wms[i].visibility = false;
					var title = '';
					if (wms[i].name == undefined)
						title = wms[i].layers;
					else
						title = wms[i].name;
					var layer = new OpenLayers.Layer.WMS(title,
					wms[i].url,
					{'layers': wms[i].layers, transparent: "true", format: "image/png"},
					{isBaseLayer: false, visibility: wms[i].visibility, opacity: 0.7}
					);
					map.addLayer(layer);
				}	
			}					
        },
		'json'   
		)
}
map.zoomToExtent(new OpenLayers.Bounds (lonmin, latmin, lonmax, latmax),true);
return (map);
}

function getLayerImageSrc(map,layerNumber){
	var url = '/restserver/services/image/get?';
	var obj = map.layers[layerNumber];
	for (property in obj.params) {
	  if ((property != 'WMTVER'))
			url = url + '&' + property +'=' + obj.params[property];
	}
	url = url.replace('&','');
	if (obj.params.LAYERS.indexOf('eko_merge') >= 0 )
		url = url + '&BASE=http://gis.esimo.ru/eko/wms';
	else
		url = url + '&BASE=' + obj.url.replace('?','');
	var size = '' + map.size;
	var sizeArray = size.replace('w=','').replace('h=','').split(',');
	url = url + '&WIDTH='+sizeArray[0]+'&HEIGHT='+sizeArray[1];
	var bbox = map.getExtent();
	url = url + '&BBOX='+bbox.left+','+bbox.bottom+','+bbox.right+','+bbox.top;
			
	return url;
}

function exportMapToCanvas(mapObj){
	if (!globalReportActive){
		var divId = 'mapexport';
		$('#'+divId+'-dialog-export').remove();
		$('body').append('<div id="'+divId+'-dialog-export" style="text-align: center;" title="Предпросмотр экспортируемого изображения">'+
		'<a id="'+divId+'-dialog-export-save" class="portlet-form-button portlet-icon icon-download-image" download="image.png" href="#" target="_blank">Сохранить</a>'+
		'<input id="'+divId+'-dialog-export-cancel" type="button" class="portlet-form-button portlet-icon icon-status-error" value="Отмена"/><br/><br/>'+
		'<img id="'+divId+'-dialog-export-img"></img><br/><br/>'+
		'</div><br/>');
		$( '#'+divId+'-dialog-export').dialog({
			minWidth: 640,
			minHeight: 480,
			modal: true,
			resizable:false,
			draggable: false,
			open: function(event, ui) {
				$('#'+divId+'-dialog-export-cancel').die().live('click', function(){
					$( '#'+divId+'-dialog-export').dialog('close');
				});	
				
				$('#'+divId+'-dialog-export-img').attr('src',getLayerImageSrc(mapObj,0));
				$('#'+divId+'-dialog-export-save').attr('href',$('#'+divId+'-dialog-export-img').attr('src'));
			}
		});
	} else {
		var uniqueId = 'id' + (new Date()).getTime();
		$('#'+uniqueId+'-dialog-export').remove();
		$('body').append('<div id="'+uniqueId+'-dialog-export" style="text-align: center;" title="">'+
		'<img id="'+uniqueId+'-dialog-export-img" width="100%" height="100%"></img><br/><br/>'+
		'</div><br/>');
		$( '#'+uniqueId+'-dialog-export').dialog({
			width: 200,
			height: 200,
			modal: false,
			resizable: true,
			draggable: true,
			open: function(event, ui) {
				$('#'+uniqueId+'-dialog-export-img').attr('src',getLayerImageSrc(mapObj,0));
			}
		}).parent().resizable({ 
			containment: "#report-div"
			}).draggable({ 
				containment: "#report-div",
			}).appendTo("#report-div").position({
			  my: "center",
			  at: "center",
			  of: "#report-div"
		});
	}
}

(function($){  

 $.fn.makemap = function() {  
    return this.each(function() {
		var namespace = $(this).attr('id');
	    var latmin = '-22';
		if ($(this).attr('latmin'))
			latmin = $(this).attr('latmin');
			
		var latmax = '85';	
		if ($(this).attr('latmax'))
			latmax = $(this).attr('latmax');
			
		var lonmin = '-90';	
		if ($(this).attr('lonmin'))
			lonmin = $(this).attr('lonmin');
			
		var lonmax = '128';	
		if ($(this).attr('lonmax'))
			lonmax = $(this).attr('lonmax');
			
		if (latmin > latmax){
			var temp = latmax;
			latmax = latmin;
			latmin = temp;
		}
		if (lonmin > lonmax){
			var temp = lonmax;
			lonmax = lonmin;
			lonmin = temp;
		}
		
		if (latmin == latmax){
			latmin = parseFloat(latmin) - 5;
			latmax = parseFloat(latmax) + 5;
			
		}
		if (lonmin == lonmax){
			lonmin = parseFloat(lonmin) - 5;
			lonmax = parseFloat(lonmax) + 5;
		}	
			
		$(this).html("<div id='"+namespace+"-map-controls' class='olControlPanel'></div>"+
		"<div id='"+namespace+"-map-small' class='portlet-map-small'></div>"+
		"<label class='portlet-form-field-label-nowidth'>Координаты верхнего левого угла</label><br/>"+
		"<input id='"+namespace+"-lat-max' name='latmax'  type='text' style='width:60px;' class='portlet-form-input-field' value='"+'90'+"'></input>&nbsp;&nbsp;"+
		"<input id='"+namespace+"-lon-min'  name='lonmin' type='text' style='width:60px;' class='portlet-form-input-field' value='"+'-180'+"'></input><br/>"+
		"<label class='portlet-form-field-label-nowidth'>Координаты нижнего правого угла</label><br/>"+
		"<input id='"+namespace+"-lat-min' name='latmin' type='text' style='width:60px;' class='portlet-form-input-field' value='"+'-90'+"'></input>&nbsp;&nbsp;"+
		"<input id='"+namespace+"-lon-max' name='lonmax' type='text' style='width:60px;' class='portlet-form-input-field' value='"+'180'+"'></input><br/>"+
		"<label class='portlet-form-field-label-nowidth'>Быстрый выбор района:</label><br/><select id='"+namespace+"-select' class='portlet-form-input-field'  style='width:150px;'>"+
		"<option value='world' selected>Мировой океан</option>"+
		"<option value='russia' >Моря России</option>"+
		"<option value='azov' >Азовское море</option>"+
		"<option value='balt' >Балтийское море</option>"+
		"<option value='barents' >Баренцево море</option>"+
		"<option value='white' >Белое море</option>"+
		"<option value='bering' >Берингово море</option>"+
		"<option value='eastsib' >Восточно-сибирское море</option>"+
		"<option value='casp' >Каспийское море</option>"+
		"<option value='kara' >Карское море</option>"+
		"<option value='lapt' >Море Лаптевых</option>"+
		"<option value='okhot' >Охотское море</option>"+
		"<option value='black' >Черное море</option>"+
		"<option value='chuk' >Чукотское море</option>"+
		"<option value='japan' >Японское море</option>"+		
		"</select><br/><br/>"
		);
		$("#"+namespace+"-lat-min,#"+namespace+"-lat-max, #"+namespace+"-lon-min, #"+namespace+"-lon-max ").keydown(function(event) {
        if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 190 || event.keyCode == 109) {
        }
        else {
            if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
                event.preventDefault(); 
            }   
        }
		});
		$(this).css('padding-bottom','150px');
		
		var oMap = makeMap(namespace, latmin, latmax, lonmin, lonmax);
		
		$("#"+namespace+"-select").change(function(event) {
			oMap.zoomToExtent(getCoords($(this).val()),true);
			$("#"+namespace+"-lat-min").val(getCoords($(this).val()).bottom);
			$("#"+namespace+"-lat-max").val(getCoords($(this).val()).top);
			$("#"+namespace+"-lon-min").val(getCoords($(this).val()).left);
			$("#"+namespace+"-lon-max").val(getCoords($(this).val()).right);
 		});
    });  
 };

 $.fn.makemaprss = function(settings){
    var config = {
        'rssurl': '',
		'iconurl':'/portal-core/themes/esimo-central/images/icons/icon-map-marker.png'
    };
    if (settings){$.extend(config, settings);} 
		
    return this.each(function() {
		var namespace = $(this).attr('id');
	    var latmin = '18';
		if ($(this).attr('latmin'))
			latmin = $(this).attr('latmin');
			
		var latmax = '82';	
		if ($(this).attr('latmax'))
			latmax = $(this).attr('latmax');
			
		var lonmin = '29';	
		if ($(this).attr('lonmin'))
			lonmin = $(this).attr('lonmin');
			
		var lonmax = '165';	
		if ($(this).attr('lonmax'))
			lonmax = $(this).attr('lonmax');
			
		if (latmin > latmax){
			var temp = latmax;
			latmax = latmin;
			latmin = temp;
		}
		if (lonmin > lonmax){
			var temp = lonmax;
			lonmax = lonmin;
			lonmin = temp;
		}
		
		if (latmin == latmax){
			latmin = parseFloat(latmin) - 5;
			latmax = parseFloat(latmax) + 5;
			
		}
		if (lonmin == lonmax){
			lonmin = parseFloat(lonmin) - 5;
			lonmax = parseFloat(lonmax) + 5;
		}	
			
		$(this).html("<div id='"+namespace+"-map-controls' class='olControlPanel'></div>"+
		"<div id='"+namespace+"-map-small' class='portlet-map-small'></div><br/>"+
		"<label class='portlet-form-field-label'>Быстрый выбор района:</label><select id='"+namespace+"-select' class='portlet-form-input-field' style='width:150px;'>"+
		"<option value='world' >Мировой океан</option>"+
		"<option value='russia' selected>Моря России</option>"+
		"<option value='azov' >Азовское море</option>"+
		"<option value='balt' >Балтийское море</option>"+
		"<option value='barents' >Баренцево море</option>"+
		"<option value='white' >Белое море</option>"+
		"<option value='bering' >Берингово море</option>"+
		"<option value='eastsib' >Восточно-сибирское море</option>"+
		"<option value='casp' >Каспийское море</option>"+
		"<option value='kara' >Карское море</option>"+
		"<option value='lapt' >Море Лаптевых</option>"+
		"<option value='okhot' >Охотское море</option>"+
		"<option value='black' >Черное море</option>"+
		"<option value='chuk' >Чукотское море</option>"+
		"<option value='japan' >Японское море</option>"+		
		"</select><br/><br/>"
		);
		
		$('#'+namespace+'-map-small').height($(this).width()*0.4);
		var oMap = makeMapRss(namespace, config.rssurl, config.iconurl, latmin, latmax, lonmin, lonmax);
		
		$("#"+namespace+"-select").change(function(event) {
			oMap.zoomToExtent(getCoords($(this).val()),true);
 		});		
    });  
 };

$.fn.makemapfull = function(settings){
    var config = {
		'basewmsurl':getWMS('eko').wmsurl,
		'basewmslayer':getWMS('eko').wmsname,
		'wms':[],
		'profileId':'',
		'featureslayer':'',
		'posturl':'',
		'postparam':'',
		'posticon':'',
        'rss': [],
		'latmin':'18',
		'latmax':'82',
		'lonmin':'29',
		'lonmax':'165',
		'title':'',
		'refreshFilter':'',
		'seaSelector': false,
		'layerSelector': {
			'enabled': false,
			'open': false
		},
		'projection':'EPSG:4326',
		'criteriaParameter':'',
		'addWMS': false
    };
    if (settings){$.extend(config, settings);} 
		
    return this.each(function() {
		var namespace = $(this).attr('id');
	    var latmin = config.latmin;
		if ($(this).attr('latmin'))
			latmin = $(this).attr('latmin');
			
		var latmax = config.latmax;	
		if ($(this).attr('latmax'))
			latmax = $(this).attr('latmax');
			
		var lonmin = config.lonmin;	
		if ($(this).attr('lonmin'))
			lonmin = $(this).attr('lonmin');
			
		var lonmax = config.lonmax;	
		if ($(this).attr('lonmax'))
			lonmax = $(this).attr('lonmax');
			
		
		try{
			if (parseFloat(latmin) > parseFloat(latmax)){
				var temp = latmax;
				latmax = latmin;
				latmin = temp;
			}
			if (parseFloat(lonmin) > parseFloat(lonmax)){
				var temp = lonmax;
				lonmax = lonmin;
				lonmin = temp;
			}
			
			if ((parseFloat(lonmin) < 0)&&(parseFloat(lonmax) > 0)){
				lonmin = '-180.0';
				lonmax = '-170.0';								
			}					
			
			if (latmin == latmax){
				latmin = parseFloat(latmin) - 5;
				latmax = parseFloat(latmax) + 5;
				
			}
			if (lonmin == lonmax){
				lonmin = parseFloat(lonmin) - 5;
				lonmax = parseFloat(lonmax) + 5;
			}	
		}catch(e){console.log(e.message);}
		
		var heightlayers = $(this).height();
		var height = heightlayers+35;
		var html = "<div id='"+namespace+"-map-controls' class='olControlPanel'></div>"+
		"<div id='"+namespace+"-map-small' class='portlet-map'></div>";
		
		if (config.layerSelector.enabled){
			html += "<div style='position:relative; top:-"+height+"px; z-index:1000; min-width:150px; width:40%;'>";
			html += "<div id='"+namespace+"-layerswitcher-button' class=' portlet-form-button portlet-section-subheader portlet-icon icon-layers' style='margin:3px 0px 2px 4px; cursor: pointer; width:40px;'>Слои</div>";
			html += "<div id='"+namespace+"-layerswitcher' class='portlet-map-layerswitcher' style='height:"+heightlayers+"px;'></div>";
			html += "</div>";
		}	
		if (config.seaSelector)
			html = html + "<label class='portlet-form-field-label' style='width: 40%;'>Быстрый выбор района:</label><select id='"+namespace+"-select' class='portlet-form-input-field' style='width:150px;'>"+
			"<option value='world' >Мировой океан</option>"+
			"<option value='russia' selected>Моря России</option>"+
			"<option value='azov' >Азовское море</option>"+
			"<option value='balt' >Балтийское море</option>"+
			"<option value='barents' >Баренцево море</option>"+
			"<option value='white' >Белое море</option>"+
			"<option value='bering' >Берингово море</option>"+
			"<option value='eastsib' >Восточно-сибирское море</option>"+
			"<option value='casp' >Каспийское море</option>"+
			"<option value='kara' >Карское море</option>"+
			"<option value='lapt' >Море Лаптевых</option>"+
			"<option value='okhot' >Охотское море</option>"+
			"<option value='black' >Черное море</option>"+
			"<option value='chuk' >Чукотское море</option>"+
			"<option value='japan' >Японское море</option>"+		
			"</select>";
			
		if (config.title != '')
		html = '<div style="font-family:Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif; font-size:12px; color:#3E576F; text-align:center; width: 100%;">'+config.title+'</div><br/>'+ html;
		
		if(config.posturl != '')
			html +='<input id="'+namespace+'-map-refresh" type="button" class="portlet-form-button portlet-icon icon-arrow-refresh" style="width:210px; display:block; margin:10px auto;" title="Обновить карту, оставив только данные по текущему району" value="Перестроить по текущему району"/>';
		
		$(this).html(html).css('padding-bottom','70px');
		
		if ((config.refreshFilter != '')&&(config.refreshFilter != undefined))
			config.postparam.refreshfilter = '(' + config.refreshFilter + ')';
		
		var profileId = config.profileId;
		if (profileId != ''){
			var wmsArr = [];
			try{
				$.ajax({
					  type: 'GET',
					  url: '/restserver/services/requests/get/'+profileId+'.json',
					  data: {},
					  async: false,
					  dataType: 'json',
					  success: function(json){
						if (json.description.profileObject == 'gis.map'){
							for (var property in json.properties)
								try{
									for (var i=0; i<json.properties[property].length; i++){
										if (json.properties[property][i].key == 'layers'){
											var layers = jQuery.parseJSON(json.properties[property][i].value);
											for (var j in layers){
												wmsArr.push({
													 "url":layers[j].url,
													 "layers":layers[j].layername,
													 "visibility":layers[j].visible
												});
											}
											
										}else if(json.properties[property][i].key == 'extent'){
											try{
												var extent = json.properties[property][i].value;
												var extentObj = new OpenLayers.Bounds (extent.split(",")[0], extent.split(",")[1], extent.split(",")[2], extent.split(",")[3]).transform("EPSG:900913","EPSG:4326");
												latmin = extentObj.bottom;
												latmax = extentObj.top;
												lonmin = extentObj.left;
												lonmax = extentObj.right;
											}catch(e){console.log(e.message);} 
										}
									}	
								}catch(e){console.log(e.message);}	
						}
					  }
				}); 
			}catch(e){console.log(e.message);}	
			if (wmsArr.length > 0)
				config.wms = wmsArr;
 	}
		
		var oMap = makeMapFull(namespace, config.basewmsurl, config.basewmslayer, config.wms, config.featureslayer, config.posturl, config.postparam, config.posticon, config.rss, latmin, latmax, lonmin, lonmax, config.layerSelector, config.projection, config.criteriaParameter);
		globalMapObject[namespace] = oMap;
		if(config.layerSelector.enabled != true)
			$('#'+namespace+' .olControlLayerSwitcher').remove();
		if (config.addWMS){
			$('#'+namespace+'-layerswitcher').prepend('<input id="'+namespace+'-addlayerbutton" class="portlet-form-button portlet-icon icon-layer-add" type="button" value="Добавить геосервис"/>');
			//var layerDefaultFirst = $('#'+namespace+'-layerswitcher .dataLayersDiv input:checkbox').first().index();
			//var layerDefaultLast = $('#'+namespace+'-layerswitcher .dataLayersDiv input:checkbox').last().index();
			$('#'+namespace+'-addlayerbutton').click(function(e){
						showDialogWmsCatalogue(namespace,globalMapObject[namespace],config.wms);
						/*var uniq = (new Date()).getTime();
						var layer = new OpenLayers.Layer.WMS(uniq,
							uniq,
							{'layers': uniq, transparent: "true", format: "image/png"},
							{isBaseLayer: false, visibility: false, opacity: 0.9}
						);
						
						globalMapObject[namespace].addLayer(layer);
						var c_LayerSwitcher = globalMapObject[namespace].getControlsByClass("OpenLayers.Control.LayerSwitcher")[0]; 
						c_LayerSwitcher.redraw(); 
						config.wms.push({
							 "url":uniq,
							 "layers":uniq,
							 "name":uniq,
							 "LatLonBoundingBox": '',
							 "EX_GeographicBoundingBox": '',
							 "visibility": false
						});
						//console.log(layerDefaultFirst);
						//console.log(layerDefaultLast);
						
						addLayerGeoSearch(namespace,globalMapObject[namespace],config.wms);*/
						
			});
		}
		
		if(config.posturl != '')
			$('#'+namespace+'-map-refresh').die().live('click',function(){
				var refreshConfig = config;
				refreshConfig.latmin = globalMapObject[namespace].getExtent().bottom;
				refreshConfig.latmax = globalMapObject[namespace].getExtent().top;
				refreshConfig.lonmin = globalMapObject[namespace].getExtent().left;
				refreshConfig.lonmax = globalMapObject[namespace].getExtent().right;
				refreshConfig.refreshFilter = '(m4311 between '+refreshConfig.latmin+' and '+refreshConfig.latmax+') and (m4312 between '+refreshConfig.lonmin+' and '+refreshConfig.lonmax+')';
				$('#'+namespace).html('').makemapfull(refreshConfig);
			});
		
		if (!(config.layerSelector.open))
			$("#"+namespace+"-layerswitcher").slideToggle({
				'duration': 0
			});
		
		$("#"+namespace+"-select").change(function(event) {
			oMap.zoomToExtent(getCoords($(this).val()),true);
 		});
		$("#"+namespace+"-layerswitcher-button").click(function(event) {
			$("#"+namespace+"-layerswitcher").slideToggle({
				'duration': 100
			});
 		});

    });  
 };
 

 $.fn.makeMapDataFilterResource = function(settings){
    var config = {
		'basewmsurl':getWMS('eko').wmsurl,
		'basewmslayer':getWMS('eko').wmsname,
		'resourceId':'',
		'column':'',
		'latmin':'18',
		'latmax':'82',
		'lonmin':'29',
		'lonmax':'165',
		'title':'',
		'filter':[],
		'refreshFilter':'',
		'allowExport': true,
		'metadataResource':{
				'resourceId':'',
				'codeIn':'',
				'codeOut':''
		},
		'wms':[],
		'criteriaParameter':''
    };
    if (settings){$.extend(config, settings);} 
		
    return this.each(function() {
		var namespace = $(this).attr('id');
	    var latmin = parseFloat(config.latmin);
		if ($(this).attr('latmin'))
			latmin = parseFloat($(this).attr('latmin'));
			
		var latmax = parseFloat(config.latmax);	
		if ($(this).attr('latmax'))
			latmax = parseFloat($(this).attr('latmax'));
			
		var lonmin = parseFloat(config.lonmin);	
		if ($(this).attr('lonmin'))
			lonmin = parseFloat($(this).attr('lonmin'));
			
		var lonmax = parseFloat(config.lonmax);	
		if ($(this).attr('lonmax'))
			lonmax = parseFloat($(this).attr('lonmax'));
			
		if (latmin > latmax){
			var temp = latmax;
			latmax = latmin;
			latmin = temp;
		}
		if (lonmin > lonmax){
			var temp = lonmax;
			lonmax = lonmin;
			lonmin = temp;
		}
		
		if (latmin == latmax){
			latmin = parseFloat(latmin) - 5;
			latmax = parseFloat(latmax) + 5;
			
		}
		if (lonmin == lonmax){
			lonmin = parseFloat(lonmin) - 5;
			lonmax = parseFloat(lonmax) + 5;
		}			
		
		var heightlayers = $(this).height();
		var height = heightlayers+50;
		var width = $(this).width();
		var html = "<div id='"+namespace+"-map-controls' class='olControlPanel'></div>"+
		"<div id='"+namespace+"-map-small' class='portlet-map'></div><br/>";
		
		if (config.title != '')
		html = '<div style="font-family:Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif; font-size:12px; color:#3E576F; text-align:center; width: 100%;">'+config.title+'</div><br/>'+ html;
		
		//if (config.allowExport){
		//	html += '<input id="'+namespace+'-map-export" title="Экспортировать рисунок" class="portlet-form-button portlet-icon-notext icon-export-image" style="position:relative; right:-'+(width-27)+'px; top:-'+(height+2)+'px; z-index:1000; width:22px; height:22px;" type="button"></input>';			
		//}
		
		html +='<input id="'+namespace+'-map-refresh" type="button" class="portlet-form-button portlet-icon icon-arrow-refresh" style="width:210px; display:block; margin:0 auto;" title="Обновить карту, оставив только данные по текущему району"  value="Перестроить по текущему району"/>';
		
		$(this).html(html).css('padding-bottom','100px');
		
		var filterstr = '';
		if ((config.filter.length > 0)||(config.refreshFilter != '')){
			for (var i=0; i<config.filter.length; i++)
				filterstr += 'and (' + config.filter[i] + ')';
			if (config.refreshFilter != '')
				filterstr += 'and (' + config.refreshFilter + ')';
			filterstr = filterstr.replace('and ','');
		}
		
		var oMap = makeMapFilterResource(namespace, config.basewmsurl, config.basewmslayer, config.resourceId, filterstr, config.column, lonmin, latmin, lonmax, latmax,config.metadataResource,config.wms,config.criteriaParameter);
		globalMapObject[namespace] = oMap;
		$('#'+namespace+'-map-refresh').die().live('click',function(){
			var refreshConfig = config;
			refreshConfig.latmin = globalMapObject[namespace].getExtent().bottom;
			refreshConfig.latmax = globalMapObject[namespace].getExtent().top;
			refreshConfig.lonmin = globalMapObject[namespace].getExtent().left;
			refreshConfig.lonmax = globalMapObject[namespace].getExtent().right;
			refreshConfig.refreshFilter = '(m4311 between '+refreshConfig.latmin+' and '+refreshConfig.latmax+') and (m4312 between '+refreshConfig.lonmin+' and '+refreshConfig.lonmax+')';
			$('#'+namespace).html('').makeMapDataFilterResource(refreshConfig);
		});
		
		//$('#'+namespace+'-map-export').die().live('click',function(){
		//	exportMapToCanvas(oMap);
		//});

    });  
 };
 
 function addWmsToMap(mapObj, wmsUrl){
 
 }
 
 $.fn.makeMapFromWMS = function(settings){
    var config = {
		'latmin':'18',
		'latmax':'82',
		'lonmin':'29',
		'lonmax':'165',
		'wmsurl':'',
		'projection':'EPSG:4326'
    };
    if (settings){$.extend(config, settings);} 
		
    return this.each(function() {
		if (config.wmsurl != ''){
			if ($(this).attr('id') == undefined)
				$(this).attr('id','id' + (new Date()).getTime());
			var domObj = $(this).get();			
			var wmsurl = config.wmsurl;
			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);}
			//alert(wmsurl);
			var url = '/restserver/services/c/convert.json?url='+wmsurl+capabilities;
			if (wmsurl.indexOf('gptl.ru') >= 0)
				url = '/dataview/xmltojson?xmlurl='+wmsurl.replace("?","&")+capabilities;
			//console.log(url);
			$(domObj).html('<div class="portlet-font portlet-icon icon-loading-bar-small" style="width:100px;height:15px; position: absolute; top:50%; left:50%; margin:-8px 0 0 -50px;">Загрузка</div>');
			$.ajax({
				  type: 'GET',
				  url: url,
				  //url: '/restserver/services/c/capabilities.json',
				  //data: {"url":wmsurl},
				  async: true,
				  dataType: 'json',
				  timeout: 30000,
				  error: function(e){
						$(domObj).html('<div class="portlet-font portlet-icon icon-status-error" style="width:200px;height:15px; position: absolute; top:50%; left:50%; margin:-8px 0 0 -100px;">Ошибка чтения геосервиса</div>');
				  },
				  success: function(json){
						try{
							//alert(json.toSource());
							var layersArray = json.Capability.Layer.Layer;
							var wmsObj = [];
							for (var i = layersArray.length-1;i>=0; i--){
								try{
									if ((layersArray[i].Name != undefined)&&(layersArray[i].Name != '')){
										wmsObj.push({
											 "url":config.wmsurl,
											 "layers":layersArray[i].Name,
											 "name":layersArray[i].Title,
											 "LatLonBoundingBox": layersArray[i].LatLonBoundingBox,
											 "EX_GeographicBoundingBox": layersArray[i].EX_GeographicBoundingBox,
											 "visibility": false
										});
									}	
								}catch(e){console.log(e.message);}
							}	
							
							wmsObj = sortByKey(wmsObj, 'name');	

							var projection = config.projection;
							try{
								var projectionArray = layersArray[0]['SRS'];
								if (projectionArray != undefined)
									for (var i = 0; i<projectionArray.length; i++)
										if (projectionArray[i] == 'EPSG:900913')
											projection = 'EPSG:900913';
							}catch(e){console.log(e.message);}

							$(domObj).html('').makemapfull({
								 "wms": wmsObj,
								 'latmin': config.latmin,
								 'latmax': config.latmax,
								 'lonmin': config.lonmin,
								 'lonmax': config.lonmax,
								 'layerSelector':{
									'enabled': true,
									'open': true
								 },
								'addWMS': true,
								'projection': projection
							});
						} catch(e){
							$(domObj).html('<div class="portlet-font portlet-msg-error" style="width:300px;height:15px; position: absolute; top:50%; left:50%; margin:-8px 0 0 -100px;">Ошибка получения списка слоев из геосервиса</div>');;
						}	
				  }
			});			
		}
    });  
 }; 
 
	$.fn.makeMapPopup = function(settings){
		var config = {
			'basewmsurl':getWMS('eko').wmsurl,
			'basewmslayer':getWMS('eko').wmsname,
			'wms':[],
			'profileId':'',
			'featureslayer':'',
			'posturl':'',
			'postparam':'',
			'posticon':'',
			'rss': [],
			'latmin':'18',
			'latmax':'82',
			'lonmin':'29',
			'lonmax':'165',
			'title':'',
			'refreshFilter':'',
			'seaSelector': false,
			'layerSelector': {
				'enabled': false,
				'open': false
			},
			'projection':'EPSG:4326',
			'criteriaParameter':'',
			'addWMS': false
		};
		if (settings){$.extend(config, settings);} 
	
		return this.each(function() {
				var tempmapid = new Date().getMilliseconds();
				var title = config.title;
				$('body').append('<div id="'+tempmapid+'" title="'+title+'" style="text-align: center;">'+
				'<div id="'+tempmapid+'-display" style="width:100%;height:90%;"></div><br/>'+
				'</div>');
				$( '#'+tempmapid ).dialog({
					width:640,
					height:480,
					resizable: false
				}).parent().draggable({ 
					containment: $('body')
				});				
				config.title = '';
				$('#'+tempmapid).makemapfull(config);
		});  
	};
	
	$('.clickable-preview').die().live('click', function(){
		var posturl = '';
		var postparam = '';
		var posticon = '';
		if ($(this).attr('esimo-resource') != undefined){
			posturl = '/dataview/viewgeo';
			postparam = {resourceId:$(this).attr('esimo-resource'),filter:''};
		}	
		if ($(this).attr('esimo-platform') != undefined){
			try{
				posticon = globalPlatformTypes[$(this).attr('esimo-platform')];
				posticon = posticon.substring(posticon.indexOf('icon-platform-'),posticon.indexOf('icon-platform-')+16);
			}catch(e){ console.log(e.message);}	
		}
		
		var wms = [];
		if ($(this).attr('esimo-wmsurl'))
		if ($(this).attr('esimo-layer')){
			wms.push({
				 "url":$(this).attr('esimo-wmsurl'),
				 "layers":$(this).attr('esimo-layer'),
				 "name":'Слой',
				 "visibility": true
			});
		}
		var latmin = 18;
		var latmax = 82;
		var lonmin = 29;
		var lonmax = 165;
		try{
			if ($(this).attr('esimo-bbox'))
			if ($(this).attr('esimo-bbox') != 'undefined'){
				latmin = $(this).attr('esimo-bbox').split(',')[0];
				latmax = $(this).attr('esimo-bbox').split(',')[2];
				lonmin = $(this).attr('esimo-bbox').split(',')[1];
				lonmax = $(this).attr('esimo-bbox').split(',')[3];
			}
		}catch(e){
			console.log(e.message);
		}
		$(this).makeMapPopup({
			'title': 'Предпросмотр',
			'posturl': posturl,
			'postparam': postparam,
			'posticon':posticon,
			'wms': wms,
			'latmin':latmin,
			'latmax':latmax,
			'lonmin':lonmin,
			'lonmax':lonmax
		});		
	});
	
	$('.clickable-profilepreview').die().live('click', function(){
		var profileId = $(this).attr('esimo-mapprofile');
		if (profileId)
			$(this).makeMapPopup({
				'title':'Предпросмотр профиля #'+profileId,
				'profileId':profileId,
				'layerSelector': {
						'enabled': true,
						'open': false
				},
				'addWMS': true
			});		
	});
	
	$('.clickable-wmspreview').die().live('click', function(){
		var wmsurl = $(this).attr('esimo-wmsurl');
		if (wmsurl){
			var tempmapid = new Date().getMilliseconds();
			var title = 'Предпросмотр WMS';
			$('body').append('<div id="'+tempmapid+'" title="'+title+'" style="text-align: center;">'+
			'<div id="'+tempmapid+'-display" style="width:100%;height:90%;"></div><br/>'+
			'</div>');
			$( '#'+tempmapid ).dialog({
				width:900,
				height:600,
				resizable: false
			}).parent().draggable({ 
				containment: $('body')
			});		
			var bbox = $(this).attr('esimo-bbox');
			if (bbox)
				$('#'+tempmapid).makeMapFromWMS({
					'wmsurl':wmsurl,
					'latmin':bbox.split(',')[1],
					'latmax':bbox.split(',')[3],
					'lonmin':bbox.split(',')[0],
					'lonmax':bbox.split(',')[2]
				});
			else
				$('#'+tempmapid).makeMapFromWMS({
					'wmsurl':wmsurl					
				});			
		}	
	});

})(jQuery); 



var pageX;
var pageY;
$(document).mousemove(function(e){
  pageX = e.pageX;
  pageY = e.pageY;
}); 