var map;

var mandant;
var config;

var G_EMPTY_MAP = null;

var slider1;
var catMenu;
var frame = null;
var adressFrame = null;
var tabbedPane1 = null;

var markerArray = new Array();
var polygonArray = new Array();
var polylineArray = new Array();

var wmsArray = new Array();
var wmsOverviewArray = new Array();

var stdicon;
var stdicon2;
var stdicon3;
var stdicon4;

var foundAdresses = new Array();

var cancelNextClick = false;

var pinIcon;
var dateIcon;

var detailmap;

var measureMarkers = new Array();

var adressMarker = null;

var lastPolygonOverLay;

var measureHandle;

var infoWindow;

var drawPolygons = true;

var currentMarker;

var currentPolygon;

var measureDialog = null;
var measureArea = false;

var measureDrag = false;

var debug = false;

var markerZIndex = 0;

var isMeasureMode = false;

var isSearchMode = false;

var isInfoMode = false;

var isZoomPlusMode = false;

var alertDialog = null;

var isDatingMode = false;
var dateDialog = null;
var datingEventHandle = null;

var isRoutingMode = false;
var routingEventHandle = null;
var routingStart = null;
var routingEnd = null;
var route = null;
var routeDialog = null;
var direction = null;

var isTrackingMode = false;
var trackingDialog = null;
var trackingObserver = null;
var trackingMarker = null;
var trackingLabels = null;
var trackingPolylines = null;
var trackingType = 0;
var trackingInterval = 30;

var mapMode = 0;

var waitCounter = 0;

var dimensions;

var geocoder = null;

var centerMarker = null;
var centerMarkerEventHandle = null;
var centerDialog = null;

var circleMarkers = null;
var overviewCircleMarkers = null;
var circleResponse = null;

var highlightMarker = null;
var highlightPolygon = null;
var highlightPolyline = null;

var selectBoxEvent = false;

var selectBoxCatId = null;

var infoBoxFilter = "";

var infoBoxGTyp = -1;

var skin = "";

var datingPoint = null;
var datingMarker = null;
var datingZoom = null;
var datingMessage = null;

var overviewMapControl = null;

var tgSelectBox = null;

var tgZoom = null;

var checkZoomFlag = true;

var previousMapType = null;

var preselectedCats = null;

var requestedMapType = null;

var preselectedWMS = null;

var zoomHandle = null;

var moveHandle = null;

var wmsLoaded = new Array();

var undoArray = new Array();

var localOverlay = null;

var standalone = true;

var speedMarkers = null;

var lastRouteInfo = "";

var grpname = null;

var pwd = null;

var paramsObj = null;

var lastMarkerId = null;

var cwin;

window.name="mapFenster";

// Eintrittspunkt
function load()
{	
	//URL-Parameter holen
	paramsObj = document.URL.toQueryParams();
	try
    {
        if(window.parent.location.search != window.location.search)
    	{
    	    // Befinde mich im Frame ...
    	    standalone = false;
            
    	    var parentParams = window.parent.location.search.toQueryParams();
    	    
            paramsObj = $H(paramsObj).merge(parentParams);
    	}
	}
    catch(e)
    {
        
    }
    
	if(paramsObj.debug)
	{
	   debug = paramsObj.debug;    
	}
	
	if(paramsObj.mandant)
	{
	    mandant = paramsObj.mandant;
	}
	else
	{
	    mandant = "";
	}

    if(paramsObj.skin)
	{
	    skin = paramsObj.skin;
	}
	
	if(paramsObj.dpLat && paramsObj.dpLon)
	{
	    datingPoint = new GLatLng(parseFloat(paramsObj.dpLat),parseFloat(paramsObj.dpLon));
	}
	
	if(paramsObj.mid && paramsObj.gtyp)
	{
	    datingMarker = new Array(paramsObj.mid,paramsObj.gtyp);
	}
	
	if(paramsObj.z)
	{
	    datingZoom = paramsObj.z;
	}
	
	if(paramsObj.m)
	{
	    datingMessage = paramsObj.m;
	}
    
    if(paramsObj.es)
	{
	    preselectedCats = paramsObj.es;
	}
    
    if(paramsObj.mty)
    {
        requestedMapType = paramsObj.mty;
    }
    
    if(paramsObj.ew)
    {
        preselectedWMS = paramsObj.ew;
    }
	
	var myAjax = new Ajax.Request
    (
    	  serverUrl + 'php/ajax_control.php', 
    	  {
    		method: 'POST', 
    		parameters: 'functionId=0&mandant=' + mandant, 
    	    onSuccess: callbackLoad,
    	    onLoading: showSearchWaitDiv,
    	    onLoaded: hideSearchWaitDiv,
    	    onException : initFailure,
    	    onFailure : hideSearchWaitDiv
    	  }
    );
}

function callbackLoad(request)
{	
	// Konfiguration auslesen
	config = eval('(' + request.responseText + ')');
	config.area_name = unescape(config.area_name);
	if(debug) GLog.write("Config : " + config);
	
	document.title = document.title + " - " + config.area_name;
	
	// evtl. Skin setzen
	if(skin != "") config.skin = skin;
	
	if(config.skin != 'default')
	{
	    setSkin();
	}
	else
	{
	   $("toolbar").style.backgroundImage = "url(" + unescape(config.skin_server) + unescape(config.skin) + "/bgtoolbar.gif)";
	}
	
	// 2 Accordion's erzeugen
	ac = new Accordion('accordionDiv',{width: 230,headerheight: 20});
	infoWindow = new Accordion('infoDiv',{width: 230,headerheight: 20})
	
	slider1 = new TGSlider('slider1',{width: 100,height: 20,min: 0,max: 18,value: 13,step : 10,handleimage: 'images/vissliderhandle.gif',trackimage : 'images/slider.gif'});
	slider1.registerDragEndHook(changeScale);
   
    $('ortsname').innerHTML = config.area_name; 
    
    var tabs = new Array();
    
    // Suchmodus auswerten
    if(config.searchtype != 4)
    {
    	tabs[0] = new TGTab("Suche", "searchTab1");
    }
    
    // Erweiterte Suche ?
    if(config.searchtype == 2)
    {
        tabs[1] = new TGTab("Erweitert", "searchTab2");
        tabs[2] = new TGTab("Umkreis", "searchTab3");
    }
    else if(config.searchtype == 4)
    {
        tabs[0] = new TGTab("Suche", "searchTab2");
        tabs[1] = new TGTab("Umkreis", "searchTab3");
        
    }
    
    tabbedPane1 = new TGTabbedPane("searchTabs","tabbedPane1",{tabs : tabs});

    if(config.searchtype == 2)
    {
        $('tfPlz').value = config.plz; 
        $('tfOrt').value = config.area_name; 
    }
    else if(config.searchtype == 4)
    {
   		$('tfPlz').value = "Plz"; 
        $('tfOrt').value = "Ort";
    } 
    // Routing anzeigen ?
    
    if(config.routing == "true")    
    {
        Element.show("routing_button");
    }
    else
    {
        $('dating_button').style.left = "415px";
    }
    
    if(config.dating == "true")    
    {
        Element.show("dating_button");
    }
    
    if(config.tracking)
    {
        if(config.tracking == "true")    
        {
            Element.show("tracking_button");
        }
    }
	// Google Maps initialisieren
	if (GBrowserIsCompatible()) 
    {
    	var mapDivision = $("mapDivision"); 
        
        // anfaengliche Groesse ermitteln
        onReSizeHandler();
        // Kartenobjekt erzeugen
        map = new GMap2(mapDivision);
		
		map.enableScrollWheelZoom();
        
        // fuer Koordinatenanzeige und GUI-Aktualiserungen bei Zoom
        GEvent.addListener(map,"mousemove",onMouseMoved);        	    
        zoomHandle = GEvent.addListener(map,"zoomend",onZoomed);
        moveHandle = GEvent.addListener(map,"moveend",onMoved);
        GEvent.addListener(map,"load",onMapLoaded);
        
     	// Accordion's im DOM auf die Karte umkopieren
     	var accordion = $("accordionDiv");//.remove();
     	accordion.style.position = "absolute";
     	accordion.style.top = "40px";
     	accordion.style.left = "0px";
        accordion.style.zIndex = 10000;     	
	   
       
	    var infoDiv = $("infoDiv");//.remove();
     	infoDiv.style.position = "absolute";
     	infoDiv.style.top = "40px";
     	infoDiv.style.left = dimensions.width - 230 + "px";
        infoDiv.style.zIndex = 10000;

        
        tgSelectBox = new TGSelect($('infoBox'),{height:200});
     	tgSelectBox.registerOnClick(onInfoSelectClicked);
	    
	    // Icons fuer Standardmarker erzeugen
	    
	    stdicon  = new GIcon();
  		stdicon.iconSize=new GSize(30,30);
	    stdicon.shadowSize=new GSize(56,32);
  		stdicon.iconAnchor=new GPoint(15,15);
 		stdicon.infoWindowAnchor=new GPoint(15,0);
 		
 		stdicon2  = new GIcon();
  		stdicon2.iconSize=new GSize(8,8);
  		stdicon2.iconAnchor=new GPoint(4,4);
 		stdicon2.infoWindowAnchor=new GPoint(4,4);
 		
 		stdicon3  = new GIcon();
  		stdicon3.iconSize=new GSize(36,36);
	    stdicon3.shadowSize=new GSize(1,1);
  		stdicon3.iconAnchor=new GPoint(18,33);
 		stdicon3.infoWindowAnchor=new GPoint(18,0);
        
        stdicon4  = new GIcon();
  		stdicon4.iconSize=new GSize(20,34);
	    stdicon4.shadowSize=new GSize(37,34);
  		stdicon4.iconAnchor=new GPoint(17,0);
 		stdicon4.infoWindowAnchor=new GPoint(17,0);
 		
 		pinIcon = new GIcon(stdicon,"http://maps.google.com/mapfiles/kml/pal5/icon14.png" , null, null); 
 		dateIcon = new GIcon(stdicon,"http://maps.google.com/mapfiles/kml/pal4/icon39.png" , null, null); 
 		
 		// Leeren GMapType erzeugen
 		
 		
 		var dummylayer = new GTileLayer(new GCopyrightCollection(),0,40);
		dummylayer.getTileUrl = function() { return "images/blind.gif"; };
		dummylayer.isPng = function() { return false;};
		dummylayer.getOpacity = function() { return 1.0; }
	        var dummyLayerArray = new Array(dummylayer);
                G_EMPTY_MAP = new GMapType(dummyLayerArray, new GMercatorProjection(41), "empty", {errorMessage:"No data available"}); 		
 		
 		
 		// Bei Klick in die Karte Info's anzeigen
 		GEvent.addListener(map, "click", showPolygonVCard); 

        overviewMapControl = new GOverviewMapControl();
 		map.addControl(overviewMapControl);    
        map.enableDoubleClickZoom(); 
    	map.enableContinuousZoom();
      
        
        if(!datingPoint && !datingMarker)
        {
           map.setCenter(new GLatLng(parseFloat(config.lat),parseFloat(config.lon)),parseInt(config.zoom));   
        }
        else if(datingPoint) 
        {
            // auf von aussen uebergebenen Punkt fahren       
            
            
                datingMarker = new GMarker(datingPoint,dateIcon);
                            
                if(datingZoom)
                {
                    map.setCenter(datingPoint,parseInt(datingZoom));      
                }
                else
                {
                    map.setCenter(datingPoint,15);      
                }
                
                if(!paramsObj.show)
                {
			map.addOverlay(datingMarker);   

			if(datingMessage)
			{
			    GEvent.addListener(datingMarker, "click", function() 
			    {
				datingMarker.openInfoWindowHtml("<div style='width:220px;height:100px;background-color:#FFFFFF;overflow:auto;'>" + Tool.decode(datingMessage) + "</div>",{maxWidth : 100});
			    });   

			    datingMarker.openInfoWindowHtml("<div style='width:220px;height:100px;background-color:#FFFFFF;overflow:auto;'>" + Tool.decode(datingMessage) + "</div>",{maxWidth : 100});
			}
	        }
            
        }
        else if(datingMarker)
        {
            if(datingZoom)
            {
                map.setCenter(new GLatLng(parseFloat(config.lat),parseFloat(config.lon)),parseInt(datingZoom));      
            }
            else
            {
                map.setCenter(new GLatLng(parseFloat(config.lat),parseFloat(config.lon)),15);      
            }
            setDatingMarker();
        }
        
        map.addMapType(G_EMPTY_MAP);
        
        if(requestedMapType)
        {
            var mapTypes = map.getMapTypes();
            
            for(var i = 0;i < mapTypes.length;i++)
            {
                if(mapTypes[i].getName(false).toLowerCase() == requestedMapType.toLowerCase())
                {
                    map.setMapType(mapTypes[i]);
                    break;
                }
            }
        }
        else
        {
            map.setMapType(G_HYBRID_MAP);
        }

        tgZoom = new TGZoom(map, {yOffset : 40});
        
        
        
        // WMS-Server einbinden        
        getCapabilities();
		
		hideSearchWaitDiv();
    }
    
    hideSearchWaitDiv();
    
    Event.observe(window,"resize",onReSizeHandler);
    
    // Auf Eingaben im Filterfeld reagieren
    Event.observe("filterString","keyup",infoBoxFilterChanged);
    
    GEvent.addListener(map,"maptypechanged",onMapTypeChanged);
    
    //GEvent.addListener(map,"infowindowclose",onInfoWindowClosed);

}

