var mapLayers = [];

var SHOWMETADATA= false;
var SHOWLEGEND = false;


/*
function displayPrintPopup() {
	//don't allow printing on the smallest scales -> just do nothing.
	//if (map.getZoom() < 3)
	//	return;
	
	displayPrintPopup2();
}
*/

function displayPrintPopup() {
	
	
	removePopups();
	var htmlContent = 
		//'<div class="map_printmenu_dialog" style="width: 200px; height: 251px;">Tulosteen asettelu<form method="post"><div><input type="radio" name="PrintMenuTypeSetting">Pysty</div><div><input type="radio" name="PrintMenuTypeSetting">Vaaka</div></form><div class="print_papersize">Paperin koko<div><input type="radio" name="papersize">A4<input type="radio" name="papersize">A3</div><form name="printOptions">Tulostetaanko kohteiden tiedot?<div><input type="radio" name="mapMetaElect" value="true">Kyll�<input type="radio" name="mapMetaElect" value="false">Ei</div>Tulosta indeksikartta?<div><input type="radio" name="mapIndexElect" value="true">Kyll�<input type="radio" name="mapIndexElect" value="false">Ei</div>Tulosta merkkien selitteet?<div><input type="radio" name="legendElect" value="true">Kyll�<input type="radio" name="legendElect" value="false">Ei</div>Kirjoita tulosteen otsikko<br><input type="text" name="headerInput" id="printHeader" onfocus="javascript:selectTxtFieldContent(printHeader)"></form></div><div><input type="Button" value="Sulje"><input type="Button" value="Tulosta"></div></div>';
		
//		'<div id="printPopupDiv" class="popupContentFrame">'+
		'<div class="popupContentDiv">'+
		
		'<a class="formLabelHeader">'+Language.get('paperorientation')+'</a>'+
		'<div class="formInputGroup">'+
		'<input class="formInput" type="radio" name="PrintMenuTypeSetting" value="V" checked="true"><a class="formLabel">'+Language.get('portrait')+'</a>'+
		'<input class="formInput" type="radio" name="PrintMenuTypeSetting" value="H"><a class="formLabel">'+Language.get('landscape')+'</a>'+
		'</div>'+
		
		'<a class="formLabelHeader">'+Language.get('papersize')+'</a>'+
		'<div class="formInputGroup">'+
		'<input class="formInput" type="radio" name="papersize" value="A4" checked="true"><a class="formLabel">A4</a>'+
		'<input class="formInput" type="radio" name="papersize" value="A3"><a class="formLabel">A3</a>'+
		'</div>'+

		'<a class="formLabelHeader">'+Language.get('destinationinfo')+'</a>'+
		'<div class="formInputGroup">'+
		'<input class="formInput" type="radio" name="mapMetaElect" value="true" checked="true"><a class="formLabel">'+Language.get('yes')+'</a>'+
		'<input class="formInput" type="radio" name="mapMetaElect" value="false"><a class="formLabel">'+Language.get('no')+'</a>'+
		'</div>'+
		
		'<a class="formLabelHeader">'+Language.get('printindexmap')+'</a>'+
		'<div class="formInputGroup">'+
		'<input class="formInput" type="radio" name="mapIndexElect" value="true"><a class="formLabel">'+Language.get('yes')+'</a>'+
		'<input class="formInput" type="radio" name="mapIndexElect" value="false" checked="true"><a class="formLabel">'+Language.get('no')+'</a>'+
		'</div>'+
		
		'<a class="formLabelHeader">'+Language.get('printmaplegend')+'</a>'+
		'<div class="formInputGroup">'+
		'<input class="formInput" type="radio" name="legendElect" value="true"><a class="formLabel">'+Language.get('yes')+'</a>'+
		'<input class="formInput" type="radio" name="legendElect" value="false" checked="true"><a class="formLabel">'+Language.get('no')+'</a>'+
		'</div>'+
		
		'<div class="formInputGroup">'+
		'<a class="formLabelHeader">'+Language.get('printheader')+'</a><br>'+
		'<input class="formInput" type="text" name="headerInput" id="printHeader"></div>'+

		'<div class="formInputGroup">'+
		'<a class="formActionLabel" onclick="removePopups()">'+Language.get('close')+'</a>'+
		'<a class="formLabel">&nbsp;|&nbsp;'+
//		'<a class="formActionLabel" onclick="doPrint();">'+Language.get('print')+'</a>'+
		'<a class="formActionLabel" onclick="checkIfPrintAllowed();">'+Language.get('print')+'</a>'+
		'</div>';
//		'</div>';

		
		var printDiv = document.createElement('div');
		printDiv.className = 'popupContentFrame';
		printDiv.id = 'printPopupDiv';
		printDiv.style.position = 'absolute';
		printDiv.innerHTML = htmlContent;
		printDiv.style.right = "5px";
//		printDiv.style.top = parseInt(map.div.offsets[1])+31+'px';
		printDiv.style.top = parseInt(map.div.offsets[1])+35+'px';
		
		printDiv.style.zIndex = parseInt(map.Z_INDEX_BASE.Control) + parseInt(100);
		/*
		printDiv.style.left = parseInt(map.div.offsets[0])+160+'px';
		printDiv.style.top = parseInt(map.div.offsets[1])+31+'px';
		*/
		document.body.appendChild(printDiv);
		
	/*left-top corner of the map...*/
/*
	var lonlat = map.getLonLatFromViewPortPx(new OpenLayers.Pixel(160,31));
	map.addPopup(new OpenLayers.Popup.FramedCloud(
		"printpopup",
		lonlat,
	//	new OpenLayers.Size(200,200),
		null,
		htmlContent,
		null,
		true),
		true);
*/
}


