var overviewmap_width = 300;
var overviewmap_height = 200;

var popups = [];
var tilecache_url = $('#tilecache_url').val();//"http://cache2.map2web.eu/cache";

var map = null;
var map_mode = 'standard';
var navigationList = [];

var nutzungsbedingungen_ffb = false;

var ffb_mode='photovoltaik';

var searchbox_clicked = false;


var activated_layers = [];

var serverResolutions = [
    1747.17810630859389675607,
    873.58905315429694837803,
    436.79452657714847418902,
    218.39726328857423709451,
    109.19863164428711854725,
    54.59931582214355927363,
    27.29965791107177963681,
    13.64982895553588981841,
    6.82491447776794490920,
    3.41245723888397245460,
    1.70622861944198622730,
    0.85311430972099311365,
    0.42655715486049655683,
    0.213278577430248278415
];

var serverResolutions_osm = [
    156543.03390624999883584678,
    78271.51695312499941792339,
    39135.75847656249970896170,
    19567.87923828124985448085,
    9783.93961914062492724042,
    4891.96980957031246362021,
    2445.98490478515623181011,
    1222.99245239257811590505,
    611.49622619628905795253,
    305.74811309814452897626,
    152.87405654907226448813,
    76.43702827453613224407,
    38.21851413726806612203,
    19.10925706863403306102,
    9.55462853431701653051,
    4.77731426715850826525,
    2.38865713357925413263,
    1.19432856678962706631,
    0.59716428339481353316,
    0.29858214169740676658
];

var serverResolutions_at = [
    1747.17810630859389675607,
    873.58905315429694837803,
    436.79452657714847418902,
    218.39726328857423709451,
    109.19863164428711854725,
    54.59931582214355927363,
    27.29965791107177963681,
    13.64982895553588981841,
    6.82491447776794490920,
    3.41245723888397245460,
    1.70622861944198622730,
    0.85311430972099311365,
    0.42655715486049655683,
    0.213278577430248278415
];  

var serverResolutions_ro = [
    3331.57812500000000000000,
    1665.78906250000000000000,
    832.89453125000000000000,
    416.44726562500000000000,
    208.22363281250000000000,
    104.11181640625000000000,
    52.05590820312500000000,
    26.02795410156250000000,
    13.01397705078125000000,
    6.50698852539062500000,
    3.25349426269531250000,
    1.62674713134765625000,
    0.81337356567382812500,
    0.40668678283691406250,
    0.20334339141845703125,
    0.10167169570922851562,
    0.05083584785461425781,
    0.02541792392730712891,
    0.01270896196365356445,
    0.00635448098182678223
];

function onDragComplete(feature,pixel)
{
    var center = feature.geometry.getBounds().getCenterLonLat();
    var markergeom = new OpenLayers.LonLat(center.lon,center.lat);
    map.moveTo(markergeom);
}


function initOverviewMap(gisdata){

			var bounds = new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34);

            var map = new OpenLayers.Map({
                controls: [],
                div: "overviewMap",
                projection: new OpenLayers.Projection("EPSG:900913"),
                units: "m",
                maxExtent: bounds
            });

            var gmap = new OpenLayers.Layer.Google("Google Streets",
                {
                	"sphericalMercator": true, 
                    numZoomLevels: 20
                }
            );

            map.addLayers([gmap]);

        	return map;
}


$.plugin('vdbpager', {
	printPagingNumbers: function() {

		this.$el.find('.seiteninfo').empty();

		var maxpages = 4;
		var seitenstart;
		var page = this._opt.start/this._opt.pagesize;
		var gesamtAnzahl = this._opt.gesamtanzahl;
		var seitenanzahl = Math.floor(gesamtAnzahl/this._opt.pagesize);
		var seitenende;

		this.$el.find('.pagination').show();

        if($('html').attr('lang') == 'hu')
    		this.$el.find('.seiteninfo').html((parseInt(page)+1) + ' ' + $.i18n('Map2Web', 'of') + ' ' + (parseInt(seitenanzahl)+1) + ' ' + $.i18n('Map2Web', 'Page') );
        else
      		this.$el.find('.seiteninfo').html($.i18n('Map2Web', 'Page')+ ' ' + (parseInt(page)+1) + ' ' + $.i18n('Map2Web', 'of') + ' ' + (parseInt(seitenanzahl)+1) );          
	},


	buildRows: function(data) {

		this.$el.find('#ergebnisliste').empty();
		this.$el.find('#ergebnisliste').show();

		var here = this;

	    $.each(data.objekte, function(i,item){

	    	var row = $($.LI({},
	              		$.A({'class':here._opt.itemclass,'id':item.id,'href':'#'}, item.name)
	          		  ));

	        if(i % 2 == 0)
	        {
	        	row.addClass('alt4');
	        }
	        here.$el.find('#ergebnisliste').append(row);
	    });

		this.printPagingNumbers();

	    },


	build: function() {
	        var markup='<ul id="ergebnisliste" class="listLevel hide" />\
				<li class="pagination" style="display:none">\
				<a href="#" id="firstResults">&lt;&lt;</a>\
				<a href="#" id="prevResults">&lt;</a>\
				<div class="seiteninfo" style="display:inline;"/>\
				<a href="#" id="nextResults">&gt;</a>\
				<a href="#" id="lastResults">&gt;&gt;</a>\
				</li>';
	        this.$el.append(markup);
	    },

    init: function() {
        this.build();
        this.input = this.$el;
        var here = this;
        this.start = 0;

		var searchitemsstring = "";

		for(var l=0;l<=here._opt.searchitems.length-1;l++)
		{
			searchitemsstring = searchitemsstring + here._opt.searchitems[l] + ',';
		}

		this.searchitemsstring = searchitemsstring;

		$.post(this._opt.baseurl,{'id':this._opt.id,'searchitems':this.searchitemsstring,'querystring':this._opt.querystring,'pagesize':this._opt.pagesize,'start':0,'projection':this._opt.projection},
            function(data)
            {
            	here._opt.gesamtanzahl = data.anzahl;
				$('#suchergebnis_zahl').html(data.anzahl);
                here.buildRows(data);
            },
        'json');


        var first = this.$el.find("#firstResults");
        first.click(
            function()
            {
            	here._opt.start = 0;
                $.post(here._opt.baseurl,{'id':here._opt.id,'searchitems':here.searchitemsstring,'querystring':here._opt.querystring,'pagesize':here._opt.pagesize,'start':0,'projection':here._opt.projection},
                    function(data)
                    {
                         here.buildRows(data);
                    },
                'json');
                return false;
            }
        );

        var last = this.$el.find("#lastResults");
        last.click(
            function()
            {
				var pages = Math.floor(here._opt.gesamtanzahl/here._opt.pagesize);
				start = pages * parseFloat(here._opt.pagesize);
            	here._opt.start = start;

                $.post(here._opt.baseurl,{'id':here._opt.id,'searchitems':here.searchitemsstring,'querystring':here._opt.querystring,'pagesize':here._opt.pagesize,'start':here._opt.start,'projection':here._opt.projection},
                    function(data)
                    {
                         here.buildRows(data);
                    },
                'json');
                return false;
            }
        );


        var prev = this.$el.find("#prevResults");
        prev.click(
            function()
            {
                if(here._opt.start > 0)
                    here._opt.start = here._opt.start - here._opt.pagesize;
                	$.post(here._opt.baseurl,{'id':here._opt.id,'searchitems':here.searchitemsstring,'querystring':here._opt.querystring,'pagesize':here._opt.pagesize,'start':here._opt.start,'projection':here._opt.projection},
                    function(data)
                    {
                         here.buildRows(data);
                    },'json'
                );
                return false;
            }
        );

        var next = this.$el.find("#nextResults");
        next.click(
            function()
            {
                here._opt.start = here._opt.start + here._opt.pagesize;
                $.post(here._opt.baseurl,{'id':here._opt.id,'searchitems':here.searchitemsstring,'querystring':here._opt.querystring,'pagesize':here._opt.pagesize,'start':here._opt.start,'projection':here._opt.projection},
                    function(data)
                    {
                         here.buildRows(data);
                    },'json'
                );
                return false;
            }
        );

    }

});


$.plugin('searchAllPager', $.vdbpager, {
	build: function() {
        var markup='<span class="pagination" style="display:none">\
			<a href="#" id="firstResults">&lt;&lt;</a>\
			<a href="#" id="prevResults">&lt;</a>\
			<div class="seiteninfo" style="display:inline;"/>\
			<a href="#" id="nextResults">&gt;</a>\
			<a href="#" id="lastResults">&gt;&gt;</a>\
			</span>';
        this.$el.append(markup);
    },

	buildRows: function(data) {

		$('dl').remove();
		var here = this;

	    $.each(data.objekte, function(i,item){
			var linkclass = 'show' + item.type.charAt(0).toUpperCase() + item.type.slice(1);

			var links = [];
/*
			if(item.type == 'wirtschaft')
			{
				for(var l=0;l<=item.schlagworte.length-1;l++)
				{
					links.push($.SPAN({'class':'category'},'[' + item.schlagworte[l].name + ']'));
				}
			}
*/

	    	var row = $($.DL({},
	              			$.DT({},
	              				$.SPAN({'class':'num'},
	              					$.A({},i+1)
	              				)
	              			),
	              			$.DD({},
	              				links,
	              				$.A({'class':linkclass, 'id':item.id,'href':'#'},item.name)
	              				//$.SPAN({'class':'category'}, ' [' + item.type + ']'),
	              			)
	          		  	));
	        $($('#suchergebnis .pagination')[0]).before(row);

	    });

		this.printPagingNumbers();

	   }


    });


var Weite = 0;
var Hoehe = 0;


function getAjaxUrl(){
	var projektid = $("#projektid").val();
	var objektid = $("#objektid").val();
    //var projektid = "st-poelten-neu";

    //--- Für Testzwecke ---

    if(parseInt(objektid) == 26696)
        projektid = 'test';

    //--- Für Testzwecke ---
    //if(projektid == 'st-poelten')
    //    projektid = 'st-poelten-neu';

	return "http://" + projektid + ".map2web.eu";
	//return "http://172.16.1.131:5000";
	//alert ("http://" + projektid + ".map2web.eu");
}

String.prototype.trim = function() {

 // skip leading and trailing whitespace
 // and return everything in between
  var x=this;
  x=x.replace(/^\s*(.*)/, "$1");
  x=x.replace(/(.*?)\s*$/, "$1");
  return x;
}


function Fensterweite () {
  if (window.innerWidth) {
    return window.innerWidth;
  } else if (document.body && document.body.clientWidth) {
    return document.body.clientWidth;
  } else {
    return 0;
  }
}

function Fensterhoehe () {
  if (window.innerHeight) {
    return window.innerHeight;
  } else if (document.body && document.body.clientHeight) {
    return document.body.clientHeight;
  } else {
    return 0;
  }
}
function ieload() {
	if (!window.Weite && document.body && document.body.clientWidth) {
	  window.onresize = ausrichten;
	  Weite = Fensterweite();
	  Hoehe = Fensterhoehe();
	}
}
//richtet alle Elemente beim Laden und ändern der Fenstergröße aus.
var firstLoad = true;
function ausrichten(){

}

/* Überwachung von Netscape initialisieren */
if (!window.Weite && window.innerWidth) {
  window.onresize = ausrichten;
  Weite = Fensterweite();
  Hoehe = Fensterhoehe();
}
function iestart(){
/* Überwachung von Internet Explorer initialisieren */
if (!window.Weite && document.body && document.body.clientWidth) {
  window.onresize = ausrichten;
  Weite = Fensterweite();
  Hoehe = Fensterhoehe();
}
}

function osm_getTileURL(bounds) {
    var res = this.map.getResolution();
    var x = Math.round((bounds.left - this.maxExtent.left) / (res * this.tileSize.w));
    var y = Math.round((this.maxExtent.top - bounds.top) / (res * this.tileSize.h));
    var z = this.map.getZoom();
    var limit = Math.pow(2, z);

    if (y < 0 || y >= limit) {
        return OpenLayers.Util.getImagesLocation() + "404.png";
    } else {
        x = ((x % limit) + limit) % limit;
        return this.url + z + "/" + x + "/" + y + "." + this.type;
    }
}



function imprint (url) {
 fenster = window.open(url, "Popupfenster", "width=600,height=600,resizable=yes,scrollbars=yes");
 fenster.focus();
 return false;
}


function initKulturMap(extent,min_zoom,max_zoom){

            $( "#overviewMap" ).dialog('close');
            $("#infoBlase").fadeOut();

    		var tilecache_url = "http://cache2.map2web.eu/cache";
            var projection = $("#projection").val();

			//(var extent = $('#extent').val().split(',');
			var rendering_extent = $('#rendering_extent').val().split(',');

	        var map;
            var untiled;
            var tiled;

            var pureCoverage = false;
            OpenLayers.IMAGE_RELOAD_ATTEMPTS = 5;
            OpenLayers.DOTS_PER_INCH = 25.4 / 0.28;

            format = 'image/png';


            
    
		    if(projection == 'EPSG:32633'){
				var karte = "kulturrundgang";
                serverResolutions = serverResolutions_at;
			}
			else if(projection == 'EPSG:32632'){
				var karte = "kulturrundgang32";
                serverResolutions = serverResolutions_at;
			}
			else if(projection == 'EPSG:900913'){
				var karte = "kulturrundgang";
                serverResolutions = serverResolutions_osm;
                tilecache_url = $('#tilecache_url').val();//"http://cache3.map2web.eu/cache";
			}


			var extent = extent.split(',');

			if(extent.length != 4)
			{
				alert('Please insert the max. extent in the following format (x1, y1, x2, y2)');
				return 0;
			}


            var restrictedbounds = new OpenLayers.Bounds(
                parseFloat(extent[0]),parseFloat(extent[1]),
                parseFloat(extent[2]),parseFloat(extent[3])
            );

            var renderingextent = new OpenLayers.Bounds(
                parseFloat(rendering_extent[0]),parseFloat(rendering_extent[1]),
                parseFloat(rendering_extent[2]),parseFloat(rendering_extent[3])
            );


			var projection = $('#projection').val();

            var options = {
                controls: [],
                maxExtent: renderingextent,
                restrictedExtent: restrictedbounds,
                maxResolution: serverResolutions[min_zoom],
                minResolution: serverResolutions[max_zoom],
                projection: projection,
                units: 'm'
            };

            map = new OpenLayers.Map('map', options);



	


            tilecache = new OpenLayers.Layer.TileCache("Karten Layer",
                [tilecache_url],
                karte,
                {
                	"serverResolutions": serverResolutions,
                	//"minZoomLevel" : 1,
                	//"maxZoomLevel" : 12,
					"format": "image/png"
                }

            );

        	var vectorLayer = new OpenLayers.Layer.Vector("Vector Layer",{"isBaseLayer": false});

            map.addLayers([tilecache,vectorLayer]);

			var panZoomBar = new OpenLayers.Control.PanZoomBar();
			map.addControl(panZoomBar);

			panZoomBar.div.style.marginTop = "-50px";
			panZoomBar.div.style.marginLeft = "-6px";
        	panZoomBar.div.style.zIndex = "1100";


            //map.addControl(new OpenLayers.Control.Navigation());
            //map.addControl(new OpenLayers.Control.LayerSwitcher());

			OpenLayers.Control.CustomNavToolbar = OpenLayers.Class(OpenLayers.Control.Panel, {

			    initialize: function(options) {
			        OpenLayers.Control.Panel.prototype.initialize.apply(this, [options]);
			        this.addControls([
			          new OpenLayers.Control.Navigation({'title':$.i18n('Map2Web', 'verschieben')}),
			          new OpenLayers.Control.ZoomBox({'title':$.i18n('Map2Web', 'rechteckzoom'), alwaysZoom:true})
			        ]);
					this.displayClass = 'Map2WebToolbar';
			    },

			    draw: function() {
			        var div = OpenLayers.Control.Panel.prototype.draw.apply(this, arguments);
			        this.activateControl(this.controls[0]);
			        return div;
			    }

			});

			var button_zoom_max_extent = new OpenLayers.Control.Button({
                            'title':$.i18n('Map2Web', 'zoomtomaxextent'),
			    displayClass: "olControlZoomToMaxExtent",
			    trigger: function(){
	            	map.zoomToExtent(restrictedbounds);
			    }
			});


			var panel = new OpenLayers.Control.CustomNavToolbar();

     		panel.addControls([button_zoom_max_extent]);

        	map.addControl(panel);
 
     function onPopupClose(evt) {
        selectControl.unselect(selectedFeature);
    }

    function onFeatureSelect(feature) {
        selectedFeature = feature;

		//--- Anzeigedaten im Shape (Wikipedia) ---
		if(feature.name != '' && feature.name != null)
		{
            var data = $.DIV({},			
            	$.DIV({},
            		$.STRONG({},feature.name)
            	),
            	$.DIV({},feature.summary),
            	$.DIV({},
            		$.A({'target':'_blank','href':'http://' + feature.url},'Wikipedia Eintrag')
            	)
            );

			popup = new OpenLayers.Popup.FramedCloud("chicken",
            	feature.geometry.getBounds().getCenterLonLat(),
            	null,
            	data.innerHTML,
                null, true, onPopupClose);
	        feature.popup = popup;
	        popups.push(popup);
	        map.addPopup(popup);




		}
		//--- Anzeigedaten aus Map2Web ---
		else
		{
			$.post( getAjaxUrl() + "/projekt/getDetailInformationHtml",{'id':feature.objektid},
				function(data)
				{
			        popup = new OpenLayers.Popup.FramedCloud("chicken",
	                	feature.geometry.getBounds().getCenterLonLat(),
	                	null,
	                	data,
	                    null, true, onPopupClose);
			        feature.popup = popup;
			        popups.push(popup);
			        map.addPopup(popup);

			       	$($('.olPopup').find('a[rel]')).overlay({

					mask: '#000',
					effect: 'apple',

					onBeforeLoad: function() {
						var wrap = this.getOverlay().find(".contentWrap");
						wrap.load(this.getTrigger().attr("href"));
					}

				});


				}
			);
		}
    }

    function onFeatureUnselect(feature) {
        map.removePopup(feature.popup);
        feature.popup.destroy();
        popups.pop(popup);
        feature.popup = null;
    }




 
    selectControl = new OpenLayers.Control.SelectFeature(vectorLayer,
        {onSelect: onFeatureSelect, onUnselect: onFeatureUnselect});
    map.addControl(selectControl);
	selectControl.activate();

			map.setBaseLayer(tiled);
            map.zoomToExtent(restrictedbounds);
        	return map;

}