function onMapLoaded()
{
    if(debug) GLog.write("Map loaded");
	speedMarkers = new SpeedMarkers(map);
        speedMarkers.format = "html";
        map.addOverlay(speedMarkers);
    // Kategorien-Menu erzeugen
	catMenu = new Menu('innerCategoryContent',{selectable : true ,categoriesUrl : serverUrl + 'php/ajax_control.php', categoriesParams : 'functionId=11&mandant=' + mandant, queryable : true});
	catMenu.waitDiv = 'indicator1';
    
    catMenu.registerCheckboxHook(categorieChoosed);
	catMenu.registerInfoHook(infoClicked);
	catMenu.registerSearchHook(searchClicked);
	catMenu.registerLoadedListener(catsLoaded);
	
	if(debug)
	{
	    GLog.write("Bounds sw : " + map.getBounds().getSouthWest().toUrlValue());
	    GLog.write("Bounds ne : " + map.getBounds().getNorthEast().toUrlValue());
	}
}

function onInfoSelectClicked(a,b)
{
    highlightMarkerFunctionIE(a,b);
    infoBoxDblClicked();
}

function setDatingMarker()
{
     var myAjax = new Ajax.Request
     (
    	serverUrl + 'php/ajax_control.php', 
    	{
    		   method: 'POST', 
    		   parameters: 'functionId=8&markerId=' + datingMarker[0] + '&gtyp=' + datingMarker[1] + '&mandant=' + mandant, 
    		   onSuccess: callbackInfoBoxDblClicked,
   			   onLoading: showSearchWaitDiv,
       		   onLoaded:  hideSearchWaitDiv,
       		   onFailure: hideSearchWaitDiv
   		}
      );
     
}

// Hilfsfunktion fuer Sortierfunktion
function catSort(a,b)
{
    if(a.obj < b.obj) return -1;
    if(a.obj > b.obj) return  1;
    return 0;
}

// Wird aufegerufen nachdem Kategoriebaum erzeugt wurde
function catsLoaded()
{
    var subCats = catMenu.getAllSubCats();
    
    // Kategorien alphabetisch sortieren
    subCats.sort(catSort);
    
    // Kategorien in Umfeldsuche-Kategoriebox eintragen
    var selectBox = $('seCats').options;
    
    for(var i=0; i<subCats.length; i++) 
    {
        var oOption = document.createElement("OPTION");
        oOption.text=unescape(subCats[i].obj);
        oOption.value=subCats[i].objId;
        oOption.title=unescape(subCats[i].obj);
        selectBox.add(oOption);	    
    }
    
    if(preselectedCats)
    {
        catMenu.setEncodedSelection(preselectedCats);
    }
    
    externalInterfaceObj(paramsObj);
}

function setSkin()
{
    // Skinspezifische Grafiken 
    $("home_button").src= "images/skins/" + config.skin + "/home.gif";
    $("sat_button").src= "images/skins/" + config.skin + "/sat.gif";
    $("globe_button").src= "images/skins/" + config.skin + "/globe.gif";
    $("print_button").src= "images/skins/" + config.skin + "/print.gif";
    $("print_button").src= "images/skins/" + config.skin + "/print.gif";
    $("measureButton").src= "images/skins/" + config.skin + "/measure.gif";
    $("zoomplus_button").src= "images/skins/" + config.skin + "/zoomplus.gif";
    if ($("dating_button")) {$("dating_button").src= "images/skins/" + config.skin + "/date.gif";}
    if ($("routing_button")) {$("routing_button").src= "images/skins/" + config.skin + "/routing.gif";}
    if ($("tracking_button")) { $("tracking_button").src= "images/skins/" + config.skin + "/tracking.gif";}
    if ($("info_button")) { $("info_button").src= "images/skins/" + config.skin + "/search2.gif";}
    $("back_button").src= "images/skins/" + config.skin + "/backbutton.gif";
    $("toolbar").style.backgroundImage = "url(" + unescape(config.skin_server) + unescape(config.skin) + "/bgtoolbar.gif)";
    $("indicator1").src= "images/skins/" + config.skin + "/indicator.gif";
    if ($("hilfe_button")) {$("hilfe_button").src= "images/skins/" + config.skin + "/help.gif"; }
    
}

function onReSizeHandler()
{
    // auf Groessenaenderung reagieren
    dimensions = Element.getDimensions(document.body);
    dimensions.width = Tool.getInnerWidth();
	dimensions.height = Tool.getInnerHeight() - 40;
    var mapDivision = $("mapDivision"); 
    mapDivision.style.width = dimensions.width + "px";
    mapDivision.style.height = dimensions.height + "px";
    $('toolbar').style.width = dimensions.width + "px";
    $('indicator1').style.left = (dimensions.width - 35) + "px";
    
    $('infoDiv').style.left = (dimensions.width - 230) + "px";
    
    if(map)
    {
        map.checkResize();
    }
    
    if(wmsArray)
    {
        for(var i=0;i < wmsArray.length;i++)
        {
            if(wmsArray[i].overlay.image)
            {
                wmsArray[i].overlay.dragend();
            }
        }
    }
    
    if(tgZoom)
    {
        tgZoom.updateSize();
    }
    
    hideSearchWaitDiv();
}

function initFailure(f)
{
    alert("Init-Fehler " + f.statusText);
}

function callBackClosure(url,mime,filter,params,opacity)
{
    return function(request)
    {
        callbackGetCapabilities(request,url,mime,filter,params,opacity);    
    }
}

function wmsFailureClosure(url)
{
    return function(e)
    {
        wmsFailure(e,url);    
    }
}

function getCapabilities()
{
     // Ueber alle WMS-Urls laufen
     if(config.wms_capabilities.length > 0)
     {
         for(var i =0;i < config.wms_capabilities.length;i++)
         {
             var wms_image_server = config.wms_capabilities[i].capabilities;
             
             var mime_type = config.wms_capabilities[i].mime;
             
             var layer_filter = config.wms_capabilities[i].filter;
             
             wms_image_server = wms_image_server.replace("\<ip\>", getIP());
			// alert("Image-Server: "+wms_image_server);
             
             var params = config.wms_capabilities[i].params;
             
             if(params.charAt(0) != '&')
             {
                 params = "&" + params;
             }
             
             var opacity = parseFloat(config.wms_capabilities[i].opacity);
             
             var url = "WMSURL=" +  escape(wms_image_server) + "&FILTER=" + layer_filter;
             
             if(debug) GLog.write("getCapabilities : " + url + "\n");
        
             // In Warteschlange haengen
             var obj = new Object();
             obj.url = wms_image_server;
             obj.bval = false;
             wmsLoaded[wmsLoaded.length] = obj;
             
             var callback = callBackClosure(wms_image_server,mime_type,layer_filter,params,opacity);
             
             var failureClosure = wmsFailureClosure(wms_image_server);
             
             // WMS-URL an Server uebergeben 
             var myAjax = new Ajax.Request
             (
            	  serverUrl + 'php/wms.php', 
            	  {
            		parameters : url,
            		method: 'POST', 
            	    onSuccess: callback,
            	    onLoading: showSearchWaitDiv,
            		onLoaded:  hideSearchWaitDiv,
            	    onFailure: failureClosure,
            	    onException : failureClosure
            	  }
             )
         }
     }
     else
     {
         if(debug) GLog.write("Kein WMS-Eintrag vorhanden !");
     }
     hideSearchWaitDiv();
}

function callbackGetCapabilities(request,url,mime,filter,params,opacity)
{
    hideSearchWaitDiv();
    if(debug) 
    {
        GLog.write("callbackGetCapabilities : " + request.responseText);
        
        GLog.write("mime : " + mime);
        
        GLog.write("filter : " + filter);

        GLog.write("params : " + params);
    }
    
    // Geparste Capabilities auswerten
    var layers = eval('(' + request.responseText + ')');
    
    if(layers)
    {
        if(isQueryable(layers))
        {
            Element.show('info_button');
        }
        
        
        // WMS-Overlay erzeugen
        var wms_layer_url = layers.wms_url;
        
        wms_layer_url = wms_layer_url.replace("\<ip\>", getIP());
        			// alert("Layer-URL: "+wms_layer_url);

        //wms_layer_url = wms_layer_url.replace("Blue Marble", "BlueMarble");
        
        var bounds = new GLatLngBounds(new GLatLng(parseFloat(layers.miny),parseFloat(layers.minx)),new GLatLng(parseFloat(layers.maxy),parseFloat(layers.maxx)));
         
        if(wms_layer_url.indexOf("?") == -1) 
        {
            wms_layer_url += "?";
        }
        else
        {
            if(wms_layer_url[wms_layer_url.length -1] != "&")
            {
               wms_layer_url += "&";
            }
        }
        var wmsLayer = new TGWMSOverlay(wms_layer_url + "REQUEST=GetMap&VERSION=1.1.1&SRS=EPSG:4326&FORMAT=" + mime + params,layers.name,bounds);
		var wmsLayer2 = wmsLayer.copy();
        wmsLayer2.setOpacity(opacity);
        wmsLayer.setOpacity(opacity);
        
        var wmsmenu = new WMSMenu("wmstree",layers,wmsLayer,wmsLayer2,{queryMode : true,waitDiv : 'indicator1'});
        
        // Handler-Funktionen anmelden
        wmsmenu.registerCheckboxHook(function(layerString,layer,overlay,overviewOverlay)
    	{
		   overlay.layersChanged(layerString);
		   overviewOverlay.layersChanged(layerString);
           map.removeOverlay(overlay);
           //overviewMapControl.getOverviewMap().removeOverlay(overviewOverlay);
           if(layerString != "")
           {
			  //overviewMapControl.getOverviewMap().addOverlay(overviewOverlay);
              map.addOverlay(overlay);
           }
        })
        
        wmsmenu.registerInfoHook(function(layer)
        {
            var bounds = new GLatLngBounds(new GLatLng(parseFloat(layer.miny),parseFloat(layer.minx)),new GLatLng(parseFloat(layer.maxy),parseFloat(layer.maxx)));
            if(debug) GLog.write("infoClicked : " + bounds.getCenter());   
            map.setCenter(bounds.getCenter(),map.getBoundsZoomLevel(bounds));
        });
    
        wmsArray[wmsArray.length] = wmsmenu;
    }
    hideSearchWaitDiv();
    
    for(var i = 0;i < wmsLoaded.length;i++)
    {
        if(wmsLoaded[i].url == url)
        {
            wmsLoaded[i].bval = true;
            break;
        }
    }
    checkWmsLoaded();
}

function checkWmsLoaded()
{
    if(wmsLoaded.length == config.wms_capabilities.length)
    {
        var loaded = true;
        
        for(var i = 0;i < wmsLoaded.length;i++)
        {
              if(wmsLoaded[i].bval == false)
              {
                  loaded = false;
                  break;
              }    
        }
        
        if(loaded) 
        {
            if(debug) GLog.write("checkWMSLoad : " + loaded);
            setChosenWMS();
        }
    }
}

function setChosenWMS()
{
    if(preselectedWMS)
    {
        var pwms = Tool.decode(preselectedWMS);
        
        var res = eval('(' + pwms + ')');
        
        for(var i = 0;i < res.length;i++)
        {
            for(var j = 0;j < wmsArray.length;j++)
            {
                if(wmsArray[j].layers.title == res[i].t)
                {
                    wmsArray[j].setEncodedLayers(res[i].a);
                    break;
                }
            }
        }
    }
}

// ueberprueft rekursiv ob abfragbare WMS-Layer enthalten sind
function isQueryable(layer)
{
    if(layer.queryable)
    {
        return true;
    }
    else
    {
        if(layer.layers != null)
        {
           for(var i=0; i<layer.layers.length; i++) 
           {
           	   return isQueryable(layer.layers[i]);
           }   
        }
    }
    
    return false;
}

// Zoomt auf Googis-Ausgangspunkt
function home()
{
    map.setCenter(new GLatLng(parseFloat(config.lat),parseFloat(config.lon)),parseInt(config.zoom));   
}

function wmsFailure(e,url)
{
    for(var i = 0;i < wmsLoaded.length;i++)
    {
        if(wmsLoaded[i].url == url)
        {
            wmsLoaded[i].bval = true;
            break;
        }
    }
    hideSearchWaitDiv();
    if(debug) GLog.write("Fehler beim Laden der WMS-Capabilities : " + e.status + " " + e.statusText);
}

function createMarker(point,icon,markerId,tooltip) 
{ 
  var tgmarker = new TGMarker(point,icon,markerId,tooltip,getZIndex);

  markerArray[markerId] = tgmarker;
  
  GEvent.addListener(tgmarker.marker, "click", function() 
  {
      currentMarker = tgmarker.marker;
      //parameters: 'functionId=5&markerId=' + markerId + '&mandant=' + mandant + "&site=" + window.parent.location.hostname + window.parent.location.pathname, 
	    
      var myAjax = new Ajax.Request
      (
	  serverUrl + 'php/ajax_control.php', 
	  {
		method: 'POST', 
		parameters: 'functionId=5&markerId=' + markerId + '&mandant=' + mandant + "&site=" + server +"/"+ mandant+"/", 
	    onSuccess: callbackShowVCard,
	    onLoading: showSearchWaitDiv,
	    onLoaded: hideSearchWaitDiv,
	    onFailure: hideSearchWaitDiv
	  }
    )
   });
  return tgmarker.marker;
}

// Marker automatisch nach oben legen
function getZIndex(a,b)
{
    markerZIndex++;
    if(markerZIndex > 1000)
    {
        markerZIndex = 0;
    }
    return markerZIndex;
}

function createPolygon(pointString,polygonId,stcolor,stweight,stopacity,fcolor,fopacity)
{
    var coords = pointString.split(',');
	    
    var coordsArray = new Array();
    
    for(var i = 0;i < coords.length;i++)
    {
       var tmp = coords[i].split(' ');
       
       var point = new GLatLng(parseFloat(tmp[0]),parseFloat(tmp[1]));    
       
       coordsArray[coordsArray.length] = point;
    }
    
    if(!isLineClosed(coordsArray))
    {
        if(coordsArray.length > 2)
        {
            coordsArray[coordsArray.length] = coordsArray[0];
        }
    }
    
    var polyline = new GPolygon(coordsArray,  stcolor, stweight,parseFloat(stopacity),fcolor,parseFloat(fopacity));
    
    var poly = new TGPolygon(polyline,polygonId);
      
    polygonArray[polygonArray.length] = poly;
	if(debug) GLog.write("PolygonArray : " + polygonArray[0].optId);

    
    return polyline;
}