/*
function doPrint() {
	
	if (map.getZoom() < 3)
		return;
	
	//no government grounds -> no print! If there are, callback will execute displayPrintPopup2
	checkIfPrintAllowed();
	
}
*/

/*checks whether there are govenment areas within map range. If not, don't allow print */
function checkIfPrintAllowed() {
	
	var spatial = new OpenLayers.Filter.Spatial({type: OpenLayers.Filter.Spatial.BBOX, value: map.getExtent()});
	//exclude municipalities
	var exclusion = new OpenLayers.Filter.Comparison({type: "!=", property:"category_id", value: 1000});
	var filter = new OpenLayers.Filter.Logical({type:"&&", filters: [spatial, exclusion]});
	var featureReader = new OpenLayers.Protocol.WFS.v1_1_0(
	{
		url:  wfsUrl,
		featureType: 'allareas',
		maxFeatures: 1,
		featurePrefix: "retkikartta",
		srsName: "EPSG:2393",
		callback: function(e) {
		
			if (e && e.features && e.features.length > 0) {
				doPrint();
			} else {
				alert(Language.get('printnotallowed'));
			}
		},
		extractAttributes: true
		//propertyNames: ["id"]
	});
			
	featureReader.read({filter: filter});
	
}


/*create the params and call the popup.*/
function doPrint() 
{
	//TODO: layers, center.
	var reqLayers = '';
	for (var i = 0; i < map.layers.length; i++) {
		if (map.layers[i].layerId) {
			reqLayers += map.layers[i].layerId+'_'+map.layers[i].opacity+':';
		}
	}
	reqLayers = reqLayers.substring(0,reqLayers.length -1);
	
	var poiFilter = generatePoiIdString();
	
//	var destinationFilter = destinationsLayer.filter;
	//Highlight the selected destination on the printable map.
	var destinationId = '';
	if (destinationsLayer.destinationId && destinationsLayer.visibility)
		destinationId = destinationsLayer.destinationId;
	
	var x = map.getCenter().lon;
	var y = map.getCenter().lat;
	var zoom = map.getZoom();
	
	var directions = document.getElementsByName('PrintMenuTypeSetting');
	var papersizes = document.getElementsByName('papersize');
	var papersize,direction,sx,sy = '';
	
	var papersize = 'A4';
	var direction = 'V';
	//index 1 = A3
	if (document.getElementsByName('papersize')[1].checked)
		papersize = 'A3';
	//index 1 = A3
	if (document.getElementsByName('PrintMenuTypeSetting')[1].checked)
		direction = 'H';
	//index 0 = value true. If checked, print metainfo.
	var meta = document.getElementsByName('mapMetaElect')[0].checked;
	var index = document.getElementsByName('mapIndexElect')[0].checked;
	var legend = document.getElementsByName('legendElect')[0].checked;

	var mapHeader = document.getElementById('printHeader').value;
	if (papersize == 'A4') {
		if (direction == 'V') {
			sx = 670;//680;
			sy = 890;//900;
		} else {
			sx = 990;//1000;
			sy = 570;//580;
		}
	} else if (papersize == "A3") {
		if (direction == 'V') {
			sx = 990;//1000;
			sy = 1360;//1370;
		} else {
			sx = 1460;//1470;
			sy = 890;//905;
		
		}
	}

	var lang = 'fi';
	if (LANGUAGE_SELECTION)
		lang = LANGUAGE_SELECTION;

	var url = './print.php?'+
				'lang='+lang+'&'+
				'layers='+reqLayers+'&'+
				'x='+x+'&'+
				'y='+y+'&'+
				'zoom='+zoom+'&'+
				'sx='+sx+'&'+
				'sy='+sy;
	if (meta)
		url += '&meta=true';			
	if (index)
		url += '&index=true';			
	if (legend)
		url += '&legend=true';			
	if (mapHeader && mapHeader.length > 0) {
		url += '&header='+mapHeader;			
	}
	

	if (poiFilter && poiFilter.length) {
		url += '&pois='+poiFilter;
	}
	
	if (destinationId && destinationId.length) {
		url += '&dest='+destinationId;
	}


	removePopups();
	window.open(url,'printwindow');
}