function getWikipediaEntries()
{
	var formatter = new OpenLayers.Format.GeoJSON();

	$.post(getAjaxUrl() + "/projekt/getWikipediaEntries",
		{'language':$('html').attr('lang'),'projection':$('#projection').val().split(':')[1],'id':$('#objektid').val(),'extent':formatter.write(map.getExtent().toGeometry())},
		function(data)
		{
			mehrLayer = map.getLayersByName('Info Layer')[0];
			for(var i=0;i<=data.length-1;i++)
			{
				drawFeatures(data[i].shape,mehrLayer,false);
			}
		},
	'json');
}

function getPublicBuildingsEntries()
{
	var formatter = new OpenLayers.Format.GeoJSON();

	$.post(getAjaxUrl() + "/projekt/getPublicBuildingsByExtent",
		{'id':$('#objektid').val(),'extent':formatter.write(map.getExtent().toGeometry())},
		function(data)
		{

			mehrLayer = map.getLayersByName('Mehr Layer')[0];

			var gisdata = data.geometries.geometries;
			for(var i=0;i<=gisdata.length-1;i++)
			{
				drawFeatures(gisdata[i],mehrLayer,false);
			}
		},
	'json');
}
/*
function removeFeatureByObjtype(objtype)
{

	try
	{
		var mehrlayer = map.getLayersByName('Mehr Layer')[0];
		var features = mehrlayer.features;
	}
	catch(e)
	{
		var features = [];
	}

	//--- Alle Popups entfernen ---
	for(var i=0;i<=features.length-1;i++)
	{
		if(features[i].popup != null)
			features[i].popup.destroy();
	}

	//--- alle Features löschen ---
	if(objtype == null)
	{
		try
		{
			mehrlayer.removeFeatures(features);
		}
		catch(e)
		{
		}
	}
	else
	{
		var featurelist = [];

		for(var i=0;i<=mehrlayer.features.length-1;i++)
		{
			if(mehrlayer.features[i].objtype == objtype)
			{
				featurelist.push(mehrlayer.features[i]);
			}
		}

		mehrlayer.removeFeatures(featurelist);
	}
}

*/

function getAllObjectsByExtent(extent)
{

    var formatter = new OpenLayers.Format.GeoJSON();

    $.post("/projekt/getAllObjectsByExtent",
        {'extent':formatter.write(map.getExtent().toGeometry()),'activated_layers':activated_layers.join()+',','projection':$('#projection').val()},
        function(data)
        {
            //removeFeatureByObjtype(map);
	        var gisdata = data.objects;
            var vectorLayer = initVectorLayer(map);
	        for(var i=0;i<=gisdata.length-1;i++)
	        {
		        drawFeatures(gisdata[i].gisdata,vectorLayer,false,map,16);
	        }
        },
    'json'); 

}

function on_move_end(){

    //alert(this.getZoom());


    if(map_mode == 'tclayer')
    {
        if($('#projection').val() == 'EPSG:900913' && this.getZoom() >= 18)
        {
            getAllObjectsByExtent();
        }
        else if($('#projection').val() == 'EPSG:32632' && this.getZoom() >= 5)
        {
            getAllObjectsByExtent();
        }
        else if($('#projection').val() == 'EPSG:32633' && this.getZoom() >= 5)
        {
            getAllObjectsByExtent();
        }
        else
        {
            removeFeatureByObjtype(map);
        }
    }

    latitude = map.getCenter().lat;
    longitude = map.getCenter().lon;



    //--- Übersichtskarte ---
    if($('#projection').val() == 'EPSG:900913')
    {

        var markergeom = new OpenLayers.LonLat(longitude,latitude);

        map_overview.setCenter(markergeom,map_overview.getZoomForResolution(map.getResolution())-4);

        var poly = map.getExtent().toGeometry();

        vector = new OpenLayers.Feature.Vector();
        vector.geometry = poly;

        var movelayer = map_overview.getLayersByName('Move Layer')[0];
        if(movelayer != null)
        {
            var features = movelayer.features;
            movelayer.removeFeatures(features);
            movelayer.addFeatures(vector);
        }   


    }



}


function on_zoom_end()
{

    if($('#projection').val() == 'EPSG:900913')
    {
        if(map.getZoom() < 14 && ( $('#viewoptions #basemap').hasClass('current') ||  $('#viewoptions #luftbild').hasClass('current') ) )
        {
            map.getLayersByName('Projekt Layer')[0].setVisibility(false);
			map.setBaseLayer(map.getLayersByName('Google Streets')[0]);
            var maps = $('#viewoptions li');
            for(var i=0;i<=maps.length-1;i++)
            {
                $(maps[i]).removeClass('current');
            }
            $('#viewoptions #google').addClass('current');
            
        }

        if(map.getZoom() >= 14)
        {
            $('#viewoptions #basemap a').css('color','#000000');
            $('#viewoptions #basemap').removeClass('notAvailable');
            $('#viewoptions #luftbild a').css('color','#000000');
            $('#viewoptions #luftbild').removeClass('notAvailable');
 
        }
        else
        {
            $('#viewoptions #basemap a').css('color','#CCCCCC');
            $('#viewoptions #basemap').addClass('notAvailable');
            $('#viewoptions #luftbild a').css('color','#CCCCCC');
            $('#viewoptions #luftbild').addClass('notAvailable');
        }


        if(map.getZoom() == 14 && !$('#viewoptions #basemap').hasClass('current'))
        {
            $("#basemap a").animate( { backgroundColor: 'red' }, 120).animate( { backgroundColor: 'white' }, 120).animate( { backgroundColor: 'red' }, 120).animate( { backgroundColor: 'white' }, 120); 
            $("#infoBlase").fadeIn();
        }
        else
        {
            $("#infoBlase").fadeOut();
        }

    }

}


function initMap(gisdata){
	var map;
        var untiled;
        var tiled;
            $( "#overviewMap" ).dialog('open');
			var projecttype = $("#projecttype");

			var min_zoom = $('#min_zoom').val();
			var max_zoom = $('#max_zoom').val();

			var tilecache_url = $('#tilecache_url').val();//"http://cache2.map2web.eu/cache";


            var pureCoverage = false;
            OpenLayers.IMAGE_RELOAD_ATTEMPTS = 5;
	        OpenLayers.DOTS_PER_INCH = 96;
            format = 'image/png';

			var extent = $('#extent').val().split(',');
			var rendering_extent = $('#rendering_extent').val().split(',');

            var ortho_url = "";

			var projection = $('#projection').val();

            serverResolutions = serverResolutions_ro;

			if(projecttype.val() == 'simple')
			{
				serverResolutions = serverResolutions_at;
				var karte = "austria-cc";
			}
			else if(projecttype.val() == 'simple_ro')
			{
				serverResolutions = serverResolutions_ro;
				var karte = "romania_700k";
			}
			else if(projecttype.val() == 'webmercator')
			{
				serverResolutions = serverResolutions_osm;
                tilecache_url = $('#tilecache_url').val();//"http://cache3.map2web.eu/cache";
                ortho_url = "ortho";
				var karte = "basemap";
			}
			else if(projection == 'EPSG:32633'){
				serverResolutions = serverResolutions_at;
				var karte = "austria";
                ortho_url = "ortho-austria";
			}
			else if(projection == 'EPSG:32632'){
				serverResolutions = serverResolutions_at;
				var karte = "austria32";
                ortho_url = "ortho-austria32";
			}
			else if(projection == 'EPSG:32634'){
				var karte = "romania";
			}
			else if(projection == 'EPSG:900913'){
				serverResolutions = serverResolutions_osm;
				var karte = "osm";
			}

			var projektid = $('#projektid').val();

			if(extent.length != 4)
			{
				alert('Please insert the max. extent in the following format (x1, y1, x2, y2)');
				return 0;
			}

			var bounds = new OpenLayers.Bounds(
                parseFloat(rendering_extent[0]),parseFloat(rendering_extent[1]),
                parseFloat(rendering_extent[2]),parseFloat(rendering_extent[3])
            );

            var restrictedbounds = new OpenLayers.Bounds(
                parseFloat(extent[0]),parseFloat(extent[1]),
                parseFloat(extent[2]),parseFloat(extent[3])
            );

			var start_extent = $('#start_extent').val().split(',');

            var startextent = new OpenLayers.Bounds(
                parseFloat(start_extent[0]),parseFloat(start_extent[1]),
                parseFloat(start_extent[2]),parseFloat(start_extent[3])
            );


            var maxresolution = serverResolutions[min_zoom];
            var minresolution = serverResolutions[max_zoom];

            if($('#projection').val() == 'EPSG:900913')
            {
                maxresolution = serverResolutions[0];
                minresolution = serverResolutions[19];
            }


            map = new OpenLayers.Map({
                controls: [],
                div: "map",
                projection: new OpenLayers.Projection($('#projection').val()),
                units: "m",
                restrictedExtent: restrictedbounds,
                maxResolution: maxresolution,
                minResolution: minresolution,
                "serverResolutions": serverResolutions,
                maxExtent: bounds
            });


            tilecache2 = new OpenLayers.Layer.TileCache("Karten Layer",
                [tilecache_url],
                karte,
                {
                	"serverResolutions": serverResolutions
                }
            );

            ortho_layer2 = new OpenLayers.Layer.TileCache("Ortho Layer",
                [tilecache_url],
                ortho_url,
                {
                	"serverResolutions": serverResolutions,
					"format": "image/jpeg"
                }
            );

            schwechat_layer2 = new OpenLayers.Layer.TileCache("Projekt Layer",
                [tilecache_url],
                projektid,
                {
                	"serverResolutions": serverResolutions,
					"alpha":true,
					"isBaseLayer": false,
					"format": "image/png"
                },
                {"isBaseLayer": false}

            );

            var gmap = new OpenLayers.Layer.Google("Google Streets",
                {
                	"sphericalMercator": true, 
                    minResolution: serverResolutions[0],
                    maxResolution: serverResolutions[19],
                    numZoomLevels: 22
                    
                }

            );

            var gmapsat = new OpenLayers.Layer.Google("Google Satelit",
                {
                	"sphericalMercator": true, 
                    maxResolution: serverResolutions[0],
                    maxResolution: serverResolutions[19],
                    type: G_HYBRID_MAP, 
                    numZoomLevels: 22
                }

            );


        	var vectorLayer = new OpenLayers.Layer.Vector("Vector Layer",{"isBaseLayer": false});

            var measureLayer = new OpenLayers.Layer.Vector("Measure Layer");

            //map.events.unregister("moveend",null,on_move_end);


            var infolayer = new OpenLayers.Layer.Vector("Mehr Layer");

    function onPopupClose(evt) {
        selectControl.unselect(selectedFeature);
    }

    function onFeatureSelect(feature) {
        selectedFeature = feature;

		//--- Anzeigedaten im Shape (Wikipedia) ---
		if(feature.name != '' && feature.name != null)
		{
            var data = $.DIV({},
            	$.DIV({},
            		$.STRONG({},feature.name)
            	),
            	$.DIV({},feature.summary),
            	$.DIV({},
            		$.A({'target':'_blank','href':'http://' + feature.url},'Wikipedia Eintrag')
            	)
            );

			popup = new OpenLayers.Popup.FramedCloud("chicken",
            	feature.geometry.getBounds().getCenterLonLat(),
            	null,
            	data.innerHTML,
                null, true, onPopupClose);
	        feature.popup = popup;
	        popups.push(popup);
	        map.addPopup(popup);




		}
		//--- Anzeigedaten aus Map2Web ---
		else
		{
			$.post( getAjaxUrl() + "/projekt/getDetailInformationHtml",{'id':feature.objektid,'objtype':feature.objtype,'ffb_mode':ffb_mode},
				function(data)
				{
			        popup = new OpenLayers.Popup.FramedCloud("chicken",
	                	feature.geometry.getBounds().getCenterLonLat(),
	                	null,
	                	data,
	                    null, true, onPopupClose);
			        feature.popup = popup;
			        popups.push(popup);
			        map.addPopup(popup);

			       	$($('.olPopup').find('a[rel]')).overlay({

					mask: '#000',
					effect: 'apple',

					onBeforeLoad: function() {
						var wrap = this.getOverlay().find(".contentWrap");
						wrap.load(this.getTrigger().attr("href"));
					}

				});


				}
			);
		}
    }

    function onFeatureUnselect(feature) {
        map.removePopup(feature.popup);
        feature.popup.destroy();
        popups.pop(popup);
        feature.popup = null;
    }




            map.addLayers([tilecache2,gmap,gmapsat,ortho_layer2,measureLayer,infolayer,vectorLayer,schwechat_layer2]);


            //map.addControl(new OpenLayers.Control.Scale('scale'));
            var scaleLine = new OpenLayers.Control.ScaleLine();
            map.addControl(scaleLine);

            scaleLine.div.style.left = "20px";
            scaleLine.div.style.bottom = "52px";
            


            //map.addControl(new OpenLayers.Control.ScaleLine());
            //map.addControl(new OpenLayers.Control.MousePosition('location'));
        	//map.addControl(new OpenLayers.Control.LayerSwitcher());

    selectControl = new OpenLayers.Control.SelectFeature(vectorLayer,
        {onSelect: onFeatureSelect, onUnselect: onFeatureUnselect});
    map.addControl(selectControl);
	selectControl.activate();

	var panZoomBar = new OpenLayers.Control.PanZoomBar();
	map.addControl(panZoomBar);
	for (var p = 0; p < 4; p++) {
	    panZoomBar.buttons[p].style.display = 'none';
	}
	panZoomBar.div.style.marginTop = "-50px";
	panZoomBar.div.style.marginLeft = "-6px";
        panZoomBar.div.style.zIndex = "1100";

			OpenLayers.Control.CustomNavToolbar = OpenLayers.Class(OpenLayers.Control.Panel, {

			    initialize: function(options) {
			        OpenLayers.Control.Panel.prototype.initialize.apply(this, [options]);
			        this.addControls([
			          new OpenLayers.Control.Navigation({'title':$.i18n('Map2Web', 'verschieben')}),
			          new OpenLayers.Control.ZoomBox({'title':$.i18n('Map2Web', 'rechteckzoom'), alwaysZoom:true})
			        ]);
					this.displayClass = 'Map2WebToolbar';
			    },

			    draw: function() {
			        var div = OpenLayers.Control.Panel.prototype.draw.apply(this, arguments);
			        this.activateControl(this.controls[0]);
			        return div;
			    }

			});

			OpenLayers.Control.CustomNavToolbarLayerSwitcher = OpenLayers.Class(OpenLayers.Control.Panel, {

			    initialize: function(options) {
			        OpenLayers.Control.Panel.prototype.initialize.apply(this, [options]);
					this.displayClass = 'Map2WebLayerSwitcher';
			    },

			    draw: function() {
			        var div = OpenLayers.Control.Panel.prototype.draw.apply(this, arguments);
			        this.activateControl(this.controls[0]);
			        return div;
			    }

			});

	       var lineedit = new OpenLayers.Control.DrawFeature(
                measureLayer, OpenLayers.Handler.Path,
                {
                   handlerOptions: {freehand: false, multi: true},
                   displayClass: "olControlDrawFeatureLine",
                   'title':$.i18n('Map2Web', 'längenmessung'),
                   featureAdded: function(){
                   		if(this.layer.features.length > 1)
                   			this.layer.removeFeatures(this.layer.features[0]);
                   		printLineLength(this);
                   }
                }
            );

	       var areaedit = new OpenLayers.Control.DrawFeature(
                measureLayer, OpenLayers.Handler.Polygon,
                {
                   handlerOptions: {freehand: false, multi: true},
                   displayClass: "olControlDrawFeaturePolygon",
                   'title':$.i18n('Map2Web', 'flächenmessung'),
                   featureAdded: function(){
                   		if(this.layer.features.length > 1)
                   			this.layer.removeFeatures(this.layer.features[0]);
                   		printAreaSize(this);
                   }
                }
            );

			var button_zoom_max_extent = new OpenLayers.Control.Button({
                            'title':$.i18n('Map2Web', 'zoomtomaxextent'),
			    displayClass: "olControlZoomToMaxExtent",
			    trigger: function()
                {
    				$('.switchMap').removeClass('current');                    
	            	map.zoomToExtent(startextent);
	                map.setBaseLayer(map.getLayersByName('Karten Layer')[0]);
                    map.getLayersByName('Projekt Layer')[0].setVisibility(true);
                    $('#basemap').addClass('current');
                    $("#infoBlase").fadeOut();
			    }
			});


			var panel = new OpenLayers.Control.CustomNavToolbar();

            if(projecttype.val() != 'simple')
    			panel.addControls([lineedit,areaedit,button_zoom_max_extent]);
            else
     			panel.addControls([button_zoom_max_extent]);

        	map.addControl(panel);


			if($('#start_extent').val() != '' && $('#start_extent').val() != null)
			{
	            map.zoomToExtent(startextent,false);
			}
			else
			{
				map.zoomToExtent(restrictedbounds);
			}


            map.events.register("moveend",null,on_move_end);   
            map.events.register("zoomend",null,on_zoom_end);       


            //--- Übersichtskarte anzeigen ---
            if($('#projection').val() == 'EPSG:900913')
            {
                $( "#overviewMap" ).dialog({'width':overviewmap_width,'height':overviewmap_height,'resizable':false,'position':[$(window).width()-overviewmap_width,$(document).height()-overviewmap_height]});
                $( "#overviewMap" ).css('height',overviewmap_height);

                map_overview = initOverviewMap();

                map_overview.zoomToMaxExtent();

                var movelayer = new OpenLayers.Layer.Vector("Move Layer");
                map_overview.addLayer(movelayer);

                var drag = new OpenLayers.Control.DragFeature(movelayer,{'onComplete':onDragComplete});

                map_overview.addControl(drag);
                drag.activate();

            }








        	return map;

}

