window.addEventListener ? window.addEventListener('load', init, false) : window.attachEvent('onload', init);

var mapProjections;
var initProjections = function() {
	mapProjections = [{
		units: "dd",
		projection: new OpenLayers.Projection("epsg:4326"),
		initialExtent: new OpenLayers.Bounds(-10.6700, 34.5000, 31.5500, 71.0500),
		maxExtent: new OpenLayers.Bounds(-180, -90, 180, 90)
	}];
}

var map;
var geoportal;
var searchGrid;
var searchLayer;
var paramsParsed = false;
var args

function init () {
  initProjections();
	OpenLayers.Util.IMAGE_RELOAD_ATTEMPTS = 2;
	HSLayers.feedbackScript = "/map/feedback.php";
	HSLayers.Layer.WarpedWMS.proxy = "/wwwlibs/warper";
	Proj4js.libPath = "/wwwlibs/proj4js/";
	HSLayers.Print.printerUrl = "/hsprinter/print";

	OpenLayers.Marker.defaultIcon = function () {
		var size = new OpenLayers.Size(32, 32),
			offset = new OpenLayers.Pixel(-16, -32);
		return new OpenLayers.Icon(OpenLayers.Util.getImagesLocation() + "icons/blue.png", size, offset);
	};

	HS.setCookiePath('/');
	HS.setLang(HS.getLastLangCode(), true);
	OpenLayers.ProxyHost = "/cgi-bin/hsproxy.cgi?toEncoding=utf-8&url=";
	HSLayers.WMCManager.getImagesURL = "/wmc/images.php";
	HSLayers.WMCManager.inspireThemesURL = '/wmc/xsl/codelists_' + HS.getLang() + '.xml';
	HSLayers.WMCManager.wmcHandlerURL = "/wmc/index.php";

	var windowWidth = Ext.get("map").dom.scrollWidth,
		windowHeight = document.body.parentNode.clientHeight,
		headerHeight = Ext.select('#north').elements[0].clientHeight,
		mapHeight = windowHeight - headerHeight - 1;

	geoportal = new HSLayers.MapPortal({
		layout: 'fit',
		renderTo: 'map',
		height: mapHeight,
		width: windowWidth,
		stateUrl: '/wwwlibs/statusmanager/index.php',
		queryHandlerClass: OpenLayers.Handler.Point,
		panels:[ "layerSwitcher", "infoPanel", "owsPanel"],
		mapOptions: {
		projection: new OpenLayers.Projection("epsg:3035"),
		maxExtent: new OpenLayers.Bounds(-3000000, -4000000, 14000000, 11000000),
		initialExtent: new OpenLayers.Bounds(2426378.0132, 1528101.2618, 6293974.6215, 5446513.5222),
		scales: [50000000, 25000000, 10000000, 5000000, 2000000, 1000000, 500000, 250000, 100000, 50000, 20000, 10000, 5000, 2000, 1000],
		units: 'm'
		}, 
		mapProjections: mapProjections
	});

	initCatClientCompositon();

	var osm4326 = new OpenLayers.Layer.WMS(OpenLayers.i18n("OpenStreetMap"),
		"http://apps.esdi-humboldt.cz/cgi-bin/tilecache/tilecache.cgi",
		{
			layers: 'osmeurope4326',
			format: "image/png"
		}, {
			displayInLayerSwitcher: true,
			group: "OpenStreetMap",
			visibility: true,
			buffer: 1,
			ratio: 1,
			projections: [new OpenLayers.Projection("epsg:4326")],
			transitionEffect: "resize",
                        context: {
                                url: "http://osm.ccss.cz/cgi-bin/ows/wms/europe",
                                name: 'default',
                                info_format: 'text/html'
                        },
			isBaseLayer: false,
//			attribution: "<a href=\"http://www.openstreetmap.org\">OpenStreetMap</a>",
			isBaseGroup: true,
			saveWMC: false,
			singleTile: false,
      tileSize: new OpenLayers.Size(256, 256)
		}),

		osm3035 = new OpenLayers.Layer.WMS(OpenLayers.i18n("OpenStreetMap"),
		"http://apps.esdi-humboldt.cz/cgi-bin/tilecache/tilecache.cgi",
		{
			layers: 'osmeurope3035',
			format: "image/png"
		}, {
			displayInLayerSwitcher: true,
			group: "OpenStreetMap",
			visibility: true,
			buffer: 1,
			ratio: 1,
			projections: [new OpenLayers.Projection("epsg:3035")],
			transitionEffect: "resize",
                        context: {
                                url: "http://osm.ccss.cz/cgi-bin/ows/wms/europe",
                                name: 'default',
                                info_format: 'text/html'
                        },
			isBaseLayer: false,
//			attribution: "<a href=\"http://www.openstreetmap.org\">OpenStreetMap</a>",
			isBaseGroup: true,
			saveWMC: false,
			singleTile: false,
      tileSize: new OpenLayers.Size(256, 256)
		}),

	natura = new OpenLayers.Layer.WMS(OpenLayers.i18n("EEA Natura 2000 - Habitat"),
		"http://eea.4thway2sdi.org/cgi-bin/ows/wms/natura2000",
		{
			layers: 'Habitat class',
			format: "image/png"
		}, {
			displayInLayerSwitcher: true,
			group: "EEA - Natura2000",
			visibility: true,
			buffer: 1,
			alpha: true,
			projections: mapProjections,
			scales: [500000, 200000, 100000, 50000, 20000, 10000, 5000, 2000, 1000],
			transitionEffect: "resize",
			isBaseLayer: false,
			isBaseGroup: false,
			saveWMC: false,
			singleTile: true
		}),
	natura2 = new OpenLayers.Layer.WMS(OpenLayers.i18n("EEA Natura 2000 - Border"),
		"http://eea.4thway2sdi.org/cgi-bin/ows/wms/natura2000",
		{
			layers: 'Border',
			format: "image/png"
		}, {
			displayInLayerSwitcher: true,
			group: "EEA - Natura2000",
			visibility: true,
			buffer: 1,
			alpha: true,
			projections: mapProjections,
			scales: [5000000, 2000000, 1000000],
			transitionEffect: "resize",
			isBaseLayer: false,
			isBaseGroup: false,
			saveWMC: false,
			singleTile: true
		}),
	urban3035 = new OpenLayers.Layer.WMS(OpenLayers.i18n("EEA Urban Atlas"),
		"http://apps.esdi-humboldt.cz/cgi-bin/tilecache/tilecache.cgi",
		{
			layers: 'urban3035',
			format: "image/png"
		}, {
			displayInLayerSwitcher: true,
			group: "EEA - Urban atlas",
			visibility: true,
			buffer: 1,
			alpha: true,
			projections: [new OpenLayers.Projection("epsg:3035")],
			scales: [500000, 200000, 100000, 50000, 20000, 10000, 5000, 2000, 1000],
			transitionEffect: "resize",
                        context: {
                                url: "http://eea.4thway2sdi.org/cgi-bin/ows/wms/urban_atlas",
                                name: 'default',
                                info_format: 'text/html'
                        },
			isBaseLayer: false,
			isBaseGroup: false,
			saveWMC: false,
			singleTile: false,
      tileSize: new OpenLayers.Size(256, 256)
		}),

	urban4326 = new OpenLayers.Layer.WMS(OpenLayers.i18n("EEA Urban Atlas"),
		"http://apps.esdi-humboldt.cz/cgi-bin/tilecache/tilecache.cgi",
		{
			layers: 'urban4326',
			format: "image/png"
		}, {
			displayInLayerSwitcher: true,
			group: "EEA - Urban atlas",
			visibility: true,
			buffer: 1,
			alpha: true,
			projections: [new OpenLayers.Projection("epsg:4326")],
			scales: [500000, 250000, 100000, 50000, 20000, 10000, 5000, 2000, 1000],
			transitionEffect: "resize",
                        context: {
                                url: "http://eea.4thway2sdi.org/cgi-bin/ows/wms/urban_atlas",
                                name: 'default',
                                info_format: 'text/html'
                        },
			isBaseLayer: false,
			isBaseGroup: false,
			saveWMC: false,
			singleTile: false,
			tileSize: new OpenLayers.Size(256, 256)
	}),
	DEM = new OpenLayers.Layer.WMS(OpenLayers.i18n("DEM"),
		"http://129.194.231.202/ArcGIS/services/EnviroGrids/eg_dem_srtm/MapServer/WMSServer",
		{
			layers: '0',
			format: "png"
		}, {
			displayInLayerSwitcher: true,
			visibility: false,
			buffer: 1,
			ratio: 1,
			projections: mapProjections,
			transitionEffect: "resize",
			isBaseLayer: false,
			singleTile: false,
			displayOutsideMaxExtent: true,
			tileSize: new OpenLayers.Size(256, 256),
			saveWMC: false
		});

	searchLayer = new HSLayers.Layer.SearchParser("OSM Gazetter",{isBaseLayer:false,
		visibility:true,
		showDescription: true,
		target: geoportal.infoPanel,
		formatOptions:{extractStyles:true},
		externalProjection: new OpenLayers.Projection("epsg:4326"),
		internalProjection: new OpenLayers.Projection("epsg:3035"),
		displayInLayerSwitcher: false,
		iconCls: "search-box"
	});

	geoportal.map.addLayers([osm4326, osm3035, urban4326, urban3035, natura, natura2, DEM, searchLayer]);

	geoportal.infoPanel.on("clearPanel",function(){
		searchLayer.destroyFeatures();
	});

	geoportal.mapPanel.getTopToolbar().insert(4, new Ext.Button({
		cls : "x-btn-icon",
		icon : "/stuff/img/" + "embed.png",
		scope: this,
		handler: function() {
			onEmbedClicked(geoportal.mapPanel.getWidth(), geoportal.mapPanel.getHeight());
		},
		tooltip : OpenLayers.i18n("Embed into HTML")
	}));

	geoportal.mapPanel.getTopToolbar().insert(4, new Ext.Button({
		cls : 'x-btn-icon',
		icon : "/stuff/img/"+'wps.png',
		scope: this,
		handler: function() {
			onWPSClicked(geoportal.mapPanel.getWidth(), geoportal.mapPanel.getHeight());
		},
		tooltip : OpenLayers.i18n("Analyze (OGC WPS)")
	}));

	geoportal.afterInit();
	window.setTimeout("zoomToExtent()",400);
	geoportal.readStateControl.getState();
	geoportal.readStateControl.events.register("read",this,parseParams);
};