function initPrintableMap() {

	//???
	OpenLayers.Util.onImageLoadErrorColor = "";
	
	//comment out for umbriel!
	//if (!OpenLayers.ProxyHost) {
	//	OpenLayers.ProxyHost = "/cgi-bin/proxy.cgi?url=";
	//}
	
	initLayerTree();
	
	var layers = getRequestParam('layers');
	var x = getRequestParam('x');
	var y = getRequestParam('y');
	
	//div size in pixels -> dependent on paper size / direction.
	var sx = getRequestParam('sx');
	var sy = getRequestParam('sy');
	
	document.getElementById('print_map').style.width = sx +'px';
	document.getElementById('print_map').style.height = sy +'px';

	document.getElementById('print_header').style.width = sx +'px';
	document.getElementById('printMetaData').style.width = sx +'px';

	var pois = getRequestParam('pois');
	var zoom = getRequestParam('zoom');
	var meta =  getRequestParam('meta');
	var legend =  getRequestParam('legend');
	var index =  getRequestParam('index');
	SHOWMETADATA = meta;
	SHOWLEGEND = legend;


	//add the header for legend graphics div.
	/*
	if (SHOWLEGEND) {
		document.getElementById('legendgraphicDiv').innerHTML = 
			'<br/><div class="formLabel" style="font-size:16px; font-weight: bold;">'+
				Language.get('legendgraphic')+
			'</div>';
	}
	*/
	
	
	var mapHeader = getRequestParam('header');
	
	
	var lang = getRequestParam('lang');
	LANGUAGE_SELECTION = 'fi';
	if (lang && (lang=='fi' || lang=='se' || lang=='en') )
		LANGUAGE_SELECTION = lang;
	if (mapHeader)
		document.getElementById('mapHeader').innerHTML = mapHeader;
	
	
	var destinationId = getRequestParam('dest');
	
	mapLayers = [];
//	alert(layers+' '+x+' '+y+' '+pois);

	var layerSplit = layers.split(':');
	for (var i = 0; i < layerSplit.length; i++) {
	
		var	layerId = layerSplit[i].split('_')[0];
		var	opacity = layerSplit[i].split('_')[1];
		for (var j = 0; j < layerTree.length; j++) {
			if (layerTree[j].layerId && layerTree[j].layerId == layerId) {
				
				//SCREWS UP IE!
				layerTree[j].setOpacity(opacity);
				//Works with ie, but isn't of any use to anyone printing a map
				//layerTree[j].setOpacity(1);
				mapLayers.push(layerTree[j]);
				
			}
		}
		
	}

	var MBR = new Array('3000000','6550000','3800000','7900000','3380000','6730000');
	map = new OpenLayers.Map( 'print_map',
	{ 
		maxExtent: new OpenLayers.Bounds(0,0,3750000,7850000),
		controls: [],
		units: 'm', 
		projection: "EPSG:2393",
//		resolutions: 	[3172.931125,794.034895,264.639239,132.291931,26.458386,13.229193,6.614597,4.234905,2.116577]
		resolutions: [794.034895,264.639239,132.291931,26.458386,13.229193,6.614597,4.234905,2.116577,1.411246]
	},
	{
		buffer:0
	});
		 
	
    base = new OpenLayers.Layer("",{isBaseLayer: true, displayInLayerSwitcher: false});
    map.addLayers([base]);
    //areas_with_feature id -> view to all areas, with field id as featureid included. 
	if (destinationId) {
		var filter = generateFilter(destinationId);
	    destinationsLayer = new OpenLayers.Layer.WMS('Areas',wmsUrl,
//			              	{layers: 'retkikartta:allareas',styles:'', transparent: true, filter: filter}, 
			              	{layers: 'retkikartta:allareas',styles:'', transparent: true, filter: filter}, 
			              	{singleTile: true, layerId: 'allareas', minScale:0, maxScale: 10000000, 
			              	opacity: 1, isBaseLayer: false,displayInLayerSwitcher: true,
			              	visibility:true,buffer:0, filter: filter});
	}
	
	restrictionsLayer = new OpenLayers.Layer.WMS('Restrictions',wmsUrl,
//          	{layers: 'retkikartta:restriction_split_view',styles:'', transparent: true}, 
          	{layers: 'retkikartta:restriction_split_view',styles:'', transparent: true}, 
          	{singleTile:true, layerId: 'restrictions', minScale:0, maxScale: 10000000, 
          	opacity: 0.5, isBaseLayer: false,displayInLayerSwitcher: true,
          	visibility:false,buffer:0});
	
	
//	restrictionsLayer.setOpacity(1);
	
	
	//Point-type geometries clustered.
	if (pois) {
		poiLayer = generateVectorLayer();
		
		poiLayer.styleMap.styles["default"].defaultStyle.label = null;
		poiLayer.moveTo = function() {
			this.filter = generatePoisFilterByIds(pois);
			OpenLayers.Layer.Vector.prototype.moveTo.apply(this, arguments);
		};
		
		poiLayer.addFeatures = function(features, options) {
			OpenLayers.Layer.Vector.prototype.addFeatures.apply(this, arguments);
			
			//Show only if metacontent was selected!
			if (SHOWMETADATA || SHOWLEGEND)
				generateWfsMetacontent(this.features);
		};
	}

	map.addLayers([base]);
	
	for (var i = 0; i < mapLayers.length; i++) {
		if (mapLayers[i].layerId == "taustakartta") {
			mapLayers[i].getURL = getUrlRetkikartta;
		}
		mapLayers[i].visibility = true; 
		if (mapLayers[i].visibility) {
			map.addLayer(mapLayers[i]);
			
			//a layer has got restrictions attached to it -> visualize those as well.
			if (layerToRestrictionMappings[mapLayers[i].layerId]) {
				restrictionsLayerCategoriesOn[mapLayers[i].layerId] = true;
			}
		}
	}

	
	map.addLayer(restrictionsLayer);
	//Restrictions visualised.
	toggleRestrictionsLayer();
	
	
	if (index) {
		var indexMap = createIndexMap();
		//disable updating the map by dragging the indexmap rectangle!
		map.addControl(indexMap);
		indexMap.maximizeControl();
		indexMap.div.style.bottom = "0px";
		updateIndexMapVisualAppearance();
		indexMap.updateMapToRect = null;
		indexMap.updateOverView = null;
		indexMap.rectDrag = null;
		indexMap.mapDivClick = null;
//		indexMap.updateRectToMap = null;
	}
	map.setCenter(new OpenLayers.LonLat(x, y), zoom);
	
	
	
	var scaleLine = new OpenLayers.Control.ScaleLine({maxWidth: 200});
	
	
	map.addControl(scaleLine);
	
//    var scaleDiv = scaleLine.div;
//    map.div.removeChild(scaleDiv);
//	scaleLine.div.style.backgroundColor = "";
	scaleLine.div.style.backgroundColor = "transparent";
	scaleLine.div.style.background = "none";
    scaleLine.div.style.marginTop = "0px";
    scaleLine.div.style.bottom = "7px";
    scaleLine.div.style.position="absolute";
	scaleLine.div.style.opacity = "1";
//	scaleLine.div.style.filter = "alpha(opacity=100)";
	scaleLine.div.style.filter = "background-color: transparent; background: none;";
	
	scaleLine.eTop.style.backgroundColor = "transparent";
	scaleLine.eTop.style.background = "none";
	scaleLine.eTop.style.marginBottom = "0px";
	scaleLine.eTop.style.opacity = "1";
//	scaleLine.eTop.style.filter = "alpha(opacity=100)";
	scaleLine.eTop.style.filter = "background-color: transparent; background: none;";

	scaleLine.eBottom.style.backgroundColor = "transparent";
	scaleLine.eBottom.style.background = "none";
	scaleLine.eBottom.style.opacity = "1";
//	scaleLine.eBottom.style.filter = "alpha(opacity=100)";
	scaleLine.eBottom.style.filter = "background-color: transparent; background: none;";
	scaleLine.eBottom.style.visibility = "hidden";
	scaleLine.eBottom.style.display = "none";

	
	if (poiLayer) {
		map.addLayer(poiLayer);

		//strategies[0] = BBOX, strategies[1] = cluster
		poiLayer.strategies[0].features = [];
		poiLayer.strategies[1].features = [];
		poiLayer.destroyFeatures();
		poiLayer.filter = generatePoisFilterByIds(pois);
		poiLayer.setVisibility(true);
	}
	
	
	generateWmsMetaContent();
	generateTimeStamp();

	//add the destinations's bounds on top, if were visualised.
	if (destinationId)
	    map.addLayer(destinationsLayer);
	
	
	/*tilestitching to create a printable map for ie...*/
	if (isIeOrChrome()) {
		printMap();
	}
}