function createPolyline(pointString,polygonId,stcolor,stweight,stopacity)
{
    var coords = pointString.split(',');
	    
    var coordsArray = new Array();
    
    for(var i = 0;i < coords.length;i++)
    {
       var tmp = coords[i].split(' ');
       
       var point = new GLatLng(parseFloat(tmp[0]),parseFloat(tmp[1]));    
       
       coordsArray[coordsArray.length] = point;
    }
       
    var polyline = new GPolyline(coordsArray,  stcolor, stweight, parseFloat(stopacity));
    
    var poly = new TGPolyline(polyline,polygonId);
      
    polylineArray[polylineArray.length] = poly;
	if(debug) GLog.write("PolylineArray : " + polylineArray[0].optId);
    
    return polyline;
}

function showVCardMap(markerId,lat,lon)
{
//alert(serverUrl); 
//alert(mandant);
//parameters: 'functionId=5&markerId=' + markerId + "&mandant=" + mandant + "&site=" + window.parent.location.hostname + window.parent.location.pathname, 
    var myAjax = new Ajax.Request
    (
	  serverUrl + 'php/ajax_control.php', 
	  {
		method: 'POST',         
		parameters: 'functionId=5&markerId=' + markerId + "&mandant=" + mandant + "&site=" + server+ "/"+mandant+"/", 
         
	    onSuccess: callbackShowVCardMapClosure(lat,lon)
	  }
    )
}

function callbackShowVCardMapClosure(lat,lon)
{
    return function(request)
    {
        callbackShowVCardMap(request,lat,lon);    
    }
}

function callbackShowVCardMap(request,lat,lon)
{	
	var p = new GLatLng(parseFloat(lat),parseFloat(lon));
    map.closeInfoWindow();
	
	var infoTabs = [new GInfoWindowTab("Info",request.responseText),new GInfoWindowTab("Karte", '<div id="detailmap" style="width: 250px;height: 150px;border:1px solid gray;"></div>')];

    var z = map.getCurrentMapType().getMaximumResolution() - 2;
    //map.setCenter(p,z);  // deaktivert by TMJ
	map.openInfoWindowTabsHtml(p,infoTabs);

	var dMapDiv = $("detailmap");
	
	// Karten in Baloon anzeigen
	detailmap = new GMap2(dMapDiv);
	detailmap.setCenter(p , 16,G_HYBRID_MAP);
	detailmap.addControl(new GSmallZoomControl());

	var CopyrightDiv = dMapDiv.firstChild.nextSibling;
    var CopyrightImg = dMapDiv.firstChild.nextSibling.nextSibling;
	CopyrightDiv.style.display = "none"; 
	CopyrightImg.style.display = "none"; 
    detailmap.addOverlay(new GMarker(p,pinIcon));
}

function showVCard(markerId, marker)
{
   if(debug) GLog.write("showVCard : " + markerId + "\n");
   currentMarker = marker;
//parameters: 'functionId=5&markerId=' + markerId + '&mandant=' + mandant + "&site=" + window.parent.location.hostname + window.parent.location.pathname,      
   var myAjax = new Ajax.Request
   (
	  serverUrl + 'php/ajax_control.php', 
	  {
		method: 'POST', 
		
        parameters: 'functionId=5&markerId=' + markerId + '&mandant=' + mandant + "&site=" + server+"/"+mandant+"/", 
	    onSuccess: callbackShowVCard,
	    onLoading: showSearchWaitDiv,
	    onLoaded: hideSearchWaitDiv,
	    onFailure: hideSearchWaitDiv
	  }
    )
}
  
function callbackShowVCard(request)
{	
	showSearchWaitDiv();
	map.closeInfoWindow();
	if(debug) GLog.write("callbackShowVCard : " + request.responseText + "\n");
	var infoTabs = [new GInfoWindowTab("Info", request.responseText),new GInfoWindowTab("Karte", '<div id="detailmap" style="width: 250px;height: 150px;border:1px solid gray;"></div>')];

	currentMarker.openInfoWindowTabsHtml(infoTabs);

	var dMapDiv = $("detailmap");
	
	// Karten in Baloon anzeigen
	detailmap = new GMap2(dMapDiv);
	detailmap.setCenter(currentMarker.getPoint() , 16,G_HYBRID_MAP);
	detailmap.addControl(new GSmallZoomControl());

	var CopyrightDiv = dMapDiv.firstChild.nextSibling;
    var CopyrightImg = dMapDiv.firstChild.nextSibling.nextSibling;
	CopyrightDiv.style.display = "none"; 
	CopyrightImg.style.display = "none"; 
    detailmap.addOverlay(new GMarker(currentMarker.getPoint(),pinIcon));
    hideSearchWaitDiv();
}

function showPolygonVCardById(polygon,gtyp)
{
    if(gtyp == 2)
    {
        currentPolygon = polygon.polyline.getVertex(0);
    }
    else if(gtyp == 3)
    {
        currentPolygon = polygon.getCenter();
    }
//parameters: 'functionId=9&id=' + polygon.optId + '&mandant=' + mandant + "&site=" + window.parent.location.hostname + window.parent.location.pathname,     
    var myAjax = new Ajax.Request
    (
         serverUrl + 'php/ajax_control.php', 
    	 {
    	    method: 'POST', 
    		parameters: 'functionId=9&id=' + polygon.optId + '&mandant=' + mandant + "&site="  + server+"/"+mandant+"/", 
            
    	    onSuccess: callbackShowPolygonVCard,
    	    onLoading: showSearchWaitDiv,
    	    onLoaded: hideSearchWaitDiv,
    	    onFailure: hideSearchWaitDiv
    	 }
    )
}

function showPolygonVCard(marker, point)
{
    if(isInfoMode)
    {
        queryFeatureInfo(point);
    }
    else if(marker instanceof GPolygon)
    {
        if(polygonArray)
        {
           if(marker)
           {
               if(debug) GLog.write("called showPolygonVCard()");
               for(var i = 0;i< polygonArray.length;i++)
               {
                   if(polygonArray[i].polygon == marker)
                   {
                       currentPolygon = marker.getBounds().getCenter();
                       //parameters: 'functionId=9&id=' + polygonArray[i].optId + '&mandant=' + mandant + "&site=" + window.parent.location.hostname + window.parent.location.pathname, 
                       var myAjax = new Ajax.Request
                       (
                            serverUrl + 'php/ajax_control.php', 
                    	    {
                    	       method: 'POST', 
                    		   parameters: 'functionId=9&id=' + polygonArray[i].optId + '&mandant=' + mandant + "&site=" + server+"/"+mandant+"/", 
                    	       onSuccess: callbackShowPolygonVCard,
                    	       onLoading: showSearchWaitDiv,
                    	       onLoaded: hideSearchWaitDiv,
                    	       onFailure: hideSearchWaitDiv
                    	    }
                       )
                       break;
                    }
               }
           }
        }
    }
    else if(marker instanceof GPolyline)
    {
        if(polylineArray)
        {
           if(marker)
           {
               if(debug) GLog.write("called showPolygonVCard()");
               for(var i = 0;i< polylineArray.length;i++)
               {
                   if(polylineArray[i].polyline == marker)
                   {
                       currentPolygon = marker.getVertex(0);
                       //parameters: 'functionId=9&id=' + polylineArray[i].optId + '&mandant=' + mandant + "&site=" + window.parent.location.hostname + window.parent.location.pathname, 
                       
                       var myAjax = new Ajax.Request
                       (
                            serverUrl + 'php/ajax_control.php', 
                    	    {
                    	       method: 'POST', 
                    		   parameters: 'functionId=9&id=' + polylineArray[i].optId + '&mandant=' + mandant + "&site="         + server+"/"+mandant+"/", 
                       
                    	       onSuccess: callbackShowPolygonVCard,
                    	       onLoading: showSearchWaitDiv,
                    	       onLoaded: hideSearchWaitDiv,
                    	       onFailure: hideSearchWaitDiv
                    	    }
                       )
                       break;
                    }
               }
           }
        }
    }
        
}

function callbackShowPolygonVCard(request)
{
    showSearchWaitDiv();
	map.closeInfoWindow();
	if(debug) GLog.write("callbackShowPolygonVCard : " + request.responseText + "\n");

	map.openInfoWindowHtml(currentPolygon,request.responseText);

    hideSearchWaitDiv();
}

// Kategorie wurde angeklickt
function categorieChoosed(cb,catId,gtyp,obj)
{   
	if(cb.checked)
	{
		if(gtyp > 1)
		{
        	var myAjax = new Ajax.Request
            (
        		serverUrl + 'php/ajax_control.php', 
        		{
        			   method: 'POST', 
        			   parameters: 'functionId=4&catId=' + catId + "&gtyp=" + gtyp + '&mandant=' + mandant, 
        			   onSuccess: callbackCategoriesChoosed,
        			   onLoading: showSearchWaitDiv,
        			   onLoaded: hideSearchWaitDiv,
            		   onFailure: hideSearchWaitDiv
        		}
        	);
		}
		else
		{
			speedMarkers.addLayer(catId);
		}
	}
	else
	{
		if(gtyp > 1)
		{
    		var myAjax = new Ajax.Request
    	    (
    			serverUrl + 'php/ajax_control.php', 
    			{
    				   method: 'POST', 
    				   parameters: 'functionId=4&catId=' + catId + "&gtyp=" + gtyp + '&mandant=' + mandant, 
    				   onSuccess: callbackCategoriesChoosedNotChecked,
    				   onLoading: showSearchWaitDiv,
    	    		   onLoaded: hideSearchWaitDiv,
    	    		   onFailure: hideSearchWaitDiv
    			}
    		);
		}
		else
		{
		    speedMarkers.removeLayer(catId);
		}
	}
	
	//if(gtyp < 2) speedMarkers.redraw(true);
}

// Hilfsfunktion fuer Sortierfunktion
function markerSorter(a,b)
{
    return a.markerId - b.markerId;
}

function markerComparator(marker,id)
{
    return marker.markerId - id;
}
// Kategorie selektiert
function callbackCategoriesChoosed(request)
{
	if(debug) GLog.write('callbackCategoriesChoosed : ' + request.responseText);
	
	var res = eval('(' + request.responseText + ')');
    
    for(var i = 0; i < res.length;i++)
	{
    	if(res[i].gtyp == 2)
    	{        
    	    var contains = false;
    	    
    	    for(var j = 0;j < polylineArray.length;j++)
        	{
        	   if(polylineArray[j].optId == res[i].id) 
        	   {
        	       contains = true;
        	       break;
        	   }    
        	}
    	    if(!contains)
    	    {
    	       var poly = createPolyline(res[i].pos,res[i].id,res[i].stcolor,res[i].stweight,res[i].stopacity);
    	       
    	       var tmpPolyline = new TGPolyline(poly,res[i].id);
               
               map.addOverlay(poly);
    	    }
    	}
    	else if(res[i].gtyp == 3)
    	{        
    	    var contains = false;
    	    
    	    for(var j = 0;j < polygonArray.length;j++)
        	{
        	   if(polygonArray[j].optId == res[i].id) 
        	   {
        	       contains = true;
        	       break;
        	   }    
        	}
    	    if(!contains)
    	    {
    	       var poly = createPolygon(res[i].pos,res[i].id,res[i].stcolor,res[i].stweight,res[i].stopacity,res[i].fcolor,res[i].fopacity);

    	       var tmpPolygon = new TGPolygon(poly,res[i].id);
               
    	       map.addOverlay(poly);
    	    }
    	}
	}
    hideSearchWaitDiv();
}

// Kategorie deselektiert
function callbackCategoriesChoosedNotChecked(request)
{
    map.closeInfoWindow();
	var res = eval('(' + request.responseText + ')');
    if(debug) GLog.write(request.responseText);
    
    for(var i = 0;i < res.length;i++)
	{	
		if(res[i].gtyp == 2)
        {
	        if(highlightPolyline)
    		{
        		if(highlightPolyline.objId == res[i].id )
        		{
        		     map.removeOverlay(highlightPolyline.obj);   
        		     highlightPolyline = null;
        		}
    		}
	        
	        for(var j = 0;j < polylineArray.length;j++)
    		{
    			var m = polylineArray[j];
    			
    			if(m.optId == res[i].id)
    			{
    				map.removeOverlay(m.polyline);
    				polylineArray[j] = null;
    				break;
    			}
    		}
    		polylineArray = polylineArray.compact();
        }
        else if(res[i].gtyp == 3)
        {
	        if(highlightPolygon)
    		{
        		if(highlightPolygon.objId == res[i].id )
        		{
        		     map.removeOverlay(highlightPolygon.obj);   
        		     highlightPolygon = null;
        		}
    		}
    		
	        for(var j = 0;j < polygonArray.length;j++)
    		{
    			var m = polygonArray[j];
    			
    			if(m.optId == res[i].id)
    			{
    				map.removeOverlay(m.polygon);
    				polygonArray[j] = null;
    				break;
    			}
    		}
    		polygonArray = polygonArray.compact();
        }
	}
	hideSearchWaitDiv();
}

// Textfeld leeren
function initTf(el,value)
{
    if(value == el.value) el.value = "";
}

function searchAdress()
{
	if(geocoder == null)
	{
	   geocoder = new GClientGeocoder();
	}
	
	var strasse = $F('strasse');
	var nr =  $F('nr');
	
	if(strasse == $('strasse').title) 
	{
	   strasse = '';
	}
	

	if(strasse != '')
	{
		if((nr != '') && (nr != "Nr"))
		{
		   strasse += '+' + nr;
		}
		
		showSearchWaitDiv();

        geocoder.getLocations(strasse + "+" + config.area_name + "+" + config.plz,callbackSearchAdress);
	}
}