var zoomToExtent = function () {
	if (!geoportal.map.getCenter()){
		geoportal.map.zoomToExtent(new OpenLayers.Bounds(2426378.0132, 1528101.2618, 6293974.6215, 5446513.5222));
	}
	if (!paramsParsed) {
		parseParams();
	}

};

function parseParams() {
	args = OpenLayers.Util.getParameters();

	if (args.q) {
		parseAddress(args.q);
		geoportal.toolsPanel.setActiveTab(geoportal.infoPanel);
	}

	if (args.wmc) {
		OpenLayers.loadURL (
			args.wmc,
			{_rand: Math.random()},
			geoportal,
			function(r) {
				geoportal.overwriteLocalMapContext = {
					newLayers:true, // add new layers
					oldLayers:true, // set visibility to old layers
					title:true // set title of map
					};
				var oldExtent = geoportal.map.getExtent();
				geoportal.parseWMC(r);
				geoportal.map.zoomToExtent(oldExtent);
			}
		);
	}

	paramsParsed = true;

}

var onSimpleFormSubmit = function () {
	try {
		geoportal.searchGeoNames(document.simpleForm.anytext);
	} catch (e) {
		console.log(e);
	}
	return false;
};

var searchInCatalogue = function () {
	var anytext = document.simpleForm.anytext.value;
	window.location = "/catalogue/?anytext=" + anytext + "&menuId=menu0&type=";
};