/*
function isIeOrChrome() {
	
	//chrome uses the same print-functionality...so, do the same for chrome as well
	var isChrome = (navigator.userAgent.toLowerCase().indexOf('chrome') > -1);

//	alert(isChrome);
	if (navigator.appName == 'Microsoft Internet Explorer' || isChrome)
		return true;
	
	return false;
}
*/

/*tilestitcher for ie!*/
function printMap() {
	var holdOnDiv = document.createElement('div');
	
	holdOnDiv.id = 'holdOnDiv';
	holdOnDiv.style.width="100%";
	holdOnDiv.style.height="100%";
	holdOnDiv.style.left = "0px";
	holdOnDiv.style.top = "0px";
	holdOnDiv.style.position = "absolute";
	holdOnDiv.style.zIndex = map.Z_INDEX_BASE.Control;
	holdOnDiv.style.backgroundColor = "#F0F0F0";
	holdOnDiv.style.opacity = "0.9";
	holdOnDiv.style.filter = "alpha(opacity=90)";
	
	holdOnDiv.innerHTML = "<h2 style='text-align:center;width:100%;height:100%;white-space:nowrap;'>"+Language.get('pleasewait')+"</h2>";
	map.viewPortDiv.appendChild(holdOnDiv);
	map.viewPortDiv.style.cursor = "wait";
	document.body.style.cursor = "wait";
    //-- post a wait message
	
//    print_wait_win = window.open("empty.html", "print_wait_win", "scrollbars=no, status=0, height=5, width=10, resizable=1");

    // go through all layers, and collect a list of objects
    // each object is a tile's URL and the tile's pixel location relative to the viewport
    var size  = map.getSize();
    var tiles = [];
    
    for (layername in map.layers) {
        // if the layer isn't visible at this range, or is turned off, skip it
    	
    	var layer = map.layers[layername];
//        if (!layer.getVisibility()) continue;
//        if (!layer.calculateInRange()) continue;
        // iterate through their grid's tiles, collecting each tile's extent and pixel location at this moment
        for (tilerow in layer.grid) {
            for (tilei in layer.grid[tilerow]) {
                var tile     = layer.grid[tilerow][tilei]
                var url      = layer.getURL(tile.bounds);

                if (url.indexOf('ntile1.navici.com') > -1)
                	url = url.replace('ntile1.navici.com', '192.168.60.156');
                var position = tile.position;
                var opacity  = layer.opacity ? parseInt(100*layer.opacity) : 100;
                tiles[tiles.length] = {url:url, x:position.x, y:position.y, opacity:opacity};
            }
        }
    }

    // hand off the list to our server-side script, which will do the heavy lifting
    var tiles_json = JSON.stringify(tiles);
    var printparams = 'width='+size.w + '&height='+size.h + '&tiles='+escape(tiles_json) ;
    OpenLayers.Request.POST(
      { url:'./print2.php',
        data:OpenLayers.Util.getParameterString({width:size.w,height:size.h,tiles:tiles_json}),
        headers:{'Content-Type':'application/x-www-form-urlencoded'},
        callback: function(request) {
        	
			var size = map.getSize();
			var extent = map.getExtent();
			
			
			var url = './'+request.responseText;
	    	
	    	var imgLayer = new OpenLayers.Layer.Image("ImageLayer",url,extent, size, 
			{
	    		maxExtent: extent,
	    		restrictedExtent: extent,
	    		units: "m",
	    		isBaseLayer: false,
				alwaysInRange: true,
				visibility:true,
				projection: "EPSG:2393"
			});
	    	
           map.addLayer(imgLayer);
           
           	/*set the pois and labels on top of the imagelayer.*/
			
           //poilayer,destinations' layer and restrictions' layer on top!!!
           
			if (poiLayer){
				map.setLayerIndex(poiLayer, map.layers.length);
 	   		}
			
			if (restrictionsMarkerLayer){
				map.setLayerIndex(restrictionsMarkerLayer, map.layers.length);
			}
			
			
			if (markerLayer){
				map.setLayerIndex(markerLayer, map.layers.length);
	   		}
			map.viewPortDiv.style.cursor = "default";
			document.body.style.cursor = "default";
			map.viewPortDiv.removeChild(document.getElementById('holdOnDiv'));
        }
      }
    );
}