function searchAdressEx()
{
	if(geocoder == null)
	{
	   geocoder = new GClientGeocoder();
	}
	
	var strasse = $F('strasseEx');
	
	if(strasse == $('strasseEx').title)
	{
           strasse = "";
	}
	
	var nr =  $F('nrEx');
    var plz = $F('tfPlz');
    var ort = $F('tfOrt');
       
    if(nr == "Nr")
	{
	    nr = "";
	}
	
	if(plz == "Plz")
	{
	    plz = "";
	}
	
	if(ort == "Ort")
	{
	    ort = "";
	}
	
	geocoder.getLocations(strasse + " " + nr + " " + plz + " " + ort + ", " + config.land ,callbackSearchAdress);
}

function searchWord()
{
    var begriff = $F('begriff');
    
    var bounds = map.getBounds();
    
    if(begriff != "")
    {
        var url = "http://maps.google.de/maps?near=" + config.area_name + "&geocode=&q=" + begriff + "&f=li&output=kml&hl=de&sll=" + bounds.getCenter().toUrlValue() + "&sspn=" + bounds.toSpan().toUrlValue();
        if(debug) GLog.write(url);
        
        removeLocalOverlay();
        
        localOverlay = new GGeoXml(url);
        
        map.addOverlay(localOverlay);        
    }
}

function removeLocalOverlay()
{
    if(localOverlay)
    {
        map.removeOverlay(localOverlay);
        localOverlay = null;
    }
}

function showSearchWaitDiv()
{
	Element.show('indicator1');
	
	// Workaround fuer Indicator-Icon
    window.setTimeout(hideSearchWaitDiv,3000);
}

function hideSearchWaitDiv()
{
	//Element.hide('indicator1');
	document.getElementById('indicator1').style.display = "none";
}

function callbackSearchAdressSec(result)
{
     var res = eval('(' + result.responseText + ')');
     
     callbackSearchAdress(res);
}

function callbackSearchAdress(result)
{	
	if(adressFrame && !adressFrame.isClosed) 
    {
        adressFrame.close();
        adressFrame = null;
    }
    
	if(result.Status.code == 200)
	{
		if(result.Placemark.length == 1)
		{
    		var place = result.Placemark[0];
    		
    		var adressArray = place.address.split(",");
    		
    		var htmlAdress = "";
    		
    		for(var i=0; i<adressArray.length -1; i++) 
    		{
    		    htmlAdress += adressArray[i] + "<br />";
    		}
    		
    		showAdress(place.Point.coordinates[1],place.Point.coordinates[0],htmlAdress);
		}
		else
		{    
            var width = 200;
            var height = 200;
            
            var center = map.fromLatLngToDivPixel(map.getCenter());
         
            adressFrame = new TGFrame("Suchergebnis",{x: 235,y: 42,width : width,height: height,parentWindow:$("mapDivision"),draggable : false,opacity: 0.8, contentBackground : "#E4E0D8" });
            adressFrame.content.style.height = (height - 20) +"px";
            adressFrame.content.style.width =  width + "px";
            adressFrame.content.style.overflow = "auto";
            
            var content = "<div><ul class='searchresults'>";
            
            for(var i=0; i<result.Placemark.length; i++) 
            {
                var adressArray = result.Placemark[i].address.split(",");
        		
        		var adress = "";
        		
        		for(var j=0; j<adressArray.length -1; j++) 
        		{
        		    adress += adressArray[j] + "<br />";
        		}
        		
        		if(adress != "")
        		{
        		  content += "<li class='searchresult' onmouseover='this.className=\"searchresult selected\"' onmouseout='this.className=\"searchresult\"' onclick='showAdress(" + result.Placemark[i].Point.coordinates[1] + "," + result.Placemark[i].Point.coordinates[0] + ",\"" + adress + "\")'>" + adress + "</li>";
        		}
            }
            
            content += "</ul></div>";
            
            adressFrame.content.innerHTML = content;
		}
	}
	else
	{
		myAlert("Es wurde keine Adresse gefunden !");
	}
	
	hideSearchWaitDiv();
}

function showAdress(lat,lon,text)
{
    if(adressMarker)
    {
        map.closeInfoWindow();
        map.removeOverlay(adressMarker);
        adressMarker = null;
    }
    
    var center = new GLatLng(parseFloat(lat),parseFloat(lon));
    
    adressMarker = new GMarker(center,pinIcon); 
    		
    map.addOverlay(adressMarker);
    
    map.setCenter(center,15);
    
    adressMarker.openInfoWindowHtml(text);
}

function setCenterMarker()
{
    if(centerMarker)
    {
        if(centerMarkerEventHandle)
        {
            GEvent.removeListener(centerMarkerEventHandle);
            centerMarkerEventHandle = null;
        }
        map.removeOverlay(centerMarker);
        centerMarker = null;
    }
    
    if(isMeasureMode)
    {
       stopMeasuring();
    }
    
    if(isInfoMode)
    {
        stopInfoMode();
    }
    
    if(isDatingMode)
    {
        stopDatingMode();
    }
    
    if(isZoomPlusMode)
    {
        stopZoomPlusMode();
    }
    
    if(isRoutingMode)
    {
        stopRoutingMode();
    }
        
    if(!centerDialog || centerDialog.isDestroyed())
    {
        centerDialog = new TGDialog("Tipp",{parentElement:$("mapDivision"),width:200});     
        centerDialog.setContent("<p>Der Mittelpunkt wird automatisch in der Mitte der Karte platziert. Sie k&ouml;nnen ihn jedoch verschieben.</p>")
    }
    centerDialog.moveToCenter();
    centerDialog.show();
        
    centerMarker = new GMarker(map.getCenter(),{draggable:true});

    centerMarkerEventHandle = GEvent.addListener(centerMarker,"dragend",removeCircleMarkers);

    map.addOverlay(centerMarker);
}

function removeCircleMarkers()
{
    if(circleMarkers)
    {
        for(var j=0; j<circleMarkers.length; j++) 
        {
            map.removeOverlay(circleMarkers[j]);
            //overviewMapControl.getOverviewMap().removeOverlay(overviewCircleMarkers[j]);
        }
        circleMarkers = null;
        overviewCircleMarkers = null;
    }
    
    if(circleResponse)
    {
       var res = eval('(' + circleResponse.responseText + ')');
       
       for(var i =0; i < res.length; i++) 
       {
           speedMarkers.removeId(res[i].id);
       }
        
       speedMarkers.redraw(true);
        
       circleResponse = null;
    }
}

function removeCenterMarker()
{
    if(centerMarker)
    {
        if(centerMarkerEventHandle)
        {
            GEvent.removeListener(centerMarkerEventHandle);
            centerMarkerEventHandle = null;
        }
        map.removeOverlay(centerMarker);
        centerMarker = null;
    }
}

function searchCircumference()
{
	var cb = $("seDistance");
    var selectedIndex = cb.selectedIndex;
    
    var distance = cb.options[selectedIndex].value;
    
    var cb2 = $("seCats");
    var selectedIndex2 = cb2.selectedIndex;
    
    var subCatId = cb2.options[selectedIndex2].value;
    
    var center = null;
    removeCircleMarkers();
    if(centerMarker)
    {
       center = centerMarker.getPoint();
    }
    else
    {
       center = map.getCenter();    
       centerMarker = new GMarker(center,{draggable : true});
       centerMarkerEventHandle = GEvent.addListener(centerMarker,"dragend",removeCircleMarkers);
       map.addOverlay(centerMarker);
    }
    circleMarkers = new Array();
    overviewCircleMarkers = new Array();
    var gradient = new TGGradient(new TGColor(255,0,0),new TGColor(255,255,0),selectedIndex+1);
    
    circleMarkers[0] = new TGCircle(center,parseFloat(cb.options[0].value),gradient.colors[0].toString(),0.5,0.5,gradient.colors[0].toString(),0.5);
    overviewCircleMarkers[0] = circleMarkers[0].copy();
    
    map.addOverlay(circleMarkers[0]);
    //overviewMapControl.getOverviewMap().addOverlay(overviewCircleMarkers[0]);
    
    for(var i=1; i <= selectedIndex; i++) 
    {	  
        circleMarkers[i] = new TGRing(center,parseFloat(cb.options[i-1].value),parseFloat(cb.options[i].value),gradient.colors[i].toString(),0.5,(1/selectedIndex) * i,gradient.colors[i].toString(),0.5);  
        overviewCircleMarkers[i] = circleMarkers[i].copy();      
    	map.addOverlay(circleMarkers[i]);
    	//overviewMapControl.getOverviewMap().addOverlay(overviewCircleMarkers[i]);
    }
    
    var myAjax = new Ajax.Request
    (
		serverUrl + 'php/ajax_control.php', 
		{
			   method: 'POST', 
			   parameters: "functionId=13&subcat=" + subCatId + "&lat=" + center.lat() + "&lon=" + center.lng() + "&dist=" + distance/2.0 +  "&mandant=" + mandant, 
			   onSuccess: callbackSearchCircumference,
			   onLoading: showSearchWaitDiv,
			   onLoaded: hideSearchWaitDiv,
    		   onFailure: hideSearchWaitDiv
		}
	);
}

function callbackSearchCircumference(request)
{
    circleResponse = request;
    
    var res = eval('(' + request.responseText + ')');
     
    if(tgSelectBox.getSize() > 0)
	{
	   tgSelectBox.clearList();
	}
    
    var anz_Objekte = 0;
    
    if(res && (res.length > 0))
	{   
        var cb2 = $("seCats");
        var selectedIndex2 = cb2.selectedIndex;
    
        var subCatName = cb2.options[selectedIndex2].text;
    
        $('infoCatName').innerHTML = subCatName;
        
        showSearchWaitDiv();
	
    	for(var i =0; i < res.length; i++) 
        {
            speedMarkers.addId(res[i].id);
        }
        
        speedMarkers.redraw(true);
        
    	var filterEntries = $('filter_entries').checked;
    	 
    	var bounds = null;
    	
    	if(filterEntries)    
    	{
    	   bounds = map.getBounds();
    	}
    	
    	for(var i = 0;i < res.length;i++)
    	{	
    		var insert = true;
    		
    		if(infoBoxFilter != "")
    		{
                   if(unescape(res[i].tooltip).toLowerCase().indexOf(infoBoxFilter.toLowerCase()) == -1)  
                   {
                       insert = false;
                   }
    		}
    		
    		if(insert)
    		{
        		   if(filterEntries)
        		   {        
        	              var point = new GLatLng(parseFloat(res[i].lat), parseFloat(res[i].lon));
        	       
        	              if(bounds.contains(point))     
        	              {
        	                 var oOption = new TGItem(unescape(res[i].tooltip),unescape(res[i].info),res[i].id + ';' + res[i].gtyp,unescape(res[i].tooltip));
                	         oOption.icon = res[i].image;
                	         tgSelectBox.addElement(oOption);	           
                             anz_Objekte++;
        	              }
        		   }
        		   else
        		   {
        		       var oOption = new TGItem(unescape(res[i].tooltip),unescape(res[i].info),res[i].id + ';' + res[i].gtyp,unescape(res[i].tooltip));
                	   oOption.icon = res[i].image;
                	   tgSelectBox.addElement(oOption);	        
                       anz_Objekte++;   
        		   }
    		}
    		
    	}
    	
    	Element.show('infoPanel');
    	Element.show('infoContent');
        if(anz_Objekte == 1)
        {
            $('infoCatAnzahl').innerHTML = anz_Objekte + ' Objekt';
        }
        else
        {
            $('infoCatAnzahl').innerHTML = anz_Objekte + ' Objekte';
        }
        infoWindow.setHandleIconMinus(0);
	}
	else
	{
	    myAlert("Es wurden keine Ergebnisse zur&uuml;ckgeliefert !");
	}
	
    hideSearchWaitDiv();
}

function mapup()
{
	if(isMeasureMode) map.enableDragging();
    map.panDirection(0, 1);
	if(isMeasureMode) map.disableDragging();
}

function mapdown()
{
	if(isMeasureMode) map.enableDragging();
    map.panDirection(0, -1);
	if(isMeasureMode) map.disableDragging();
}

function mapright()
{
	if(isMeasureMode) map.enableDragging();
    map.panDirection(-1, 0);
	if(isMeasureMode) map.disableDragging();
}

function mapleft()
{
	if(isMeasureMode) map.enableDragging();
    map.panDirection(1, 0);
	if(isMeasureMode) map.disableDragging();
}

function onMapTypeChanged()
{
    slider1.setMax(map.getCurrentMapType().getMaximumResolution(map.getCenter()));    
}

function onZoomed(oldLevel,newLevel)
{
    addPosition(new TGPosition(map.getCenter(),newLevel));
    if(debug) GLog.write("Zoomed !");
    slider1.setValue(newLevel);
}

function onMoved()
{
    addPosition(new TGPosition(map.getCenter(),map.getZoom()));
}

function addPosition(pos)
{
    if(undoArray.length > 0)
    {
        if(!undoArray[undoArray.length -1].equals(pos))
        {
            undoArray[undoArray.length] = pos;
        }
    }
    else
    {
        undoArray[undoArray.length] = pos;
    }
}
 
