if (OVMODE=="view") {
	window.PROXY = (window.PROXY_URL+"&urltoproxify=" || "") .replace("&amp;","&");
	//TODO: make configurable
	var im = new Image();
	//im.src = 'http://oceanviewer.ru/resources/web/';
	im.src = CONFIG.composer.uploadUrl;

	//constants

	Ext.BLANK_IMAGE_URL = CONFIG.blankImageUrl;

	GPOpenLayers.ImgPath = CONFIG.GPOpenLayersImgPath;

	Gispro.Utils.TRANSLATE_URL = CONFIG.translateUrl;

	Gispro.Utils.METADATA_URL = CONFIG.metadataUrl;

	GPOpenLayers.IMAGE_RELOAD_ATTEMPTS = CONFIG.imageReloadAttempts;

	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	Ext.override(GPOpenLayers.Layer.GeoRSS, {
		parseData: RssPopupParseData
	});

	Ext.override(GPOpenLayers.Control.WMSGetFeatureInfo, {
		getInfoForClick: RssPopupGetInfoForClick
	});

	Ext.override(GeoExt.tree.LayerNode, {
		render: RssPopupLayerNodeRender
	});

	Ext.override(gxp.Viewer, {
		getState: RssPopupGetState
	});

	Ext.override(GeoExt.tree.LayerLoader, {
		addLayerNode: RsspopupAddLayerNode
	});

	Ext.override(gxp.plugins.RemoveLayer, {
		addActions: RssPopupAddActions
	});

	//Ext.override(gxp.WMSLayerPanel, {
	//	createDisplayPanel: RssSourceCreateDisplayPanel
	//});

	Ext.override(GeoExt.LegendPanel, {
		addLegend : animationAddLegend
	});

	Ext.override(GeoExt.tree.LayerNode, {
		render : animationRender
	});

	Ext.override(GeoExt.LegendPanel, {
		recordIndexToPanelIndex : animationRecordIndexToPanelIndex
	});

	Ext.override(GeoExt.data.LayerStore, {
		onAdd : animationOnAdd
	});

	Ext.override(GeoExt.tree.LayerNode, {
		onStoreAdd : animationOnStoreAdd
	});

	Ext.override(GeoExt.tree.LayerLoader, {
		onStoreAdd : animationLayerLoaderOnStoreAdd
	});
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

	Ext.onReady(function(){
		// hack to dynamic ovverride portal css
		var interval = window.setInterval(function(){
			if ($('.olControlZoomOutItemInactive')||$('.olControlZoomInItemInactive')){
				$(".olControlZoomOutItemInactive, .olControlZoomInItemInactive").css("margin", 0);
				$(".olControlZoomOutItemInactive, .olControlZoomInItemInactive").css("border", 0);
				$(".olControlZoomOutItemInactive, .olControlZoomInItemInactive").css("background", "url("+OVROOT+"/externals/ext/resources/images/gray/panel/tool-sprites.gif)");
				$(".olControlZoomOutItemInactive").css("background-position", "15px -255px");
				$(".olControlZoomInItemInactive").css("background-position", "15px -240px");
				window.clearInterval(interval);
			}			
		}, 200);		
	});
	
	var isAlreadyInUse = function(t) {
		var count=0;;
		app.mapPanel.layers.each(function(record, index) {			
			if (record.get("title") && record.get("title").indexOf(t)+1) {																
				count ++;
			}
		});					
		return count ? t + "(" + count + ")" : t;
	}
	
	var handleStore = function(store,records,status,el,ex) {
		try{
			if (!status) {
				ex && ex.push("Информация о слоях не может быть получена - запрашиваемый ресурс не найден");
				return;
			}
			var layerRecord; 
			layerRecord = records.filter(function(elt){
				return elt.data.name == el.layername;
			})[0];
			
			if (!layerRecord) {
				ex && ex.push("Слой " + el.layername + " не найден");
				return;
			}
			
			layerRecord.resourceid = el.url;
			layerRecord.layername = el.layername;
			layerRecord.url = el.url;
			//layerRecord.workspace = "";
			layerRecord.style = el.stylename;
			layerRecord.visible = el.visible;
			layerRecord.opacity = el.opacity;
			
			if (!app.layerSources[layerRecord.resourceid]) {
				 var conf = {
					url: layerRecord.url, 
					//restUrl: (node.attributes.layer.jsonNode.serverpath+"/rest").replace(/\/\//g,"/").replace("http:/","http://"),
					title: layerRecord.layername,
					version: '1.1.1'//'1.3.0'
				};
				
				app.addLayerSource({                
					id : layerRecord.resourceid || "source"+(new Date()).getTime() ,
					config: conf, // assumes default of gx_wmssource
					callback: function(id) {
						var addLayersPlugin = app.tools.gxp_addlayers_ctl;
						// TRUE
						var name = layerRecord.layername;
						var ws = layerRecord.workspace;
						var style = layerRecord.style;
						var records = [];
						app.layerSources[id].store.each(function(record, index) {
							if ((record.get("name") == ws+":"+name) ||  (record.get("name") == name)) {
								record.data.rubstyles = style;
								record.data.title = isAlreadyInUse(record.get('title'));
								records.push(record);															
							}
						});
						if (records.length==0) {
							gxp.plugins.Logger && gxp.plugins.Logger.log(locale.logger.addLayerSourceError.replace("{0}", gxp.plugins.RubricatorTree.prototype.noRecordsFound).replace("{1}", conf.url) , gxp.plugins.Logger.prototype.LOG_LEVEL_NETWORK_LOCAL_ERRORS);														
						}
						addLayersPlugin.addLayers(records,app.layerSources[id],false,el);																												
						updateProgressbar();
					},
					fallback: function(source, msg) {
						ex && ex.push(msg);
						gxp.plugins.Logger && gxp.plugins.Logger.log(locale.logger.proxyException.replace("{0}", conf.url), gxp.plugins.Logger.prototype.LOG_LEVEL_NETWORK_LOCAL_ERRORS);													
						updateProgressbar();
					},
					scope: this
				});
			}  else {	
				//console.log(layerRecord.resourceid+' exists');
				//if (app.layerSources[layerRecord.resourceid] == undefined){
					//setTimeout(function(){
						var origrecords = records;
						if (app.layerSources[layerRecord.resourceid]){
							var id = layerRecord.resourceid;
							var addLayersPlugin = app.tools.gxp_addlayers_ctl;
							// TRUE
							var name = layerRecord.layername;
							var ws = layerRecord.workspace;
							var style = layerRecord.style;
							var records = [];											
							app.layerSources[id].store.each(function(record, index) {
								if ((record.get("name") == ws+":"+name) ||  (record.get("name") == name)) {
									record.data.rubstyles = style;
									record.data.title = isAlreadyInUse(record.get('title'));
									records.push(record);
								}
							});
							if (records.length==0) {
								console.log('not added '+layerRecord.resourceid+' settimeout');
								setTimeout(function(){
									handleStore(store,origrecords,status,el,ex);
								}, 10000);
								//gxp.plugins.Logger && gxp.plugins.Logger.log(locale.logger.addLayerSourceError.replace("{0}", gxp.plugins.RubricatorTree.prototype.noRecordsFound).replace("{1}", conf.url) , gxp.plugins.Logger.prototype.LOG_LEVEL_NETWORK_LOCAL_ERRORS);														
								//updateProgressbar();
							}
							else{ 
								addLayersPlugin.addLayers(records,app.layerSources[id],false,el);	
								updateProgressbar();
							}
						}/*else{
							setTimeout(function(){
								console.log(layerRecord.resourceid+' settimeout');
								handleStore(store,origrecords,status,el,ex);
							}, 15000);
						}*/
					//}, 15000);
				//}
			}
		}catch(e){console.log(e.message);}
	}
	
	var updateProgressbar = function() {
		var c = Ext.getCmp('profileLoadPb');
		c.loaded ++;
		var profileId;
		try {
			profileId = Ext.urlDecode(document.URL.split("?")[1]).profileId;
			if (profileId == undefined)
			if (PROFILE_ID != 'WRONG')
				profileId = PROFILE_ID;
		} catch (e) {
		}
		if (profileId)
			c.updateProgress(c.loaded/c.count, /*locale.labels.composer.layersLoading +*/ "Профиль #"+profileId+". Слоев загружено: " +c.loaded + ". Всего: " +  (c.count+1));
		else
			c.updateProgress(c.loaded/c.count, locale.labels.composer.layersLoading + ": " +c.loaded + "/" +  c.count);
		/*if (c.loaded >= c.count) {
			window.setTimeout(function(){c.hide();},2.5);
		}*/
	}
	
	var processWms = function (el,ex){
		app.profileStores = app.profileStores || {};
		if (!app.profileStores[el.url]) {
			app.profileStores[el.url] = new GeoExt.data.WMSCapabilitiesStore({
				url: PROXY + el.url + "/wms?service=wms&version=1.1.1&request=getcapabilities",
				autoLoad: true,
				listeners : {
					load : function(a,b,c){
						handleStore.apply(this,[a,b,c,el,ex]);
					}
				}
			});
		} else {			
			if (app.profileStores[el.url].getRange().length==0) {
				app.profileStores[el.url].on('load', function() {handleStore.apply(this,[app.profileStores[el.url],app.profileStores[el.url].getRange(),true,el,ex])});
			} else {
				handleStore.apply(this,[app.profileStores[el.url],app.profileStores[el.url].getRange(),true,el,ex]);
			}
		}	
	}
	
	var processRss = function(el,ex) {
		var _el = el;
		GPOpenLayers.Request.issue({
			method: "GET",
			url: OVROOT + "/services?service=rss&action=getSingle&id="+el.id,
			async: true,                    
			callback: function(request) {
				var res;
				try { 
					res = JSON.parse(request.responseText);
				} catch (e) {
					ex && ex.push(request.responseText);
				}
				if (!res || !res.services[0]) return;
				else res = res.services[0];
				
				var source = app.layerSources['rss'];
				if (!source)
					source = new gxp.plugins.RssSource();
				
				var records = [];										
				app.layerSources['rss'].getLayersStore().each(function(record, index) {
					if (record.get("url") == res.url) {																														
						record.data.title = record.get('title') + (isAlreadyInUse(record.get('title')) ? " ("+res.title+")" : "");												
						record.data.style = res.icon;												
						records.push(record);																
					}
				});
				if (records.length==0) {
					var config = {
						url: res.url,
						title: res.title,
						name: res.name,
						icon:res.icon
					};

					record = source.createLayerRecord(config); 
					
					var rssStore = source.getLayersStore();
					
					_el.opacity = typeof (_el.opacity) == "undefined" ? 1 : _el.opacity;
					_el.visible = typeof (_el.visible) == "undefined" ? true : _el.visible;
					record.get("layer").setOpacity(_el.opacity);
					record.get("layer").setVisibility(_el.visible);
					
					rssStore.add([record]);														
					app.mapPanel.layers.add([record]);
				} else {
					var record = source.createRecord(res.name); 											

					if (record) {
						_el.opacity = typeof (_el.opacity) == "undefined" ? 1 : _el.opacity;
						_el.visible = typeof (_el.visible) == "undefined" ? true : _el.visible;
						record.get("layer").setOpacity(_el.opacity);
						record.get("layer").setVisibility(_el.visible);
						app.mapPanel.layers.add([record]);	
					}
				}
				updateProgressbar();
			}
		});		
	}
	
	var processArcgis = function(el,ex) {
	var _el = el;
		GPOpenLayers.Request.issue({
			method: "GET",
			url: OVROOT + "/services?service=arcgis&action=getSingle&id="+el.id,
			async: true,                    
			callback: function(request) {
				var res;
				try { 
					res = JSON.parse(request.responseText);
				} catch (e) {
					ex && ex.push(request.responseText);
				}
				if (!res || !res.servers[0]) return;
				else res = res.servers[0];				
		
			
				var source = app.layerSources['arcgis93']; 
				if (!source)
					source = new gxp.plugins.ArcGIS93Source();
				var url = res.url;
				var layerStore = app.mapPanel.layers;
				
				var curl  = url + '?layers=show:' + res.id;
				var layer = source.createLayer(res.title, curl);
				_el.opacity = typeof (_el.opacity) == "undefined" ? 1 : _el.opacity;
				_el.visible = typeof (_el.visible) == "undefined" ? true : _el.visible;
				layer.setOpacity(_el.opacity);
				layer.setVisibility(_el.visible);
				record = source.createRecord(res.id, layer);
				if (record)
					layerStore.add([record]);
				
				updateProgressbar();
			}
		});
	}
	
	var processAnimation = function(el,ex) {
		GPOpenLayers.Request.issue({
			method: "GET",
			url: OVROOT + "/services?service=animation&action=getSingle&anim_id="+el.id,
			async: true,                    
			callback: function(request) {
				var res;
				try { 
					res = JSON.parse(request.responseText);
				} catch (e) {
					ex && ex.push(request.responseText);
				}
				if (!res || !res.layers[0]) return;
				else res = res.layers[0];			
				
				var source = app.layerSources['animation'];
				if (!source)
					source = new gxp.plugins.AnimationSource();
				
				var records = [];										
				app.layerSources['animation'].getLayersStore().each(function(record, index) {
					if (record.get("url") == res.url) {																														
						record.data.title = record.get('title') + (isAlreadyInUse(record.get('title')) ? " ("+res.title+")" : "");												
						record.data.style = res.style;												
						record.data.format = res.format;												
						records.push(record);																
					}
				});

				if (records.length==0) {
					var config = {
						url: res.url,
						title: res.title,
						name: res.layers.join(","),
					};

					record = source.createLayerRecord(config); 
					
					var store = source.getLayersStore();
					store.add([record]);														
					app.mapPanel.layers.add([record]);
				} else {
					//var record = source.createRecord(res.layername); 											
					record = source.createRecord(res.title,res.user_created,res.url)
					if (record) {
						app.mapPanel.layers.add([record]);	
					}
				}
				updateProgressbar();
			}
		});
	}
	
	var getProfile = function(cb) {
		var profileId;
		var profileDescription;
		var found = false;
		try {
			profileId = Ext.urlDecode(document.URL.split("?")[1]).profileId;
			if (profileId == undefined)
			if (PROFILE_ID != 'WRONG')
				profileId = PROFILE_ID;
		} catch (e) {
		}		
		// load pre-chosen profile
		if (profileId) {
			GPOpenLayers.Request.issue({
				method: "GET",
				url: /*PROXY + */CONFIG.composer.restUrl + "/get/"+profileId+".json",
				async: true,                    
				callback: function(request){
					if (request.responseText=="") return;
					profileDescription = JSON.parse(request.responseText);			
					try{
						if (profileDescription.description.profileName.indexOf('[Матрица]') != -1)
							$('.portlet-titlebar-title:contains("Интерактивная карта")').each(function(){
								$(this).html('Интерактивная карта -'+profileDescription.description.profileName.replace('[Матрица]',''));
							});
					}catch(e){					
						console.log(e.message);
					}
					cb.call(null,profileDescription);				
				}
			});
						
		}else{
			cb.call(null,profileDescription);
			Ext.getCmp('profileLoadPb') && Ext.getCmp('profileLoadPb').hide();
		}
		/* else {
			 load default profile
			var def={};
			GPOpenLayers.Request.issue({
				method: "GET",
				url: PROXY  + "&getPreference=1&key=ov_defaultProfile",
				async: false,                
				callback: function(request) 
				{					
					def = JSON.parse(request.responseText);
				}
			}); 
			def.ov_defaultProfile = PROFILE_ID;
			console.log(def.ov_defaultProfile);
			if (def.ov_defaultProfile != undefined)
			if (def.ov_defaultProfile != "")
			if (def.ov_defaultProfile != "WRONG") {
				try {
					GPOpenLayers.Request.issue({
						method: "GET",
						url: PROXY + CONFIG.composer.restUrl + "/get/"+def.ov_defaultProfile+".json",
						async: true,                    
						callback: function(request) 
						{
							if (request.responseText=="") return;
							profileDescription = JSON.parse(request.responseText);
							cb.call(null,profileDescription);
						}
					});
				}catch(e){
					//alert ("Ошибка при получении профиля по умолчанию")
				}
			} else {
				cb.call(null,profileDescription);	
				Ext.getCmp('profileLoadPb') && Ext.getCmp('profileLoadPb').hide();				
			}			
		}*/
		
	}
	
	var getTools = function(p) {
		var toolsArr = p.properties ? p.properties.entry.filter(function(el){return el.key=="tools"}) : [];
		if (toolsArr.length>0) {
			return JSON.parse(toolsArr[0].value);
		} 
	}
	
	var setMapView = function(p) {
		if (!p.properties) return;
		var basemapArr = p.properties.entry.filter(function(el){return el.key=="basemap"});
		if (basemapArr && basemapArr.length>0) {
			var layers = app.mapPanel.layers.getRange().filter(function(el){return (el.get('group')=="background" && el.get('name')==basemapArr[0].value)});
			if (layers.length>0) {app.mapPanel.map.setBaseLayer(layers[0].getLayer());layers[0].getLayer().setVisibility(true);}
		}
		app.mapPanel.map.zoomIn();app.mapPanel.map.zoomOut();
		
		var projectionsArr =  p.properties.entry.filter(function(el){return el.key=="projection"});
		if (projectionsArr.length>0) {
			var viewMenu;
			for (var i in app.tools){
			  if(app.tools[i].ptype=="gispro_viewmenu") viewMenu = app.tools[i]
			}
			if (viewMenu) {
				var proj = (projectionsArr[0].value == "EPSG:900913" ? "EPSG:3857" : projectionsArr[0].value);
				viewMenu.reprojectMap(proj); // ui problem!!!
				Ext.getCmp('ovProjectionRadioGroup').setValue(proj);
			}
		}
		
		window.setTimeout(function(){
			var extentArr = p.properties.entry.filter(function(el){return el.key=="extent"});
			if (extentArr.length>0) {
				app.mapPanel.map.zoomToExtent(new GPOpenLayers.Bounds(extentArr[0].value.split(",")));
			}
		},3000)
		
	}
	
	var loadLayers = function(p) {
		var layers = p.properties ?  p.properties.entry.filter(function(el){return el.key=="layers"}) : [];
		if (layers.length>0) {			
			var layersArr = JSON.parse(layers[0].value);
			if (layersArr.length>0) {
				Ext.getCmp('profileLoadPb').show();
				Ext.getCmp('profileLoadPb').loaded = 0;
				Ext.getCmp('profileLoadPb').count = layersArr.length;
				updateProgressbar();
			} else {
				Ext.getCmp('profileLoadPb').hide();
			}
			var ex = [];
			layersArr.forEach(function(el){									
				
				var layerStore = app.mapPanel.layers;									
				
				
				if (el.source=="wms") {
					processWms(el,ex);
				} else 
				if (el.source=="rss") {
					processRss(el,ex);
				} else 
				if (el.source=="arcgis") {
					processArcgis(el,ex);
				} else 
				if (el.source=="animation") {
					processAnimation(el,ex);
				} 
			});
			if (ex.length>0) {
					new gxp.plugins.AlarmReportWindow({html:"При загрузке профиля возникли ошибки",extendedMessage:ex.join("\r\n") }).show();					
				}
		}else {
			Ext.getCmp('profileLoadPb').hide();
		}
	}
	
	try{
		window.setTimeout(function(){
			try{
				var elem = document.getElementById("first-loading");
				elem.parentNode.removeChild(elem);
			}catch(e){console.log(e.message);}
			app.mapPanel.map.zoomToExtent(new GPOpenLayers.Bounds(1903954.7096012, 6124746.2015817, 13771873.467619, 11672239.965634));
		},2000);		
	}catch(e){
		console.log(e.message);
	}
	
	getProfile(function(profile){
		CONFIG.composer.profile = profile;
		CONFIG.composer.preparedTools = profile ? getTools(profile) : undefined;
		try{
			CONFIG.composer.preparedTools.splice(CONFIG.composer.preparedTools.indexOf('gxp_featureeditorpanel'),1);			
		}catch(e){console.log(e.message);}
		app = new GeoExplorer.Composer(CONFIG.composer)	
		
		try{
			downloadArcgis();
		}catch(e){
		}
		try{		
			downloadRSS();
		}catch(e){
		}
		try{
			wmsStore.load();
		}catch(e){
		}
		app.on("ready", function(){
			Ext.QuickTips.getQuickTip().maxWidth = 800
			try{
				//animationStore.load();
			}catch(e){
			}
			try{
				//aquaStore.load();
			}catch(e){
			}
			
			try{
				this.mapPanel.on('beforeprojectionchanged', function(projection){
				  if(projection == 'EPSG:3857' || projection == 'EPSG:4326'){
				//this - mapPanel
				this.layers.each(function(rec){
				  if(rec.getLayer() && rec.getLayer().params && rec.getLayer().params.LAYERS == 'eko_merge_v'){
					rec.getLayer().params.LAYERS = 'eko_merge'
				  }})
				  } else if (projection == 'EPSG:102012' || projection == 'EPSG:3576' || projection == 'EPSG:3976') {
				//this - mapPanel
				this.layers.each(function(rec){
				  if(rec.getLayer() && rec.getLayer().params && rec.getLayer().params.LAYERS == 'eko_merge'){
					rec.getLayer().params.LAYERS = 'eko_merge_v'
				  }})
				  }
				})
			}catch(e){
			}
		
			if(CONFIG.onloadResources){
			  for(var k in CONFIG.onloadResources.sources){

				this.addLayerSource({
					id: k,
					config: CONFIG.onloadResources.sources[k].config,

					callback: function(sourceId){

					  for(var i=0,len=CONFIG.onloadResources.sources[sourceId].layers.length; i<len; i++){

					app.mapPanel.layers.add([ 
					  app.layerSources[ sourceId ].createLayerRecord({
						name: CONFIG.onloadResources.sources[sourceId].layers[i],
						source: CONFIG.onloadResources.sources[sourceId].id,
						group: CONFIG.onloadResources.sources[sourceId].group,
						cached: false,
						visibility: false
					  })
					])

					  }

					}
				});

			  }
			}
			
			if (app.profile) {
				/*if (window.JOSSO_USER=="null"){
					Ext.Msg.alert(locale.labels.composer.profileLoadErrorTitle, locale.labels.composer.profileLoadError);
					gxp.plugins.Logger.log(locale.log.unauthorizedProfileLoadAttemptText.replace("{0}", app.profile.description.profileId ), gxp.plugins.Logger.prototype.LOG_LEVEL_NETWORK_LOCAL_ERRORS);
					Ext.getCmp('profileLoadPb').hide();
					return;
				}*/
				loadLayers(app.profile);
				setMapView(app.profile);
			} else {
				Ext.getCmp('profileLoadPb').hide();
			}
		})
		
		
	});
	
	

}