function generateTimeStamp() {
	var d = new Date();
	var content = '';
	var minutes = d.getMinutes()+'';
	if (minutes.length == 1)
		minutes = '0'+minutes;
	
	var displayScale = "";
	for (var i = map.resolutions.length-1; i >= 0; i--) {
		var scale = Math.round(OpenLayers.Util.getScaleFromResolution(map.resolutions[i], "m"),true);
		if (scale == Math.round(map.getScale()))
			displayScale = shownScales[i].toString();
	}
	
//	content += Language.get('mapscale')+' 1:'+parseInt(map.getScale());
	content += Language.get('mapscale')+' 1:'+parseInt(displayScale);
	content += ' - '+Language.get('mapprinttimestamp')+' '+d.getDate()+'.'+(d.getMonth()+1)+'.'+d.getFullYear()+' '+d.getHours()+':'+minutes;
	document.getElementById('mapScaleAndTimestamp').innerHTML = content; 	
	document.getElementById('mapScaleAndTimestamp').style.float = "right";//.innerHTML = content; 	
}

/*number of asyncronous requests pending.*/
var noPendingRequests = 0;
/*number of asyncronous callbacks handled.*/
var noResponsesHandled = 0;

function generateWmsMetaContent() {
	/*get the visible wms-layers' featureinfos by wfs as well!*/
	var i = 0;
	while (i < mapLayers.length) {
		if (mapLayers[i].CLASS_NAME == 'OpenLayers.Layer.WMS' &&
			mapLayers[i].layerId != 'kunnat' &&
			mapLayers[i].layerId != 'allareas' &&
			mapLayers[i].layerId != 'restrictions') {
			
			noPendingRequests++;
			
			
			
			var featureReader = new OpenLayers.Protocol.WFS.fromWMSLayer(mapLayers[i], 
			{
//				url:  "http://demo.navici.com/geoserver/wfs",
				url:  wfsUrl,
				featureType: mapLayers[i].layerName,
				maxFeatures: 100,
				featurePrefix: "retkikartta",
				callback: getWmsFeaturesCallback,
				extractAttributes: true,
				propertyNames: ["id","name_fi","name_se","name_en","minx","maxx","miny","maxy","category_id"]
			});
			var filter = new OpenLayers.Filter.Spatial({
					type: OpenLayers.Filter.Spatial.BBOX,
					value: map.getExtent()
			});

			featureReader.read({filter: filter});
			
		}
		i++;
	}
}

var markerLayer = null;
var currentWmsFeatureIndex = 0;



//var wmsFeatureIds = [];
//Collect all the features from wmslayers' wfs-callbacks.
var wmsFeatures = [];


function generateMarkerLayer() {
	var style = new OpenLayers.Style({
			label: "${getLabel}",
			fontColor: "#000000",
            backgroundColor: "#FFFFFF",
            fontSize: "16px",
            fontFamily: "Tahoma",
            fontWeight: "bold"
		}, 
      	{
			context: 
			{
	            getLabel: function(feature) {
	            	return feature.attributes["order"];
	            }
	      	}
		
		});
	markerLayer = new OpenLayers.Layer.Vector("TEMP",
	{
		visibility: true,
		projection: "EPSG:2393",
		styleMap: new OpenLayers.StyleMap({
        	"default": style,
            "select": {
	            fillColor: "#8aeeef",
	            strokeColor: "#32a8a9"
			}
		})
	});
	
	map.addLayer(markerLayer);
}

var restrictionsMarkerLayer = null;
function generateRestrictionsMarkerLayer() {
	
	/*IE can't handle the backgroundgraphic!!!*/
	var style = '';
	
	
	if (!isIeOrChrome()) {
		style = new OpenLayers.Style({
			label: "${getLabel}",
			fontColor: "#FF0000",
            fontSize: "12px",
            fontFamily: "Tahoma",
            //fontWeight: "bold",
            externalGraphic: './images/empty.gif',
            graphicWidth: "50",
            graphicHeight: "14",
            backgroundGraphic: './images/scale.gif'
		}, 
      	{
			context: 
			{
	            getLabel: function(feature) {
					return "R"+feature.attributes["id"];
	            }
	      	}
		
		});
	} else {
		
		//IE -> No backgroundgraphic!
		style = new OpenLayers.Style({
			label: "${getLabel}",
			fontColor: "#FF0000",
            fontSize: "12px",
            fontFamily: "Tahoma",
            //fontWeight: "bold",
            externalGraphic: './images/empty.gif',
            graphicWidth: "50",
            graphicHeight: "14"
		}, 
      	{
			context: 
			{
	            getLabel: function(feature) {
					return "R"+feature.attributes["id"];
	            }
	      	}
		
		});
		
	}
	restrictionsMarkerLayer = new OpenLayers.Layer.Vector("restrictionsMarkers",
	{
		visibility: true,
		projection: "EPSG:2393",
		styleMap: new OpenLayers.StyleMap({
        	"default": style,
            "select": {
	            fillColor: "#8aeeef",
	            strokeColor: "#32a8a9"
			}
		})
	});
	
	map.addLayer(restrictionsMarkerLayer);
}




function getWmsFeaturesCallback(e) {

	noResponsesHandled++;
//	if (!markerLayer)
//		generateMarkerLayer();
//	var nameField = "name_"+getRequestParam('lang');
	
	var markers = [];
	if (e.features && e.features.length > 0) {
		var content = '';
		for (var i = 0; i < e.features.length; i++) {
//			currentWmsFeatureIndex++;
			
			//USED FOR FILTERING RESTRICTIONS!
			//wmsFeatureIds.push(e.features[i].attributes["id"]);
			wmsFeatures.push(e.features[i]);
		}
	}
	
	
	if (noResponsesHandled == noPendingRequests) {
		noResponsesHandled = 0;
		noPendingRequests = 0;
		generateRestrictions();
	}
}