function checkZoomLevel(oldLevel,newLevel)
{
    var highest = map.getCurrentMapType().getMaximumResolution(map.getCenter());
    
    if(newLevel >= highest)
    {
        var wmsActive = false;
        if(wmsArray)
        {
            for(var i=0;i < wmsArray.length;i++)
            {
                if(wmsArray[i].overlay.image)
                {
                    wmsActive = true;
                    break;
                }
            }
        }
        
        var mapTypes = map.getMapTypes();
        
        var va = highest;
        var index = -1;
        
        for(var i = 0; i < mapTypes.length;i++)
        {
            var v = mapTypes[i].getMaximumResolution(map.getCenter());
            if(v > highest)
            {
                va = v;
                index = i;
                break;
            }
        }
        
        if(mapTypes[index] == G_EMPTY_MAP)
        {
            if(wmsActive)
            {
                if(map.getCurrentMapType() != G_EMPTY_MAP)
                {
                    previousMapType = map.getCurrentMapType();
                }
                map.setMapType(G_EMPTY_MAP);
            }
            else
            {
                checkZoomFlag = false;
                map.setZoom(highest);        
            }
        }
        else
        {
            map.setMapType(mapTypes[index]);
        }
               
    } 
    else if(newLevel < oldLevel)
    {
        if(previousMapType)
        {
             if(previousMapType.getMaximumResolution(map.getCenter()) <=  newLevel)
             {
                 map.setMapType(previousMapType);
                 previousMapType = null;
             }   
        }
    }
  
}

function changeScale()
{
    map.setZoom(slider1.value);
}

function measure()
{
    showSearchWaitDiv();
	
	if(isInfoMode)
	{
	   stopInfoMode();
	}
	
	if(isRoutingMode)
	{
	   stopRoutingMode();    
	}
	
	if(isDatingMode)
	{
	    stopDatingMode();
	}
	    
    if(isZoomPlusMode)
    {
        stopZoomPlusMode();
    }
        
    if (isMeasureMode == false)
	{	
	    if(measureDialog && !measureDialog.isDestroyed())
        {
            measureDialog.destroy();
            measureDialog = null;
        }
    
        measureDialog = new TGDialog("Messen",{parentElement:$("mapDivision"),width:200,closeFunction : stopMeasuring});
    
        measureDialog.setContent("<br /><input type='text' id='measure' style='width:50px;' value='0' /><span id='unit' style='padding-left:3px;font-size: 8pt;'>m</span><br /><br /><img src='images/ml_down.gif' id='ml' style='border:none;' onclick='setMeasureType(0);' title='Distanz messen' onmouseover='ml_button_onmouseover(this);' onmouseout='changeMLIcon(this,\"ml\");' /><img src='images/ma.gif' id='ma' style='border:none;' onclick='setMeasureType(1);' title='Fl&auml;che messen' onmouseover='ma_button_onmouseover(this);' onmouseout='changeMAIcon(this,\"ma\");' /><img src='images/mr.gif' id='mr' style='border:none;' onclick='deleteMeasureOverlay();' title='Auswahl l&ouml;schen' onmouseover='mr_button_onmouseover(this);' onmouseout='mr_button_onmouseout(this);' />");
        measureDialog.moveToCenter();
        measureDialog.show();
		isMeasureMode = true;
	    $("measureButton").src = 'images/skins/'+ config.skin +'/measure_down.gif';
	    
	    map.disableDragging();

	    $('mapDivision').style.cursor = 'crosshair';
		
	    
	    measureHandle = GEvent.addListener(map, "click", addMeasureMarker);
	}
	else
	{
		if(measureDialog && !measureDialog.isDestroyed())
        {
            measureDialog.destroy();
            measureDialog = null;
        }
    
        $("measureButton").src = 'images/skins/'+ config.skin +'/measure.gif';
    
        $('mapDivision').style.cursor = '';
        map.enableDragging();
        if(measureHandle)
        {
            GEvent.removeListener(measureHandle);
            measureHandle = null;
        }
    
        deleteMeasureOverlay();   
    
        isMeasureMode = false;
	}
	 
	hideSearchWaitDiv();
}


function search()
{

    showSearchWaitDiv();
	
    if (isSearchMode == false)
	{	
	
		isSearchMode = true;
	    $("searchButton").src = "images/search2_down.gif";
	    
	   
	    infoWindow.setHandleIconMinus(2);
		Element.show('searchPanel');
		Element.show('searchContent');
		
	  
	}
	else{
    
	    $("searchButton").src = "images/search2.gif";

	    
	    isSearchMode = false;
		
		infoWindow.setHandleIconMinus(2);
		Element.hide('searchPanel');
		Element.hide('searchContent');
	}
	hideSearchWaitDiv();
}


function addMeasureMarker(marker, point)
{
    if(cancelNextClick)
    {
        cancelNextClick = false;   
    }
    else
    {
        if (marker) 
        {
             // Pruefen ob auf einen Marker oder ein Polygon 
            // geklickt wurde (Version >= 2.88)
            if(marker instanceof GMarker)
            {
               for(var i = 0;i < measureMarkers.length;i++)
               {   
                   var point = measureMarkers[i].getPoint();
                   if((point.lat() == marker.getPoint().lat()) && (point.lng() == marker.getPoint().lng()) )
                   {
                       measureMarkers[i] = null;
                       map.removeOverlay(marker);
                       break;
                   }
               }
               measureMarkers = measureMarkers.compact();
            }
        } 
        else 
        {
            if(measureMarkers.indexOf(point) < 0)
            {
                var icon = new GIcon(stdicon2, "images/point_marker.gif" , null, null); 
                
                var marker = new GMarker(point,{icon:icon, draggable:true,bouncy:false});
                GEvent.addListener(marker,"drag",dragPoly);
                GEvent.addListener(marker,"dragend",dragEndPoly);
                measureMarkers[measureMarkers.length] = marker;
                map.addOverlay(marker);
            }
        }
                
        redrawPoly();
    }
}

function dragEndPoly()
{
    cancelNextClick = true;   
}
function dragPoly()
{
    redrawPoly();
}

function redrawPoly()
{
    if(lastPolygonOverLay)
    {
       map.removeOverlay(lastPolygonOverLay);
       lastPolygonOverLay = null;
    }
    
    var distance = 0;
    
    var pointArray = new Array();
    
    for(var i = 0;i < measureMarkers.length;i++)
    {
      if(i > 0)
      {
         if(!measureArea)
         {
            distance += measureMarkers[i-1].getPoint().distanceFrom(measureMarkers[i].getPoint());
         }
      }
      pointArray[pointArray.length] = measureMarkers[i].getPoint();
    } 
    
    var polyline = null;
        
    if(measureArea)
    {
        if(!isLineClosed(pointArray))
        {
            if(pointArray.length > 1)
            {
                pointArray[pointArray.length] = pointArray[0];
            }
        }
        polyline = new GPolygon(pointArray,  "#FF0000", 5,  0.5,"#FF0000",  0.5);
    }
    else
    {
        polyline = new GPolyline(pointArray, "#FF0000", 5);   
    }
        
    map.addOverlay(polyline);   
    
    var area = 0;
    
    if(measureArea)
    {
        area = calculateArea(pointArray);
        
        if(area > (1000000))
        {
            area /= 1000000;
            $('unit').innerHTML = 'km&sup2;'
        }
        else
        {
            $('unit').innerHTML = 'm&sup2;'
        }
        
        $('measure').value = Math.round(area * 100) /100;
    }
    else
    {
        if(distance > 1000)
        {
            distance /= 1000;
            $('unit').innerHTML = 'km'
        }
        else
        {
            $('unit').innerHTML = 'm'
        }
        
        $('measure').value = Math.round(distance * 100) /100;
    }
    
    
    lastPolygonOverLay = polyline;
}

function stopMeasuring()
{
    if(measureDialog && !measureDialog.isDestroyed())
    {
        measureDialog.destroy();
        measureDialog = null;
    }
    
    $("measureButton").src = 'images/skins/'+ config.skin +'/measure.gif';
    
    $('mapDivision').style.cursor = '';
    map.enableDragging();
    if(measureHandle)
    {
        GEvent.removeListener(measureHandle);
        measureHandle = null;
    }
    
    deleteMeasureOverlay();   
    
    isMeasureMode = false;
}

function deleteMeasureOverlay()
{
    $('measure').value = "0";
    
    if(lastPolygonOverLay)
    {
        map.removeOverlay(lastPolygonOverLay);
        lastPolygonOverLay = null;
        
        measureMarkers.each(function(item)
        {
           map.removeOverlay(item) ;
        });
        
        measureMarkers.clear();
    }
}

function isLineClosed(points)
{
    if(points.length > 1)
    {
      var pointStart = points[0];
      var pointEnd = points[points.length -1];
    
      return(pointStart.equals(pointEnd));
    }
    return false;
}


function printmap() 
{
 window.open("googis_print.html", "printWindow", "width=750,height=700,dependent=yes,location=no,menubar=no,toolbar=no,scrollbars=yes");	
}

function infoClicked(event,catId,gtyp,obj)
{
    unhighlightMarkerFunction();
    if(debug) GLog.write("gtyp : " + gtyp + "\n");
    selectBoxCatId = catId;
    infoBoxGTyp = gtyp;
    
    var myAjax = new Ajax.Request
	(
		serverUrl + 'php/ajax_control.php', 
		{
			   method: 'POST', 
			   parameters: 'functionId=7&catId=' + catId + '&gtyp=' + gtyp + '&mandant=' + mandant, 
			   onSuccess: callbackInfoClicked,
			   onLoading: showSearchWaitDiv,
    		   onLoaded:  hideSearchWaitDiv,
    		   onFailure: hideSearchWaitDiv
		}
	);
}

function callbackInfoClicked(request)
{
    showSearchWaitDiv();

    var res = eval('(' + request.responseText + ')');
    
	$('infoCatName').innerHTML = unescape(res[0].kategorie);
	
	var filterEntries = $('filter_entries').checked;
	
	if(tgSelectBox.getSize() > 0)
	{
	   tgSelectBox.clearList();
	}
	 
	var bounds = null;
	
	if(filterEntries)    
	{
	   bounds = map.getBounds();
	}
	
    var anz_Objekte;
	anz_Objekte = 0;

	for(var i = 0;i < res.length;i++)
	{	
		var insert = true;
		
		if(infoBoxFilter != "")
		{
               if(unescape(res[i].anzeigename).toLowerCase().indexOf(infoBoxFilter.toLowerCase()) == -1)  
               {
                   insert = false;
               }
		}
		
		if(insert)
		{
    		   if(filterEntries)
    		   {        
    	              var point = new GLatLng(parseFloat(res[i].lat), parseFloat(res[i].lon));
    	       
    	              if(bounds.contains(point))     
    	              {
    	                 var oOption = new TGItem(unescape(res[i].anzeigename),unescape(res[i].tooltip),res[i].markerId + ';' + res[i].gtyp);
                	     oOption.icon = res[i].icon;
                	     tgSelectBox.addElement(oOption);	      
                         anz_Objekte++;     
       	              }
    		   }
    		   else
    		   {
    		       var oOption = new TGItem(unescape(res[i].anzeigename),unescape(res[i].tooltip),res[i].markerId + ';' + res[i].gtyp);
                   oOption.icon = res[i].icon;
                   tgSelectBox.addElement(oOption);
                   anz_Objekte++;	           
    		   }
		}
		
	}
	
	Element.show('infoPanel');
	Element.show('infoContent');
    if(anz_Objekte == 1)
    {
       $('infoCatAnzahl').innerHTML = anz_Objekte + ' Objekt';
    }
    else
    {
       $('infoCatAnzahl').innerHTML = anz_Objekte + ' Objekte';
    }
    infoWindow.setHandleIconMinus(0);
    hideSearchWaitDiv();
}

function filterEntriesClicked(checked)
{
   if(infoBoxGTyp != -1)    
   infoClicked(null,selectBoxCatId,infoBoxGTyp,null);   
}

function onInfoWindowClosed()
{
    unhighlightMarkerFunction();
}

function highlightMarkerFunctionIE(a,b)
{
    unhighlightMarkerFunction();
    if(debug) GLog.write("highlightMarkerFunctionIE : " + b);
    
    var vArray = b.value.split(";");
    
    highlightMarkerFunction(vArray[0],vArray[1]);
}

function highlightMarkerFunction(a,b)
{
    if(debug) GLog.write("Higlight : " + a + "    " + b);
    
    if((b == 1) || (b == 0))
	{
    	  
	       var myAjax = new Ajax.Request
           (
        		serverUrl + 'php/ajax_control.php', 
        		{
        			   method: 'POST', 
        			   parameters: 'functionId=12&mandant=' + mandant + "&markerId=" + a, 
        			   onSuccess: callbackHighlightMarker,
        			   onLoading: showSearchWaitDiv,
            		   onLoaded:  hideSearchWaitDiv,
            		   onFailure: hideSearchWaitDiv
        		}
           );       
	 }
	 else if(b == 2)
	 {
	      var tmpPolygon = null;
	      
	      for(var i = 0;i < polylineArray.length;i++)
	      {
	          if(polylineArray[i].optId == parseInt(a))
	          {
	             tmpPolygon = polylineArray[i];        
	             break;
	          }
	      }
	      
	      if(tmpPolygon)
    	  {
    	       var pntList = new Array();
    	       
    	       for(var i=0; i<tmpPolygon.polyline.getVertexCount(); i++) 
    	       {
    	           pntList[i] = tmpPolygon.polyline.getVertex(i);
    	       }
    	       
    	       var polyline = new GPolyline(pntList,"#FF0000","5");
    	       highlightPolyline = new IdWrapper(polyline,tmpPolygon.optId);
    	       map.addOverlay(highlightPolyline.obj);
    	  }
	  }
	  else if(b == 3)
	  {
	      var tmpPolygon = null;
	      
	      for(var i = 0;i < polygonArray.length;i++)
	      {
	          if(polygonArray[i].optId == parseInt(a))
	          {
	             tmpPolygon = polygonArray[i];        
	             break;
	          }
	      }
	      
	      if(tmpPolygon)
    	  {
    	       var pntList = new Array();
    	       
    	       for(var i=0; i<tmpPolygon.polygon.getVertexCount(); i++) 
    	       {
    	           pntList[i] = tmpPolygon.polygon.getVertex(i);
    	       }
    	       
    	       var polygon  = new GPolygon(pntList,"#FF0000","5");
    	       highlightPolygon = new IdWrapper(polygon,tmpPolygon.optId);
    	       map.addOverlay(highlightPolygon.obj);
    	  }
	  } 
}