function calculateItems()
{
	var itemheight = 23;
	var listHeight;

	if(navigator.userAgent.indexOf("MSIE 6.0") != -1)  listHeight = document.body.clientHeight - 233 -52;
	else listHeight = $(document).height() - 233 -52;

	//listHeight = $(document).height() - 233 -52;

	var gezeigteAnzahl = Math.floor(listHeight / itemheight)-1;

	return gezeigteAnzahl;

}

function printLineLength(feature)
{
	var formatter = new OpenLayers.Format.GeoJSON();
	var gisdata = formatter.write(feature.layer.features[0].geometry);

	$.post("/projekt/calculateLineLength", {'gisdata':gisdata,'projection':$('#projection').val()},
			function(data)
			{
				var laenge = parseFloat(data);
				if(laenge > 1000)
				{
					laenge = laenge / 1000;
					$.jGrowl(laenge.toFixed(3) + " km",
						{
							'sticky':true,
							close:function()
							{
								resetMeasureLayer();
							}
						}
					);
				}
				else
				{
					$.jGrowl(laenge.toFixed(2) + " m",
						{
							'sticky':true,
							close:function()
							{
								resetMeasureLayer();
							}
						}
					);
				}
			}
		,'json');
}

function printAreaSize(feature)
{
	var formatter = new OpenLayers.Format.GeoJSON();
	var gisdata = formatter.write(feature.layer.features[0].geometry);

	$.post("/projekt/calculateAreaSize", {'gisdata':gisdata,'projection':$('#projection').val()},
			function(data)
			{
				var flaeche = parseFloat(data);
				if(flaeche > 1000000)
				{
					flaeche = flaeche / 1000000;
					$.jGrowl(flaeche.toFixed(3) + " km²",
						{
							'sticky':true,
							close:function()
							{
								resetMeasureLayer();
							}
						}
					);
				}
				else
				{
					$.jGrowl(flaeche.toFixed(2) + " m²",
						{
							'sticky':true,
							close:function()
							{
								resetMeasureLayer();
							}
						}
					);
				}
			}
		,'json');
}

function resetMeasureLayer(){

	try
	{
		var measureLayer = map.getLayersByName('Measure Layer')[0];
		measureLayer.removeFeatures(measureLayer.features);
	}
	catch(ex)
	{

	}

}




function initVectorLayer(map){

	vectorLayer = map.getLayersByName('Vector Layer')[0];
    //vectorLayer.removeFeatures(vectorLayer.features);

    /*

	try
	{
		map.removeLayer(vectorLayer);
	}
	catch(ex)
	{

	}

	var vectorLayer = new OpenLayers.Layer.Vector("Vector Layer",{"isBaseLayer": false});

    */


/*
    selectControl = new OpenLayers.Control.SelectFeature(vectorLayer,
        {onSelect: onFeatureSelect, onUnselect: onFeatureUnselect});
    map.addControl(selectControl);
	selectControl.activate();

*/


    /*

    var controls = map.controls;
   
    for(var i=0;i<=controls.length-1;i++)
    {
        if(controls[i].displayClass=='olControlNavigation'){
            var navi = controls[i];
            map.removeControl(controls[i]);
            map.addControl(navi);
        }
            //controls[i].activate();
            //map.removeControl(controls[i]);  
    }
    naviControl = new OpenLayers.Control.Navigation(vectorLayer);
    map.addControl(naviControl);
    
    */

    /*

    function onPopupClose(evt) {
        selectControl.unselect(selectedFeature);
    }

    function onFeatureSelect(feature) {
        selectedFeature = feature;

		//--- Anzeigedaten im Shape (Wikipedia) ---
		if(feature.name != '' && feature.name != null)
		{
            var data = $.DIV({},
            	$.DIV({},
            		$.STRONG({},feature.name)
            	),
            	$.DIV({},feature.summary + "1234"),
            	$.DIV({},
            		$.A({'target':'_blank','href':'http://' + feature.url},'Wikipedia Eintrag')
            	)
            );

			popup = new OpenLayers.Popup.FramedCloud("chicken",
            	feature.geometry.getBounds().getCenterLonLat(),
            	null,
            	data.innerHTML,
                null, true, onPopupClose);
	        feature.popup = popup;
	        map.addPopup(popup);
		}
		//--- Anzeigedaten aus Map2Web ---
		else
		{
			$.post( getAjaxUrl() + "/projekt/getDetailInformationHtml",{'id':feature.objektid},
				function(data)
				{
			        popup = new OpenLayers.Popup.FramedCloud("chicken",
	                	feature.geometry.getBounds().getCenterLonLat(),
	                	null,
	                	data,
	                    null, true, onPopupClose);
			        feature.popup = popup;
			        map.addPopup(popup);
		        $($('.olPopup').find('a[rel]')).overlay({

					mask: '#000',tclayer
					effect: 'apple',

					onBeforeLoad: function() {
						var wrap = this.getOverlay().find(".contentWrap");
						wrap.load(this.getTrigger().attr("href"));
					}

				});

				}
			);
		}
    }

    function onFeatureUnselect(feature) {
        map.removePopup(feature.popup);
        feature.popup.destroy();
        feature.popup = null;
    }

*/
	return vectorLayer;

}

function drawFeatures(geom, layer,zoomin,noicon,iconsize){
	var formatter = new OpenLayers.Format.GeoJSON();
	var vectorLayer = layer;

	removeAllPopups();

    if(iconsize == null)
    {        
        iconsize = 14;
    }

	if(geom.type == 'MultiLineString' || geom.type == 'LineString')
	{
		var style_dyn = {
			'strokeColor': '#' + geom.color,
			'strokeWidth': 4,
			'pointRadius': 4,
			'pointerEvents': "visiblePainted",
			'strokeOpacity': 0.8
		};

		var vector = formatter.read(geom);
		vector[0].style =  style_dyn;
		vector[0].objektid = geom.objektid;
		vectorLayer.addFeatures(vector);
	}
	else if(geom.type == 'Point' || geom.type == 'MultiPoint')
	{
		var feature = formatter.read(geom);
        size = new OpenLayers.Size(12,12);

		var iconpath = "";
		var size = iconsize;


	    if(geom.icon == null || geom.icon == '')
	    {
		    iconpath = "/js/images/marker2.gif";
		    var size = 10;
	    }
	    else
	    {
		    iconpath=geom.icon;
	    }
	    feature[0].style={
    	    'pointRadius': size,
		    'externalGraphic': iconpath,
		    'graphicWidth':size,
		    'graphicHeight':size
	    }


		feature[0].objektid = geom.objektid;

		feature[0].name = geom.name;
		feature[0].summary = geom.summary;
		feature[0].url = geom.url;
		feature[0].image = geom.image;
		feature[0].objtype = geom.objtype;


		//feature[0].attributes = {type:'triangle'};

		vectorLayer.addFeatures(feature);

		if(zoomin==true)
		{
			$.post( getAjaxUrl() + "/projekt/getDetailInformationHtml",{'id':feature[0].objektid},
				function(data)
				{
				popup = new OpenLayers.Popup.FramedCloud("chicken",
		        	feature[0].geometry.getBounds().getCenterLonLat(),
		        	null,
		        	data,
		            	null, true,
				function()
				{
					map.removePopup(popup);
				}
				);
				feature.popup = popup;
				map.addPopup(popup);

		        $($('.olPopup').find('a[rel]')).overlay({

					mask: '#000',
					effect: 'apple',

					onBeforeLoad: function() {
						var wrap = this.getOverlay().find(".contentWrap");
						wrap.load(this.getTrigger().attr("href"));
					}

				});



				}
			);

			var x = feature[0].geometry.x;
			var y = feature[0].geometry.y;

			if(x != 0 || y != 0)
			{
		        	var newbounds = new OpenLayers.Bounds(
		                    x-100, y-100,
		                    x+100, y+100
		                );
				map.zoomToExtent(newbounds);
			}
		}

	}
	else if(geom.type == 'MultiPolygon' || geom.type == 'Polygon')
	{
		var feature = formatter.read(geom);


        if(geom.objtype != 'solar')
        {
		    feature[0].style = {
			    'strokeColor': '#' + geom.color,
			    'fillColor': '#' + geom.color,
			    'strokeWidth': 1,
			    'pointerEvents': "visiblePainted",
			    'strokeOpacity': 1,
			    'fillOpacity': 0.5
		    };
        }
        else
        {
		    feature[0].style = {
			    'strokeColor': '#' + geom.color,
			    'fillColor': '#' + geom.color,
			    'strokeWidth': 1,
			    'pointerEvents': "visiblePainted",
			    'strokeOpacity': 1,
			    'fillOpacity': 0
		    };
        }

		feature[0].objektid = geom.objektid;
		feature[0].objtype = geom.objtype;
		vectorLayer.addFeatures(feature);

		if(zoomin==true)
		{
            var center = formatter.read(geom.center);
            if(center != null)
            {
                var moveto = new OpenLayers.LonLat(center[0].geometry.x,center[0].geometry.y);
                map.setCenter(moveto);
            }

        }


	}


}


function removeAllPopups()
{
	var popups = map.popups;
	for(var i=0;i<=popups.length-1;i++)
	{
		map.removePopup(popups[i]);
	}
}

function onPopupClose(evt) {
    function onFeatureUnselect(feature) {
        map.removePopup(feature.popup);
        feature.popup.destroy();
        feature.popup = null;
    }
}

function removeFeatureByObjtype(map)
{
	var vectorLayer = map.getLayersByName('Mehr Layer')[0];

    var features = new Array();

	for(var l=0;l<=vectorLayer.features.length-1;l++){
        features.push(vectorLayer.features[l]);
	}
    vectorLayer.removeFeatures(features);


	var vectorLayer = map.getLayersByName('Vector Layer')[0];

    var features = new Array();

	for(var l=0;l<=vectorLayer.features.length-1;l++){
        features.push(vectorLayer.features[l]);
	}
    vectorLayer.removeFeatures(features);


}


function printHouseNumbers(map,here)
{

	if($(here).val() != '-1')
	{

		var vectorLayer = map.getLayersByName('Vector Layer')[0];

        var features = new Array();

		for(var l=0;l<=vectorLayer.features.length-1;l++){
			if(vectorLayer.features[l].vtype == 'hnr')
            {
				features.push(vectorLayer.features[l]);
            }

		}
        vectorLayer.removeFeatures(features);


		$.post(getAjaxUrl() + "/projekt/getHousenumberGisData",{'id':$(here).val(),'projection':$('#projection').val()},
			function(data)
			{

				var formatter = new OpenLayers.Format.GeoJSON();

				for(var i=0;i<=data.geometries.length-1;i++)
				{
	                var vector = formatter.read(data.geometries[i]);

                    if(data.geometries[i].type == 'Point')
					{
						vector[0].style={
                    	    'pointRadius': 10,
							'externalGraphic': '/js/images/marker2.gif',
							'graphicWidth':10,
							'graphicHeight':10
               			};
                        // --- Zur Hausnummer moven ---
                        var center = new OpenLayers.LonLat(data.geometries[i].coordinates[0],data.geometries[i].coordinates[1])
                        map.moveTo(center);
					}

	                if(data.geometries[i].type == 'MultiPolygon' || data.geometries[i].type == 'Polygon')
	                {
		                vector[0].style = {
			                'strokeColor': '#0000FF',
			                'fillColor': '#0000FF',
			                'strokeWidth': 1,
			                'pointerEvents': "visiblePainted",
			                'strokeOpacity': 1,
			                'fillOpacity': 0.5
		                };
                        vector[0].vtype = 'hnr';
	                }

					vector[0].vtype = 'hnr';
	                vectorLayer.addFeatures(vector);

				}
			}
		,'json');

	}
	else
	{
		var vectorLayer = map.getLayersByName('Vector Layer')[0];

		for(l=0;l<=vectorLayer.features.length-1;l++){
			if(vectorLayer.features[l].vtype == 'hnr')
				vectorLayer.removeFeatures(vectorLayer.features[l]);
		}

	}

}





window.onload = function() {

	map = initMap();

	var pfad = $('#pfad').val();
	var object_path = pfad.split('/').reverse();
	//alert(object_path[0]);
    //--- Nur Objektanzeige, keine Menüs aufklappen ---
    if(object_path.length == 1 && object_path[0] != '')
    {
	    $.post(getAjaxUrl() + "/projekt/getWirtschaftGisData",{'id':object_path[0],'projection':$('#projection').val()},
		    function(data)
		    {
			    var style_blue = {
	        			'pointRadius': 10,
				    'externalGraphic': '/js/images/marker2.gif',
				    'graphicWidth':10,
				    'graphicHeight':10
			    };

			    initVectorLayer(map);

			    var gisdata = data;

		        var vectorLayer = initVectorLayer(map);
                //map.addLayers([vectorLayer]);

	            function onPopupClose(evt) {
	                selectControl.unselect(selectedFeature);
	            }

                if(data.hasOwnProperty('geometries'))
                {
                    for(var i=0;i<=data.geometries.length-1;i++)
                    {
                        drawFeatures(data.geometries[i],vectorLayer,false);
                    } 
                }
                else
                {
		            drawFeatures(gisdata,vectorLayer,true);
                }  

		    }

	    ,'json');
    }
    //--- Anzeige inklusive Menüs ---
    else if(object_path.length > 1)
    {
	    for(var i=0;i<=object_path.length-2;i++)
	    {
		    navigationList.push("li#" + object_path[i]);
	    }

	    switchModules(object_path[object_path.length-1]);


    }
	    $('#map').height($(window).height()-102);
	    $('#map').width($(window).width()-291);

	if($('#start_extent').val() != '' && $('#start_extent').val() != null)
	{
		var start_extent = $('#start_extent').val().split(',');

        var startextent = new OpenLayers.Bounds(
            parseFloat(start_extent[0]),parseFloat(start_extent[1]),
            parseFloat(start_extent[2]),parseFloat(start_extent[3])
        );

        var center = startextent.getCenterLonLat();
        map.setCenter(center,$('#max_zoom').val());
        map.zoomToExtent(startextent,false);
	}

}

