var delay=null;
var requestsRunning=0;
var tooltiptimeout=function(){};
function toggleWaitInfo(){
	return;
	requestsRunning-=1;
	try {
		if ( (requestsRunning<=0)  ) {
 			Effect.Fade('waitInfo',{to: 0, duration: .3});
 			}
 		}
	catch(e) {alert (e);}
}

           OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, {
								ui: null,
                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) {
										this.ui.closePopups();
										this.ui.controls["hover"].activate();
                }

            });

c_mymap = OpenLayers.Class({
	selectableLayers: Array(),
	activeLayers: Array(),
	rasterLayers: null,
	rasteroverlays: null,
	vectorLayers: null,
	map: null,
	bufferBounds: null,
	lastBbox: null,
	newBbox: null,
	controls: Array(),

	initialize: function(op) {
		var maxBounds = new OpenLayers.Bounds (12.04,54.067,12.206,54.19);
//		maxbounds=maxBounds.transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));

		var map_options = {
			projection: new OpenLayers.Projection("EPSG:4326"),
			displayProjection: new OpenLayers.Projection("EPSG:4326"),
 			units: "degrees",
			numZoomLevels: 20,
			maxExtent: maxBounds,
			tileSize: new OpenLayers.Size (256,256)
			};

		this.map = new OpenLayers.Map( 'map' ,map_options);
		this.map.addControl(new OpenLayers.Control.LayerSwitcher());

		this.map.maxExtent= maxBounds;
		this.lastBbox="0 0,0 0";
	},

	initControls: function(parentObj) {
		this.map.events.register("zoomend",this,this.zoomend);
		this.map.events.register("moveend",this,this.moveend);
		this.map.events.register("changelayer",this,this.changelayer);

		var mybasestyle = new OpenLayers.Style({
                    pointRadius: "${type}", // sized according to type attribute
                    fillColor: "#ffcc66",
                    strokeColor: "#ff9933",
                    strokeWidth: 1
                });

		var mySelectStyle = OpenLayers.Util.extend({}, mybasestyle);
		OpenLayers.Util.extend(mySelectStyle, {strokeColor: "#ff0000"});
// 		var ctrl = new OpenLayers.Control.SelectFeature(layer, {selectStyle: mySelectStyle});

		var j=0;
		for (i=0;i<this.vectorLayers.length;i++){
			if (this.vectorLayers[i].selectable) this.selectableLayers[j++]=this.vectorLayers[i];
		}

		this.controls["hover"]=new OpenLayers.Control.SelectFeature(this.selectableLayers,{onSelect: this.featureHover, hover:true, multiple: false, onUnselect: this.featureUnhover, onClick: this.featureClick ,parent: this, selectStyle:mySelectStyle});
		this.controls["highlight"]=new OpenLayers.Control.SelectFeature(this.selectableLayers,{onSelect: this.featureHighlight, hover:true, onUnselect: this.featureUnhighlight, parent: this, selectStyle:mySelectStyle});
		this.controls["click"]= new OpenLayers.Control.Click({ui:this});
		this.map.addControl(this.controls["hover"]);
		this.map.addControl(this.controls["highlight"]);
		this.map.addControl(this.controls["click"]);

		this.controls["hover"].activate();


	},

	featureClick: function(feature){	
		showWait();
		if (typeof feature.attributes.js != 'undefined') {
				eval (feature.attributes.js );
				return;
				}
		var request = OpenLayers.Request.POST({
			url: "index.php",
			params: {
					cmd: "showInfo",
					layer:feature.layer.id,
					feature:feature.id
			},
			success: function(request){
					toggleWaitInfo();
					window.clearTimeout(tooltiptimeout);
					mymap.showPopup (feature,request.responseText,"details");
					opentab(0,"popup");
					mymap.map.popups[0].updateSize();
					mymap.map.popups[0].panIntoView();
			},
			failure:function(request){
					alert('BOOOOOO!');
			}
		});
	},

	featureHover: function(feature) {  //ggf Features auf anderen Layern Highlighten
		this.parent.controls["highlight"].select(feature);
		if (feature.layer.connect_to) {
			var targetLayers=this.map.getLayersBy("id",feature.layer.connect_to);
			var targetLayer=targetLayers[0];
			for (i=0;i<targetLayer.features.length;++i) {
				if (typeof feature.attributes.targets != 'undefined') {
					for (j=0;j<feature.attributes.targets.length;++j) {
						if (targetLayer.features[i].id==feature.attributes.targets[j]) {this.parent.controls["highlight"].select(targetLayer.features[i]);};
					}
				}
			}
		}

		//nach 1s tooltip anzeigen
		delay=function(x,y) { 
			var pixel = new OpenLayers.Pixel (x,y);
			var mapsize = mymap.map.getSize();
 			var side_x=(((mapsize.h/2)-pixel.x)>0)?(1):(-1);
			var position = mymap.map.getLonLatFromPixel (pixel.offset(new OpenLayers.Pixel(5*side_x,5)));

			mymap.showTooltip(feature,position);
			}
		tooltiptimeout=window.setTimeout("delay("+this.handlers.feature.x+","+this.handlers.feature.y+")", 1000);
		
	},

	featureUnhover: function(feature){
		delay=function(){};
 		if (feature.popup!=null) {
			feature.popup.hide();
		}
		this.parent.controls["highlight"].unselect(feature);
		this.parent.controls["highlight"].unselectAll();
	},

	zoomIn: function (feature){ this.map.setCenter(feature.geometry.getBounds().getCenterLonLat(),this.map.getZoom()+1)	},

	zoomToObject: function (layerId,featureId,x,y){
		var lonlat=new OpenLayers.LonLat(x,y);
 		this.getSingleFeatureKML(layerId,featureId);
		var layers=this.map.getLayersBy("id",layerId);
// 		this.map.setCenter(new OpenLayers.LonLat(x,y),18);
// 		this.update();
// 		feature ausfindig machen und selektieren (getfeaturebyid geht aus irgendeinemgrunde nciht
		for (i=0;i<layers[0].features.length;++i) {
			if (layers[0].features[i].fid==featureId) {
				var feature=layers[0].features[i];
 				this.map.zoomToExtent(feature.geometry.getBounds(),true);
				this.controls["highlight"].select(feature);
				return;
			}
		}
	},

	showLegend: function () {
		showWait();
		var request = OpenLayers.Request.POST({
			url: "index.php",
			params: {
					cmd: "getLegendHTML",
					newbbox:this.newBbox,
					layers:this.activeLayers
			},
			success: function(request){
					document.getElementById("legendContent").innerHTML=request.responseText;
					toggleWaitInfo();
			},
			failure:function(request){
					alert('BOOOOOO!');
			}
		});
	},

	featureHighlight: function(feature)
	{
		var baseStyle = feature.style.CLASS_NAME == "OpenLayers.Style" ? feature.style.createStyle(feature) : OpenLayers.Util.extend({}, feature.style);

		if (feature.geometry.CLASS_NAME=="OpenLayers.Geometry.Point") {
			var style = {graphicWidth: feature.style.graphicWidth+8,graphicHeight: feature.style.graphicHeight+8,graphicXOffset:feature.style.graphicXOffset-4,graphicYOffset: feature.style.graphicYOffset-4};
			feature.layer.drawFeature(feature,OpenLayers.Util.extend(baseStyle, style));
 		}
	},

	featureUnhighlight: function(feature)
	{
		if (feature.geometry.CLASS_NAME=="OpenLayers.Geometry.Point") {
			feature.layer.drawFeature(feature);
		}
	},

	showPopup: function (feature,html,type,position) {
			this.controls["hover"].deactivate();
			if (position==null) {
				var position = feature.geometry.getBounds().getCenterLonLat();
			}
			var popup = new OpenLayers.Popup.FramedCloud("popup", 
					position,
					null,html,this.popupanchor,true,this.closeDetailPopup);
			popup.map=this.map;
			this.controls["click"].activate();
			popup.feature=feature;
			popup.panMapIfOutOfView = true;
			this.flagNoMoveEvent = true;
			popup.autoSize = true;
			popup.type=type;
			popup.parentObj=this;
			feature.popup = popup;
			this.map.addPopup(feature.popup,true);
			popup.updateSize();
	},

	closeDetailPopup: function (evt) {
		mymap.controls["hover"].activate();
		this.hide();
	},
	
	showTooltip: function (feature,position) {
			if (position==null) {
				var position = feature.geometry.getBounds().getCenterLonLat();
			}
			
			var popup = new OpenLayers.Popup.Anchored("popup", 
					position,
					null,feature.attributes.tt,null,false);
			popup.contentDisplayClass= "tooltipContent",
			popup.autoSize=true;
			popup.contentDiv.className = popup.contentDisplayClass
			popup.updateSize();
			popup.panMapIfOutOfView=false;
			popup.parent=this;
			feature.popup = popup;
			this.map.addPopup(feature.popup,true);
			popup.setBorder("1px solid #aaa");
	},

	closePopups: function() {
			try {
			this.map.popups[0].hide();
			}
			catch (e) {alert (e);}
	},

	addLayers: function() {
		var myStyles;

		//Rasterlayer
		for (i=0;i<this.rasterLayers.length;i++){
			this.map.addLayer(this.rasterLayers[i]);
		}

		//Vektorlayer
		for (i=0;i<this.vectorLayers.length;i++){
			this.map.addLayer(this.vectorLayers[i]);
		}
		this.initControls(this.map);
	},

	search: function () {

		var inputs= Array;
		inputs = document.forms.searchform.getElementsByTagName("input");
		var values = Array();

		for (i=0;i<inputs.length;++i) {
			if (inputs[i].type=="checkbox") {
				values.push(inputs[i].id+"="+inputs[i].checked);
			}
			else {
				values.push(inputs[i].id+"="+inputs[i].value);
			}
		} 

		values=values.join("&");

 		var options = { 
 			method:"post", 
			asynchronous: true,
 			postBody:"cmd=search&"+values,
 			onComplete:function(transport) {
				document.getElementById('searchresults').innerHTML=transport.responseText;
				document.getElementById('searchresults').style.display='block';
				}
 		}; 
 		new Ajax.Request('index.php',options);
		},

	//Event-Handler der Map
	update: function(){
		document.getElementById("viewport").value=this.getBboxString();
		document.getElementById("buffer").value=this.bufferBounds;

		this.activeLayers=new Array();
		for (i=0;i<this.vectorLayers.length;++i) {
			if (this.vectorLayers[i].getVisibility() == true) this.activeLayers.push(this.vectorLayers[i].id);
		}
		for (i=0;i<this.rasterLayers.length;++i) {
			if (this.rasterLayers[i].getVisibility() == true) this.activeLayers.push(this.rasterLayers[i].id);
		}
		document.getElementById("activeLayers").value=this.activeLayers.join(',');

		this.setServerParameters();

		for (i=0;i<this.vectorLayers.length;++i) {
			if (this.vectorLayers[i].getVisibility()) { this.getFeaturesKML(this.vectorLayers[i].id); }
		}
		this.showLegend();
	},

	moveend: function(){
		this.setBufferBounds();
		this.newBbox=this.getBboxString();
		this.removeOffBoundFeatures();
		this.update();
	},

	zoomend: function(){
		this.setBufferBounds();
		this.newBbox=this.getBboxString();
		this.removeOffBoundFeatures();
	},

	changelayer: function(){
		this.update();
		this.showLegend();
	},

	setServerParameters: function () {
		var lonlat = this.map.getCenter();	
		showWait();
		var request = OpenLayers.Request.POST({
			url: "index.php",
			params: {
					cmd: "setMapParameters",
					institutes: document.getElementById("activeInstitutes").value,
					zoom:this.map.getZoom(),
 					lon:lonlat.lon,
 					lat:lonlat.lat,
					bbox:this.getBboxString(),
					layers:this.activeLayers.join(",")
			},
			success: function(request){
					toggleWaitInfo();
			},
			failure:function(request){
					alert('BOOOOOO!');
			}
		});
	},

	clearLayer: function(layer) {
// 		GLog.write("clearing layer "+layer.name);
 		layer.destroyFeatures();
		layer.renderer.clear();
		return;
	},

	getSingleFeatureKML: function (layerId,featureId) {
		var layers=this.map.getLayersBy("id",layerId);
		var layer=layers[0];
		if (layer.clearAfterZoom) { this.clearLayer(layer);}
		var map=this.map;
		showWait();
		this.request=OpenLayers.Request.POST({
				url: "index.php",
				asynchronous:false,
				async:false,
				params: { 
					cmd:"getvectorfeature",	
					layerId:layerId,
					featureId:featureId
				},
			success: function(request) {
				toggleWaitInfo();
				var data = request.responseText;
				var in_options = {
							'internalProjection': map.baseLayer.projection,
							'externalProjection': new OpenLayers.Projection("EPSG:4326"),
							'extractStyles': true
						};

				var formatierer = new OpenLayers.Format.KML(in_options);
				this.featurelist_polygon = formatierer.read(data);
				var n=0;
				for (i=0;i<this.featurelist_polygon.length;++i) {
					if (typeof this.featurelist_polygon[i].style!="undefined") {
						var baseStyle = this.featurelist_polygon[i].style.CLASS_NAME == "OpenLayers.Style" ? this.featurelist_polygon[i].style.createStyle(featurelist_polygon[i]) : OpenLayers.Util.extend({}, this.featurelist_polygon[i].style);
						this.featurelist_polygon[i].style = OpenLayers.Util.extend(baseStyle, {});
					}
					if (typeof this.featurelist_polygon[i].attributes.targets!='undefined') {
						this.featurelist_polygon[i].attributes.targets=this.featurelist_polygon[i].attributes.targets.replace(/\}/,"").replace(/\{/,"").split(",");
					}
					this.featurelist_polygon[i].id = this.featurelist_polygon[i].fid;
					this.featurelist_polygon[i].type = "objekt";
					if (layer.getFeatureById(this.featurelist_polygon[i].fid)) {;}
					else {layer.addFeatures([this.featurelist_polygon[i]]);n++;}
				}
			}
		});
	},

	getFeaturesKML: function (layerId) {
		var layers=this.map.getLayersBy("id",layerId);
		var layer=layers[0];
		if (layer.clearAfterZoom) { 
			this.clearLayer(layer);
			}
		var map=this.map;

		showWait();
		this.request=OpenLayers.Request.POST({
				url: "index.php",
				params: { 
					cmd:"getvectorfeatures",	
					newbbox:this.newBbox,
					lastbbox:this.lastBbox,
					institutes:document.getElementById("activeInstitutes").value,
					layerid:layerId
				},
			success: function(request) {
				toggleWaitInfo();
				var data = request.responseText;
				var in_options = {
							'internalProjection': map.baseLayer.projection,
							'externalProjection': new OpenLayers.Projection("EPSG:4326"),
							'extractStyles': true
						};
				var formatierer = new OpenLayers.Format.KML(in_options);
				this.featurelist_polygon = formatierer.read(data);
// 				if (layer.id=="locations") {alert ("adding feature to layer locations "+this.featurelist_polygon.length);};
				var n=0;
				for (i=0;i<this.featurelist_polygon.length;++i) {
 					if (typeof this.featurelist_polygon[i].style!="undefined") {
						this.featurelist_polygon[i].originalstyle = null;
 						var baseStyle = this.featurelist_polygon[i].style.CLASS_NAME == "OpenLayers.Style" ? this.featurelist_polygon[i].style.createStyle(featurelist_polygon[i]) : OpenLayers.Util.extend({}, this.featurelist_polygon[i].style);
						this.featurelist_polygon[i].originalstyle=this.featurelist_polygon[i].style;
 					}
					if (typeof this.featurelist_polygon[i].attributes.targets!='undefined') {
						this.featurelist_polygon[i].attributes.targets=this.featurelist_polygon[i].attributes.targets.replace(/\}/,"").replace(/\{/,"").split(",");
					}
					this.featurelist_polygon[i].id = this.featurelist_polygon[i].fid;
// 					this.featurelist_polygon[i].layer = layer;
					this.featurelist_polygon[i].type = "objekt";
					if (layer.getFeatureById(this.featurelist_polygon[i].fid)) {;}
					else {layer.addFeatures([this.featurelist_polygon[i]]);n++;}
				}
			}
		});
	},

	getBboxString: function () {
		var proj = this.map.baseLayer.projection;
		var tl = new OpenLayers.Geometry.Point (this.bufferBounds.left,this.bufferBounds.top);
		var br = new OpenLayers.Geometry.Point (this.bufferBounds.right,this.bufferBounds.bottom);
		var tl_ll = tl.transform(proj, new OpenLayers.Projection("EPSG:4326"));
		var br_ll = br.transform(proj, new OpenLayers.Projection("EPSG:4326"));
		var bbox = tl_ll.x+" "+br_ll.y + "," + br_ll.x+" "+tl_ll.y ;
		return bbox;
	},

	setBufferBounds: function () {
		var tl = new OpenLayers.Geometry.Point (this.map.getExtent().left,this.map.getExtent().top);
		var br = new OpenLayers.Geometry.Point (this.map.getExtent().right,this.map.getExtent().bottom);
		var xext = br.x-tl.x;
		var yext = tl.y-br.y;
		this.bufferBounds = new OpenLayers.Bounds((tl.x-xext/10),(br.y-yext/10),(br.x+xext/10),(tl.y+yext/10));
	},

/**
	*Features vergessen, die auï¿½xerhalb von Bufferbounds liegen
	*/
	removeOffBoundFeatures: function() {
		var k=0;
		for (var j=0;j<this.vectorLayers.length; ++j) {
			for (var i=0; i<this.vectorLayers[j].features.length; ++i) {
				try{ if (!this.vectorLayers[j].features[i].geometry.intersects(this.bufferBounds.toGeometry())) {
					this.vectorLayers[j].destroyFeatures([this.vectorLayers[j].features[i]]);
				}}
				catch (e) {;};
			}
		}
	},

	toggleControl: function(name) {
		if (typeof name!="string") {name=this.currentControl;}
		for(key in this.controls) {
			var control = this.controls[key];
			if (typeof control != 'object') { continue;}
			control.deactivate();
		}
		for(key in this.controls) {
			var control = this.controls[key];
			if(name == key ) {
				try  {control.activate();
				this.currentControl = name; } catch (e) {;}
			}
		}
		ele=name+"Toggle";
		var element = document.getElementById(ele); 
		if (element) element.checked = true;
	},

	CLASS_NAME: "c_map"
});