function callbackHighlightMarker(request)
{
     var res = eval('(' + request.responseText + ')');
       
      var w = parseInt(res.mark_width);
      var h = parseInt(res.mark_height);
      
      var mIcon  = new GIcon();
 	  mIcon.iconSize=new GSize(w,h);
	  mIcon.iconAnchor=new GPoint( w/2 + parseInt(res.mark_offset_x), h/2 + parseInt(res.mark_offset_y));
	  mIcon.infoWindowAnchor=new GPoint(w /2,0);
	  
	  var icon = new GIcon(mIcon,unescape(res.mark_image) , null, null); 
	  
	  var p = new GLatLng(parseFloat(res.lat), parseFloat(res.lon));
      
      //highlightMarker = new TGMarker(p,icon,res.id,"",function(){return 2000});
      //map.addOverlay(highlightMarker.marker); 
}

function unhighlightMarkerFunction()
{
    try
    {
        if(debug) GLog.write("Hide Highlight");
        if(highlightMarker) 
        {
           map.removeOverlay(highlightMarker.marker);
           highlightMarker = null;
        }
    
        if(highlightPolyline) 
        {
           map.removeOverlay(highlightPolyline.obj);
           highlightPolyline = null;
        }
    
        if(highlightPolygon) 
        {
           map.removeOverlay(highlightPolygon.obj);
           highlightPolygon = null;
        }

    }
    catch(e)
    {}
}



function infoBoxFilterChanged(event)
{
   infoBoxFilter = $F('filterString');
   
   if(infoBoxGTyp != -1)
   infoClicked(null,selectBoxCatId,infoBoxGTyp,null);
}

function infoBoxDblClicked()
{
    var sel = tgSelectBox.getSelectedIndex();
    
    if(sel > -1)
	{
	  var value = tgSelectBox.getSelectedItem().value;
	  if(debug) GLog.write('infoBoxDblClicked:' + sel +","+ value );
	  
	  var res = value.split(';');
	  
	  if(debug) GLog.write('infoBoxDblClicked res : ' + res[1] + '\n');
	  
	  if((res[1] == 1) || (res[1] == 0))
	  {
    	  
	      if(lastMarkerId)
	      {
	          speedMarkers.removeId(lastMarkerId);
	      }
	      
	      lastMarkerId = res[0];
	      
	      var myAjax = new Ajax.Request
          (
        		serverUrl + 'php/ajax_control.php', 
        		{
        			   method: 'POST', 
        			   parameters: 'functionId=8&markerId=' + res[0] + '&gtyp=' +  res[1] + '&mandant=' + mandant, 
        			   onSuccess: callbackInfoBoxDblClicked,
        			   onLoading: showSearchWaitDiv,
            		   onLoaded:  hideSearchWaitDiv,
            		   onFailure: hideSearchWaitDiv
        		}
          );
    	  
	  }
	  else if(res[1] == 2)
	  {
	      var tmpPolygon = null;
	      
	      for(var i = 0;i < polylineArray.length;i++)
	      {
	          if(polylineArray[i].optId == parseInt(res[0]))
	          {
	             tmpPolygon = polylineArray[i];        
	             break;
	          }
	      }
	      
	      if(tmpPolygon)
    	  {
    	       map.setCenter(tmpPolygon.polyline.getVertex(0),13);
    	    
               showPolygonVCardById(tmpPolygon,2);
    	  }
	      else
	      {
    	      var myAjax = new Ajax.Request
              (
            		serverUrl + 'php/ajax_control.php', 
            		{
            			   method: 'POST', 
            			   parameters: 'functionId=8&markerId=' + res[0] + '&gtyp=' +  res[1] + '&mandant=' + mandant, 
            			   onSuccess: callbackInfoBoxDblClicked,
            			   onLoading: showSearchWaitDiv,
                		   onLoaded:  hideSearchWaitDiv,
                		   onFailure: hideSearchWaitDiv
            		}
               );
	      }
	  } 
	  else if(res[1] == 3)
	  {
	      var tmpPolygon = null;
	      
	      for(var i = 0;i < polygonArray.length;i++)
	      {
	          if(polygonArray[i].id == parseInt(res[0]))
	          {
	             tmpPolygon = polygonArray[i];        
	             break;
	          }
	      }
	      
	      if(tmpPolygon)
    	  {
    	       map.setCenter(tmpPolygon.getCenter(),16);
    	    
               showPolygonVCardById(tmpPolygon,3);
    	  }
	      else
	      {
    	      var myAjax = new Ajax.Request
              (
            		serverUrl + 'php/ajax_control.php', 
            		{
            			   method: 'POST', 
            			   parameters: 'functionId=8&markerId=' + res[0] + '&gtyp=' +  res[1] + '&mandant=' + mandant, 
            			   onSuccess: callbackInfoBoxDblClicked,
            			   onLoading: showSearchWaitDiv,
                		   onLoaded:  hideSearchWaitDiv,
                		   onFailure: hideSearchWaitDiv
            		}
               );
	      }
	  } 
	  
	  
	}
}

function callbackInfoBoxDblClicked(request)
{
    hideSearchWaitDiv();
    if(debug) GLog.write("callbackInfoBoxDblClicked : " + request.responseText + "\n");
    
    var res = eval('(' + request.responseText + ')');

    
	if((res.gtyp == 1) || (res.gtyp == 0))        	
    {		
        speedMarkers.addId(res.id);
        
        speedMarkers.redraw(true);
        
        if(datingMarker) map.setCenter(point);

        var p =new GLatLng(parseFloat(res.lat),parseFloat(res.lon));
        
        showVCardMap(res.id,parseFloat(res.lat),parseFloat(res.lon));
	}
	else if(res.gtyp == 2)
	{
	    var coords = res.pos.split(',');
	    
	    var coordsArray = new Array();
	    
	    for(var i = 0;i < coords.length;i++)
	    {
	       var tmp = coords[i].split(' ');
	       
	       var point = new GLatLng(parseFloat(tmp[0]),parseFloat(tmp[1]));    
	       
	       coordsArray[coordsArray.length] = point;
	    }
	    

        var poly = createPolyline(res.pos,res.id,res.stcolor,res.stweight,res.stopacity);
        map.addOverlay(poly);
        var tmpPolyline = new TGPolyline(poly,res.id);
       
        map.setCenter(poly.getVertex(0),13);
        showPolygonVCardById(tmpPolyline,2);
	}
	else if(res.gtyp == 3)
	{
	    var coords = res.pos.split(',');
	    
	    var coordsArray = new Array();
	    
	    for(var i = 0;i < coords.length;i++)
	    {
	       var tmp = coords[i].split(' ');
	       
	       var point = new GLatLng(parseFloat(tmp[0]),parseFloat(tmp[1]));    
	       
	       coordsArray[coordsArray.length] = point;
	    }

        var poly = createPolygon(res.pos,res.id,res.stcolor,res.stweight,res.stopacity,res.fcolor,res.fopacity);
        map.addOverlay(poly);
        var tmpPolygon = new TGPolygon(poly,res.id);
        
        map.setCenter(tmpPolygon.getCenter(),16);
        showPolygonVCardById(tmpPolygon,3);
	}
}

function onMouseMoved(point)
{
    $('lat').innerHTML = '<table style="padding-left:10px;font-size: 10pt;">' + formatCoords(point.y,"lat") + formatCoords(point.x,"lon") + "</table><br />";
}
function formatCoords(base,coordType) 
{
    var t, t2;
    var degrees = Math.floor(base);
    var minutes = Math.floor(t = ( base - degrees ) * 60);
    var seconds = Math.floor(t2 = ( t - minutes ) * 6000);
    seconds = seconds / 100.00;
    
    var ret = '<tr><td align="right">' + Math.abs(degrees) + '\u00B0</td><td align="right">' + minutes + '\u0027</td><td align="right" style="width:60px">' + seconds + '\u0022' ;

       
    if(coordType == "lat")
    {
        if(degrees >= 0)
        {
            ret += " N";
        }
        else
        {
            ret += " S";
        }
    }
    else
    {
        if(degrees >= 0)
        {
            ret += " O";
        }
        else
        {
            ret += " W";
        }
    }
    
    ret += "</td></tr>";
    
    return ret;
}

var degreesPerRadian=180.0/Math.PI;
var radiansPerDegree=Math.PI/180.0;
var earthRadiusMeters=6367460.0;
var metersPerDegree=2.0*Math.PI*earthRadiusMeters/360.0;

function calculateArea(points)
{
	var a=0.0;
	for(var i=0;i<points.length;++i)
	{
		var j=(i+1)%points.length;
		var xi=points[i].lng()*metersPerDegree*Math.cos(points[i].lat()*radiansPerDegree);
		var yi=points[i].lat()*metersPerDegree;var xj=points[j].lng()*metersPerDegree*Math.cos(points[j].lat()*radiansPerDegree);
		var yj=points[j].lat()*metersPerDegree;a+=xi*yj-xj*yi;
	}
	return Math.abs(a/2.0);
}

function searchClicked(event,subCat)
{
    if(debug) GLog.write("searchClicked");
    
    if(frame && !frame.isClosed) 
    {
        frame.close();
        frame = null;
    }    

    frame = new TGFrame("Suche",{x: ac.width + 1,y: Event.pointerY(event) - 25,width : 200,height: 70,parentWindow:"mapDivision",draggable : false,opacity: 0.8, contentBackground : "#E4E0D8" });
    frame.content.style.padding = "2px";
    frame.content.innerHTML = unescape(subCat.subCatName) + "<form style='margin-top:0px;' onsubmit='searchCategorie(" + subCat.subCatId + "," + subCat.subCatGTyp + ");return false;' action=''><input type='text' id='tfSearch'>&nbsp;<input type='submit' value='ok' title='In Kategorie suchen ...'></form>";
    
    $('tfSearch').focus();
}

function searchCategorie(subCatId,gtyp)
{
    var t = $F("tfSearch"); 
    
    if(debug) GLog.write("searchCatgeorie : " + subCatId + "," + gtyp + "," + t);
    
    var myAjax = new Ajax.Request
	(
		serverUrl + 'php/ajax_control.php', 
		{
			   method: 'POST', 
			   parameters: 'functionId=10&subCatId=' + subCatId + '&gtyp=' + gtyp + '&sv=' + t + '&mandant=' + mandant, 
			   onSuccess: callbackSearchCategorie,
			   onLoading: showSearchWaitDiv,
    		   onLoaded:  hideSearchWaitDiv,
    		   onFailure: hideSearchWaitDiv
		}
	);
	
	if(frame && !frame.isClosed) 
    {
        frame.close();
        frame = null;
    }
}

function callbackSearchCategorie(request)
{
    if(debug) GLog.write("callbacksearchCatgeorie : " + request.responseText);
    if(request.responseText.length > 2)   
    {
        callbackInfoClicked(request);
    }
    else
    {
        myAlert("Ihre Suche lieferte keine Treffer !");
    }
}

function setMeasureType(t)
{
    if(t==0)
    {
        if(measureArea)
        {
            $("ma").src = 'images/ma.gif';
            $("ml").src = 'images/ml_down.gif';
        
            measureArea = false;
        }
    }
    else if(t==1)
    {
        if(!measureArea)
        {
            $("ml").src = 'images/ml.gif';
            $("ma").src = 'images/ma_down.gif';
        
            if(lastPolygonOverLay)
            {
                map.removeOverlay(lastPolygonOverLay);
                lastPolygonOverLay = null;
            }
            
            measureArea = true;
        }
    }
    
    redrawPoly();
}

function startInfoMode()
{
    if (!isInfoMode)
	{	
	    if(isMeasureMode)
	    {
	       stopMeasuring();
	    }
	 
	    if(isRoutingMode)
	    {
	       stopRoutingMode();    
	    }
	    
	    if(isDatingMode)
	    {
	        stopDatingMode();
	    }
        
        if(isZoomPlusMode)
        {
            stopZoomPlusMode();
        }
	    
		isInfoMode = true;
	    $("info_button").src = 'images/skins/'+ config.skin +'/search2_down.gif';
	     
	    map.disableDragging();

	    $('mapDivision').style.cursor = 'crosshair';
		
	    
	    //Event.observe(map.getPane(G_MAP_MAP_PANE), "click", queryFeatureInfo);
	}
	else
    { 
        stopInfoMode();
    }
}

function stopInfoMode()
{
   if (isInfoMode)
   { 
        $("info_button").src = 'images/skins/'+ config.skin +'/search2.gif';
        
        $('mapDivision').style.cursor = '';
        map.enableDragging();

        //Event.stopObserving(map.getPane(G_MAP_MAP_PANE), "click", queryFeatureInfo);
        
        isInfoMode = false;
   }
}