var onPrintClicked = function() {
        var dialog = new HSLayers.Print.PrintDialog({
                map: geoportal.map,
                printResolution: 200,
                printTemplates: [
                        ["naturnet.html", "html", "A4 portrait (HTML)",[794,425]],
                        ["naturnet.html", "pdf", "A4 portrait (PDF)",[794,425]]
                ],
                printUrl: HSLayers.Print.printerUrl
        });
        dialog.setMap(geoportal.map);
        dialog.show();
};

var onEmbedClicked = function(width, height) {
	var dialog = new HSLayers.Embed.GeneratorDialog({
		map: geoportal.map,
		saveUrl: "/wwwlibs/statusmanager/index-embed.php",
		generateParams: {
			hslayersPath: "/wwwlibs/hslayers",
			scriptPath: "/wwwlibs/hslayers-scripts/embed.php",
			width: width,
			height: height
		}
	});
	dialog.showDialog();
}


var onWPSClicked = function(width, height) {
	wpsForm = new CCSS.WPSClient({
		url: "http://briseide02.ingr.briseide.eu:8080/geoserver/ows",
		map: geoportal.map
	});
	var win = new Ext.Window({
		width: width,
		height: height,
		items: [wpsForm]
	});
	win.show();
};

Ext.EventManager.onWindowResize(function () {
	windowWidth = document.body.parentNode.clientWidth;
	windowHeight = document.body.parentNode.clientHeight;
	headerHeight = Ext.select('#north').elements[0].clientHeight;
	this.geoportal.setHeight(windowHeight - headerHeight - 1);
	this.geoportal.setWidth(windowWidth);
}, geoportal);