function printWirtschaft(id){

			var extent = map.getExtent().toBBOX();
			var lon = map.getExtent().getCenterLonLat().lon;
			var lat = map.getExtent().getCenterLonLat().lat;
			var zoom = map.getZoom();
			var ooid = id;
			neuesFenster = window.open(getAjaxUrl() + "/projekt/viewprint/" + $('#objektid').val() + "?extent=" + extent + "&lonlat=" + lon + "," + lat + "&zoom=" + zoom + "&ooid=" + ooid+ "&mode=wirtschaft", "Druckfenster");
			neuesFenster.focus();
}

function printAGObjekt(id){

			var extent = map.getExtent().toBBOX();
			var lon = map.getExtent().getCenterLonLat().lon;
			var lat = map.getExtent().getCenterLonLat().lat;
			var zoom = map.getZoom();
			var ooid = id;
			neuesFenster = window.open(getAjaxUrl() + "/projekt/viewprint/" + $('#objektid').val() + "?extent=" + extent + "&lonlat=" + lon + "," + lat + "&zoom=" + zoom + "&ooid=" + ooid+ "&mode=agobjekt", "Druckfenster");
			neuesFenster.focus();
}

function printObjekt(id){

			var extent = map.getExtent().toBBOX();
			var lon = map.getExtent().getCenterLonLat().lon;
			var lat = map.getExtent().getCenterLonLat().lat;
			var zoom = map.getZoom();
			var ooid = id;
			neuesFenster = window.open(getAjaxUrl() + "/projekt/viewprint/" + $('#objektid').val() + "?extent=" + extent + "&lonlat=" + lon + "," + lat + "&zoom=" + zoom + "&ooid=" + ooid + "&mode=objekt", "Druckfenster");
			neuesFenster.focus();
}


function switchModules(id,link)
{
		removeAllPopups();
		resetMeasureLayer();

        $("#viewoptions").show();

        $("#bottomInfo").remove();

        map.events.listeners['moveend'];
        //map.getControlsBy('title','moveend')[0].unregister(); 

        if(map_mode=='kultur')
        {
            $('#viewoptions #flaewi').remove();
            $('#viewoptions').show();
			$("#map_OpenLayers_ViewPort").remove();
            map_mode="standard";
            map = initMap();
        }

		if($(link).hasClass('kulturmodul'))
		{
            //alert('kultur');

            $('#viewoptions').hide();
			$("#map_OpenLayers_ViewPort").remove();
			var here = $(this);
			$.post(getAjaxUrl() + "/kulturmodul/getExtent",{'id':id},
				function(data)
				{
					map_mode = 'kultur';
					map = initKulturMap(data.max_extent,data.min_zoom,data.max_zoom);
				}
			,'json');

            //map.events.unregister("moveend",null,on_move_end);

			var ul = $(link).parent();
			ul.find('ul').remove();

			$.post(getAjaxUrl() + "/kulturmodul/getSchlagwortBaum",{'id':$('#objektid').val(),'projection':$('#projection').val()},
				function(data)
				{
							var newul = $.UL({'class':'Level2nd'});
							$(newul).css('display','block');
							ul.append(newul);

							for(i=0;i<=data.length-1;i++)
							{
								var element = 	$.LI({'id':data[i].id,'class':'Level2nd'},
												$.A({'id':data[i].id,'class':'showKultur','href':'#'},data[i].name)
											);
								$(newul).append(element);

							}
							/*
							var vectorLayer = initVectorLayer(map);

	            			map.addLayers([vectorLayer]);


							if(navigationList.length>0)
								navigateList();
								*
							*/

							var formatter = new OpenLayers.Format.GeoJSON();
							var vectorLayer = initVectorLayer(map);
	            			//map.addLayers([vectorLayer]);

							for(var i=0;i<=data.length-1;i++)
							{
								var vector = data[i].allchilds;
								drawFeatures(vector,vectorLayer,false);
							}

					}
			,'json');


		}
		else if($(link).hasClass('flaewimodul'))
		{

            //$('#viewoptions #flaewi').remove();
			//$('#suchmodul').val('flaewi');
			map_mode = 'flaewi';
            //$('#viewoptions #flaewi').remove();
            //$('#viewoptions').show();
			//$("#map_OpenLayers_ViewPort").remove();
            //map = initMap();
            map.getLayersByName('Projekt Layer')[0].setVisibility(false);

            if($('#projektid').val() == 'st-poelten')
            {
                $('#map2web').prepend('<span id="bottomInfo" style="margin-right:20px;">Kein Rechtsanspruch aus der Karte ableitbar.</span>');
            }   

            $("#viewoptions").hide();

            var ul = $(link).parent();
            ul.find('ul').remove();

            var tilecache_url = "http://cache2.map2web.eu/cache";

            if($('#projection').val() == 'EPSG:900913')
                {
                    tilecache_url = 'http://cache3.map2web.eu/cache'

                    tilecache_layer = new OpenLayers.Layer.TileCache("Tilecache Layer",
                        [tilecache_url],
                        $(link).attr('href'),
                        {
			                "isBaseLayer": false,
                            "visible":true
                        }

                    );
                }
                else if($('#projection').val() == 'EPSG:32633' || $('#projection').val() == 'EPSG:32632')
                {
                    tilecache_layer = new OpenLayers.Layer.TileCache("Tilecache Layer",
                        [tilecache_url],
                        $(link).attr('href'),
                        {
                        	"serverResolutions": serverResolutions_at,
			                "isBaseLayer": false,
                            "visible":true
                        }
                    );
                }


            if($(link).attr('href') != '')
                map.addLayers([tilecache_layer]);

            map.raiseLayer(tilecache_layer,-1);


            $.post(getAjaxUrl() + "/flaewimodul/getSchlagwortBaum",{'id':$(link).attr('id')},
            function(data)
            {
                  var newul = $.UL({'class':'Level2nd'});
                  $(newul).css('display','block');
                  ul.append(newul);

                  for(i=0;i<=data.objs.length-1;i++)
                  {
                    var element =   $.LI({'id':data.objs[i].id,'class':'Level2nd'},
                            $.A({'href':data.objs[i].url,'target':'_blank'},data.objs[i].name)
                          );
                    $(newul).append(element);

                  }

              }
            ,'json');

			$("#suche_auswahl").hide();
			$("#suche_auswahl_flaewi").show();
		}
        else if($(link).hasClass('agservice'))
        {
            $('#viewoptions #flaewi').remove();
            var ul = $(link).parent();
            ul.find('ul').remove();

            $('#viewoptions').show();
           
            if($('#flaechenwidmungsplan').val() == 'True')
            {
                $("#viewoptions").append('<li id="flaewi" class="switchMap flaewi"><a href="/">Flächenwidmungsplan</a></li>');
            }

          $.post(getAjaxUrl() + "/agservice/getSchlagwortBaum",{'id':$(link).attr('id')},
            function(data)
            {
                  var newul = $.UL({'class':'Level2nd'});
                  $(newul).css('display','block');
                  ul.append(newul);

                  for(i=0;i<=data.objs.length-1;i++)
                  {
                    if(data.objs[i].type != 'direktlink')
                    {
                        var element =   $.LI({'id':data.objs[i].id,'class':'Level2nd'},
                            $.A({'id':data.objs[i].id,'class':'navigate '+data.objs [i].type,'href':'#'},data.objs[i].name)
                          );
                    $($(element).find('a')[0]).css('color','#'+data.objs[i].color);
                    }
                    else
                    {
                        var element =   $.LI({'id':data.objs[i].id,'class':'Level2nd'},
                            $.A({'href':data.objs[i].url,'target':'_blank'},data.objs[i].name)
                          );
                    }
                    $(newul).append(element);

                  }

                  var vectorLayer = initVectorLayer(map);

                  //map.addLayers([vectorLayer]);
                  var formatter = new OpenLayers.Format.GeoJSON();



                  for(var i=0;i<=data.selfgeometries.geometries.length-1;i++)
                  {
                    drawFeatures(data.selfgeometries.geometries[i],vectorLayer,false);
                  }


                  //drawFeatures(data.geometries,vectorLayer,true)

                  if(navigationList.length>0)
                    navigateList();
              }
          ,'json');






        }

        else if($(link).hasClass('aglayer'))
        {
          var ul = $(link).parent();
          ul.find('ul').remove();
          $.post(getAjaxUrl() + "/aglayer/getSchlagwortBaum",{'id':$(link).attr('id'),'projection':$('#projection').val()},
            function(data)
            {
                  var vectorLayer = initVectorLayer(map);
                  //map.addLayers([vectorLayer]);
                  var formatter = new OpenLayers.Format.GeoJSON();


                      var newul = $.UL({'class':'Level2nd'});
                      $(newul).css('display','block');
                      ul.append(newul);

                      for(i=0;i<=data.objs.length-1;i++)
                      {
                        var element =   $.LI({'id':data.objs[i].id,'class':'Level2nd'},
                                $.A({'id':data.objs[i].id,'class':'showAGObjekt','href':'#'},data.objs[i].name)
                              );
                        $(newul).append(element);
                      }

                      for(var i=0;i<=data.selfgeometries.geometries.length-1;i++)
                      {
                        drawFeatures(data.selfgeometries.geometries[i],vectorLayer,false);
                      }


                  if(navigationList.length>0)
                    navigateList();
              }
          ,'json');

        }



		else if($(link).hasClass('tclayer'))
		{

            map_mode="standard";



            if($('#projektid').val() == 'st-poelten')
            {
                $('#map2web').prepend('<span id="bottomInfo" style="margin-right:20px;">Kein Rechtsanspruch aus der Karte ableitbar.</span>');
            }  

            if($('#projektid').val() == 'fuerstenfeldbruck' && nutzungsbedingungen_ffb == false)
            {

                $("#nutzungsbedingungen_ffb").overlay({
	                top: 20,
	                mask: {
		                color: '#fff',
		                loadSpeed: 200,
		                opacity: 0.5
	                }
                });

                var api = $("#nutzungsbedingungen_ffb").data("overlay");
                api.load();

                return false;
            }


			map_mode = 'tclayer';

            $('#viewoptions #flaewi').remove();

            tilecache_url = $('#tilecache_url').val();//"http://cache2.map2web.eu/cache";

            if($('#projecttype').val() == 'webmercator')
			{
                tilecache_url = $('#tilecache_url').val();//"http://cache3.map2web.eu/cache";
			}

            if($('#projection').val() == 'EPSG:900913')
            {
                tilecache_layer = new OpenLayers.Layer.TileCache("Tilecache Layer",
                    [tilecache_url],
                    $(link).attr('href'),
                    {
					    "isBaseLayer": false,
                        "visible":true
                    }

                );
            }
            else if($('#projection').val() == 'EPSG:32633' || $('#projection').val() == 'EPSG:32634')
            {
                tilecache_layer = new OpenLayers.Layer.TileCache("Tilecache Layer",
                    [tilecache_url],
                    $(link).attr('href'),
                    {
                    	"serverResolutions": serverResolutions_at,
					    "isBaseLayer": false,
                        "visible":true
                    }
                );
            }



   			var ul = $(link).parent();
			ul.find('ul').remove();
			$.post(getAjaxUrl() + "/tclayer/getSchlagwortBaum",{'id':$(link).attr('id')},
				function(data)
				{
		
                    if(data!=null)
                    {
        					var newul = $.UL({'class':'Level2nd'});
							$(newul).css('display','block');
							ul.append(newul);
        
							for(i=0;i<=data.objs.length-1;i++)
							{
                                if(data.objs[i].type == 'direktlink')
                                {
								    var element = 	$.LI({'class':'Level2nd'},
												    $.A({'href':data.objs[i].href,'target':'_blank'},data.objs[i].name)
											    );
                                }
                                else if(data.objs[i].icon != undefined && data.objs[i].icon != '')
                                {
								    var element = 	$.LI({},
                                                                $.TABLE({},
															        $.TBODY({},
																        $.TR({},
																	        $.TD({'class':'thumbnail'},
																		        $.IMG({'src':data.objs[i].icon})
																	        ),
																	        $.TD({'class':'thumbnailText'},
																		        $.A({'id':data.objs[i].id,'href':'#'},data.objs[i].name)															
                                                                            )

																        )
															        )
                                                                )
															    );


                                    $(element).find('a').css('color','#' + data.objs[i].color)
                                }
                                else
                                {
								    var element = 	$.LI({'class':'Level2nd'},
												    $.A({'id':data.objs[i].id,'class':'navigate '+data.objs[i].type,'href':data.objs[i].layer},data.objs[i].name)
											    );
                                    $(element).find('a').css('color','#' + data.objs[i].color);

                                    if(data.objs[i].hascheckbox == true)
                                    {
                                        $(element).find('a').wrapAll('<label />');
                                        $(element).prepend('<input style="float:left;margin-left:10px;margin-top:6px;" type="checkbox" class="appendLayerToMap" value="' + data.objs[i].layer + '"/>');
                                    }
                                }

								$(newul).append(element);

							}

                            if(data.geom.geometries.length>0)
                            {

							    var vectorLayer = initVectorLayer(map);

                                for(var i=0;i<=data.geom.geometries.length-1;i++)
                                {
                                    drawFeatures(data.geom.geometries[i],vectorLayer,false);
                                }

                            }
							var formatter = new OpenLayers.Format.GeoJSON();

							if(navigationList.length>0)
    								navigateList();

                            //--- Auf Unterordner springen ---
                            if($('#projektid').val() == 'fuerstenfeldbruck')
                            {
                                $('#43018').click();
                            }

                    }

                
					}
			,'json');


            if($(link).attr('href') != '')
                map.addLayers([tilecache_layer]);


            //map.raiseLayer(tilecache_layer,-1);

		}
		else if($(link).hasClass('verkehrsmodul'))
		{
            //$('#viewoptions #flaewi').remove();
            //$('#viewoptions').show();
			//$("#map_OpenLayers_ViewPort").remove();
            map_mode="standard";
            //map = initMap();

            //map.events.unregister("moveend",null,on_move_end);
			var ul = $(link).parent();
			ul.find('ul').remove();
			$.post(getAjaxUrl() + "/verkehrsmodul/getSchlagwortBaum",{'id':$('#objektid').val(),'projection':$('#projection').val()},
				function(data)
				{
							var newul = $.UL({'class':'Level2nd'});
							$(newul).css('display','block');
							ul.append(newul);
							//var newul = ul;

							for(i=0;i<=data.objs.length-1;i++)
							{
                                var href='#';
                                if(data.objs[i].layer != undefined)
                                {
                                    href=data.objs[i].layer;
                                }

								var element = 	$.LI({'id':data.objs[i].id,'class':'Level2nd'},
												$.A({'id':data.objs[i].id,'class':'navigate '+data.objs[i].type,'href':href},data.objs[i].name)
											);
								$(newul).append(element);

                                if(data.objs[i].hascheckbox == true)
                                {
                                    $(element).find('a').wrapAll('<label />');
                                    $(element).prepend('<input style="float:left;margin-left:10px;margin-top:6px;" type="checkbox" class="appendLayerToMap" value="' + data.objs[i].layer + '"/>');
                                }

							}




							//var vectorLayer = initVectorLayer(map);

	            			//map.addLayers([vectorLayer]);
							var formatter = new OpenLayers.Format.GeoJSON();

							if(navigationList.length>0)
								navigateList();
					}
			,'json');






		}









		else
		{
            $('#viewoptions #flaewi').remove();
            $('#viewoptions').show();
			$("#map_OpenLayers_ViewPort").remove();
            map_mode="standard";
            map = initMap();



			if(map_mode=='kultur')
			{
				$('#map').empty();
				map = initMap();
			}

            //map.events.unregister("moveend",null,on_move_end);


			kartenLayer = map.getLayersByName('Karten Layer')[0];
			kartenLayer.setOpacity(1);

			var here = $(this);

			var ul = $(link).parent();
			ul.find('ul').remove();

			if(id == -1 || id == -2 || id == -3)
			{
				var url = "/projekt/getOrte";

				if(id == -2)
					url = "/projekt/getTouristicObjectives";
				else if(id == -3)
					url = "/projekt/getNationalParks";

				$.post(getAjaxUrl() + url, {'id':-1,'portalid':$('#projektid').val()},
					function(data)
					{
						if(data.objs.length > 0)
						{
							var newul = $.UL({'class':'Level2nd'});
							$(newul).css('display','block');
							ul.append(newul);
							//var newul = ul;

							for(i=0;i<=data.objs.length-1;i++)
							{

								var element = 	$.LI({'id':data.objs[i].id,'class':'Level2nd'},
													$.A({'id':data.objs[i].id,'class':'navigate '+data.objs[i].type,'href':'#'},
														$.SPAN({'class':'naviHeadline'},data.objs[i].name),
														$.SPAN({'class':'naviText'},data.objs[i].adresse)
													)
											);

                                if(data.objs[i].name != '')
    								$(newul).append(element);
							}

							var vectorLayer = initVectorLayer(map);

	            			//map.addLayers([vectorLayer]);
							var formatter = new OpenLayers.Format.GeoJSON();

							if(navigationList.length>0)
								navigateList();

						}
					}
				,'json');
			}
			else
			{
				$.post(getAjaxUrl() + "/wirtschaftmodul/getSchlagwortBaum",{'id':id,'gisdata':false,'projection':$('#projection').val()},
					function(data)
					{
						if(data.objs.length > 0)
						{
							var newul = $.UL({'class':'Level2nd'});
							$(newul).css('display','block');
							ul.append(newul);
							//var newul = ul;

							for(i=0;i<=data.objs.length-1;i++)
							{
							//--- Bild vorhanden ---
							if(data.objs[i].images.length > 0)
							{
								firstImage = data.objs[i].images[0];
	

								var element = 	$.LI({},
                                                            $.TABLE({},
															    $.TBODY({},
																    $.TR({},
																	    $.TD({'class':'thumbnail'},
																		    $.IMG({'src':firstImage})
																	    ),
																	    $.TD({'class':'thumbnailText'},
																		    $.A({'id':data.objs[i].id,'class':'navigate '+data.objs[i].type,'href':'#'},
																			    data.objs[i].name,
																			    $.SPAN({},data.objs[i].adresse)
																		    )															)
																	    )
																    )
                                                                )
															);


							}
							//--- kein Bild vorhanden ---
							else
							{
								var element = 	$.LI({'id':data.objs[i].id,'class':'Level2nd'},
													$.A({'id':data.objs[i].id,'class':'navigate '+data.objs[i].type,'href':'#'},
														$.SPAN({'class':'naviHeadline'},data.objs[i].name),
														$.SPAN({'class':'naviText'},data.objs[i].adresse)
													)
											);
							}
							$(newul).append(element);

							}

							var vectorLayer = initVectorLayer(map);

	            			//map.addLayers([vectorLayer]);
							var formatter = new OpenLayers.Format.GeoJSON();

							if(navigationList.length>0)
								navigateList();

						}
					}
				,'json');
			}
		}



}