function generateRestrictions() {


	var catfilters = [];
	
	
	var idsAlreadyAdded = [];
	var exists = false;
//	for (var i = 0; i < wmsFeatureIds.length; i++) {
	for (var i = 0; i < wmsFeatures.length; i++) {
		exists = false;
		for (var z = 0; z < idsAlreadyAdded.length; z++) {
			if (wmsFeatures[i].attributes["id"] == idsAlreadyAdded[z]) {
				exists = true;
				break;
			}
		}
		
		if (!exists) {
			var comp = new OpenLayers.Filter.Comparison({
					type: '==',
					property:"area_id",
					value: wmsFeatures[i].attributes["id"]
			});
			
			catfilters.push(comp);
			idsAlreadyAdded.push(wmsFeatures[i].attributes["id"]);
		} 
	}

	var bounding = new OpenLayers.Filter.Spatial({
			type: "BBOX",
			value: map.getExtent()
	});
	
	var or = new OpenLayers.Filter.Logical({
			type: "||",
			filters: catfilters
	});
	
	var filter = new OpenLayers.Filter.Logical({
			type: "&&",
			filters: [bounding, or]
	});
	
	var featureReader = new OpenLayers.Protocol.WFS.v1_1_0(
	{
//		url:  "http://demo.navici.com/geoserver/wfs",
		url:  wfsUrl,
//		featureType: 'restriction',
		featureType: 'restriction_split_view',
		maxFeatures: 100,
		featurePrefix: "retkikartta",
		srsName: "EPSG:2393",
		callback: getRestrictionsCallback,
		extractAttributes: true,
//		propertyNames: ["id","area_id","restriction_fi","restriction_se",
//		                "restriction_en","definition_fi","definition_se","definition_en",
//		                "geometry_envelope"]
		        		propertyNames: ["id","area_id","restr_fi","restr_se",
		        		                "restr_en","def_fi","def_se","def_en",
		        		                "geometry_envelope"]
	});
	
	featureReader.read({filter: filter});

}

function getWmsFeatureContent(feature, index) {

	var nameField = "name_"+LANGUAGE_SELECTION;
	var content = '<div id="area_'+feature.attributes["id"]+'">';
//	content += 	'<a class="printMapLabel">'+currentWmsFeatureIndex +' '+feature.attributes[nameField];
	content += 	'<a class="printMapLabel">'+index +' '+feature.attributes[nameField];
	content += ' - '+categories[feature.attributes.category_id].name+'</a>';
	if (feature.attributes["external_link"])	
		content += ' - <a target="_new" href="'+feature.attributes["external_link"]+'">'+
					feature.attributes.external_link+'</a>';
	content += "<br/>";
	content += "</div>";
	
	return content;
}

function getLabelForFeature(feature, index) {
	//alert('getLabelForFeature '+index+' '+feature.attributes["name_fi"]);
	var xy = getFeatureCoordinates(parseInt(feature.attributes["minx"]),
			  parseInt(feature.attributes["miny"]),
			  parseInt(feature.attributes["maxx"]),
			  parseInt(feature.attributes["maxy"]));

	var x = xy[0];
	var y = xy[1];
	
	/*too close to the right border -> take back a notch.*/
	var px = map.getViewPortPxFromLonLat(new OpenLayers.LonLat(x,y));
	var tolerance = 15;
	if (parseInt(px.x) > parseInt(map.div.style.width) - parseInt(tolerance))
		px.x = parseInt(map.div.style.width) - parseInt(tolerance);
	if (parseInt(px.x) < parseInt(tolerance))
		px.x = parseInt(tolerance);
	
	if (parseInt(px.y) > parseInt(map.div.style.height) - parseInt(tolerance))
		px.y = parseInt(map.div.style.height) - parseInt(tolerance);
	if (parseInt(px.y) < parseInt(tolerance))
		px.y = parseInt(tolerance);
	
	var adjustedLonLat = map.getLonLatFromViewPortPx(px);
//	var f = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(x,y),null,null);
	var f = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(adjustedLonLat.lon,adjustedLonLat.lat),null,null);
	f.attributes["order"] = index;
	
	return f;

}