function queryFeatureInfo(point)
{
    var atLeastOne = false;
    
    if(point)
    {
        var featureArray = new Array();
        
        for(var i=0; i<wmsArray.length; i++) 
        {
          var layer = wmsArray[i];
          
          var layerString = layer.getFeatureInfoString(layer.layers);	
          
          if(layerString != "")
          {
              atLeastOne = true;
              var featureUrl = layer.layers.feature_url;
              
              if(featureUrl == "")
              {
                  featureUrl = layer.layers.wms_url;
              }
              
              featureUrl = featureUrl.replace("\<ip\>", getIP());
			  			// alert(featureUrl);

              
              var bounds = new GLatLngBounds(new GLatLng(parseFloat(layer.layers.miny),parseFloat(layer.layers.minx)),new GLatLng(parseFloat(layer.layers.maxy),parseFloat(layer.layers.maxx)));           
              
              var mapBounds = map.getBounds();
      
              var ne = mapBounds.getNorthEast();  
              var sw = mapBounds.getSouthWest(); 
      
              var c1 = map.fromLatLngToDivPixel(sw);
              var c2 = map.fromLatLngToDivPixel(ne);
      
              var bestFormat = "text/plain";
              
              if(layer.layers.feature_format.indexOf("text/html") > -1)
              {
                  bestFormat = "text/html";
              }
              else if(layer.layers.feature_format.indexOf("text/xml") > -1)
              {
                  bestFormat = "text/xml";
              }
              
              var pixPoint = map.fromLatLngToContainerPixel(point);
              var format="png";
              var featureInfoQuery = unescape(featureUrl) + "REQUEST=GetFeatureInfo&VERSION=1.1.1&SRS=EPSG:4326&INFO_FORMAT=" + bestFormat+ "&LAYERS=" + layerString + "&QUERY_LAYERS=" + layerString + "&BBOX=" + sw.lng()+ "," + sw.lat() + "," + ne.lng() + "," + ne.lat() + "&WIDTH=" + (c2.x - c1.x) + "&HEIGHT=" + (c1.y - c2.y) + "&X=" + pixPoint.x + "&Y=" + pixPoint.y+"&FORMAT=" + format;
              
              featureArray[featureArray.length] = featureInfoQuery;
              
              if(debug) GLog.write("featureInfoQuery : " + featureInfoQuery);
            
          } 
        }   
        
        if(atLeastOne)
        {
            for(var i=0; i<featureArray.length; i++) 
            {
                var featureWindow = window.open(featureArray[i], "featureWindow" + i , "width=400,height=400,dependent=yes,location=no,menubar=no,toolbar=no");	
                featureWindow.focus();     
            }
        }
        else
        {
            myAlert("Sie haben keine Layer f&uuml;r die Abfrage markiert !");
        }
    }
}

function myAlert(message)
{
    if(alertDialog && !alertDialog.isDestroyed())
    {
        alertDialog.destroy();
        alertDialog = null;
    }
    
    alertDialog = new TGDialog("Tipp",{parentElement:$("mapDivision"),width:200});
    
    alertDialog.setContent(message + "<br><p align='center'><input type='button' value='OK' title='Fenster schliessen ...' onclick='closeAlert()' /></p>");
    alertDialog.moveToCenter();
    alertDialog.show();
}

function closeAlert()
{
    if(alertDialog && !alertDialog.isDestroyed())
    {
        alertDialog.destroy();
        alertDialog = null;
    }
}

function startRoutingMode()
{
   if(!isRoutingMode)    
   {
       isRoutingMode = true;
       
        if(isMeasureMode)
	    {
	       stopMeasuring();
	    }
	    
	    if(isInfoMode)
	    {
	        stopInfoMode();
	    }
	    
	    if(isDatingMode)
	    {
	        stopDatingMode();
	    }
        
        if(isZoomPlusMode)
        {
            stopZoomPlusMode();
        }
	    
	    $("routing_button").src = 'images/skins/'+ config.skin +'/routing_down.gif';
	    
	    
        if(routingStart)      
        {
           map.removeOverlay(routingStart);
           routingStart = null;
        }
        
	    if(routingEnd)      
        {
           map.removeOverlay(routingEnd);
           routingEnd = null;
        }
        
        if(route)
        {
            map.removeOverlay(route);
            route = null;
        }
	    
	    routingEventHandle = GEvent.addListener(map, "click", setRoutingPoint);
	    
	    if((!routeDialog) || routeDialog.isDestroyed())
        {
            routeDialog = new TGDialog("Tipp",{parentElement:$("mapDivision"),width:200});
        }
        routeDialog.setContent("Klicken sie in die Karte um einen Startpunkt f&uuml;r die Route festzulegen.");
        routeDialog.moveToCenter();
        routeDialog.show();
   }
   else
   {
       stopRoutingMode();
   }
}

function stopRoutingMode()
{
   if (isRoutingMode)
   { 
        $("routing_button").src = 'images/skins/'+ config.skin +'/routing.gif';
        
        if(direction)
        {
            direction.clear();
        }
        
        if(routingStart)      
        {
           map.removeOverlay(routingStart);
           routingStart = null;
        }
        
	    if(routingEnd)      
        {
           map.removeOverlay(routingEnd);
           routingEnd = null;
        }
	    
        if(routingEventHandle)
        {
           GEvent.removeListener(routingEventHandle);
           routingEventHandle = null;
        }
        
        if(route)
        {
            map.removeOverlay(route);
            route = null;
        }
     
        isRoutingMode = false;
        
        if(routeDialog)
        {
            routeDialog.destroy();
            routeDialog=null;
        }
   }
}

function setRoutingPoint(marker,point)
{
    if(point)
    {
         if(!routingStart)   
         {
             if((!routeDialog) || routeDialog.isDestroyed())
             {
                 routeDialog = new TGDialog("Tipp",{parentElement:$("mapDivision"),width:200});
             }
             routeDialog.setContent("Klicken sie in die Karte um das Ziel der Route festzulegen.");
             routeDialog.moveToCenter();
             routeDialog.show();
             
             var startIcon = new GIcon(stdicon,"http://maps.google.com/mapfiles/kml/pal4/icon62.png" , null, null); 
             //var startIcon = new GIcon(stdicon4,"http://www.google.com/intl/de_ALL/mapfiles/dd-start.png" , null, null);
             routingStart = new GMarker(point,{draggable : true,icon : startIcon});
             map.addOverlay(routingStart);
         }
         else if(!routingEnd)
         {
             if((!routeDialog) || routeDialog.isDestroyed())
             {
                 routeDialog = new TGDialog("Tipp",{parentElement:$("mapDivision"),width:200});
             }
             routeDialog.setContent("<p>Verschieben sie evtl. ihre Start- und Zielpunkte, und klicken sie auf 'OK' .</p><p align='center'><input type='button' value='OK' title='Route berechnen' onclick='calculateRoute();' /></p>");
             routeDialog.moveToCenter();
             routeDialog.show();
                          
             var endIcon = new GIcon(stdicon,"http://maps.google.com/mapfiles/kml/pal4/icon15.png" , null, null); 
             //var endIcon = new GIcon(stdicon4,"http://www.google.com/intl/de_ALL/mapfiles/dd-end.png" , "http://www.google.com/intl/de_ALL/mapfiles/shadow50.png", null);
             routingEnd = new GMarker(point,{draggable : true,icon : endIcon});
             map.addOverlay(routingEnd);
         }
    }
}

function calculateRoute()
{       
    if(routeDialog)
    {
        routeDialog.destroy();
        routeDialog = null;
    }
    
    routeDialog = new TGDialog("Route",{parentElement:$("mapDivision"),width:300,height:350});
    routeDialog.setContent("<div id='routeInfo' style='height:300px;overflow:auto;'></div>");
    routeDialog.moveToCenter();
    
    direction = new GDirections(map,$("routeInfo"));
    var query = "from: " + routingStart.getPoint().toUrlValue() + " to: " + routingEnd.getPoint().toUrlValue();
     
    direction.load(query, { locale: "de",getPolyline : true,preserveViewport : true,getSteps:true});
    GEvent.addListener(direction, "load", onGDirectionsLoad);   
}

function onGDirectionsLoad()
{   
    map.removeOverlay(routingEnd);
    
    map.removeOverlay(routingStart);
    
    routeDialog.show();
}

function startZoomPlusMode()
{
     if (!isZoomPlusMode)
	{	
	    if(isMeasureMode)
	    {
	       stopMeasuring();
	    }
	 
	    if(isRoutingMode)
	    {
	       stopRoutingMode();    
	    }
	    
	    if(isDatingMode)
	    {
	        stopDatingMode();
	    }
	    
	    if(isInfoMode)
	    {
	        stopInfoMode();
	    }
	    
		isZoomPlusMode = true;
        
	    $("zoomplus_button").src = 'images/skins/'+ config.skin +'/zoomplus_down.gif';
	     
	    
        tgZoom.activate();
        
	}
	else
    { 
        stopZoomPlusMode();
    }   
}

function stopZoomPlusMode()
{
   if (isZoomPlusMode)
   { 
        tgZoom.deactivate();
        
        $("zoomplus_button").src = 'images/skins/'+ config.skin +'/zoomplus.gif';
        
        isZoomPlusMode = false;
   }
}

function startDatingMode()
{
    if (!isDatingMode)
	{	
	    if(isMeasureMode)
	    {
	       stopMeasuring();
	    }
	 
	    if(isRoutingMode)
	    {
	       stopRoutingMode();    
	    }
	    
	    if(isDatingMode)
	    {
	        stopDatingMode();
	    }
	    
	    if(isInfoMode)
	    {
	        stopInfoMode();
	    }
        
        if(isZoomPlusMode)
        {
            stopZoomPlusMode();
        }
	    
		isDatingMode = true;
	    $("dating_button").src = 'images/skins/'+ config.skin +'/date_down.gif';
	     
	    map.disableDragging();
             
	    datingEventHandle = GEvent.addListener(map, "click", createDatingPoint);
	    
	    $('mapDivision').style.cursor = 'crosshair';
		
	    if((!dateDialog) || dateDialog.isDestroyed())
        {
           dateDialog = new TGDialog("Tipp",{parentElement:$("mapDivision"),width:200});
        }
        
        dateDialog.setContent("Klicken sie in die Karte um einen Treffpunkt festzulegen.");
        dateDialog.moveToCenter();
        dateDialog.show();
	}
	else
    { 
        stopDatingMode();
    }
}

function stopDatingMode()
{
   if(dateDialog)
   {
       dateDialog.destroy();
       dateDialog = null;
   }
   
   if(datingMarker)
   {
       map.removeOverlay(datingMarker);
       datingMarker = null;
   }
    
   if (isDatingMode)
   { 
        $("dating_button").src = 'images/skins/'+ config.skin +'/date.gif';
        
        $('mapDivision').style.cursor = '';
        map.enableDragging();

        if(datingEventHandle)
        {
           GEvent.removeListener(datingEventHandle);
           datingEventHandle = null;
        }
        
        isDatingMode = false;
   }
}

function createDatingPoint(marker,point)
{
    if(point)
    {
       if(dateDialog)
       {
          dateDialog.destroy();
          dateDialog = null;
       }
    
       if(datingEventHandle)
       {
           GEvent.removeListener(datingEventHandle);
           datingEventHandle = null;
       }
    
    
         if(datingMarker)
         {
             map.removeOverlay(datingMarker);
             datingMarker = null;
         }
         
         datingMarker = new GMarker(point,{draggable : true,icon : dateIcon});
         map.addOverlay(datingMarker);
         
         dateDialog = new TGDialog("Tipp",{parentElement:$("mapDivision"),width:200,closeFunction:stopDatingMode});
        
         dateDialog.setContent("<br>Empf&auml;nger :<br><input id='receiver' type='text'><br><br>Ihre Nachricht :<br><textarea id='datingTextMessage' cols='21' rows='5'></textarea><p align='center'><input type='button' value='OK' title='Treffpunkt per Mail verschicken' onclick='sendDatingPoint();' /></p>");
         dateDialog.moveToCenter();
         dateDialog.show();
    }
}

function sendDatingPoint()
{
    var encodedSelection = catMenu.getEncodedSelection();
    
    var encodedLayerStrings = "";
    
    for(var i = 0;i < wmsArray.length;i++)
    {
        var els = wmsArray[i].getEncodedLayers();
        
        if(els != "")
        {
            if(encodedLayerStrings != "") encodedLayerStrings += ",";
            encodedLayerStrings +='{"t":"' + wmsArray[i].layers.title + '","a":' + els + '}';   
			if (debug) {
				GLog.write("EncodedLayers: "+els);
				GLog.write("an URL: "+wmsArray[i].layers.wms_url);
			}

		}
	}
    
    encodedLayerStrings = "[" + encodedLayerStrings + "]";
    var b64LayerStrings = escape(Tool.encode(encodedLayerStrings));
     
    var mty = map.getCurrentMapType().getName(false);
    var datingMessage = $F('datingTextMessage');
    datingMessage = Tool.encode(datingMessage);
    
    var receiver = $F('receiver');
    
    var bodyHtml = "\nIhnen wurde ein Googis-Treffpunkt geschickt :\n\n";
    
    //bodyHtml += "http://" + window.parent.location.hostname + window.parent.location.pathname + "?dpLat=" + datingMarker.getPoint().lat() + "&dpLon=" + datingMarker.getPoint().lng() + "&z=" + map.getZoom() + "&m=" + escape(datingMessage) + "&mty=" + mty + "&ew=" + b64LayerStrings;
    bodyHtml += "http://" +server+"/"+mandant+"?dpLat=" + datingMarker.getPoint().lat() + "&dpLon=" + datingMarker.getPoint().lng() + "&z=" + map.getZoom() + "&m=" + escape(datingMessage) + "&mty=" + mty + "&ew=" + b64LayerStrings;
            
    
    if(encodedSelection != "")
    {
       bodyHtml += "&es=" + encodedSelection; 
    }
    
    try
    {
       window.location.href = "mailto:" + receiver + "?subject=Googis%20Treffpunkt&body=" + escape(bodyHtml) ; 
    }
    catch(e)
    {
        myAlert("Das Versenden ist aufgrund ihrer Sicherheitseinstellungen ihres Browers nicht möglich !");
    }
    
    
    if(datingMarker)
    {
       map.removeOverlay(datingMarker);
       datingMarker = null;
    }
         
    stopDatingMode();
}

function startTrackingMode()
{
    if (!isTrackingMode)
	{	
		isTrackingMode = true;
	    $("tracking_button").src = 'images/skins/'+ config.skin +'/tracking_down.gif';
	     
	    if((!trackingDialog) || trackingDialog.isDestroyed())
        {
           trackingDialog = new TGDialog("Tracking",{parentElement:$("mapDivision"),width:230});
        }
        
        var tmpChecked = "";
        var tmpDisplay = "none";
        
        if(trackingType == 1)
        {
            tmpChecked = "checked";
            tmpDisplay="";
        }
        
        
        trackingDialog.setContent("<br><input id='trackingType' onclick='trackingShowMenu(this);' type='checkbox' " + tmpChecked + " />Nur aktuelle Position zeigen<br><br><span style='display:" + tmpDisplay + "' id='trackingIntvField'>Updateintervall:<br><input type='text' size='4' value='" + trackingInterval + "' id='trackingInterval' /><br></span><br>Gruppenname :<br><input id='trackingGrpName' type='text'><br><br>Passwort :<br><input id='trackingPwd' type='password' /><p align='center'><input type='button' value='OK' title='Tracking starten' onclick='startTracking();' /></p>");
        trackingDialog.moveToCenter();
        trackingDialog.show();
	}
	else
    { 
        stopTrackingMode();
    }
}