function navigateList()
{

	var here = $(navigationList.pop()).find('a');



	if(here.parent().hasClass('active'))
	{
		var vectorLayer = initVectorLayer(map);
        //map.addLayers([vectorLayer]);
		here.parent().find('ul').remove();
		here.parent().removeClass('active');
		return false;
	}
	else
	{

	here.append($($.IMG({'src':'/js/images/ajax-loader.gif','id':'ajax-loading'})).css('margin-left',10));
		var vectorLayer = initVectorLayer(map);
        //map.addLayers([vectorLayer]);

		if(here.hasClass('verkehrsmodul_ordner') || here.hasClass('verkehrsmodul') || here.hasClass('verkehrsmodul_linie') || here.hasClass('verkehrsmodul_flaeche') || here.hasClass('verkehrsmodul_punkt'))
			var url = getAjaxUrl() + "/verkehrsmodul/getSchlagwortBaum";
		else
			var url = getAjaxUrl() + "/wirtschaftmodul/getSchlagwortBaum";



		$.post(url,{'id':here.attr('id'),'projection':$('#projection').val()},
			function(data)
			{
				//--- Eigene Gemoetrie falls vorhanden anzeigen ---
				if(data.selfgeometries != null)
				{
					if(data.selfgeometries.geometries.length == 1 )
					{
						drawFeatures(data.selfgeometries.geometries[0],vectorLayer,true);
					}
					else
					{
						for(var i=0;i<=data.selfgeometries.geometries.length-1;i++)
						{
							drawFeatures(data.selfgeometries.geometries[i],vectorLayer,false);
						}
					}
				}

				//--- Geometrie der untergeordneten Objekte anzeigen ---
				if(data.objs.length > 0)
				{
					var ul = $.UL({});

					for(var i=0;i<=data.objs.length-1;i++)
					{
						if(data.objs[i].type == 'wirtschaft')
						{


							var fistimage;
							var images = [];
							//--- Bild vorhanden ---
							if(data.objs[i].images.length > 0)
							{
								firstImage = data.objs[i].images[0];
								var element = 	$.LI({'id':data.objs[i].id},
													/*
													$.DIV({'class':'naviImage'},
														$.IMG({'src':firstImage})
													),
													*/
													$.A({'id':data.objs[i].id,'class':'navigate '+data.objs[i].type,'href':'#'},
														$.IMG({'src':firstImage}),
														$.SPAN({'class':'naviHeadline'},data.objs[i].name),
														$.SPAN({'class':'naviText'},data.objs[i].adresse)
													)
											);
							}
							//--- kein Bild vorhanden ---
							else
							{
								var element = 	$.LI({'id':data.objs[i].id},
													$.A({'id':data.objs[i].id,'class':'navigate '+data.objs[i].type,'href':'#'},
														$.SPAN({'class':'naviHeadline'},data.objs[i].name),
														$.SPAN({'class':'naviText'},data.objs[i].adresse)
													)
											);
							}
							$(ul).append(element);

						}
						// --- Verkehr od. Schlagwort ---
						else
						{

							if(data.objs[i].type == 'verkehrsmodul_flaeche' || data.objs[i].type == 'verkehrsmodul_linie')
							{
								var div = $.DIV({'class':'verkehrfarbe'});
								$(div).css('background-color','#'+data.objs[i].color);
								var element = 	$.LI({'id':data.objs[i].id},
													div,
													$.A({'id':data.objs[i].id,'class':'navigate '+data.objs[i].type,'href':'#'},data.objs[i].name)
												);
							}
							else
							{
								var element = 	$.LI({'id':data.objs[i].id},
													$.A({'id':data.objs[i].id,'class':'navigate '+data.objs[i].type,'href':'#'},data.objs[i].name)
												);
							}
							$(ul).append(element);
						}
					}
					here.parent().append(ul);
					here.parent().addClass('active');

					for(i=0;i<=data.objs.length-1;i++)
					{
						if(data.objs[i].allchilds.geometries != null && data.objs[i].allchilds.geometries.length > 0)
						{
							var geom = data.objs[i].allchilds.geometries;
							for(var l=0;l<=geom.length-1;l++)
							{
								drawFeatures(geom[l],vectorLayer);
							}
						}
					}

				}
				$('#ajax-loading').remove();

				if(navigationList.length > 0)
					navigateList();

			}
		,'json');
		return false;
	}



}