function getRestrictionsCallback(e) {
	
    //alert(e.features);
	
	if (e.features && e.features.length && !restrictionsMarkerLayer)
		generateRestrictionsMarkerLayer();
	if (!markerLayer && wmsFeatures && wmsFeatures.length > 0) {
		generateMarkerLayer();
	}
	var restrictionMarkers = [];
	var featureMarkers = [];
	//just add ONE explanation in destinationlist, not one for each piece of geometry.
	var restrictionExplanationsAlreadyAdded = {};
	var areaExplanationsAlreadyAdded = {};
	
	//When SHOWMETADATA is false, indexing happens ONLY to features with restrictions!
	var indexWithRestrictionsOnly = 0;
	var content = '';

	/* filter out duplicate ids */
	if (wmsFeatures) {
	    var seen = new Array();
	    var temp = new Array();
	    for (var i = 0; i < wmsFeatures.length; i++) {
		if ( seen[wmsFeatures[i].attributes["id"]] != 1 ) {
		    temp.push(wmsFeatures[i]);
		    seen[wmsFeatures[i].attributes["id"]] = 1;
		}
	    }
	    wmsFeatures = temp;
	}
	/* filter out duplicate ids */
	
	for (var j = 0; j < wmsFeatures.length; j++) {
		
		//"Show metadata"-options was selected -> business as usual. 
		//Just add ALL wmsfeatures and loop through the restrictions for each one.
		if (SHOWMETADATA) {
			currentWmsFeatureIndex++;
			var wmsContent = getWmsFeatureContent(wmsFeatures[j], currentWmsFeatureIndex);
			var feature = getLabelForFeature(wmsFeatures[j], currentWmsFeatureIndex);
			if (feature)
				featureMarkers.push(feature);
			content += wmsContent;
		}
		
		for (var i = 0; i < e.features.length; i++) {
			
			e.features[i].attributes["id"] = parseInt(e.features[i].attributes["id"]);
			e.features[i].attributes["area_id"] = parseInt(e.features[i].attributes["area_id"]);
		
			if (!restrictionExplanationsAlreadyAdded[e.features[i].attributes["id"]] &&
				e.features[i].attributes["area_id"] == wmsFeatures[j].attributes["id"]) {
				
				//Don't show metadata -> only show metadata for targets with restrictions!
				if (!SHOWMETADATA && !areaExplanationsAlreadyAdded[wmsFeatures[j]["id"]]) {
					areaExplanationsAlreadyAdded[wmsFeatures[j]["id"]] = true;
					indexWithRestrictionsOnly++;
					var wmsContent = getWmsFeatureContent(wmsFeatures[j], indexWithRestrictionsOnly);
					var feature = getLabelForFeature(wmsFeatures[j], indexWithRestrictionsOnly);
					if (feature)
						featureMarkers.push(feature);
					content += wmsContent;
				}
	
				//var wrap = document.createElement("div");
				var rContent = '';
				rContent += '<a class="printMapRestrictionLabel">';
				rContent += 'R'+e.features[i].attributes["id"]+' - ';
				rContent += e.features[i].attributes["restr_"+LANGUAGE_SELECTION]+' - ';
				rContent += e.features[i].attributes["def_"+LANGUAGE_SELECTION]+'</a>';
				rContent += "<br/>";
				restrictionExplanationsAlreadyAdded[e.features[i].attributes["id"]] = true;
				content += rContent;
			}
			
			var bounds = e.features[i].geometry.getBounds();
			var xy = getFeatureCoordinates(	parseInt(bounds.left), 
											parseInt(bounds.top), 
											parseInt(bounds.right), 
											parseInt(bounds.bottom));
			var x = xy[0];
			var y = xy[1];
			var f = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(x,y),null,null);
			f.attributes["id"] = e.features[i].attributes["id"];
			restrictionMarkers.push(f);
		}
		
	}
	if (content && content.length) {
		document.getElementById('metadataDiv').innerHTML += content;
	}
	
	
	if (restrictionsMarkerLayer && restrictionMarkers && restrictionMarkers.length)
		restrictionsMarkerLayer.addFeatures(restrictionMarkers);
	
	if (markerLayer && featureMarkers && featureMarkers.length)
		markerLayer.addFeatures(featureMarkers);
	

	/*add the "dfestination info" header, if there _are_ destinations to show.*/
	if (markerLayer && markerLayer.features && markerLayer.features.length) {
		document.getElementById('metadataDiv').innerHTML = 
			'<div class="formLabel" style="font-size:16px; font-weight: bold;">'+
				Language.get('destinationinfo')+
			'</div>'+document.getElementById('metadataDiv').innerHTML;
	}
	
	
	
	/*all featureinfos have been fetched -> do the print map thingie for IE*/
//	printMap();
	
}



//returns the coordinates for the featurelabel, in case an area or a route isn't fully visible on the map.
function getFeatureCoordinates(minx, miny, maxx, maxy) {
	//x,y -> center of the polygon. Might be outside of the map.

	var mapBounds = map.getExtent();

	var miniX = (parseInt(minx) <= parseInt(mapBounds.left))?mapBounds.left : minx;
	var maxiX = (parseInt(maxx) >= parseInt(mapBounds.right))?mapBounds.right : maxx;
	var miniY = (parseInt(miny) <= parseInt(mapBounds.bottom))?mapBounds.bottom : miny;
	var maxiY = (parseInt(maxy) >= parseInt(mapBounds.top))?mapBounds.top: maxy;
		
	var	x = ((parseInt(miniX) + parseInt(maxiX)) / 2);
	var	y = ((parseInt(miniY) + parseInt(maxiY)) / 2);
		
//	alert(x+' - '+y);
	return [x,y];
}