function showWait() {
	return;
//	document.getElementById('waitInfo').style.display="block";
	requestsRunning+=1;
	if (requestsRunning>0) {Effect.Appear('waitInfo',{to:.7,duration:.3});}

}

function showRendered(caller) {
	var svg="";
	var wms= new Array;
	var wmsbase="";

	//Vektorlayer in svg rendern 
	for (j=0;j<caller.vectorLayers.length;j++) {
		layer = caller.vectorLayers[j];
		if (layer.getVisibility()) {	
			for(i=0;i<layer.features.length;i++) {
 				try{
					svg += (new XMLSerializer()).serializeToString((layer.renderer.drawFeature(layer.features[i]))); 
 				} 
				catch (e) {;}
			}
		}
	}

	for (j=0;j<caller.rasterLayers.length;j++) {
		layer = caller.rasterLayers[j];
		if (layer.getVisibility()) {
			if (layer.isBaseLayer) {
				wmsbase = layer.getFullRequestString();
			}	
			else {
				wms.push(layer.getFullRequestString());
			}
		}
	}

 	var options = { 
 			method:"post", 
			async: false,
 			postBody:"cmd=saveBitmap&wmsbase="+wmsbase+"wms="+wms.join(";")+"&svg="+svg+"&extent="+caller.map.getExtent().toBBOX(), 
 			onComplete:function(request) {;}
 		}; 
 		new Ajax.Request('index.php',options);
	}

 function var_dump(obj) {
        if(typeof obj == "object") {
           return "Type: "+typeof(obj)+((obj.constructor) ? "\nConstructor: "+obj.constructor : "")+"\nValue: " + obj;
        } else {
           return "Type: "+typeof(obj)+"\nValue: "+obj;
        }
     }