$(document).ready(function(){


    //--- Fürstenfeldbruck Solarkataster ---

    $('#43018').live('click',
        function()
        {

	        var formatter = new OpenLayers.Format.GeoJSON();
            
            //if(map.getZoom() < 5)
            //    map.zoomTo(5); 

            ffb_mode="ffb_photovoltaik"; 
/*
	        $.post("/projekt/getAllObjectsByExtent",
		        {'id':$('#portalid').val(),'layerid':$('#objectid').val(),'extent':formatter.write(map.getExtent().toGeometry())},
		        function(data)
		        {
                    removeFeatureByObjtype(map);
			        var gisdata = data.objects;
                    var vectorLayer = initVectorLayer(map);
			        for(var i=0;i<=gisdata.length-1;i++)
			        {
				        drawFeatures(gisdata[i].gisdata,vectorLayer,false,map,false);
			        }
                    //map.raiseLayer(vectorLayer,1);

		        },
	        'json'); 
*/
        }
    );

   $('#43014').live('click',
        function()
        {

        	var formatter = new OpenLayers.Format.GeoJSON();

            //if(map.getZoom() < 5)
            //    map.zoomTo(5); 

            ffb_mode="ffb_solarthermie";  
/*
	        $.post("/projekt/getAllObjectsByExtent",
		        {'id':$('#portalid').val(),'layerid':$('#objectid').val(),'extent':formatter.write(map.getExtent().toGeometry())},
		        function(data)
		        {
                    removeFeatureByObjtype(map);
			        var gisdata = data.objects;
                    var vectorLayer = initVectorLayer(map);
			        for(var i=0;i<=gisdata.length-1;i++)
			        {
				        drawFeatures(gisdata[i].gisdata,vectorLayer,false,map,false);
			        }
                    //map.raiseLayer(vectorLayer,1);
		        },
	        'json');                  
   */ 
            

        }
    );



	$.i18n($('html').attr('lang'));

	$(window).resize(
		function()
		{
			//alert('resized');
			$('#map').height($(window).height()-102);
			$('#map').width($(window).width()-268);

            $( "#overviewMap" ).dialog('option','position',[$(window).width()-overviewmap_width,$(window).height()-overviewmap_height]);


		}

	);

	$('.objekteListe').each(
		function()
		{
			var here = $(this);
			$.post(getAjaxUrl() + "/wirtschaftmodul/getSchlagwortBaum",{'id':here.attr('id'),'projection':$('#projection').val()},
				function(data)
				{
					for(i=0;i<=data.length-1;i++)
					{
						var element = 	$.LI({'id':data[i].id},
											$.A({'id':data[i].id,'class':'navigate','href':'#'},data[i].name,' [',data[i].childs,']')
										);
						here.append(element);
					}
				}
			,'json');
		}
	);

	$('.navigate').live('click',
		function()
		{
			var here = $(this);

            var vectorLayer = initVectorLayer(map);
            vectorLayer.removeFeatures(vectorLayer.features);   
            removeAllPopups();

            if(here.hasClass('verkehrsmodul_ordner') || here.hasClass('verkehrsmodul') || here.hasClass('verkehrsmodul_linie') || here.hasClass('verkehrsmodul_flaeche') || here.hasClass('verkehrsmodul_punkt')) {
                $('#viewoptions #flaewi').remove();
                $('#viewoptions').show();
                //$("#map_OpenLayers_ViewPort").remove();
                map_mode="standard";
                //map = initMap();
            }

			if(here.parent().hasClass('active'))
			{
				var vectorLayer = initVectorLayer(map);
				here.parent().find('ul').remove();
				here.parent().removeClass('active');


                removeFeatureByObjtype(map);

				if(here.hasClass('tclayer'))
				{

                    //--- aktivierten Layer löschen ---
                    var idx = activated_layers.indexOf(here.attr('id'));
                    if(idx!=-1)
                        activated_layers.splice(idx, 1);

                    //alert(activated_layers);
                    getAllObjectsByExtent();

                    
                    try
                    {
                        var tclayer = map.getLayersByName(here.attr('href'))[0];
                        map.removeLayer(tclayer);
                        return false;
                    }
                    catch(exc)
                    {

                    }
                }

				return false;
			}
			else
			{

			    here.append($($.IMG({'src':'/js/images/ajax-loader.gif','id':'ajax-loading'})).css('margin-left',10));
				var vectorLayer = initVectorLayer(map);
	            //map.addLayers([vectorLayer]);

				if(here.hasClass('verkehrsmodul_ordner') || here.hasClass('verkehrsmodul') || here.hasClass('verkehrsmodul_linie') || here.hasClass('verkehrsmodul_flaeche') || here.hasClass('verkehrsmodul_punkt')) {
					var url = getAjaxUrl() + "/verkehrsmodul/getSchlagwortBaum";
                    removeFeatureByObjtype(map);

                    //map.zoomToMaxExtent();
                }
				else if(here.hasClass('orte'))
				{
					var url = getAjaxUrl() + "/projekt/getOrte";
					map.zoomToMaxExtent();
                    removeFeatureByObjtype(map);
				}
				else if(here.hasClass('cto'))
				{
					var url = getAjaxUrl() + "/projekt/getTouristicObjectives";
					map.zoomToMaxExtent();
                    removeFeatureByObjtype(map);
				}
				else if(here.hasClass('nature'))
				{
					var url = getAjaxUrl() + "/projekt/getNationalParks";
					map.zoomToMaxExtent();
                    removeFeatureByObjtype(map);
				}
				else if(here.hasClass('tclayer'))
				{


                    activated_layers.push(here.attr('id'));

                    //alert(activated_layers);
                    if(map.getZoom() >= 18)
                    {
                        getAllObjectsByExtent();
                    }
                    //getAllObjectsByExtent();

			        map_mode = 'tclayer';

                    try
                    {
                        var tclayer = map.getLayersByName('Tilecache Layer')[0];
                        map.removeLayer(tclayer);
                    }
                    catch(exception)
                    {
                    }

                    $('#viewoptions #flaewi').remove();

                    var tilecache_url = "http://cache2.map2web.eu/cache";

                    if($('#projection').val() == 'EPSG:900913')
                    {
                        tilecache_url = "http://cache3.map2web.eu/cache";
                    }

                    var layername = 'busline';
                    if(here.attr('href') != '#')
                        layername = here.attr('href');
                
                    if($('#projection').val() == 'EPSG:900913')
                    {
                        tilecache_layer = new OpenLayers.Layer.TileCache(layername,
                            [tilecache_url],
                            layername,
                            {
					            "isBaseLayer": false,
                                "visible":true
                            }

                        );
                    }
                    else if($('#projection').val() == 'EPSG:32633' || $('#projection').val() == 'EPSG:32632')
                    {
                        tilecache_layer = new OpenLayers.Layer.TileCache(layername,
                            [tilecache_url],
                            layername,
                            {
                            	"serverResolutions": serverResolutions_at,
					            "isBaseLayer": false,
                                "visible":true
                            }
                        );
                    }





			$.post(getAjaxUrl() + "/tclayer/getSchlagwortBaum",{'id':$(here).attr('id')},
				function(data)
				{

           			var ul = $(here).parent();
			        ul.find('ul').remove();
		
                    $(here).parent().addClass('active');



                    if(data!=null)
                    {
                            //--- auf Startextent springen ---
                            if(data.startextent != null)
                            {
                                var extent = data.startextent.split(',');

                                var restrictedbounds = new OpenLayers.Bounds(
                                    parseFloat(extent[0]),parseFloat(extent[1]),
                                    parseFloat(extent[2]),parseFloat(extent[3])
                                );

                                map.zoomToExtent(restrictedbounds);

                            }


        					var newul = $.UL({'class':'Level2nd'});
                        
                            if(data.objs.length > 0)
                            {
							    $(newul).css('display','block');
							    ul.append(newul);
                            }
        
							for(i=0;i<=data.objs.length-1;i++)
							{
                                if(data.objs[i].type == 'direktlink')
                                {
								    var element = 	$.LI({'id':data.objs[i].id,'class':'Level2nd'},
												    $.A({'href':data.objs[i].href},data.objs[i].name)
											    );
                                }
                                else if(data.objs[i].icon != undefined && data.objs[i].icon != '')
                                {
								    var element = 	$.LI({},
                                                                $.TABLE({},
															        $.TBODY({},
																        $.TR({},
																	        $.TD({'class':'thumbnail'},
																		        $.IMG({'src':data.objs[i].icon})
																	        ),
																	        $.TD({'class':'thumbnailText'},
																		        $.A({'id':data.objs[i].id,'href':'#'},
																			        data.objs[i].name
																		        )															)
																	        )
																        )
                                                                    )
															    );
                                }
                                else
                                {
								    var element = 	$.LI({'id':data.objs[i].id,'class':'Level2nd'},
												    $.A({'id':data.objs[i].id,'class':'navigate '+data.objs[i].type,'href':data.objs[i].layer},data.objs[i].name)
											    );
                                }
                                $(element).find('a').css('color','#' + data.objs[i].color)
								$(newul).append(element);

							}
            /*
                            if(data.geom.geometries.length > 0)
                            {
							    var vectorLayer = initVectorLayer(map);

                                for(var i=0;i<=data.geom.geometries.length-1;i++)
                                {
                                    drawFeatures(data.geom.geometries[i],vectorLayer,false);
                                }
                            }
*/
							var formatter = new OpenLayers.Format.GeoJSON();

							if(navigationList.length>0)
    								navigateList();


                    }

                
					}
			,'json');














/*

                    
                	here.append($($.IMG({'src':'/js/images/ajax-loader.gif','id':'ajax-loading'})).css('margin-left',10));
			        $.post("/tclayer/getGeometries",{'id':$(here).attr('id')},
				        function(data)
				        {
                            var geom = data.geometries.geometries;

                            for(var i=0;i<=geom.length-1;i++)
                            {
                                drawFeatures(geom[i],vectorLayer,false);
                            }
                            //alert('loaded');                        
            				$('#ajax-loading').remove();
					    }
			        ,'json');

*/
                    $('#ajax-loading').remove();
                    map.addLayers([tilecache_layer]);
                    map.raiseLayer(tilecache_layer,-1);

				}
                else if(here.hasClass('AGLayer'))
                {
                  var url = getAjaxUrl() + "/aglayer/getSchlagwortBaum";
                }
                else if(here.hasClass('aglayer'))
                {
                  var url = getAjaxUrl() + "/aglayer/getSchlagwortBaum";
                }
				else
					var url = getAjaxUrl() + "/wirtschaftmodul/getSchlagwortBaum";


                /* erst ab 3er Ebene anzeigen */
                var gis_enabled = true;

                if($(this).parent().attr('class') == 'Level2nd')
                {
                    gis_enabled = false;
                    $('#ajax-loading').remove();
                }

				$.post(url,{'id':here.attr('id'),'portalid':$('#projektid').val(),'gisdata':gis_enabled,'projection':$('#projection').val()},
					function(data)
					{
						//--- anderen Objekt auf Ebene schliessen --
						//$("li.expanded ul").remove();
						//$("li.expanded").removeClass('expanded');

						//--- Eigene Gemoetrie falls vorhanden anzeigen ---
						if(data.selfgeometries != null)
						{
							if(data.selfgeometries.geometries.length == 1 )
							{
								drawFeatures(data.selfgeometries.geometries[0],vectorLayer,true);
							}
							else
							{
								for(var i=0;i<=data.selfgeometries.geometries.length-1;i++)
								{
									drawFeatures(data.selfgeometries.geometries[i],vectorLayer,false);
								}
							}
						}

						//--- Geometrie der untergeordneten Objekte anzeigen ---
						if(data.objs.length > 0)
						{
							var ul = $.UL();
							for(i=0;i<=data.objs.length-1;i++)
							{
								var className = "Level3rd";
								if(here.parent().hasClass('Level3rd'))
									className='Level4th';

								if(data.objs[i].type == 'wirtschaft')
								{
									var fistimage;
									var images = [];
									//--- Bild vorhanden ---
									if(data.objs[i].images.length > 0)
									{

										firstImage = data.objs[i].images[0];
										var element = 	$.LI({},
                                                            $.TABLE({},
															    $.TBODY({},
																    $.TR({},
																	    $.TD({'class':'thumbnail'},
																		    $.IMG({'src':firstImage})
																	    ),
																	    $.TD({'class':'thumbnailText'},
																		    $.A({'id':data.objs[i].id,'class':'navigate '+data.objs[i].type,'href':'#'},
																			    data.objs[i].name,
																			    $.SPAN({},data.objs[i].adresse)
																		    )															)
																	    )
																    )
                                                                )
															);
									}
									//--- kein Bild vorhanden ---
									else
									{
										var element = 	$.LI({'id':data.objs[i].id,'class':className},
															$.A({'id':data.objs[i].id,'class':'navigate '+data.objs[i].type,'href':'#'},
																data.objs[i].name,
																$.SPAN(data.objs[i].adresse)
															)
													);
									}
									$(ul).addClass(className);
									$(ul).css('display','block');
									$(ul).append(element);

								}



								else if(data.objs[i].type == 'AGObjekt')
								{
									var fistimage;
									var images = [];
									//--- Bild vorhanden ---

									var element = 	$.LI({'id':data.objs[i].id,'class':className},
														$.A({'id':data.objs[i].id,'class':'showAGObjekt','href':'#'},
															data.objs[i].name
														)
												);
					
									$(ul).addClass(className);
									$(ul).css('display','block');
									$(ul).append(element);

								}



								// --- Verkehr, Schlagwortnavigation ---
								else
								{   try{
										var div = $.A({'id':data.objs[i].id,'class':'navigate '+data.objs[i].type,'href':'#'},data.objs[i].name);
										$(div).css('color','#'+data.objs[i].color);
									}catch(exception){

									}
									if(data.objs[i].type == 'verkehrsmodul_flaeche' || data.objs[i].type == 'verkehrsmodul_linie')
									{
										var element = 	$.LI({'id':data.objs[i].id,'class':className},
															div
															//$.A({'id':data.objs[i].id,'class':'navigate '+data.objs[i].type,'href':'#'},data.objs[i].name)
														);
									}
									else
									{
										var element = 	$.LI({'id':data.objs[i].id,'class':className},
															$.A({'id':data.objs[i].id,'class':'navigate '+data.objs[i].type,'href':'#'},data.objs[i].name)
														);
									}
									$(ul).append(element);
								}
							}
							here.parent().append(ul);
							here.parent().addClass('active');

							for(i=0;i<=data.objs.length-1;i++)
							{
								if(data.objs[i].allchilds != null && data.objs[i].allchilds.geometries != null && data.objs[i].allchilds.geometries.length > 0)
								{
									var geom = data.objs[i].allchilds.geometries;
									for(var l=0;l<=geom.length-1;l++)
									{
										drawFeatures(geom[l],vectorLayer);
									}
								}
							}

						}
						$('#ajax-loading').remove();
					}
				,'json');



				return false;
			}
		}
	);


	$(".showGebaeude").live('click',
		function(){
			kartenLayer = map.getLayersByName('Karten Layer')[0];
			kartenLayer.setOpacity(1);
			$.post(getAjaxUrl() + "/projekt/getGebaeudeGisData",
					{'id':$(this).attr('id'),'projection':$('#projection').val()},
				function(data)
				{
					style_blue = {
                	    'pointRadius': 10,
						'externalGraphic': '/js/images/marker2.gif',
						'graphicWidth':10,
						'graphicHeight':10
           			}

			        var vectorLayer = initVectorLayer(map);
		            //map.addLayers([vectorLayer]);

				var gisdata = data;

				drawFeatures(gisdata,vectorLayer,true);
				}


			,'json');

			return false;
		}
	);



	$(".showObjekt").live('click',
		function(){

            if(map_mode == 'tclayer'){

            }
            else if(map_mode!='standard'){
                $("#map_OpenLayers_ViewPort").remove();
                map_mode="standard";
                map = initMap();
            }


			kartenLayer = map.getLayersByName('Karten Layer')[0];
			kartenLayer.setOpacity(1);
			$.post(getAjaxUrl() + "/projekt/getGebaeudeGisData",
					{'id':$(this).attr('id'),'projection':$('#projection').val()},
				function(data)
				{
					style_blue = {
                	    'pointRadius': 10,
						'externalGraphic': '/js/images/marker2.gif',
						'graphicWidth':10,
						'graphicHeight':10
           			}

			        var vectorLayer = initVectorLayer(map);

                    vectorLayer.removeFeatures(vectorLayer.features);

		            //map.addLayers([vectorLayer]);

				var gisdata = data;

				drawFeatures(gisdata,vectorLayer,true);
				}


			,'json');

			return false;
		}
	);


	$(".showVerkehr").live('click',
		function(){
			var here = $(this);
			var type = $(this.firstChild).attr('class');
			if(1==1)
			{

				kartenLayer = map.getLayersByName('Karten Layer')[0];
				kartenLayer.setOpacity(0.6);

				var id = $(this).attr('id');
				$.post(getAjaxUrl() + "/verkehrsmodul/getContent",
					{'id':id},
				function(data)
				{
					$('#verkehr').empty();
					if(data.parentid != $('#objektid').val())
					{
						var html = $.LI({'id':data.parentid},
										$.A({'class':'showVerkehr','id':data.parentid,'href':'#'},
											'..'
										)
									);
					}
					$('#verkehr').append(html);
					var data = data.data;
					for(i=0;i<=data.length-1;i++){
						var html = $.LI({'id':data[i].id},
										$.A({'class':'showVerkehr','id':data[i].id,'href':'#'},
											$.SPAN({'class':data[i].type},data[i].name
											)
										)
									);
						$('#verkehr').append(html);
					}
				},'json');

				$.post(getAjaxUrl() + "/verkehrsmodul/getGisData",
					{'id':id},
					function(data)
					{

						var vectorLayer = initVectorLayer(map);

	            		//map.addLayers([vectorLayer]);
						var formatter = new OpenLayers.Format.GeoJSON();

						for(i=0;i<=data.geometries.length-1;i++)
						{

							if(data.geometries[i].type == 'MultiLineString')
							{
								var style_dyn = {
									'strokeColor': '#' + data.geometries[i].color,
									'strokeWidth': 2,
									'pointRadius': 2,
									'pointerEvents': "visiblePainted",
									'strokeOpacity': 0.8
								};

								var vector = formatter.read(data.geometries[i]);
								vector[0].style =  style_dyn;
								vector[0].objektid = data.geometries[i].objektid;
								vectorLayer.addFeatures(vector);
							}
							else if(data.geometries[i].type == 'Point')
							{
								var feature = formatter.read(data.geometries[i]);

					            size = new OpenLayers.Size(12,12);
            					icon = new OpenLayers.Icon(data.geometries[i].icon);



								feature[0].style={
	                        	    'pointRadius': 14,
									'externalGraphic': data.geometries[i].icon,
									'graphicWidth':14,
									'graphicHeight':14
	                   			}
								feature[0].objektid = data.geometries[i].objektid;
	                   			vectorLayer.addFeatures(feature);
            					//vectorLayer.addMarker(new OpenLayers.Marker(feature, icon));


							}
							else if(data.geometries[i].type == 'MultiPolygon')
							{
								var feature = formatter.read(data.geometries[i]);

								feature[0].style = {
									'strokeColor': '#' + data.geometries[i].color,
									'fillColor': '#' + data.geometries[i].color,
									'strokeWidth': 1,
									'pointerEvents': "visiblePainted",
									'strokeOpacity': 1,
									'fillOpacity': 0.5
								};
								feature[0].objektid = data.geometries[i].objektid;
	                   			vectorLayer.addFeatures(feature);
							}
						}

					},
				'json');

			}

			return false;
		}
	);

	$(".showGst").live('click',
		function(){
			kartenLayer = map.getLayersByName('Karten Layer')[0];
			kartenLayer.setOpacity(1);
			var here = $(this);

		$.post(getAjaxUrl() + "/projekt/getGstGisData",{'id':$(this).attr('id'),'projection':$('#projection').val()},
				function(data)
				{
					var vectorLayer = initVectorLayer(map);
					var gisdata = data.geometries;
					for(var i=0;i<=gisdata.length-1;i++)
					{
						drawFeatures(gisdata[i],vectorLayer,false);
					}
					var x = gisdata[1].coordinates[0];
					var y = gisdata[1].coordinates[1];

					if(x != 0 || y != 0)
					{
			        	var newbounds = new OpenLayers.Bounds(
			                    x-100, y-100,
			                    x+100, y+100
			                );
						map.zoomToExtent(newbounds);
					}
				}


			,'json');



			return false;
		}
	);



	$(".showStreetflaewi").live('click',
		function(){

			kartenLayer = map.getLayersByName('Karten Layer')[0];
			kartenLayer.setOpacity(1);
			var here = $(this);

            removeAllPopups();


			$.post(getAjaxUrl() + "/projekt/getStreetGisData",
					{'id':$(this).attr('id'),'projection':$('#projection').val(),'projektid':$('#objektid').val()},
				function(data)
				{
                    var vectorLayer = initVectorLayer(map);
                    vectorLayer.removeFeatures(vectorLayer.features);
					var formatter = new OpenLayers.Format.GeoJSON();
					for(i=0;i<=data.geometries.length-1;i++)
					{
						if(data.geometries[i].type == 'LineString' || data.geometries[i].type == 'MultiLineString')
						{
							var style_dyn = {
								'strokeColor': '#66FFFF' ,
	        					'strokeWidth': 12,
	        					'pointRadius': 6,
								'pointerEvents': "visiblePainted",
								'strokeOpacity': 0.6
							};
							var vector = formatter.read(data.geometries[i]);
							vector[0].style =  style_dyn;
							vector[0].objektid = data.geometries[i].objektid;
							vectorLayer.addFeatures(vector);
						}
                        else
                        {
                            drawFeatures(data.geometries[i],vectorLayer,true);
                        }

					}

					var newbounds = new OpenLayers.Bounds(data.bounds[0],data.bounds[1],data.bounds[2],data.bounds[3]);
					map.zoomToExtent(newbounds);
					if(map.getZoomForExtent(newbounds,true)>5)
					{
						map.zoomTo(5);
					}
                                        else
					{
						map.zoomTo(map.getZoomForExtent(newbounds,true)-1);
					}

				}
			,'json');

			$.post(getAjaxUrl() + "/projekt/getHousenumbers",{'id':$(this).attr('id'),'projection':$('#projection').val()},
				function(data)
				{
					$('#hnr-selector').remove();

					if(data.length > 1)
					{
						var select = $.SELECT({'id':'hnr-selector'});
						for(i=0;i<=data.length-1;i++)
						{
							var element = $.OPTION({'value':data[i].id},data[i].name);
							$(select).append(element);
						}
						here.parent().append(select);
					}
				}
			,'json');

			return false;
		}
	);



	$(".showStreet").live('click',
		function(){
            if(map_mode == 'tclayer'){

            }
            else if(map_mode!='standard'){
                $("#map_OpenLayers_ViewPort").remove();
                map_mode="standard";
                map = initMap();
            }


            removeAllPopups();



			kartenLayer = map.getLayersByName('Karten Layer')[0];
			kartenLayer.setOpacity(1);
			var here = $(this);

			$.post(getAjaxUrl() + "/projekt/getStreetGisData",
					{'id':$(this).attr('id'),'projection':$('#projection').val(),'type':$('#projecttype').val(),'projektid':$('#objektid').val()},
				function(data)
				{
				
                    var vectorLayer = initVectorLayer(map);
                    vectorLayer.removeFeatures(vectorLayer.features);                        

					var formatter = new OpenLayers.Format.GeoJSON();

					for(i=0;i<=data.geometries.length-1;i++)
					{



						if(data.geometries[i].type == 'LineString' || data.geometries[i].type == 'MultiLineString')
						{
							var style_dyn = {
								'strokeColor': '#66FFFF' ,
	        					'strokeWidth': 12,
	        					'pointRadius': 6,
								'pointerEvents': "visiblePainted",
								'strokeOpacity': 0.6
							};

							var vector = formatter.read(data.geometries[i]);
							vector[0].style =  style_dyn;
							vector[0].objektid = data.geometries[i].objektid;
							vectorLayer.addFeatures(vector);

			                $.post(getAjaxUrl() + "/projekt/getHousenumbers",{'id':here.attr('id'),'projection':$('#projection').val(),'projektid':$('#objektid').val()},
				                function(data)
				                {
					                $('#hnr-selector').remove();

					                if(data.length > 1)
					                {
						                var select = $.SELECT({'id':'hnr-selector'});
						                for(i=0;i<=data.length-1;i++)
						                {
							                var element = $.OPTION({'value':data[i].id},data[i].name);
							                $(select).append(element);
						                }
						                here.parent().append(select);
					                }
				                }
			                ,'json');


						}
                        else
                        {
                            drawFeatures(data.geometries[i],vectorLayer,true);
                        }

					}

					var newbounds = new OpenLayers.Bounds(data.bounds[0],data.bounds[1],data.bounds[2],data.bounds[3]);
					map.zoomToExtent(newbounds);
     

				}
			,'json');



			return false;
		}
	);


	if ($.browser.msie)
	{
		$("#hnr-selector").live('click',
			function()
			{
				printHouseNumbers(map,this);
			}
		);
	}
	else
	{
		$('#hnr-selector').live('change',
			function()
			{
				printHouseNumbers(map,this);
			}
		);
	}

	$(".showWirtschaft").live('click',
		function(){
            if(map_mode == 'tclayer'){

            }
            else if(map_mode!='standard'){
                $("#map_OpenLayers_ViewPort").remove();
                map_mode="standard";
                map = initMap();
            }
			$.post(getAjaxUrl() + "/projekt/getWirtschaftGisData",
					{'id':$(this).attr('id'),'projection':$('#projection').val()},
				function(data)
				{
					var style_blue = {
                	    			'pointRadius': 10,
						'externalGraphic': '/js/images/marker2.gif',
						'graphicWidth':10,
						'graphicHeight':10
	    				};

					initVectorLayer(map);

					var gisdata = data;

				var vectorLayer = initVectorLayer(map);

                vectorLayer.removeFeatures(vectorLayer.features);
		            //map.addLayers([vectorLayer]);

			        function onPopupClose(evt) {
			            selectControl.unselect(selectedFeature);
			        }

				drawFeatures(gisdata,vectorLayer,true);
				}

			,'json');

			return false;
		}
	);


	$(".showKultur").live('click',
		function(){


               if(map_mode=='standard')
                    {
                        $('#viewoptions').hide();
			            $("#map_OpenLayers_ViewPort").remove();
			            var here = $(this);
                        var id = $('a.kulturmodul').attr('id');
                        //alert(id);
			            $.post(getAjaxUrl() + "/kulturmodul/getExtent",{'id':id},
				            function(data)
				            {
					            map_mode = 'kultur';
					            map = initKulturMap(data.max_extent,data.min_zoom,data.max_zoom);
				            }
			            ,'json');

                    }


			$.post(getAjaxUrl() + "/projekt/showKultur",
					{'id':$(this).attr('id'),'projection':$('#projection').val()},
				function(data)
				{


     

					var style_blue = {
                	    'pointRadius': 10,
						'externalGraphic': '/js/images/marker2.gif',
						'graphicWidth':10,
						'graphicHeight':10
	    				};

					initVectorLayer(map);

					var gisdata = data;

					var vectorLayer = initVectorLayer(map);



                    var features = new Array();

                    for(var l=0;l<=vectorLayer.features.length-1;l++){
                        features.push(vectorLayer.features[l]);
                    }
                    vectorLayer.removeFeatures(features);





                    //removeFeatureByObjtype(map);

		            //map.addLayers([vectorLayer]);

			        function onPopupClose(evt) {
			            selectControl.unselect(selectedFeature);
			        }

				drawFeatures(gisdata,vectorLayer,true);
				}

			,'json');

			return false;
		}
	);

	$("#suchbutton").click(
		function()
		{
			$("#leftbox").show();
			$("#suche_auswahl").show();
			$("#ergebnisliste").show();
			$("#schlagwortbaum").hide();
			$("#reiter").find('li').removeClass('active');
			$($("#reiter").find('li')[0]).addClass('active');
			$("#hauptnavi").hide();
			$("#images").fadeOut();

			var suchtype = $(".suche_auswahl:checked").val();

			//--- Straßensuche ---
			if(suchtype == "1")
			{
				var pagesize = calculateItems();
				var querystring = $('#suchfeld').val();
				var id = $('#objektid').val();
				$('#suche_auswahl_erweitert').empty();
				$('#suche_auswahl_erweitert').vdbpager({'id':id,'itemclass':'showStreet','querystring':querystring,'pagesize':14,'start':0,projection:'EPSG:32633','baseurl':getAjaxUrl() + '/projekt/getStreets'});
			}
			//--- Objektsuche ---
			else if(suchtype == "2")
			{
				var pagesize = calculateItems();
				var querystring = $('#suchfeld').val();
				var id = $('#objektid').val();
				$('#suche_auswahl_erweitert').empty();
				$('#suche_auswahl_erweitert').vdbpager({'id':id,'itemclass':'showObjekt','querystring':querystring,'pagesize':14,'start':0,projection:'EPSG:32633','baseurl':getAjaxUrl() + '/projekt/getObjekte'});
			}
			//--- Orte / Rumania County ---
			else if(suchtype == "-1")
			{
				var pagesize = calculateItems();
				var querystring = $('#suchfeld').val();
				var id = $('#objektid').val();
				$('#suche_auswahl_erweitert').empty();
				$('#suche_auswahl_erweitert').vdbpager({'id':id,'itemclass':'showOrte','querystring':querystring,'pagesize':14,'start':0,projection:'EPSG:32634','baseurl':getAjaxUrl() + '/projekt/getOrteList'});
			}
			//--- Tourismus / Romania County ---
			else if(suchtype == "-2")
			{
				var pagesize = calculateItems();
				var querystring = $('#suchfeld').val();
				var id = $('#objektid').val();
				$('#suche_auswahl_erweitert').empty();
				$('#suche_auswahl_erweitert').vdbpager({'id':id,'itemclass':'showCTO','querystring':querystring,'pagesize':14,'start':0,projection:'EPSG:32634','baseurl':getAjaxUrl() + '/projekt/getTouristicObjectivesList'});
			}
			//--- Objektsuche ---
			else if(suchtype == "-3")
			{
				var pagesize = calculateItems();
				var querystring = $('#suchfeld').val();
				var id = $('#objektid').val();
				$('#suche_auswahl_erweitert').empty();
				$('#suche_auswahl_erweitert').vdbpager({'id':id,'itemclass':'showNationalParc','querystring':querystring,'pagesize':14,'start':0,projection:'EPSG:32634','baseurl':getAjaxUrl() + '/projekt/getNationalParcsList'});
			}
			else
			{
				var pagesize = calculateItems();
				var querystring = $('#suchfeld').val();
				var id = $('#objektid').val();
				$('#suche_auswahl_erweitert').empty();
				$('#suche_auswahl_erweitert').vdbpager({'id':suchtype,'itemclass':'showWirtschaft','querystring':querystring,'pagesize':14,'start':0,projection:'EPSG:32633','baseurl':getAjaxUrl() + '/projekt/getWirtschaft'});
			}
			$('#suche_auswahl_erweitert').show();
			return false;

		}
	);

	$("#suchfeld").bind("keydown", function(event) {
           
        var keycode = (event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode));
        if (keycode == 13) 
        {
            $("#searchSubmit").trigger('submit');
            return false;
        } 
        else  
        {
		    return true;
        }
    });


	$('#pfeil_links').live('click',
		function()
		{
			var alleBilder = eval($('#allimages').val());
			var bildnr = parseInt($('#bildnr').val()) - 1;
			if(bildnr == -1)
				bildnr = alleBilder.length - 1;
			$('#bildnr').val(bildnr);
			var bild = alleBilder[bildnr];
			$('#stadtfoto').attr('src',bild);
		}
	);

	$('#pfeil_rechts').live('click',
		function()
		{
			var alleBilder = eval($('#allimages').val());
			var bildnr = parseInt($('#bildnr').val()) + 1;
			if(bildnr >= alleBilder.length)
				bildnr = 0;
			$('#bildnr').val(bildnr);
			var bild = alleBilder[bildnr];
			$('#stadtfoto').attr('src',bild);
		}
	);
/*
	$('.printWirtschaft').live('click',
		function()
		{
			alert('print');
			var extent = map.getExtent().toBBOX();
			var lon = map.getExtent().getCenterLonLat().lon;
			var lat = map.getExtent().getCenterLonLat().lat;
			var zoom = map.getZoom();
			var ooid = $(this).attr('id');
			neuesFenster = window.open(getAjaxUrl() + "/projekt/viewprint/" + $('#objektid').val() + "22?extent=" + extent + "&lonlat=" + lon + "," + lat + "&zoom=" + zoom + "&ooid=" + ooid, "Druckfenster");
			neuesFenster.focus();
			return false;
		}
	);

	$('.printAGObjekt').live('click',
		function()
		{
			var extent = map.getExtent().toBBOX();
			var lon = map.getExtent().getCenterLonLat().lon;
			var lat = map.getExtent().getCenterLonLat().lat;
			var zoom = map.getZoom();
			var ooid = $(this).attr('id');
			neuesFenster = window.open(getAjaxUrl() + "/projekt/viewprint/" + $('#objektid').val() + "22?extent=" + extent + "&lonlat=" + lon + "," + lat + "&zoom=" + zoom + "&ooid=" + ooid + "&mode=AGObjekt", "Druckfenster");
			neuesFenster.focus();
			return false;
		}
	);

*/
	$('#language_selection').live('click',
		function()
		{
			$('#language #dropdown').show();
			return false;
		}
	);

	$(".showCTO").live('click',
		function(){
			$.post(getAjaxUrl() + "/projekt/getTouristGisData",
					{'id':$(this).attr('id')},
				function(data)
				{
					var style_blue = {
                	    			'pointRadius': 10,
						'externalGraphic': '/js/images/marker2.gif',
						'graphicWidth':10,
						'graphicHeight':10
	    				};

					initVectorLayer(map);

					var gisdata = data;

				var vectorLayer = initVectorLayer(map);
		            //map.addLayers([vectorLayer]);

			        function onPopupClose(evt) {
			            selectControl.unselect(selectedFeature);
			        }

				drawFeatures(gisdata,vectorLayer,false);
				}

			,'json');

			return false;
		}
	);

	$(".showNationalParc").live('click',
		function(){
			$.post(getAjaxUrl() + "/projekt/getNationalParcGisData",
					{'id':$(this).attr('id')},
				function(data)
				{
					var style_blue = {
                	    'pointRadius': 10,
						'externalGraphic': '/js/images/marker2.gif',
						'graphicWidth':10,
						'graphicHeight':10
	    				};

					initVectorLayer(map);

					var vectorLayer = initVectorLayer(map);
		            //map.addLayers([vectorLayer]);

			        function onPopupClose(evt) {
			            selectControl.unselect(selectedFeature);
			        }

					for(var i=0;i<=data.geometries.length-1;i++)
						drawFeatures(data.geometries[i],vectorLayer,false);
				}

			,'json');

			return false;
		}
	);

	$(".showOrte").live('click',
		function(){
			$.post(getAjaxUrl() + "/projekt/getOrteGisData",
					{'id':$(this).attr('id')},
				function(data)
				{
					var style_blue = {
                	    			'pointRadius': 10,
						'externalGraphic': '/js/images/marker2.gif',
						'graphicWidth':10,
						'graphicHeight':10
	    				};

					initVectorLayer(map);

					var gisdata = data;

				var vectorLayer = initVectorLayer(map);
		            //map.addLayers([vectorLayer]);

			        function onPopupClose(evt) {
			            selectControl.unselect(selectedFeature);
			        }

				drawFeatures(gisdata,vectorLayer,false);
				}

			,'json');

			return false;
		}
	);


	$('#suchergebnisse').height($(document).height() - 233 -30);

	$("#suchbutton_flaewi").live('click',
		function(){

			var suchtype = $(".suche_auswahl_flaewi:checked").val();
			if (suchtype == '1')
			{
				var pagesize = calculateItems();
				var querystring = $('#suchfeld-flaewi').val();
				var id = $('#objektid').val();
				$('#suche_auswahl_erweitert').empty();
				$('#suche_auswahl_erweitert').vdbpager({'id':id,'itemclass':'showStreet','searchitems':"",'querystring':querystring,'pagesize':14,'start':0,projection:'EPSG:32633','baseurl':getAjaxUrl() + '/projekt/getStreets'});
				$('#suche_auswahl_erweitert').show();
			}
			else
			{
				var pagesize = calculateItems();
				var querystring = $('#suchfeld-flaewi').val();
				var id = $('#objektid').val();
				$('#suche_auswahl_erweitert').empty();
				$('#suche_auswahl_erweitert').vdbpager({'id':id,'itemclass':'showGst','searchitems':"",'querystring':querystring,'pagesize':14,'start':0,projection:'EPSG:32633','baseurl':getAjaxUrl() + '/projekt/getGst'});
				$('#suche_auswahl_erweitert').show();
			}
			return false;
		}
	);

	$('.treffer').html($.i18n('Map2Web', 'Treffer'));

	$('#browseStreets').click(
		function()
		{

            $("#viewoptions").show();

            $("#bottomInfo").remove();

            if(map_mode=='kultur')
            {
                $('#viewoptions #flaewi').remove();
                $('#viewoptions').show();
			    $("#map_OpenLayers_ViewPort").remove();
                map_mode="standard";
                map = initMap();
            }





			var id = $('#objektid').val();
			$('#strassenliste').empty();
			if(!$(this).hasClass('active'))
			{
				$('#strassenliste').vdbpager({'id':id,'itemclass':'showStreet','searchitems':"",'querystring':'%%','pagesize':16,'start':0,projection:$('#projection').val(),'baseurl':getAjaxUrl() + '/projekt/getStreets'});
			}
		}
	);

	$('#browseBuildings').click(
		function()
		{

            $("#bottomInfo").remove();
            $("#viewoptions").show();

            if(map_mode=='kultur')
            {
                $('#viewoptions #flaewi').remove();
                $('#viewoptions').show();
			    $("#map_OpenLayers_ViewPort").remove();
                map_mode="standard";
                map = initMap();
            }

			var id = $('#objektid').val();
			$('#objektliste').empty();
			if(!$(this).hasClass('active'))
				$('#objektliste').vdbpager({'id':id,'itemclass':'showObjekt','searchitems':"",'querystring':'%%','pagesize':16,'start':0,projection:$('#projection').val(),'baseurl':getAjaxUrl() + '/projekt/getObjekte'});
		}
	);


	$('#browseOrte').click(
		function()
		{
			var id = $('#objektid').val();
			$('#objektliste').empty();
			if(!$(this).hasClass('active'))
				$('#objektliste').vdbpager({'id':id,'itemclass':'showObjekt','searchitems':"",'querystring':'%%','pagesize':16,'start':0,projection:'EPSG:32633','baseurl':getAjaxUrl() + '/projekt/browseOrte'});
		}
	);

	$('#browseKultur').click(
		function()
		{
			var id = $('#objektid').val();
    		$('#objektliste').empty();
			if(!$(this).hasClass('active'))
				$('#objektliste').vdbpager({'id':id,'itemclass':'showObjekt','searchitems':"",'querystring':'%%','pagesize':16,'start':0,projection:'EPSG:32633','baseurl':getAjaxUrl() + '/projekt/getTouristicObjectives'});
		}
	);

	$('#browseNationalparks').click(
		function()
		{
			var id = $('#objektid').val();
			$('#objektliste').empty();
			if(!$(this).hasClass('active'))
				$('#objektliste').vdbpager({'id':id,'itemclass':'showObjekt','searchitems':"",'querystring':'%%','pagesize':16,'start':0,projection:'EPSG:32633','baseurl':getAjaxUrl() + '/projekt/getNationalParks'});
		}
	);

    $('a#handler').toggle(
     	function ()
     	{
     		$('#leftcol').hide();
     		$('ul#toolbarTabs').hide();
     		$(this).html('&gt;&gt;');
			$('#map').width($(window).width());
     		$('#map').css("left", "0px");
     		$('#mapBorderLeft').css("left", "-5px");

     	},
     	function()
     	{
     		$('#leftcol').show();
     		$('ul#toolbarTabs').show();
			$(this).html('&lt;&lt;');
			$('#mapBorderLeft').css("left", "0px");
			$('#map').width($(window).width()-325);
     		$('#map').css("left", "325px");
     	}
    );

    var tabContainers = $('div#leftcol > div');
    tabContainers.hide().filter(':first').show();

    $('ul#toolbarTabs a').click(function () {
            tabContainers.hide();
            tabContainers.filter(this.hash).show();
            $('ul#toolbarTabs a').removeClass('selected');
            $('ul#toolbarTabs li').removeClass('active');
            $(this).addClass('selected');
            $(this).parent().addClass('active');
            return false;
    }).filter(':first').click();

    // Striped list in Verzeichnis
         $('ul.listLevel li:odd').addClass("alt4");
         $('ul.ListLevel li.pagination').removeClass("alt");
      	 $('li.Level4th:even').addClass("alt4");

    // Rounded Corner

    $('#tipp').corner("10px");
	$('#search').corner("15px tr");


   // Testfunktion Verzeichnis


        $('#verzeichnis li a').toggle(
        	function ()
        	{
        		var childUl = $(this).siblings('ul');
        		childUl.show("slow");
        		$(this).parent().addClass('active');
        		$(this).addClass('active');

        		if($(this).hasClass('switchModule'))
        		{/*
                    if($(this).hasClass('kulturmodul'))
                    {
                        $('.Level1st a').css('color','#CCCCCC');
                        $('.Level1st ul').remove();
                        $('.Level1st li').removeClass('active');
                		var childUl = $(this).siblings('ul');
                		childUl.show("slow");
                		$(this).parent().addClass('active');
                		$(this).addClass('active');
                    }*/

					switchModules($(this).attr('id'),this);

        		}

        		return false;
        	},
        	function ()
        	{
        		$(this).siblings('ul').hide("slow");
        		$(this).parent().removeClass('active');
        		$(this).removeClass('active');


                removeFeatureByObjtype(map);

                $("#viewoptions").show();


		        if($(this).hasClass('tclayer') || $(this).hasClass('flaewimodul'))
		        {
                    try
                    {
                        var tclayer = map.getLayersByName('Tilecache Layer')[0];
                        map.removeLayer(tclayer);
                        map.getLayersByName('Projekt Layer')[0].setVisibility(true);
                        return false;

                    }
                    catch(exc)
                    {

                    }

                }
		        else if($(this).hasClass('kulturmodul'))
		        {
		            $("#map_OpenLayers_ViewPort").remove();
                    map = initMap();
                    //$('.Level1st a').css('color','#000000');
                    //$('.Level1st ul').remove();
                    //$('.Level1st li').removeClass('active');


                }
        	}
        );

    // Suchoptionen ein-/ausblenden

         $('a#viewSearchOptions').live('click',function () {
				$('div#suchoptionen').show();
         });

		/*
		 *
		 * Suche
		 *
		 */

		$('#suchfeld').live('click',
			function()
			{
                if(searchbox_clicked == false)
                {
				    $('#suchfeld').val('');
                    searchbox_clicked = true;
                }
			}
		);


        function submitFullTestSearch()
        {
				if($('#projecttype').val() == 'county')
				{
					$('#suchergebnisTab').addClass('active');
					$('#suchergebnisTab a').addClass('selected');
					$('#verzeichnisTab').removeClass('active');
					$('#verzeichnisTab a').removeClass('selected');
					$('#suchergebnis').show();
	    			$('#suchergebnis .pagination').remove();
					$('#verzeichnis').hide();

					var searchitems = [];

					$('.searchoptions:checked').each(
						function()
						{
						   	searchitems.push($(this).val());
						}
					);

					$('#suchergebnis').searchAllPager({'id':$('#objektid').val(),'searchitems':searchitems,'itemclass':'showStreet','querystring':$('#suchfeld').val(),'pagesize':10,'start':0,projection:$('#projection').val(),'baseurl':getAjaxUrl() + '/projekt/searchAllCountyItems'});
				}
                else if(map_mode=='flaewi')
                {   
					$('#suchergebnisTab').addClass('active');
					$('#suchergebnisTab a').addClass('selected');
					$('#verzeichnisTab').removeClass('active');
					$('#verzeichnisTab a').removeClass('selected');
					$('#suchergebnis').show();
	    			$('#suchergebnis .pagination').remove();
					$('#verzeichnis').hide();

					var searchitems = [];

					$('.searchoptions:checked').each(
						function()
						{
						   	searchitems.push($(this).val());
						}
					);

					$('#suchergebnis').searchAllPager({'id':$('#objektid').val(),'searchitems':searchitems,'itemclass':'showStreetFlaewi','querystring':$('#suchfeld').val(),'pagesize':10,'start':0,projection:$('#projection').val(),'baseurl':getAjaxUrl() + '/projekt/searchAllFlaewiItems'});

                }
				else
				{
					$('#suchergebnisTab').addClass('active');
					$('#suchergebnisTab a').addClass('selected');
					$('#verzeichnisTab').removeClass('active');
					$('#verzeichnisTab a').removeClass('selected');
					$('#suchergebnis').show();
	    			$('#suchergebnis .pagination').remove();
					$('#verzeichnis').hide();

					var searchitems = [];

					$('.searchoptions:checked').each(
						function()
						{
						   	searchitems.push($(this).val());
						}
					);

                    var querystring = $.trim($('#suchfeld').val());


                    if(querystring.search(/[0-9]+/) != -1)
                    {
			            $.post(getAjaxUrl() + "/projekt/searchAllItems",
					            {'id':$('#objektid').val(),'searchitems':searchitems,'itemclass':'showStreet','querystring':$('#suchfeld').val(),'pagesize':10,'start':0,projection:$('#projection').val()},
				            function(data)
				            {
                                //--- Hausnummer gefunden ---
                                if('hausnummer' in data)
                                {
					
					                var vl = initVectorLayer(map);

                                    vl.removeFeatures(vl.features);

					                var gisdata = eval('(' + data.hausnummer.geom + ')');;

                                    gisdata.icon = '/js/images/1.png';

                                    $('dl').remove();

	                            	var row = $($.DL({},
	                                      			$.DT({},
                                                        $.IMG({'src':'/js/images/1.png'})
	                                      			),
	                                      			$.DD({},
                                                        $.H3({},data.strasse.name + ' ' + data.hausnummer.hnr)
	                                      			)

	                                  		  	));
                                    $($('#suchergebnis')[0]).append(row);


                                    
                                    var formatter = new OpenLayers.Format.GeoJSON();

				                    var vectorLayer = initVectorLayer(map);
		                                //map.addLayers([vectorLayer]);

			                            function onPopupClose(evt) {
			                                selectControl.unselect(selectedFeature);
			                            }

				                    drawFeatures(gisdata,vectorLayer,true,false,20);


                                    $.post("/projekt/getPublicBuildingsByExtent",
                                        {'id':$('#objektid').val(),'extent':formatter.write(map.getExtent().toGeometry()),'projection':$('#projection').val()},
                                        function(data1)
                                        {
                                            if(data1.objekte.length > 0)
                                            {
                                            	var row = $($.DL({},
                                                      			$.DT({}
                                                      			),
                                                      			$.DD({},
                                                                    $.H2({},'In der Nähe:')
                                                      			)
                                                  		  	));


                                                $($('#suchergebnis')[0]).append(row);
                                            }

	                                        for(var l=0;l<=data1.objekte.length-1;l++)
	                                        {

	                                        	var row = $($.DL({},
	                                                  			$.DT({},
                                                                    $.IMG({'src':'/js/images/' + (l+2) + '.png'})
	                                                  			),
	                                                  			$.DD({},data1.objekte[l].name
	                                                  			)

	                                              		  	));
                                                var geom = data1.geometries.geometries[l];

                                                geom.icon = '/js/images/' + (l+2) + '.png';
                                                drawFeatures(geom,vectorLayer,false,false,16);


	                                            $($('#suchergebnis')[0]).append(row);
                                                if(l>8)
                                                {
                                                    break;
                                                }
	                                        }
return false;
                                        },
                                    'json'); 

                                }
                                //--- keine Hausnummer, Standardsuche verwenden
                                else
                                {
                                    $('dl').remove();
    
	                            	var row = $($.DL({'class':'not-found'},
	                                      			$.DT({},
                                                        $.SPAN({'class':"ui-icon ui-icon-alert"},'')
	                                      			),
	                                      			$.DD({},
                                                        $.SPAN({},'Hausnummer nicht gefunden')
	                                      			)
	                                  		  	));
	                                $($('#suchergebnis')[0]).append(row);

return false;

                                }
        

				            }

			            ,'json');               
                    }
                    else
                    {
    					$('#suchergebnis').searchAllPager({'id':$('#objektid').val(),'searchitems':searchitems,'itemclass':'showStreet','querystring':$('#suchfeld').val(),'pagesize':10,'start':0,projection:$('#projection').val(),'baseurl':getAjaxUrl() + '/projekt/searchAllItems'});
                    }
				}
	            return false;


        }


		$('#searchSubmit').live('click',
			function()
			{
                submitFullTestSearch();
                return false;
			}
		);

		$('.switchMap').live('click',
			function()
			{
                if($(this).hasClass('notAvailable'))
                {
                    return false;
                }

				$('.switchMap').removeClass('current');




                $('#map2web a img').attr('src','/map2web/images/map2web.png');

                $("#bottomInfo").remove();




                map.getLayersByName('Projekt Layer')[0].setVisibility(true);

				if($(this).attr('id') == 'luftbild')
				{
                    if($('#projektid').val() == 'bruck-an-der-mur')
                        $('#map2web a img').attr('src','http://admin2.map2web.eu/html/brugis.png');
					map.setBaseLayer(map.getLayersByName('Ortho Layer')[0]);
                    if(map_mode=='tclayer')
                    {
                        $('#map2web').prepend('<span id="bottomInfo" style="margin-right:20px;">Kein Rechtsanspruch aus der Karte ableitbar.</span>');
                    }
				}
				else if($(this).attr('id') == 'basemap')
				{
					map.setBaseLayer(map.getLayersByName('Karten Layer')[0]);

                    if(map_mode=='tclayer')
                    {
                        $('#map2web').prepend('<span id="bottomInfo" style="margin-right:20px;">Kein Rechtsanspruch aus der Karte ableitbar.</span>');
                    }
				}
				else if($(this).attr('id') == 'osm' )
   				{

                    map.getLayersByName('Projekt Layer')[0].setVisibility(false);
					map.setBaseLayer(map.getLayersByName('OSM')[0]);
				}
				else if($(this).attr('id') == 'google' )
   				{
                    map.getLayersByName('Projekt Layer')[0].setVisibility(false);
					map.setBaseLayer(map.getLayersByName('Google Streets')[0]);
				}
				else if($(this).attr('id') == 'googlesat' )
   				{
                    map.getLayersByName('Projekt Layer')[0].setVisibility(false);
					map.setBaseLayer(map.getLayersByName('Google Satelit')[0]);
				}
				else if($(this).attr('id') == 'osm_org' )
   				{
                    map.getLayersByName('Projekt Layer')[0].setVisibility(false);
					map.setBaseLayer(map.getLayersByName('OSM Orginal')[0]);
				}
				else if($(this).hasClass('kultur'))
				{
                    

    				$("#map_OpenLayers_ViewPort").remove();
					$.post(getAjaxUrl() + "/kulturmodul/getExtent",{'id':$(this).attr('id')},
						function(data)
						{
							map_mode = 'kultur';
							map = initKulturMap(data.max_extent,data.min_zoom,data.max_zoom);
						}
					,'json');

					//$('.Level1st').empty();



				}
				else if($(this).hasClass('flaewi'))
				{
					map.setBaseLayer(map.getLayersByName('Flaewi Layer')[0]);

                    if($('#projektid').val() == 'st-poelten')
                    {
                        $('#map2web').prepend('<span id="bottomInfo" style="margin-right:20px;">Kein Rechtsanspruch aus der Karte ableitbar.</span>');
                    }

				}

				$(this).addClass('current');

	            return false;
			}
		);

		$('#wikipedia_enabled').live('click',
			function()
			{
                removeAllPopups();
				if($('#wikipedia_enabled').is(':checked'))
				{
					getWikipediaEntries();
				}
				else
				{
					removeFeatureByObjtype('wikipedia');

				}

			}
		);

		$('#public_buildings_enabled').live('click',
			function()
			{
                removeAllPopups();
				if($('#public_buildings_enabled').is(':checked'))
				{
					getPublicBuildingsEntries();
				}
				else
				{
					removeFeatureByObjtype('publicbuilding');
				}
			}
		);

		$('#closeSearchOptions').live('click',
			function()
			{
				$('#suchoptionen').hide();
			}
		);

		$('img.thumb').live('click',
			function()
			{
				$('img.highres').attr('src',$(this).attr('src').replace('getpreview','getcontent'));
                $('#getFullResImage').attr('href',$(this).attr('src').replace('getpreview','getFullResImage'));
			}
		);

        $('.showAGObjekt').live('click',
            function(){
	            $.post(getAjaxUrl() + "/projekt/getAGObjektGisData",{'id':$(this).attr('id'),'projection':$('#projection').val()},
		            function(data)
		            {
			            var style_blue = {
	                			'pointRadius': 10,
				            'externalGraphic': '/js/images/marker2.gif',
				            'graphicWidth':10,
				            'graphicHeight':10
			            };

			            initVectorLayer(map);

			            var gisdata = data;

                    removeFeatureByObjtype(map);

		            var vectorLayer = initVectorLayer(map);
                        	//map.addLayers([vectorLayer]);
/*
	                    function onPopupClose(evt) {
	                        selectControl.unselect(selectedFeature);
	                    }*/
                    for(var i=0;i<=data.geometries.length-1;i++)
    		            drawFeatures(data.geometries[i],vectorLayer,true);
		            }

	            ,'json');
            }
        );

        $('#printScreen').live('click',
            function(e){
                e.preventDefault();

				var bbox = map.getExtent().toBBOX().split(',');

				alert(parseFloat(bbox[2]));

				var xl = parseFloat(bbox[2])-parseFloat(bbox[0]);
				var yl = parseFloat(bbox[3])-parseFloat(bbox[1]);

				var sv = yl/xl;

				var laenge = 10000;

				alert(sv);

				window.open('http://172.16.1.124/cgi-bin/mapserv?map=/data/maps/austria_city/main_300.map&service=wms&request=getCapabilities&SERVICE=WMS&VERSION=1.3.0&Layers=Fond,GSurfaceCover,GContourline,GAirport,GDetailContour,GRoadUnder,GWaterLine,GWaterBody,GDepthline,GRoadArea,GRailwayUnder,GStructure,GRoadPlan,GRoad,GRailway,GRoadOver,GStructureOver,GLinemodule,GMotorway,GRailwayOver,GMotorwayOver,GRoadNames,GRoadNumbers,GStaticText&REQUEST=GetMap&BBOX=' + map.getExtent().toBBOX() + '&DPI=300&&width=' + laenge + '&height=' + (laenge*sv) + '&crs=epsg:32633&format=png24&gemnr1=30201');

/*
                window.open('/projekt/printScreen?bbox='+map.getExtent().toBBOX()+'&res='+map.getResolution()+'&zoomstufe='+(parseInt(map.getZoomForResolution(map.getResolution()))+7));
*/

                return false;
            }
        );


	$("#suchfeld").bind("keydown", function(event) {
        var keycode = (event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode));
        if (keycode == 13) 
        {
            submitFullTestSearch();
            return false;
        } 
        else  
        {
            return true;
        }
    });



    //--- TCLayer zu Karte hinzufügen ---

	$(".appendLayerToMap").live('click', function(event) {
        if($(this).is(':checked'))
        {
            var tilecache_url = 'http://cache3.map2web.eu/cache';

            if($('#projection').val() == 'EPSG:900913')
            {
                var tilecache_url = 'http://cache3.map2web.eu/cache';
                tilecache_layer = new OpenLayers.Layer.TileCache($(this).attr('value'),
                    [tilecache_url],
                    $(this).attr('value'),
                    {
					    "isBaseLayer": false,
                        "visible":true
                    }

                );
            }
            else if($('#projection').val() == 'EPSG:32633' || $('#projection').val() == 'EPSG:32632')
            {
                var tilecache_url = 'http://cache2.map2web.eu/cache';
                tilecache_layer = new OpenLayers.Layer.TileCache($(this).attr('value'),
                    [tilecache_url],
                    $(this).attr('value'),
                    {
                    	"serverResolutions": serverResolutions_at,
					    "isBaseLayer": false,
                        "visible":true
                    }
                );
            }

            map.addLayers([tilecache_layer]);


        }
        else
        {
            var layer = map.getLayersByName($(this).attr('value'))[0];
            map.removeLayer(layer);
        }

    });

    $('.ffb_accept_yes').live('click',
        function()
        {
            var api = $("#nutzungsbedingungen_ffb").data("overlay");
            nutzungsbedingungen_ffb = true;
            $('#41419').click();
            $('#41419').click();
            api.close();
        }
    );

    $('.ffb_accept_no').live('click',
        function()
        {
            var api = $("#nutzungsbedingungen_ffb").data("overlay");
            nutzungsbedingungen_ffb = false;
            $('#41419').click();
            api.close();
        }
    );


    OpenLayers.IMAGE_RELOAD_ATTEMPTS = 5;
    OpenLayers.DOTS_PER_INCH = 96;


    $('#suchfeld').autocomplete({
                source: "/projekt/searchAllItemsPreview?projektid=" +  $('#objektid').val() + '&projection=' + $('#projection').val() ,
                minLength: 2
            });




});