function trackingShowMenu(checkbox)
{
    if(checkbox.checked)
    {
        $("trackingIntvField").style.display="";
    }
    else
    {
        $("trackingIntvField").style.display="none";
    }
}

function startTracking()
{
   grpName = $F("trackingGrpName");
   pwd = $F("trackingPwd");

   var tmpInterval = $F("trackingInterval");
   
   if(Number(tmpInterval))
   {
      if(tmpInterval >= 1)
      {
         trackingInterval = parseInt(tmpInterval);
      }
   }
   else
   {
       trackingInterval = 30;
   }
   
   if($("trackingType").checked)
   {
       trackingType = 1;
   }
   else
   {
       trackingType = 0;
   }

   trackingDialog.destroy();
   trackingDialog = null;
     
   if(trackingObserver)     
   {
       trackingObserver.stop();
       trackingObserver = null;
   }
   
   startTrackingPeriodically();
   
   if(trackingType == 1)
   {
      trackingObserver = new PeriodicalExecuter(startTrackingPeriodically,trackingInterval);
   }
}

function startTrackingPeriodically()
{
   if(debug)
   {
      GLog.write("startTrackingPeriodically : " + serverUrl + 'php/tracks/tracking.php?functionId=1&grp=' + grpName + '&pwd=' + pwd);
   }
   
   var params = "";
   
   if(trackingType == 0)
   {
       params = "functionId=1&grp=" + grpName + "&pwd=" + pwd;
   }
   else
   {
       params = "functionId=3&grp=" + grpName + "&pwd=" + pwd;
   }
   
   var myAjax = new Ajax.Request
   (
      serverUrl + 'php/tracks/tracking.php', 
      {
    		method: 'POST', 
    		parameters: params, 
    	    onSuccess: callBackStartTracking
      }
    );
}

function callBackStartTracking(request)
{
    if(debug)
    {
        GLog.write("callBackStartTracking : " + request.responseText)
    }
    if(trackingPolylines)
    {
        for(var i = 0;i < trackingPolylines.length;i++)    
        {
            map.removeOverlay(trackingPolylines[i]);
        }
    }
    
    if(trackingMarker)
    {
        for(var i = 0;i < trackingMarker.length;i++)    
        {
            map.removeOverlay(trackingMarker[i]);
        }
    }
    
    if(trackingLabels)
    {
        for(var i = 0;i < trackingLabels.length;i++)    
        {
            map.removeOverlay(trackingLabels[i]);
        }
    }
   
    trackingMarker = new Array(); 
    trackingLabels = new Array();
    trackingPolylines = new Array();
    
    if(request.responseText != '')
    {
        var res = eval('(' + request.responseText + ')');
            
        var lastPoint = null;
        
        var iconm  = new GIcon();
        iconm.iconSize=new GSize(16,28);
        iconm.iconAnchor=new GPoint(8,28);
 		iconm.infoWindowAnchor=new GPoint(8,14);
        
        for(var i = 0;i < res.length;i++)
        {
           if(trackingType == 0)
           {
               var icon = new GIcon(stdicon2, "images/point_marker.gif" , null, null); 
               var icon2 = new GIcon(iconm, "images/greendot.gif" , null, null); 
               
               var points = new Array();
      
               for(var j = 0; j < res[i].lat.length;j++)
               {
                   var point = new GLatLng(parseFloat(res[i].lat[j]),parseFloat(res[i].lon[j]));
                   points[points.length] = point;
               
                   var marker = null;
               
                   if(res[i].waypointdesc[j] != "")
                   {
                       marker = new GMarker(point,{icon:icon,title : res[i].waypointdesc[j], draggable:false});
                   }
                   else
                   {
                       marker = new GMarker(point,{icon:icon, draggable:false});
                   }
               
                   trackingMarker[trackingMarker.length] = marker;
                   
                   var poly = new GPolyline(points,res[i].color);
                   trackingPolylines[trackingPolylines.length] = poly;
                   map.addOverlay(poly);   
                   
                   if(j == res[i].lat.length -1)
                   {
                       lastPoint = point;
                   }
               }  
               
               var marker = new GMarker(lastPoint,{icon:icon2, draggable:false});
               var marker_label = new TGLabel(lastPoint,res[i].description,0,5);
               trackingMarker[trackingMarker.length] = marker;
               trackingLabels[trackingLabels.length] = marker_label;
           }
           else
           {   
               var icon = new GIcon(iconm, "images/greendot.gif" , null, null); 
               
               var point = new GLatLng(parseFloat(res[i].lat),parseFloat(res[i].lon));
               var marker = new GMarker(point,{icon:icon, draggable:false});
               
               var tmpTxt = res[i].description;
               
               if(res[i].waypointdesc != "")
               {
                   tmpTxt += "<br />" + res[i].waypointdesc;
               }
               
               var marker_label = new TGLabel(point,tmpTxt,0,5);
               
               trackingMarker[trackingMarker.length] = marker;
               trackingLabels[trackingLabels.length] = marker_label;
               
               if(i == res.length -1)
               {
                   lastPoint = point;
               }
           }
           
           
        }
        
        for(var i = 0;i < trackingMarker.length;i++)
        {
            map.addOverlay(trackingMarker[i]);   
        }
        
        for(var i = 0;i < trackingLabels.length;i++)
        {
            map.addOverlay(trackingLabels[i]);   
        }
        
        if(lastPoint)
        {
            if(!map.getBounds().containsLatLng(lastPoint))
            {
                map.panTo(lastPoint);
            }
        }
    }
}

function stopTrackingMode()
{
   if(trackingDialog)
   {
       trackingDialog.destroy();
       trackingDialog = null;
   }

   if(trackingObserver)
   {
       trackingObserver.stop();
       trackingObserver = null;
   }
   
   if(trackingPolylines)
   {
       for(var i = 0;i < trackingPolylines.length;i++)    
       {
           map.removeOverlay(trackingPolylines[i]);
       }
   }
   
   if(trackingMarker)
   {
        for(var i = 0;i < trackingMarker.length;i++)    
        {
            map.removeOverlay(trackingMarker[i]);
        }
   }
   
   if(trackingLabels)
   {
        for(var i = 0;i < trackingLabels.length;i++)    
        {
            map.removeOverlay(trackingLabels[i]);
        }
   }
   
   trackingPolylines = null;
   
   trackingMarker = null;
   
   trackingLabels = null;
   
   $("tracking_button").src = 'images/skins/'+ config.skin +'/tracking.gif';
        
   isTrackingMode = false;
}


function zoomBack()
{
    if(undoArray.length > 1)
    {
        var pos = undoArray[undoArray.length -2];
        
        GEvent.removeListener(zoomHandle);
        GEvent.removeListener(moveHandle);
        
        if(pos.zoom == map.getZoom())
        {
            map.panTo(pos.center);
        }
        else
        {
            map.setCenter(pos.center,pos.zoom);
        }
        
        undoArray.pop();
        slider1.setValue(pos.zoom);
        zoomHandle = GEvent.addListener(map,"zoomend",onZoomed);
        moveHandle = GEvent.addListener(map,"moveend",onMoved);
        
    }
}


function changeMeasureIcon(element)
{
    if(isMeasureMode)
    {
        element.src='images/skins/'+ config.skin +'/measure_down.gif';
    }
    else
    {
        element.src='images/skins/'+ config.skin +'/measure.gif';
    }
}

function changeSearchIcon(element, filename)
{
    if(isSearchMode)
    {
        element.src='images/skins/'+ config.skin +'/' + filename +'_down.gif';
    }
    else
    {
        element.src='images/skins/'+ config.skin +'/' + filename +'.gif';
    }
}

function changeSatMapIcon(element)
{
    if(mapMode == 0)
    {
        $('globe_button').src= 'images/skins/'+ config.skin +'/globe.gif';
        element.src='images/skins/'+ config.skin +'/sat_down.gif';
    }
    else
    {
        element.src='images/skins/'+ config.skin +'/sat.gif';
        $('globe_button').src= 'images/skins/'+ config.skin +'/globe_down.gif';
    }
}

function changeGlobeMapIcon(element)
{
    if(mapMode == 1)
    {
        $('sat_button').src= 'images/skins/'+ config.skin +'/sat.gif';
        element.src='images/skins/'+ config.skin +'/globe_down.gif';
    }
    else
    {
        element.src='images/skins/'+ config.skin +'/globe.gif';
        $('sat_button').src= 'images/skins/'+ config.skin +'/sat_down.gif';;
    }
}

function changeMAIcon(element, filename)
{
    if(measureArea)
    {
        element.src='images/' + filename + '_down.gif';
    }
    else
    {
        element.src='images/' + filename + '.gif';
    }
}

function changeMLIcon(element, filename)
{

    if(measureArea)
    {
        element.src='images/' + filename + '.gif';
    }
    else
    {
        element.src='images/' + filename + '_down.gif';
    }
}

function home_button_onmouseover(element)
{
    element.src='images/skins/' + config.skin + '/home_over.gif';
}

function home_button_onmouseout(element)
{
    element.src='images/skins/' + config.skin + '/home.gif';
}

function sat_button_onmouseover(element)
{
    element.src='images/skins/' + config.skin + '/sat_over.gif';
}

function globe_button_onmouseover(element)
{
    element.src='images/skins/' + config.skin + '/globe_over.gif';
}

function print_button_onmouseover(element)
{
    element.src='images/skins/' + config.skin + '/print_over.gif';
}

function print_button_onmouseout(element)
{
    element.src='images/skins/' + config.skin + '/print.gif';
}

function measure_button_onmouseover(element)
{
    element.src='images/skins/' + config.skin + '/measure_over.gif';
}

function ml_button_onmouseover(element)
{
    element.src='images/ml_over.gif';
}

function ma_button_onmouseover(element)
{
    element.src='images/ma_over.gif';
}


function mr_button_onmouseover(element)
{
    element.src='images/mr_over.gif';
}

function mr_button_onmouseout(element)
{
    element.src='images/mr.gif';
}

function zoomplus_button_onmouseover(element)
{
    element.src='images/skins/' + config.skin + '/zoomplus_over.gif';
}

function zoomplus_button_onmouseout(element)
{
    if(isZoomPlusMode)
    {
        element.src='images/skins/' + config.skin + '/zoomplus_down.gif';
    }
    else
    {
        element.src='images/skins/' + config.skin + '/zoomplus.gif';
    }
}


function info_button_onmouseover(element)
{
    element.src='images/skins/' + config.skin + '/search2_over.gif';
}

function info_button_onmouseout(element)
{
    if(isInfoMode)
    {
        element.src='images/skins/' + config.skin + '/search2_down.gif';
    }
    else
    {
        element.src='images/skins/' + config.skin + '/search2.gif';
    }
}

function routing_button_onmouseover(element)
{
    element.src='images/skins/' + config.skin + '/routing_over.gif';
}

function routing_button_onmouseout(element)
{
    if(isRoutingMode)
    {
        element.src='images/skins/' + config.skin + '/routing_down.gif';
    }
    else
    {
        element.src='images/skins/' + config.skin + '/routing.gif';
    }
}

function dating_button_onmouseover(element)
{
    element.src='images/skins/' + config.skin + '/date_over.gif';
}

function dating_button_onmouseout(element)
{
    if(isDatingMode)
    {
        element.src='images/skins/' + config.skin + '/date_down.gif';
    }
    else
    {
        element.src='images/skins/' + config.skin + '/date.gif';
    }
}

function tracking_button_onmouseover(element)
{
    element.src='images/skins/' + config.skin + '/tracking_over.gif';
}

function copyright_button_onmouseout(element)
{
        element.src='images/skins/' + config.skin + '/copyright.gif';
}

function copyright_button_onmouseover(element)
{
    element.src='images/skins/' + config.skin + '/copyright_over.gif';
}
function hilfe_button_onmouseover(element)
{
    element.src='images/skins/' + config.skin + '/help_over.gif';
}
function topo_button_onmouseover(element)
{
    element.src='images/skins/' + config.skin + '/topo_over.gif';
}


function tracking_button_onmouseout(element)
{
    if(isTrackingMode)
    {
        element.src='images/skins/' + config.skin + '/tracking_down.gif';
    }
    else
    {
        element.src='images/skins/' + config.skin + '/tracking.gif';
    }
}

function hilfe_button_onmouseout(element)
{
    element.src='images/skins/' + config.skin + '/help.gif';    
}
function topo_button_onmouseout(element)
{
    element.src='images/skins/' + config.skin + '/topo.gif';    
}

function back_button_onmouseover(element)
{
    element.src='images/skins/' + config.skin + '/backbutton_over.gif';
}

function back_button_onmouseout(element)
{
    element.src='images/skins/' + config.skin + '/backbutton.gif';
}

function back_button_onmousedown(element)
{
    element.src='images/skins/' + config.skin + '/backbutton_down.gif';
}

function back_button_onmouseup(element)
{
    element.src='images/skins/' + config.skin + '/backbutton_over.gif';
}

function winopen(page, width,height)
{
 var fenster = window.open(page, "image"," toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizeable=1,width=" + (parseFloat(width)+20) + ",height=" + (parseFloat(height)+10));
 fenster.focus();
}

function zoomCluster(lat, lon, zm) {
	if (zm <15) {
		zm = zm + 2;
	} else {
		zm = 17;
	}
	map.setCenter(new GLatLng(lat,lon),zm);
}