/*hack. TODO: fix the actual process, so this function will only be called once.*/
var firstTime = true;
function generateWfsMetacontent(features) {
	//pois
	
	if (features && firstTime) {
		firstTime = false;
		if (!markerLayer)
				generateMarkerLayer();			
		
		var legendGraphicHash = {};
		var markers = [];
		var poiContent = '';//<p>'; 
		for (var i = 0; i < features.length; i++) {
		
			currentWmsFeatureIndex++;
			if (features[i].attributes.count == 1) {
				poiContent += '<a class="printMapLabel">'+currentWmsFeatureIndex+
					'&nbsp;<img src="'+categoryMarkersPath + 
					categories[features[i].cluster[0].attributes.cat_id].marker+'" />&nbsp;'+
					features[i].cluster[0].attributes.name_fi+'&nbsp;'+
					' - '+categories[features[i].cluster[0].attributes.cat_id].name+'</a><br/>';
				
				
				legendGraphicHash[categories[features[i].cluster[0].attributes.cat_id].marker] = true;
			} else {
				poiContent += '<a class="printMapLabel printMapLabelSeveralDestinations">'+currentWmsFeatureIndex+' - '+Language.get('severaldestinations')+'</a><br/>';
				for (var j = 0; j < features[i].cluster.length; j++) {
					poiContent += '<a class="printMapLabel">&nbsp;&nbsp;&nbsp;'+
						'<img src="'+categoryMarkersPath + 
						categories[features[i].cluster[j].attributes.cat_id].marker+'" />&nbsp;'+
						features[i].cluster[j].attributes.name_fi+'&nbsp;'+
						' - '+categories[features[i].cluster[j].attributes.cat_id].name+'</a><br/>';

					//Add the image into hash of legendgraphics.
					legendGraphicHash[categories[features[i].cluster[j].attributes.cat_id].marker] = true;
				} 
			
			}
			
			var px = map.getViewPortPxFromLonLat(new OpenLayers.LonLat(features[i].geometry.x,features[i].geometry.y));
			
			/*(about) right top corner of the marker image!*/
			px.x += 20;
			px.y -= 10;
			
			
			var ll = map.getLonLatFromViewPortPx(px);
			var x = ll.lon;
			var y = ll.lat;
			var f = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(x,y),null,null);
			f.attributes["order"] = currentWmsFeatureIndex;
			markers.push(f);
		}
//		poiContent += '</p>';
		
		
		if (SHOWMETADATA) {
			document.getElementById('metadataDiv').innerHTML += poiContent;
			markerLayer.addFeatures(markers);
		}
		
		if (SHOWLEGEND) {
			var legendGraphicContent = '';
			var categoryAddedHash = {};
			for (var key in legendGraphicHash) {
				var itemContent = '<img src="'+categoryMarkersPath + key+'" />&nbsp;<a class="printMapLabel">';
	
				for (var categoryKey in categories) {
					if (categories[categoryKey].marker == key) {
						if (!categoryAddedHash[categories[categoryKey].name]) {
							itemContent += '&nbsp;'+categories[categoryKey].name +',';
							categoryAddedHash[categories[categoryKey].name] = true;
						}
					}
				}
				itemContent = itemContent.substr(0, itemContent.length - 1);
				itemContent += '</a><br/>';
				legendGraphicContent += itemContent;
				
			}
			if (legendGraphicContent && legendGraphicContent.length > 0)
				document.getElementById('legendgraphicDiv').innerHTML = 
					'<br/><div class="formLabel" style="font-size:16px; font-weight: bold;">'+
					Language.get('legendgraphic')+
					'</div>'+legendGraphicContent;
			else
				document.getElementById('legendgraphicDiv').innerHTML = '';
				
		}

	} // if (features && firsttime)...
}

/*
gets a given parameter from the current requeststring.
i.e. language etc.
*/
function getRequestParam(parameterName) {

		var queryString = window.top.location.search.substring(1);
		// Add "=" to the parameter name (i.e. parameterName=value)
		var parameterName = parameterName + "=";
		if ( queryString.length > 0 ) {
		// Find the beginning of the string
		begin = queryString.indexOf ( parameterName );
		// If the parameter name is not found, skip it, otherwise return the value
		if ( begin != -1 ) {
			// Add the length (integer) to the beginning
			begin += parameterName.length;
			// Multiple parameters are separated by the "&" sign
			end = queryString.indexOf ( "&" , begin );
			if ( end == -1 ) {
				end = queryString.length
			}
		// Return the string
		return unescape ( queryString.substring ( begin, end ) );
		}
		// Return "null" if no parameter has been found
		return null;
	}
}		


/*functionality for emailsending.*/
function toggleMailformVisibility() {
	if (document.getElementById('emailFormContent').style.visibility == 'hidden') {

		var content = 
			'<form method="post" id="sendMailForm" action="send_mail.php">'+
			'<input type="hidden" id="language" name="language" value="'+LANGUAGE_SELECTION+'">'+
			'<table cellspacing="0" cellpadding="0" style="vertical-align: top;margin: 0; margin-top:2px; padding: 0;">'+
			//ugly...
			//'<tr><td colspan="2"><a class="formActionLabel" onclick="toggleMailformVisibility()">&laquo;&nbsp;Piilota</a></td></tr>'+ 
			'<tr>'+
			'<td><a class="formLabel">'+Language.get('sender')+'</a></td>'+
			'<td><input class="formInput" type="text" size="45" id="mailsender" name="mailsender" value="" /></td>'+
			'</tr>'+
			'<tr>'+
			'<td><a class="formLabel">'+Language.get('to')+'</a></td>'+
			'<td><input class="formInput" type="text" size="45" id="mailreceiver" name="mailreceiver" value="" /></td>'+
			'</tr>'+
			'<tr>'+
			'<td><a class="formLabel">'+Language.get('subject')+'</a></td>'+
			'<td><input class="formInput" type="text" size="45" id="mailheader" name="mailheader" value="" /></td>'+
			'</tr>'+
			'<tr>'+
			'<td style="vertical-align: top;"><a class="formLabel">'+Language.get('message')+'</a></td>'+
			'<td><textarea class="formInput" id="mailbody" name="mailbody" rows="5" cols="45"></textarea>'+
			'<input type="hidden" id="printmapurl" name="printmapurl" value="" /><td>'+
			'</tr>'+
			'<tr>'+
			'<td colspan="2">'+
			
//			'<a class="formActionLabel" style="font-size:16px;" onclick="sendMail()"/>'+Language.get('send')+'&nbsp;&raquo;</a>'+
			'<input type="button" onclick="sendMail()" value='+Language.get('send')+' />'+
			
			'</td>'+
			'</tr>'+
			'</table>'+
			'</form>';
		document.getElementById('emailFormContent').innerHTML = content;
		document.getElementById('emailFormContent').style.visibility = 'visible';
	} else {
		document.getElementById('emailFormContent').style.visibility = 'hidden';
		document.getElementById('emailFormContent').innerHTML = '';
	}	
	
}

function sendMail() {

	document.getElementById('printmapurl').value = window.location;
	document.getElementById('sendMailForm').submit();
}

