  // Global Variables

var markers = [];
var cats    = [];
var types   = [];



var idOnMap = -1;

var cHotspot = "";
cHotspot.drawOnMap = 0;
cHotspot.circle=0;   

//var cHotspotCircle = null;
var routingEnabled = 0;


var mapDragListener=0;
//var mapClickListener = null,endPoint=null;
  var geo = new GClientGeocoder(); 
  var routeMarkersMgr= null;


//  var reqCatType              = null; 
  var reqCatType            = new ArrayList(); 
  var errorCodes  = new ArrayList();
  var errorStatus = 0;
  
  var icons         = new Array();

    var map           = null;
  var mapInitilized = false;

  var zoomendListener  = null;
  var moveendListener  = null;
  
    var jspMarkersLoc    = "markerRequest.xml";
  var infoTabs         = null;


  //var sidebarArray = [];
  
 
function KeyValue(key, value)
{
    this.key = key;
    this.value = value; //alert("key:"+key+" value:"+value);
}
//------------------------------------------------------------------------------------------------------------------------------------------------

 //
 // Author : Puneeth Kosaraju
 // Date   : 22.11.2007
 // Purpose: Ajax call to get the Req. information from the db
 //

 function getXmlHTTPObj(){
 
      var xmlhttp  = null;

     if (window.XMLHttpRequest)
          xmlhttp = new XMLHttpRequest();    // Mozilla, Safari, Opera
     else if (window.ActiveXObject) {
          try {
    	        xmlhttp = new ActiveXObject('Msxml2.XMLHTTP'); // IE 5
          } catch (e) {
	        try {
		      xmlhttp = new ActiveXObject('Microsoft.XMLHTTP'); // IE 6
	        } catch (e) {}
	  }
     } 
   
     if(xmlhttp) 
	   return xmlhttp;
     else      
	  alert("Ihr Internetbrowser unterstützt kein AJAX! Die Serververbindung konnte deswegen nicht hergestellt werden. Bitte aktualisieren Sie Ihren Internetbrowser!"); 
 }
 
 function ajaxMarkerRequest(reqType,url,isAsync,data,functionToCall,Obj)
 {
     var xmlhttp  = getXmlHTTPObj();
     var returnCode = -1;
	xmlhttp.abort();
        //xmlhttp.setRequestHeader("Content-Type", "text/xml");
        xmlhttp.open(reqType, url, isAsync);
	xmlhttp.send(data);
        if(isAsync) {
	   // onreadystatechange: Event handler for an event that fires at every state change
           xmlhttp.onreadystatechange = function(){
                  if (xmlhttp.readyState == 4)
                     if (xmlhttp.status == 200)
                          if(typeof Obj!="undefined")  returnCode = functionToCall(xmlhttp.responseXML,Obj); 
                          else returnCode  = functionToCall(xmlhttp.responseXML); 
               	     else 
                          alert("Es trat ein Fehler mit der Serververbindung auf. Bitte laden Sie die Seite erneut.");
           }
        } else { 
           if (xmlhttp.status == 200)
                   if(typeof Obj!="undefined") returnCode = functionToCall(xmlhttp.responseXML,Obj); 
                   else  returnCode  = functionToCall(xmlhttp.responseXML); 
           else alert("Es trat ein Fehler mit der Serververbindung auf. Bitte laden Sie die Seite erneut.");
        }
        return returnCode;

  }
//------------------------------------------------------------------------------------------------------------------------------------------------
  function CheckErrorStatus(errorType,errorValue,statusCode) {

     if(typeof errorValue == "undefined") errorValue="Unknown exception occured";
     switch(errorType) {

        case "HTML_ERROR":  
        case "MAP_ERROR" :  if(errorCodes.get(errorType)==0) {
                               alert(errorType+": "+errorValue); 
                               errorCodes.set(cat,1);
                               statusCode=1; // exception occured
                            }
                            return "";


        case "JS_VAR_ERROR":   if(errorCodes.get(errorType)==0) {
                                  alert(errorType+": "+errorValue); 
                                  errorCodes.set(cat,0);
                                  statusCode=0; // lenient exception occured
                               }
                               return "";

     }
     return value;
  }
//------------------------------------------------------------------------------------------------------------------------------------------------
  function ArrayList() { this.catType = new Array(); }

  ArrayList.prototype.get = function(cat){
    for( i in this.catType)
       if(i == cat) return this.catType[i];   
    this.catType[cat]=0;
    return 0;
  }

  ArrayList.prototype.set = function(cat,x){
     for( i in this.catType)
       if(i == cat){
          this.catType[i] = x;                             
          return this.catType[i];  
       }   
     return -1;
  }

 
//------------------------------------------------------------------------------------------------------------------------------------------------

 
  // This function is called when  page is loaded 
  function DRINMap()
  {
 
    if(!GBrowserIsCompatible()) {
       alert("Ihr Internetbrowser unterstützt Google Maps nicht! Bitte aktualisieren Sie Ihren Intzernetbrowser!"); 
       exit;
    } 

    // DEBUG code for checking performance of the system
/*    $(document).ready(function(){
	if (!("console" in window) || !("firebug" in console)) {
		$("html").attr("debug","false");
		$("body").css("padding-bottom",200);
		$.getScript("/firebug/firebug.js");
	}
    });

    // DEBUG CODE
    console.time("DRIN Init");
*/
    //create map
    InitDRINMap(); 

    // DEBUG CODE
//    console.timeEnd("DRIN Init"); 

    CreateGMap(document.getElementById("map"));

    $('.boxThema div.tf').click(function(){ 
         var filterId = $(this).attr("id").substring(2);
 
         // reset all highlighted icons
         $('.boxThema img').each(function(){
             if($(this).attr("src").indexOf("_on")!=-1) {
               var newLink=$(this).attr("src").split('_on');
               $(this).attr("src",newLink[0]+newLink[1]);
               $(this).parent().find("span").removeClass("highlight");
             }
         });


         // highlight current icon
         var currIconLink = $(this).find("img").attr("src").split('.');
         $(this).find("img").attr("src",currIconLink[0]+"_on."+currIconLink[1]);
         $(this).find("span").addClass("highlight");

         // call changetype method to change current themefilter
         changeType(filterId);
    });

    // themefilter loading..
    $(".boxThema span").each(function(){
        //alert($(this).html());
        types[types.length] = $(this).html().toLowerCase();
        markers[markers.length] = new DRINMarker($(this).html().toLowerCase());
    });
    
/*  
    // Create new markers for different themefilters		
    var typeElement = document.getElementById("type"); 
    var eLength     = typeElement.options.length;
    if(eLength<=0) CheckErrorStatus("HTML_ERROR","Number of themefilters in this page is NULL",errorStatus);
    if(errorStatus) return;

 for (var i=0; i < eLength; i++) {
        types[i] = typeElement.options[i].text.toLowerCase();
//	markers[typeElement.options[i].value] = new DRINMarker(typeElement.options[i].text.toLowerCase());
	markers[typeElement.options[i].value] = new DRINMarker(types[i]);

        //alert("Found loc:"+typeElement.options[i].value+ " name:"+types[i]);
    }
  */
     // get different type of categories available from the database
     if( reqCatType.get("catRequest")==0) {
            ajaxMarkerRequest('get',jspMarkersLoc+"?data=getCats",false,null,StoreCats);
            if(reqCatType.set("catRequest",1)==-1) CheckErrorStatus("JS_VAR_ERROR","couldn't store that \"catRequest\" was served.",errorStatus);    
    }
    if(errorStatus) return;

    SetAdress();
//    changeType();
$("#TF0").trigger('click');

  }
  //------------------------------------------------------------------------------------------------------------------------------------------------

  function isThemeFilter(category,id){
      for(var i=0; i<types.length; i++)
         if(types[i]==category)
            return true; 
      // disable Personen-Güterverkehr category
      if(id == 14)
         return true;
      return false;
  }


 function getThemeFilter(id) {
  
    for(var j=0;j<markers.length;j++)
       if(markers[j].themeFilterID==id)
          return markers[j].name;
    return "";

 }
  //------------------------------------------------------------------------------------------------------------------------------------------------

  function StoreCats(responseXmlObj) {
  
      
      if(responseXmlObj == null) alert("Error: XMLHttpRequest request failed!")

      var markerXML = responseXmlObj.documentElement; 
      var markerList = markerXML.getElementsByTagName("category");
      var catType = "", catDesc=null, catId=null;
      var catElement = document.getElementById("category");
      for(var i=0;i<markerList.length;i++) {
        catType  = markerList[i].getAttribute("type");
        catId = markerList[i].getAttribute("id");
        catDesc  = markerList[i].getAttribute("desc");
        if( (typeof catType != "undefined") || (catType != null) || (catType != "") )
        {   
           //alert(catType +":"+types.indexOf(catType));
           
           if(!isThemeFilter(catType.toLowerCase(),catId) ){
              cats[cats.length] = catType;
              catElement.options[catElement.options.length]    = new Option(catDesc,catType);
              // set the option element id
              catElement.options[catElement.options.length-1].id = catId;
           }
        }
      } 
      if(!markerList.length>0) { alert("Ein Fehler trat beim laden der Branchenbuch Kategorien trat auf. Bitte laden Sie die Seite erneut!"); return; }

  }


  //------------------------------------------------------------------------------------------------------------------------------------------------
  
  function InitDRINMap(){
  
		var icon = new GIcon();
		icon.image = "http://wlan-weimar.de/hsimages/icon_wlan2.png";
		icon.shadow = "http://wlan-weimar.de/hsimages/icon_wlan2_schatten.png";
		icon.iconSize = new GSize(25, 25);
		icon.shadowSize = new GSize(25, 25);
		icon.iconAnchor = new GPoint(12, 12);
		icon.infoWindowAnchor=new GPoint(12,0);
		// store the icon object with a specific category
		icons['hotspots'] = icon;
  
		var icon2 = new GIcon();
		icon2.image = "http://labs.google.com/ridefinder/images/mm_20_red.png";
		icon2.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
		icon2.iconSize = new GSize(12, 20);
		icon2.shadowSize = new GSize(22, 20);
		icon2.iconAnchor = new GPoint(6, 20);
		icon2.infoWindowAnchor=new GPoint(6,0);
		// store the icon object with a specific category
		icons['beruf'] = icon2;
		icons['lebensmittel'] = icon2;

		var icon3 = new GIcon();
		icon3.image = "http://wlan-weimar.de/hsimages/icon_parkplatz.png";
		icon3.shadow = "http://wlan-weimar.de/hsimages/icon_parkplatz_schatten.png";
		icon3.iconSize = new GSize(20, 20);
		icon3.shadowSize = new GSize(20, 20);
		icon3.iconAnchor = new GPoint(10, 20);
		icon3.infoWindowAnchor=new GPoint(10,0);
		icons['parkplatz'] = icon3;

		var icon4 = new GIcon();
		icon4.image = "http://wlan-weimar.de/hsimages/icon_arzt.png";
		icon4.shadow = "http://wlan-weimar.de/hsimages/icon_arzt_schatten.png";
		icon4.iconSize = new GSize(25, 25);
		icon4.shadowSize = new GSize(25, 25);
		icon4.iconAnchor = new GPoint(12, 20);
		icon4.infoWindowAnchor=new GPoint(12,0);
		// store the icon object with a specific category
		icons['apotheken'] = icon4;

		var icon5 = new GIcon();
		icon5.image = "http://wlan-weimar.de/hsimages/icon_wc.png";
		icon5.shadow = "http://wlan-weimar.de/hsimages/icon_wc_schatten.png";
		icon5.iconSize = new GSize(25, 25);
		icon5.shadowSize = new GSize(25, 25);
		icon5.iconAnchor = new GPoint(12, 20);
		icon5.infoWindowAnchor=new GPoint(12,0);
		// store the icon object with a specific category
		icons['toilette'] = icon5;

		var icon6 = new GIcon();
		icon6.image = "http://wlan-weimar.de/hsimages/icon_bratwurst.png";
		icon6.shadow = "http://wlan-weimar.de/hsimages/icon_bratwurst_schatten.png";
		icon6.iconSize = new GSize(40, 30);
		icon6.shadowSize = new GSize(40, 30);
		icon6.iconAnchor = new GPoint(20, 30);
		icon6.infoWindowAnchor=new GPoint(20,0);
		// store the icon object with a specific category
		icons['bratwurst'] = icon6;

		var icon7 = new GIcon();
		icon7.image = "http://wlan-weimar.de/hsimages/icon_museum.png";
		icon7.shadow = "http://wlan-weimar.de/hsimages/icon_museum_schatten.png";
		icon7.iconSize = new GSize(20, 20);
		icon7.shadowSize = new GSize(20, 20);
		icon7.iconAnchor = new GPoint(10, 20);
		icon7.infoWindowAnchor=new GPoint(10,0);
		// store the icon object with a specific category
		//icons['museum'] = icon7;
                icons['freizeit'] = icon7;

		var icon8 = new GIcon();
		icon8.image = "http://wlan-weimar.de/hsimages/icon_Veranstaltung.png";
		icon8.shadow = "http://wlan-weimar.de/hsimages/icon_Veranstaltung_Schatten.png";
		icon8.iconSize = new GSize(25, 25);
		icon8.shadowSize = new GSize(25, 25);
		icon8.iconAnchor = new GPoint(13, 25);
		icon8.infoWindowAnchor=new GPoint(13,0);
		// store the icon object with a specific category
		icons['events'] = icon8;

 

		//show the tabs
		var hotspotsNetwork = getHotspotnetwork();
		if((hotspotsNetwork!="allesdrin") && (hotspotsNetwork!="einfachdrin")){
				
				setDisplayNone('Ziel_off');
				setDisplayNone('Standort_off');
				setDisplayBlock('Ziel2'); // it is the big one
				setDisplayBlock('Standort'); // it is the small one
		}else{
				setDisplayNone('Standort_off');
				setDisplayNone('Ziel_off');
				setDisplayBlock('Standort2'); // it is the big one
				setDisplayBlock('Ziel'); // it is the small one
		}
               // reqCatType            = new ArrayList(); 

  }
//------------------------------------------------------------------------------------------------------------------------------------------------


  function CreateGMap(mapDIV) {

		// create the map
		map = new GMap2(mapDIV);
		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());
		map.addControl(new GScaleControl());
		map.addControl(new GOverviewMapControl());
		map.enableContinuousZoom();
		map.enableDoubleClickZoom();
                //map.setZoom(15); 
//		map.setCenter(new GLatLng(50.979550,11.329430), 15);
//		map.setCenter(new GLatLng(50.980668,11.330938), 15);
//		map.setCenter(new GLatLng(50.979952,11.329264), 15);
		map.setCenter(new GLatLng(50.979952,11.329264), 15);


 
		if(map.isLoaded()) { mapInitilized = true; }
/*		var mgrOptions = {borderPadding:50, minZoom:13, maxZoom:22,trackMarkers:true};
		highlightsMarkerMgr = new MarkerManager(map,mgrOptions);
		branchenburchMarkerMgr = new MarkerManager(map,mgrOptions);
		hotspotMarkerMgr = new MarkerManager(map,mgrOptions);
		eventMarkerMgr = new MarkerManager(map,mgrOptions);
	*/	
		//highlightsMarkerMgr    = new MarkerManager(map,{maxZoom:22});
                //branchenburchMarkerMgr = new MarkerManager(map,{maxZoom:22});
                //hotspotMarkerMgr       = new MarkerManager(map,{maxZoom:22});

                var mgrOptions = {borderPadding:50, minZoom:10, maxZoom:22,trackMarkers:true};
                routeMarkersMgr = new MarkerManager(map,mgrOptions);


	        zoomendListener = GEvent.addListener( map, 'zoomend', function() {onMapZoom();});
         	moveendListener = GEvent.addListener( map, 'moveend', function() {onMapMove();});

                /*mapClickListener = GEvent.addListener(map, "click", function(overlay,point) {
                                        if (point) endPoint = point; 
                                   }); */
               
  }
//------------------------------------------------------------------------------------------------------------------------------------------------




  function SetCenter(lat, lng, disableDragging) {
		center = new GLatLng(lat, lng);
		if (!mapInitilized) return;
		map.setCenter(center);
		if (disableDragging!=undefined) {
			if (disableDragging) map.disableDragging();
			else map.enableDragging();
		}
  }
//------------------------------------------------------------------------------------------------------------------------------------------------

function setCurrentAdressBlock(responseXmlObj){

    var markerXML = responseXmlObj.documentElement; 
	var markerList = markerXML.getElementsByTagName("marker");
	
   if(markerList.length!=1){
       alert("Ein Fehler trat beim laden der Hotspot Adresse trat auf. Bitte laden Sie die Seite erneut!");
	   return;
   }
   
      var myAddress = markerList[0].getAttribute("adress");
      var myCity    = markerList[0].getAttribute("city");
      if(myAddress!="" && myCity!="")
      	  document.getElementById("q1").value = myAddress+", "+myCity; 
      else {
	     alert("Ein Fehler trat beim laden der Hotspot Adresse trat auf. Bitte laden Sie die Seite erneut!");
		 return;
      }
}

   //
   // Author: puneeth kosaraju
   // Date:   05.12.2007
   // Purpose: to search for the present location marker in the hightlights 
   //          marker array and then trigger click function for this location.
   // Assume: Present Adress will be specified in highlights
   //
   function SetAdress(){

 if(reqCatType.get("highlights")==1){
   var marker = this.findMarker(getHotspotId());
   if(this.getArrayLength()>0 && marker != ""){
             document.getElementById("q1").value = marker.adress+", "+marker.city;
			 return;
   }
}
	  ajaxMarkerRequest('get',jspMarkersLoc+"?data=custom&fields=adress,city&hotspotId="+getHotspotId(),false,null,setCurrentAdressBlock);
  
	  
}  
//------------------------------------------------------------------------------------------------------------------------------------------------

      function  DRINMarker(name){

         if(!mapInitilized) return "MAP_ERROR";
         
         this.themeFilterID  = "TF"+markers.length;
	 if(typeof name != "undefined")  this.name = name;
	 else this.name = "DRINReqError";
         
       
         this.hashMap        = [];
	 this.markerArray    = [];
	 this.circleList     = [];

         this.markerCollection = [];
         this.cat              = null;
	 var mgrOptions      = {borderPadding:50, minZoom:12, maxZoom:22,trackMarkers:true};
         this.DRINMarkerManager  = new MarkerManager(map,mgrOptions);
         
         this.isMarkersOnMap = 0;
    }
   DRINMarker.prototype.findMarker = findMarker ;
   DRINMarker.prototype.addMarker  = addMarker ;

   DRINMarker.prototype.getArrayLength = getArrayLength;
   DRINMarker.prototype.getMarkerArray = getMarkerArray;

   DRINMarker.prototype.markerClickEventHandle = markerClickEventHandle;
   DRINMarker.prototype.removeClickListener=removeClickListener;
   DRINMarker.prototype.openMarkerTooltip=openMarkerTooltip;

   DRINMarker.prototype.LoadMarkers=LoadMarkers;
  // DRINMarker.prototype.StoreMarkers = StoreMarkers;
   DRINMarker.prototype.DrawMarkers=DrawMarkers;
//   DRINMarker.prototype.hideMarkers=hideMarkers;

//   DRINMarker.prototype.clickMarker=clickMarker;
//   DRINMarker.prototype.makeSidebar=makeSidebar;

   DRINMarker.prototype.clearSidebar=function() {  
       //document.getElementById("side_bar").innerHTML = "";
       $("#side_bar").text("");
   }
//------------------------------------------------------------------------------------------------------------------------------------------------


   DRINMarker.prototype.FindEvents = FindEvents;
   DRINMarker.prototype.StoreEvents=StoreEvents
   
   
   
   function findMarker(id) {
       if(typeof id != "undefined"){
              if(this.name=="events") {
		for(var index=0;index<this.markerCollection[j].events.length;index++)
		    if(this.markerCollection[j].events[index].id==id) return this.markerCollection[j].events[index]; 
                return "";  
              }
              for(var k=0;k<this.markerCollection.length;k++)
                     if(this.markerCollection[k].id==id) return this.markerCollection[k]; 
              return "";

       }
   }

   function addMarker(key,value) { //alert(this.hashMap.length+" key:"+key);
          if( typeof key!="undefined" && typeof value!="undefined")
                this.hashMap[this.hashMap.length] = new KeyValue(key,value);
   }


   function getArrayLength() {  return this.hashMap.length;  } 

   function getMarkerArray()
   {
     var sz = map.getSize();
     var bnds = map.getBounds();
     var pxDiag = Math.sqrt((sz.width*sz.width) + (sz.height*sz.height));
     var mDiagKm = bnds.getNorthEast().distanceFrom(bnds.getSouthWest()) / 1000.0;
     var pxPerKm = pxDiag/mDiagKm;

     this.circleList.length=0;
     this.markerArray.length=0;
     var cat = getCategory();

     for(var k=0;k<this.getArrayLength();k++)
          if(this.hashMap[k].value.visible == 1  && (cat=="all" || this.hashMap[k].value.category==cat ) ) { 
             var marker = this.hashMap[k].value;
             this.markerArray.push(marker); 
             if(this.hashMap[k].value.hotspot==1) {
		    var sideLen=marker.radius*pxPerKm*2;
 		    var circle,imageLoc=null;
  		    if (marker.id==getHotspotId()){ imageLoc = "hsimages/circle_orange.png" ;}
                    else {imageLoc = "hsimages/circle_grey.png";}
                    circle = new EInsert(marker.point, imageLoc, new GSize(sideLen,sideLen), map.getZoom(),-1); 		
                    this.circleList.push(circle); 
                    if(marker.id == getHotspotId()){ cHotspot.circle = circle;}
             }
             
          } 
     //s="MarkerArray:\n";
     //for(i in markerArray){ s+="marker:"+markerArray[i].id+" name:"+markerArray[i].name+"\n";}alert(s);

     return this.markerArray.length;
   }

  

function markerClickEventHandle2(marker)
{
   
   var handle=null;
   //var type = getType();

 // alert("markerId:"+markerId+" ishotspot:"+ishotspot +" type:"+type);
 

  if(typeof marker!="undefined")
    handle = GEvent.addListener(marker, "click", function(){ 
             ajaxMarkerRequest('get',jspMarkersLoc+"?data=tooltip&hotspotId="+marker.id,false,null,openMarkerTooltip);
             map.panTo(marker.getLatLng());
             marker.openInfoWindowTabsHtml(infoTabs);
            }); 
  else  alert("addListener: marker Object undefined:"+marker);
  
   // GEvent.addListener(marker, "mouseover", function() {showTooltip(index, true);});
   // GEvent.addListener(marker, "mouseout", function() {tooltipContainer.style.visibility="hidden";});

  return handle;
}
//------------------------------------------------------------------------------------------------------------------------------------------------
function markerClickEventHandle(marker,type,funcLink)
{
   
  var handle=null;
  if(typeof marker!="undefined")
    handle = GEvent.addListener(marker, "click", function(){ 
             var returnCode  = ajaxMarkerRequest('get',jspMarkersLoc+"?data="+type+"&id="+marker.id,false,null,funcLink);
             if(returnCode==1) return;
             map.panTo(marker.getLatLng());
             if(typeof marker.events != "undefined"){

                var html = '<ul id="eventlist">';
                html+='<li class="tooltip_event boldFont"><a href="#mapdiv" id="ev'+marker.id+'">'+marker.title+'</a> (<b>'+marker.start_date+'</b>)</li>';
 		for(var j=0;j<marker.events.length;j++)
                   html+='<li class="tooltip_event"><a href="#mapdiv" id="ev'+marker.events[j].id+'">'+marker.events[j].title+'</a> (<b>'+marker.events[j].start_date+'</b>)</li>';
        	infoTabs.push(new GInfoWindowTab('Übersicht', html+'</ul>'));

             }
			
              // open marker tooltip
                  // infowindow disappears, when click event is fired and map zoomlevel changes  
              //marker.openInfoWindowTabsHtml(infoTabs,{maxWidth:400});
                 // fixes the above bug too
              map.openInfoWindowTabsHtml(marker.getLatLng(),infoTabs,{maxWidth:400});

              // handle the window size by mainpulating the font size using "limitFontSize" css class
              $(".tooltip_info_title").each(function(){
                 //alert("Text:"+$(this).text()+"\nLength:"+ $(this).text().length);
                  if($(this).text().length>=75) 
                     $(this).addClass("limitFontSize");
              });

             // if($(".tooltip_info_shortdesc").text().length>=30) $(this).css("font-size","8px");
/*
 $("#loading").bind("ajaxSend", function(){
   $(this).show();
 }).bind("ajaxComplete", function(){
   $(this).hide();
 });*/
              // default: disable left anchor
              $(".routeLinks[@rel=previous]").addClass("routeLinks_disabled");
              // if only one event exists remove right anchor too
              if(typeof marker.events!="undefined" && marker.events.length<1)
                  $(".routeLinks[@rel=next]").addClass("routeLinks_disabled");


    	      $(".routeLinks[@rel=next]").click(function() { 
                  var poo = $("#eventlist").find("li.boldFont").next()
                  poo.trigger('click'); 
                });
		$(".routeLinks[@rel=previous]").click(function() { $("#eventlist").find("li.boldFont").prev().trigger('click'); });
			
		$(".tooltip_event").click(function() {
		   // dont close the current window, replace the tab code
		   $.ajax({
		      url: 'markerRequest.xml',
 		      type: 'GET',
		      data: 'data=eventTooltip&id='+$(this).find("a").attr("id").substring(2),
		      dataType: 'xml',
		      timeout: 1000,
		      error: function(){ alert('Error Connecting to Server'); },
		      success: function(xml){        
                         $("event",xml).each(function(){
		            // replace the tooltip text with the new text.
                            var event_tab = $(this).attr("tab1").split("##");
                            $("#tooltip_tab1").html($(event_tab[1]).filter('div#tooltip_tab1').html());
                            var details_tab = $(this).attr("tab2").split("##");
                            $("#tooltip_tab2").html($(details_tab[1]).filter('div#tooltip_tab2').html());
                            // enable left and right anchors and disable only for first and last child
                            $(".routeLinks").removeClass("routeLinks_disabled");

                            var evId = "ev"+$(this).attr("id");
                            // first-child; disable left anchor
                            if( $("ul#eventlist li:first-child a").attr("id") ==  evId )
                            if( $("ul#eventlist a:first").attr("id") ==  evId )
                               $(".routeLinks[@rel=previous]").addClass("routeLinks_disabled");
                            // last-child; disable right anchor
                            //if( $("ul#eventlist li:last-child a").attr("id") ==  evId )
                            if( $("ul#eventlist a:last").attr("id") ==  evId )
                               $(".routeLinks[@rel=next]").addClass("routeLinks_disabled");
 
                           //focus to first tab
			    map.getInfoWindow().selectTab(0);

                            // bold the present selected event and normal font weight for others
                            $(".tooltip_event").removeClass("boldFont");
                            $(".tooltip_event a[id='"+evId+"']").parent().addClass("boldFont");
                         });

		 	$(".routeLinks[@rel=next]").click(function()     { $("ul#eventlist").find("li.boldFont").next().trigger('click');  });
         		$(".routeLinks[@rel=previous]").click(function() { $("ul#eventlist").find("li.boldFont").prev().trigger('click');  });

	                // handle the window size by mainpulating the font size using "limitFontSize" css class
                        $(".tooltip_info_title").each(function(){ if($(this).text().length>=30) $(this).addClass("limitFontSize"); });
                       // if($(".tooltip_info_shortdesc").text().length>=30) $(this).css("font-size","8px");
                         
		      }
		    });

		    return false;
		   //onclick="javascript:map.closeInfoWindow();tooltipTrigger('+marker.events[j].id+');"
		});


            }); 
  else  alert("addListener: marker Object undefined:"+marker);
  
   // GEvent.addListener(marker, "mouseover", function() {showTooltip(index, true);});
   // GEvent.addListener(marker, "mouseout", function() {tooltipContainer.style.visibility="hidden";});

  return handle;
}
//------------------------------------------------------------------------------------------------------------------------------------------------



function removeClickListener()
{
           for(var i=0;i<this.getArrayLength();i++)
           {
              var marker = this.hashMap[i].value;
              if(marker.clickEventHandle!= null) GEvent.removeListener(marker.clickEventHandle);
           }
}
//------------------------------------------------------------------------------------------------------------------------------------------------




  function openEventTooltip(responseXmlObj){

    //var markerType = getType();
    var tabs1=null,tabs2=null,tabs3=null;
			var sData = responseXmlObj.documentElement; 
			var markerInfoXMLTag = sData.getElementsByTagName("event");
                        if(markerInfoXMLTag.length == 1){
                                     var markerId = markerInfoXMLTag[0].getAttribute("id");
	                             var temp = markerInfoXMLTag[0].getAttribute("tab1");
                                     if(temp != null){
					  temp = temp.split("##");
				          tabs1 = new GInfoWindowTab(temp[0], temp[1]);

                                          temp = markerInfoXMLTag[0].getAttribute("tab2");
                                          if(temp!=null)
                                	  {
					     temp = temp.split("##");
        			             tabs2 = new GInfoWindowTab(temp[0], temp[1]);

                         		     temp = markerInfoXMLTag[0].getAttribute("tab3");
                                             if(temp!=null)
 					     {
						temp = temp.split("##");
				                tabs3 = new GInfoWindowTab(temp[0], temp[1]);
					        infoTabs = [tabs1,tabs2,tabs3]; 
					     }
					     else { infoTabs = [tabs1,tabs2]; }
					  }
				          else {infoTabs = [tabs1];}
                                          
                                          //return infoTabs;
return 0;

 				       }
                                       else { alert("Die Daten des Informationsfensters konnten nicht geladen werden. Bitte Laden Sie die Seite erneut!");}
                         }
		 	 else {alert("Die Daten des Informationsfensters konnten nicht geladen werden. Bitte Laden Sie die Seite erneut!");      return 1;}      

  }


//------------------------------------------------------------------------------------------------------------------------------------------------

   function StoreEvents(responseXmlObj,thisObj)
   {
      if(responseXmlObj == null) alert("Error: XMLHttpRequest request failed!")

      var markerXML = responseXmlObj.documentElement; 
      var markerList = markerXML.getElementsByTagName("event");
      if(!markerList.length>0) { alert("ERROR!! Couldn't load markers on map!!"); return; }

	  //alert(markerList.length);
	  
      var id=null, title=null, lat=null, lng=null, markerPoint=null,loc=null,street=null,city=null,www=null,phone=null;
      var marker=null;
      var requestString = null;
      var geocoder=new GClientGeocoder();
      var current_icon = icons['events'];
      var s="";
      for(var i=0;i<markerList.length;i++) {

      id     = parseInt(markerList[i].getAttribute("id"));
      title  = markerList[i].getAttribute("title");
      lat    = parseFloat(markerList[i].getAttribute("lat"));
      lng    = parseFloat(markerList[i].getAttribute("lng"));
      
      start_time = markerList[i].getAttribute("start_time")
      start_date = markerList[i].getAttribute("start_date")
      end_date   = markerList[i].getAttribute("end_date")
      end_time   = markerList[i].getAttribute("end_time")
 
      loc    = markerList[i].getAttribute("loc")    || "";
      street = markerList[i].getAttribute("street") || "";
      city   = markerList[i].getAttribute("city")   || "";
      phone  = markerList[i].getAttribute("phone")  || "";
      www    = markerList[i].getAttribute("www")    || "";


		
      if ((lat!=null && lat!="lat") && (lng!=null && lng!="lng"))
	markerPoint= new GLatLng(lat, lng);  
      else
	markerPoint="";

 
         if(markerPoint == "") continue;   
         var str = loc ||street;
         marker  = new GMarker(markerPoint,{icon:current_icon,title:str});
         if(marker !=null) marker.visible = 1;

	marker.id  = id;
        marker.lat = lat;
        marker.lng = lng;
        marker.title = title;
        marker.clickEventHandle = this.markerClickEventHandle(marker,"eventTooltip",openEventTooltip);
        
     //  thisObj.addMarker(marker.id,marker);
            
        marker.start_time = start_time;
        marker.start_date = start_date;
        marker.end_date   = end_date;
        marker.end_time   = end_time;     

        marker.visible = 1;
        marker.event   = 1;
        marker.loc     = loc;
        marker.street  = street;
        marker.city    = city;
        marker.www     = www;
        marker.phone   = phone;
        marker.events  = [];

        var foundMarker = 0;//alert("marker collection:"+thisObj.markerCollection.length);
        for(var k=0;k<thisObj.markerCollection.length;k++){
           if(marker.lat == thisObj.markerCollection[k].lat && marker.lng == thisObj.markerCollection[k].lng){
              thisObj.markerCollection[k].events[thisObj.markerCollection[k].events.length]  = marker;
              foundMarker = 1; 
              break;
           }
        }
        if(foundMarker == 0)  thisObj.markerCollection[thisObj.markerCollection.length] = marker;



      } // FOR LOOP

      // sort all the events based on date
      // sort events at the same location by date

   }
//------------------------------------------------------------------------------------------------------------------------------------------------

 function getPlacemarks(response){

    // Check if there are more multiple results
    if (response.Placemark.length > 1 ) {
         /*var placemark = response.Placemark[i];
         if (response && placemark) {
	    var address = placemark.address;
         }*/
         alert("GEOCODE: Multiple locations found for given adress!")
         return;
    }
    else {
       var placemark = response.Placemark[0];
       var point = new GLatLng(placemark.Point.coordinates[1], placemark.Point.coordinates[0]);  
       return point;
   }
 }
 

 //
 // Author : Puneeth Kosaraju
 // Date   : 26.11.2007
 // Purpose: 
 //
 // readyState	Object status integer:
 //                                        0 = uninitialized
 //                                        1 = loading
 //                                        2 = loaded
 //                                        3 = interactive
 //                                        4 = complete

  function LoadMarkers(){		

     if (!mapInitilized) return;

     var cat = getCategory();
     var tfID  = this.themeFilterID.substring(this.themeFilterID.length-1);
     var themeFilter = getThemeFilter(this.themeFilterID);
     if(themeFilter=="") alert("ERROR: Cannot recognize ThemeFilter Name:"+this.themeFilterID);

     // check whether the request was served before
     if( reqCatType.get(this.themeFilterID)==0 && reqCatType.get("all")==0 && reqCatType.get(cat)==0 ){

          // DEBUG CODE
/*         console.time("Load Markers");
         console.log("LoadMarkers:"+this.themeFilterID+"; Cat:"+cat);
*/
        // if cat=="all", dump all the markers
        if(tfID==1 &&cat=="all")
          markers[tfID].markerCollection.length=0;
        // requesting markers from the server    
         $.ajax({
   	   url: 'markerRequest.xml',
 	   type: 'GET',
	   data: 'data='+themeFilter+'&category='+cat,
           async: false,
           dataType: 'xml',
	   timeout: 10000,
           error: function(){ alert('Die erforderlichen Daten konnten nicht vom Server geladen werden. Bitte Laden Sie die Seite erneut!'); },
           success: function(xml){        
                         $("marker",xml).each(function(){
                            var marker = null;
                            // if all markers load request, delete all the date in the arrays
                           // if(cat=="all") thisObj.markerCollection.length = 0;
                             
                            var point  = new GLatLng (parseFloat($(this).attr("lat"))||parseFloat(-1),
                                                      parseFloat($(this).attr("lng"))||parseFloat(-1) );
                            if(point){
                               // create new marker
                               marker = new GMarker(point,
                                                     { icon:($(this).attr("hotspot")==1?icons['hotspots']:icons[$(this).attr("category")]||icons['beruf']),
                                                       title:$(this).attr("name")||$(this).attr("adress") 
                                                     });
                               marker.id   = $(this).attr("id") || -1;
                               marker.name = $(this).attr("name");
                               marker.point= point;
                               marker.highlight= $(this).attr("highlight");
                               marker.hotspot  = isNaN($(this).attr("hotspot"))?0:$(this).attr("hotspot");
                               marker.range    = isNaN($(this).attr("range"))?0:$(this).attr("range");
                               marker.radius   = marker.range/1000;
                               marker.visible  = $(this).attr("visible");
                               marker.category = $(this).attr("category");
                               marker.adress   = $(this).attr("adress");
                               marker.city     = $(this).attr("city");

                               var telephone   = ($(this).attr("tel")=="null" || $(this).attr("tel")=="")? "" : $(this).attr("tel");
                               marker.telephone= telephone;

                               // marker event handle
                               marker.clickEventHandle = markerClickEventHandle(marker,"markerTooltip",openMarkerTooltip);

                               // push marker to array, if it doesnt exist yet
                               var foundMarker = 0;
                               // checking whether marker already exists in the array
                               /*for(var i=0;i<markers[tfID].markerCollection.length;i++)
                                  if(markers[tfID].markerCollection[i].id==marker.id){ foundMarker=1; break; }*/
                               // marker doesn't exist, add to the list
                               if(foundMarker==0) markers[tfID].markerCollection[markers[tfID].markerCollection.length] = marker;
                             } else {alert("Invalid Marker");return;}
//else {alert("Invalid Marker (ID:"+$(this).attr(\"id\")+")"); return; }
                         });

                         markers[tfID].name = themeFilter;
                         // check whether atleast one marker exist in the requested themefilter
                         if(markers[tfID].markerCollection.length<1) { 
                            alert("Error: couldn't fill \""+themeFilter+"\" array with markers!!"); return -1;
                         }
                         // note that the request was served
                         if(markers[tfID].themeFilterID=="TF1"){
                            if(reqCatType.set(cat,1)==-1) 
                                 alert("LoadMarkers() - Error: couldn't set \""+cat+"\" request.");
                         }else{
                            if(reqCatType.set(markers[tfID].themeFilterID,1)==-1) {
                                 alert("LoadMarkers() - Error: could not set \""+themeFilter+"\" request.");}
                         }         
                         // DEBUG CODE
//                         console.timeEnd("Load Markers");
              } // sucess
         }); // ajax request

      }
      

     

  }
//------------------------------------------------------------------------------------------------------------------------------------------------
   function CopyArray(themeFilter,cat){


   }

//------------------------------------------------------------------------------------------------------------------------------------------------


  function DrawMarkers()
  {
/*     console.log("Draw Markers:"+this.themeFilterID+"; Cat:"+getCategory());  
     console.time("Draw Markers");
*/
     // variables requires for drawing the hotspot coverage radius
     var sz = map.getSize();
     var bnds = map.getBounds();
     var pxDiag = Math.sqrt((sz.width*sz.width) + (sz.height*sz.height));
     var mDiagKm = bnds.getNorthEast().distanceFrom(bnds.getSouthWest()) / 1000.0;
     var pxPerKm = pxDiag/mDiagKm;

     var cat = getCategory();
     if(this.themeFilterID == "TF3"){cat="all";}
     this.markerArray.length=0;
     this.circleList.length=0;

    // alert("DrawMarkers():"+this.markerCollection.length);
     for(var i=0;i<this.markerCollection.length;i++) {
        //console.log("Marker id:"+this.markerCollection[i].id+" cat:"+this.markerCollection[i].category+" visible:"+this.markerCollection[i].visible);
        if(this.markerCollection[i].visible==1 && (cat=="all"||this.markerCollection[i].category==cat)) {
             this.markerArray.push(this.markerCollection[i]); 
//             console.log("markerArray: STORED MARKER >> id:"+this.markerCollection[i].id+" cat:"+this.markerCollection[i].category);
             // draw the hotspot range gif
             if(this.markerCollection[i].hotspot==1){
		    var sideLen=this.markerCollection[i].radius*pxPerKm*2;
 		    var circle,imageLoc=null;

  		    if (this.markerCollection[i].id==getHotspotId()) imageLoc = "hsimages/circle_orange.png" ;
                    else imageLoc = "hsimages/circle_grey.png";

                    circle = new EInsert(this.markerCollection[i].point, imageLoc, new GSize(sideLen,sideLen), map.getZoom(),-1); 		
                    this.circleList.push(circle); 
                    if(this.markerCollection[i].id == getHotspotId()){
                       if(cHotspot==""){  cHotspot=this.markerCollection[i];}
                       cHotspot.circle = circle;
                    }
             }                   
        }

     }


     // no markers to display on MAP
     if(!this.markerArray.length>0){this.isMarkersOnMap=1; this.cat=cat; return;}
     this.DRINMarkerManager.addMarkers(this.markerArray,12,20);
     this.DRINMarkerManager.addMarkers(this.circleList,15,20);
     this.DRINMarkerManager.refresh();
     this.isMarkersOnMap = 1;
     this.cat = cat;
//console.log("Set Category:"+this.cat)
     idOnMap = this.themeFilterID.substring(this.themeFilterID.length-1);
    //this.markerArray.length = 0; this.circleList.length=0;
//    console.timeEnd("Draw Markers");
  }
//------------------------------------------------------------------------------------------------------------------------------------------------
  
  //
  //  Author : puneeth kosaraju
  // Date: 19.12.2007
  // Desc: function to display the events on map
  //
  function FindEvents()
  {
     if (!mapInitilized) return;
     if( reqCatType.get("events")==0 ){
        ajaxMarkerRequest('get',jspMarkersLoc+"?data=events",false,null,StoreEvents,this);
        //if(!this.getArrayLength()>0) alert("Error: couldn't fill \"EVENTS\" array with markers!!");
        if(!this.markerCollection.length>0) alert("Error: couldn't fill \"EVENTS\" array with markers!!");
        if(reqCatType.set("events",1)==-1){ alert("Error: couldn't store that \"EVENTS\" request was served.");}
     }
  }


  //  Author  :  Puneeth kosaraju
  //  Date    :  04.12.2007
  //  Purpose :
  //  Info    :  
  //
  //

  function hideMarkers(themeFilter)
  {

      // == close the info window, in case its open on a marker that we just hid
       map.removeOverlay(cHotspot);
      
      //cHotspot = null;
      if(cHotspot.drawOnMap==1) cHotspot.drawOnMap=0;
        // document.getElementById("side_bar").innerHTML = "";
         map.closeInfoWindow();

      if(typeof themeFilter=="undefined")  
        this.DRINMarkerManager.clearMarkers(); 
      else  if(themeFilter=="all")
         for (var i=0; i < markers.length; i++) {
	    markers[i].DRINMarkerManager.clearMarkers();
            markers[i].isMarkersOnMap = 0;
         }
      map.clearOverlays();  
      //else {  alert("Error: couldn't find typeof markers to be deleted"); }
   }


//------------------------------------------------------------------------------------------------------------------------------------------------
   function openMarkerTooltip(responseXmlObj){

    //var markerType = getType();
    var tabs1=null,tabs2=null,tabs3=null;
			var sData = responseXmlObj.documentElement; 
			var markerInfoXMLTag = sData.getElementsByTagName("marker");
                        if(markerInfoXMLTag.length == 1){
                                     var markerId = markerInfoXMLTag[0].getAttribute("id");
	                             var temp = markerInfoXMLTag[0].getAttribute("tab1");
                                     if(temp != null){
					  temp = temp.split("##");
				          tabs1 = new GInfoWindowTab(temp[0], temp[1]);

                                          temp = markerInfoXMLTag[0].getAttribute("tab2");
                                          if(temp!=null)
                                	  {
					     temp = temp.split("##");
        			             tabs2 = new GInfoWindowTab(temp[0], temp[1]);

                         		     temp = markerInfoXMLTag[0].getAttribute("tab3");
                                             if(temp!=null)
 					     {
						temp = temp.split("##");
				                tabs3 = new GInfoWindowTab(temp[0], temp[1]);
					        infoTabs = [tabs1,tabs2,tabs3]; 
					     }
					     else { infoTabs = [tabs1,tabs2]; }
					  }
				          else {infoTabs = [tabs1];}
                                          
                                          //return infoTabs;
return 0;

 				       }
                                       else { alert("Die Daten des Informationsfensters konnten nicht geladen werden. Bitte Laden Sie die Seite erneut!");}
                         }
		 	 else {alert("Die Daten des Informationsfensters konnten nicht geladen werden. Bitte Laden Sie die Seite erneut!");}      



   }

//------------------------------------------------------------------------------------------------------------------------------------------------




  //  Author  :  Puneeth kosaraju
  //  Date    :  03.12.2007
  //  Purpose :
  //  Info    :  type = 0   - "branchenburch" selected
  //                  = 1   - "highlights"    selected
  //
  //
 
   function changeType(type) {

	//var type = parseInt(document.getElementById("type").value);
             // == close the info window, in case its open on a marker that we just hid
     map.closeInfoWindow();
     markers[type].clearSidebar();
        if(type == 1){                   
  	  document.getElementById("category").style.visibility="visible";
//          document.getElementById("category").selectedIndex = 14;
          // set the default select option
          $("#category option").each(function(){
             if($(this).attr("id")==15) // 15: reise thema
                 $(this).attr("selected","true");
          });     

          changeCategory();
        } 
        else { 
                 document.getElementById("category").style.visibility="hidden";
                 document.getElementById("category").selectedIndex = 0;
                 hideMarkers("all"); 

                 switch(parseInt(type)){

                    case 0:  map.setCenter(new GLatLng(50.979952,11.329264), 15);
                             markers[type].LoadMarkers();
                             markers[type].DrawMarkers();makeSidebar();
                             //markers[type].makeSidebar();
                             GEvent.trigger(markers[type].findMarker(getHotspotId()),"click");
                             break;

                    case 2:  map.setCenter(new GLatLng(50.977345,11.341581), 13);
                             markers[type].LoadMarkers();
                             markers[type].DrawMarkers();makeSidebar();
                             //markers[type].makeSidebar();
                             break;

                    case 3:  markers[type].FindEvents();
                             map.setCenter(new GLatLng(50.979550,11.329430), 15);
                             markers[type].DrawMarkers(markers[type].themeFilterID);makeSidebar();
                             //markers[type].makeSidebar();
                             break;

                    default:  break;

                 }
      }

  }

//------------------------------------------------------------------------------------------------------------------------------------------------
function changeCategory(){
   hideMarkers("all");
   //var type = document.getElementById("type").value;
   var type = -1;
   for (var i=0; i < markers.length; i++) {
      if(markers[i].isMarkersOnMap==1){
         type = i;break;}

   }
   if(type==-1) type=1;
   map.setCenter(new GLatLng(50.979550,11.329430), 15);

   markers[type].LoadMarkers(); 
   markers[type].DrawMarkers();makeSidebar();
   //markers[type].makeSidebar();

}
//------------------------------------------------------------------------------------------------------------------------------------------------


  function onMapZoom() {
        // == close the info window, in case its open on a marker that we just hid
    if(!routingEnabled){
    document.getElementById("side_bar").innerHTML = "";
     // which markers are on map
	for (var i=0; i < markers.length; i++) 
	    if(markers[i].isMarkersOnMap){
                markers[i].clearSidebar();makeSidebar();
		//markers[i].makeSidebar() ;
                return;
             }}
            
  }
//------------------------------------------------------------------------------------------------------------------------------------------------

  function onMapMove() {
        // == close the info window, in case its open on a marker that we just hid
//        map.closeInfoWindow();
    if(!routingEnabled){
     document.getElementById("side_bar").innerHTML = "";
	for (var i=0; i < markers.length; i++) 
	    if(markers[i].isMarkersOnMap){
                markers[i].clearSidebar(); makeSidebar();
		//markers[i].makeSidebar() ;
                return;
             }}
  }
//------------------------------------------------------------------------------------------------------------------------------------------------


   function getHotspotId() { return document.getElementById("hotspotid").value; }
//------------------------------------------------------------------------------------------------------------------------------------------------


   function getCategory() { return document.getElementById("category").value;  }
//------------------------------------------------------------------------------------------------------------------------------------------------



   function getType()  {  return document.getElementById("type").value; }
//------------------------------------------------------------------------------------------------------------------------------------------------


   function getHotspotnetwork()  {  return document.getElementById("hotspotnetwork").value; }
//------------------------------------------------------------------------------------------------------------------------------------------------


   // Author: Jörg
   // Description:  showLocation() is called when you click on the Search button
   //               in the form.  It geocodes the address entered into the form
   //               and adds a marker to the map at that location.

/*   function showLocation() {
	var address = document.getElementById("q2").value;
	geocoder.getLocations(address, addAddressToMap);
   }*/
//------------------------------------------------------------------------------------------------------------------------------------------------



  function gotoCurrentHotspot() {

     // == close the info window, in case its open on a marker that we just hid
     map.closeInfoWindow();
     var hotspotString = "hotspots";
     var index = -1,markerFound=0;

     /*for (var i=0; i < markers.length; i++) {
        if(markers[i].isMarkersOnMap == 1){
           if(cHotspot != ""){
              if(!markers[i].DRINMarkerManager.isGridPointVisible_(cHotspot.getPoint()) ) { map.addOverlay(cHotspot); }
              markerFound = 1;
              index = i;
            }
            break;
         }
     }*/

     if(cHotspot != ""){
         for (var i=0; i < markers.length; i++) {
            if(markers[i].isMarkersOnMap == 1 &&
                     !markers[i].DRINMarkerManager.isGridPointVisible_(cHotspot.getPoint()) )    { map.addOverlay(cHotspot); }
            markerFound = 1;
         }
     }
       

     if(markerFound==0) alert("gotoCurrenthotspot() - Error: Current Hotspot not found.")
     if(markerFound==1) {

         map.setCenter(cHotspot.getLatLng(),16); 
         // == close the info window, in case its open on a marker that we just hid
         map.closeInfoWindow();
         cHotspot.drawOnMap = 1;
         GEvent.trigger(cHotspot,"click");           makeSidebar();

     }
  }
//------------------------------------------------------------------------------------------------------------------------------------------------


   function gotoAllHotspots() 
   {

      map.closeInfoWindow();
      $("#TF2").trigger('click');
      map.setCenter(new GLatLng(50.979952,11.329264),12); 
      
   }
//------------------------------------------------------------------------------------------------------------------------------------------------
  function tooltipTrigger(themefilterID,markerId){

    var result = markers[themefilterID].findMarker(markerId);
    if(result != "") {
       GEvent.trigger(result,"click");
       return 0;
    }
    alert("Fehler: Die Informationen zum Eintrag konnten nicht gefunden werden. ID:"+markerId);
    return -1;
/*    for (var i=0; i < markers.length; i++) 
       if(markers[i].isMarkersOnMap == 1){
          var result = markers[i].findMarker(markerId);
          if(result !="")
  	     GEvent.trigger(result,"click"); return;
       }*/

  }
//------------------------------------------------------------------------------------------------------------------------------------------------
   function CreateMarkerBox(themefilterID,marker)
   {
      var markerBox = "";
      markerBox = '<div class="b_box_breite">';
      if(marker.visible==1) {
           markerBox+= '<div class="b_box_highlight ';
           if (marker.hotspot==1)  
              markerBox+= 'b_box_hotspot'; 
           else if(marker.event==1) { 
               markerBox+= 'b_box_event'; 
           }   
           markerBox += '"><h2>';

	   //markerBox += '<a href="#mapdiv" onclick="' +clickFunc+ ';">';
           markerBox += '<a href="#mapdiv" onclick="javascript:map.closeInfoWindow();tooltipTrigger('+themefilterID+','+marker.id+');">';
//           markerBox += marker.name||marker.title;
           var title = marker.name||marker.title;
           markerBox += '<span class="sidebar_box_title">'+title+'</span>';

           markerBox += '</a></h2>';
      }else{ 
           markerBox += '<div class="b_box">';
           markerBox += '<h2>';
           var title = marker.name||marker.title;
           markerBox += title + '</h2>';
      }

      markerBox += '<div class="b_box_inhalt">';
      if(typeof marker.loc!="undefined")
         markerBox += '<span class="eventLoc" style="color:#13f;">'+marker.loc +'</span><br>';

      if(marker.event==1 &&
         typeof marker.start_time !="undefined" &&
         typeof marker.start_date !="undefined" &&
         typeof marker.end_date   !="undefined" &&
         typeof marker.end_time   !="undefined"  ) {
//               markerBox += 'start-zeit: '+marker.start_date+'('+marker.start_time+' Uhr)<br/>ende-zeit: '+marker.end_date+'('+marker.end_time+' Uhr)';
               markerBox += '<span style="overflow:hidden;">Zeit: '+marker.start_date+'<br/> ('+marker.start_time+' Uhr)</span>'

      }
      else { 
         var str = marker.adress||marker.street;
         if(typeof str!="undefined" && str!="" || str!="null")  markerBox += str + '<br>';
         markerBox += marker.city ;
      }
      if(typeof marker.telephone != "undefined" && marker.telephone != "" )  markerBox += '<br>' + 'Tel:' + marker.telephone; 
      markerBox += '</div>';
      markerBox += '</div>';   
      markerBox += '</div>';  
      return markerBox;
   }

//------------------------------------------------------------------------------------------------------------------------------------------------

   function makeSidebar() {

//      console.time("Make Sidebar");
      var marker = null;
      var markerBox= "";
      var totalSidebarMarkers  = 0;
      var nVmarkers=[], vmarkers=[], hmarkers=[];
      var cHotspotID = -1;
      //var category = getCategory();

      // if current hotspot is to be displayed, add to the sidebar first      
      if(cHotspot != null && cHotspot.drawOnMap == 1) { 
         cHotspotID = cHotspot.id;
         if(map.getBounds().containsLatLng(cHotspot.getPoint())) {
            markerBox += CreateMarkerBox(0,cHotspot);
            if(markerBox != "") vmarkers.push(markerBox);
         }
      }

      for(var k=0;k<markers.length;k++) {
         if(markers[k].isMarkersOnMap==1 && markers[k].markerCollection.length>0){
                  for(var i=0;i<markers[k].markerCollection.length;i++)   {
                     marker = markers[k].markerCollection[i];
                     if(cHotspotID == marker.id) continue;
                     if(map.getBounds().containsLatLng(marker.getPoint())) {
                        //console.log("SibeBar: Marker cat:"+marker.category +" && ReqCat:"+markers[k].cat);
                        if(markers[k].cat=="all" || markers[k].cat==marker.category) {
                           markerBox = CreateMarkerBox(k,marker);
                           if(markerBox != "" ){
                              if(marker.visible == 0)
                                 nVmarkers.push(markerBox);
                              else if(marker.hotspot==1)
                                 hmarkers.push(markerBox);
                              else
                                 vmarkers.push(markerBox);
                           }
                        }
                     }   
                  }  // for loop
         }           // if loop
      }              // for loop


      var newSidebarArray = hmarkers.concat(vmarkers,nVmarkers); 

      newScript=new virtualpaginate("b_box_breite", 9,"div","side_bar",newSidebarArray);
      newScript.buildpagination("scriptspaginate"); 
//      console.timeEnd("Make Sidebar");
   }
//------------------------------------------------------------------------------------------------------------------------------------------------


  function DrinUnload()
  {

     /*
     reqCatType           = null;*/
     //removeClickListeners();
     if(moveendListener != null){GEvent.removeListener(moveendListener);}
     if(zoomendListener != null){GEvent.removeListener(zoomendListener);}
     GUnload();
     markers = null;
//cHotspot = null;
//cHotspotCircle = null; 
  }
//------------------------------------------------------------------------------------------------------------------------------------------------




		// ==================================================
		function showAddress(address) {/*
		  if (geocoder) {
			geocoder.getLatLng(
			  address,
			  function(point) {
				if (!point) {
				  alert(address + " not found");
				} else {
				  map.setCenter(point, 13);
				  var marker = new GMarker(point);
				  map.addOverlay(marker);
				  marker.openInfoWindowHtml(address);
				  alert(point + " found");
				}
			  }
			);
		  }*/
		}

//--------------------------------------------------------------------------------
		
	function showMarkerInfoText(text, pos_x, pos_y){/*
        	var theDiv = document.getElementById("markerInfoText");
		theDiv.style.position = "absolute";
//		theDiv.style.top = pos_y;
//		theDiv.style.left = pos_x;
		theDiv.style.visibility = "visible";
		theDiv.innerHtml = text;*/


        }


		//--------------------------------------------------------------------------------
		// == a checkbox has been clicked ==
 		function boxclick(box,category) {/*
			if (box.checked) {
				show(category);
			} else {
				hide(category);
			}
			// == rebuild the side bar
			makeSidebar();*/
		}
		//--------------------------------------------------------------------------------


 //------------------------------------------------------------------------------------------------------------------------------------------------
  /*
   * Inspired from : http://econym.googlepages.com/example_multi2.htm
   *
   */
      // ====== Array for decoding the failure codes ======
  var reasons=[];
      reasons[G_GEO_SUCCESS]            = "Abfrage erfolgreich";
      reasons[G_GEO_MISSING_ADDRESS]    = "Fehlende Adresse: Entweder fehlt die Adresse oder sie hat keinen Wert.";
      reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unbekannte Adresse: Für die angegebene Adresse konnte keine übereinstimmende geografische Position gefunden werden.";
      reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Nicht verfügbare Adresse: Der Geocode für die angegebene Adresse kann auf Grund von gesetzlichen oder vertraglichen Gründen nicht wiedergegeben werden.";
      reasons[G_GEO_BAD_KEY]            = "Ungültiger Schlüssel: Der angegebene API-Schlüssel ist entweder abgelaufen oder ist mit der Domain, für die er angegeben wurde, nicht kompatibel.";
      reasons[G_GEO_TOO_MANY_QUERIES]   = "Zu viele Abfragen: Die tägliche Anzahl an Geocoding-Abfragen für diese Seite wurde überschritten.";
      reasons[G_GEO_SERVER_ERROR]       = "Serverfehler: Die Geocodingabfrage war nicht erfolgreich.";
      reasons[G_GEO_BAD_REQUEST]        = "Die Routenabfrage war leider nicht erfolgreich.";
      reasons[G_GEO_MISSING_QUERY]      = "Die Eingabe enthält keine Abfrage.";
      reasons[G_GEO_UNKNOWN_DIRECTIONS] = "Das GDirection-Objekt konnte die Route zwischen den Punkten nicht berechnen.";

   // Global variables
   var startAddress=null, endAddress=null;
   var startPoint = null, endPoint = null;
   var gdir=null,poly=null,pLine=null;

   //gdir=new GDirections(null, document.getElementById("side_bar"));
gdir=new GDirections();
   //gdir=new GDirections(map, null);

   GEvent.addListener(gdir,"error", function() {
        var code = gdir.getStatus().code;
        var reason="Code "+code;
        if (reasons[code]){
          //reason = reasons[code] +" (Google Error Code:"+code+")";
          alert("Error: "+ reasons[code]);
        }
        else
          alert("Routingfunktion: Unknown Error!!");
              });

   GEvent.addListener(gdir, "load", function() {
        if (poly) map.removeOverlay(poly);
        poly = gdir.getPolyline();
        map.addOverlay(poly);
        routingEnabled = 1;
        getRouteInfo();
      });


  
 // function mapClickRouting() { if(endPoint != null) showLocation(endPoint);}
 

  function CreateMarker(point, iconType){
     var marker = new GMarker(point, {draggable:true,icon:iconType});
     mapDragListener = GEvent.addListener(marker, "dragend", function() { showLocation(marker,1); });
     map.addOverlay(marker); 
     return marker;
  }


  function findAddress(address,needMarker) { 
    geo.getLatLng(address, function (point) { 
            var reason = null, endMarker = null;
            if (point){ //alert("found Point:"+point+" StartPOint:"+state);
              if (typeof needMarker == "undefined") 
                 startPoint = point;
              else if (needMarker==1){
                 endMarker = CreateMarker(point,G_END_ICON); // create new draggable marker for END ADDRESS
                 endPoint = endMarker.getPoint();
                 DrawRoute();
              }
            }
            else {
              var result=geo.getCache().get(address);
              if (result) {
                reason="Code "+result.Status.code;
                if (reasons[result.Status.code]) reason = reasons[result.Status.code]
              } 
              else reason = "";
              alert('Die Adresse "'+address+ '" konnte nicht gefunden werden. ' + reason);
            }
          }
    );
 }


  // isMarker = 1 eaddress is of GMarker type
  // isMarker = 0 eAddress is an adress and need geocoding
  // if startpoint already exists in the array, do not geocode again
  function showLocation(address,isMarker)
  {
     
     var startMarker=null;

     gdir.clear(); // Clears any existing directions results
     hideMarkers("all"); // clears all markers existing on map
 
     startAddress = document.getElementById("q1").value;
     if(typeof isMarker == "undefined")
        endAddress   = address

     // START ADDRESS
     for(var i=0;i<markers.length;i++)
        if(markers[i].isMarkersOnMap == 1){
           startMarker = markers[i].findMarker(getHotspotId());
           break;
        }
     if(startMarker == null || startMarker=="")
        findAddress(startAddress);
     else 
        startPoint = startMarker.getPoint();


    // END ADDRESS
    if(typeof isMarker == "undefined")
       findAddress(address,1);
    else if(isMarker == 1) {
       endPoint = address.getPoint();
       endAddress = "--";
       //map.addOverlay(address);
       DrawRoute();
       return ;
    }



  }


  function DrawRoute(){

     gdir.clear();
     map.closeInfoWindow();

     var bounds = map.getBounds();
     bounds.extend(startPoint);
     bounds.extend(endPoint);
     map.setZoom(map.getBoundsZoomLevel(bounds));
     map.setCenter(bounds.getCenter());

     document.getElementById("side_bar").innerHTML = "";
     var paginateArray = appendRule('div','scriptspaginate');
     for(var i=0;i<paginateArray.length;i++)
        paginateArray[i].style.display="none"
    document.getElementById("side_bar").style.font="9pt Arial,Verdana,Helvetica,sans-serif";

     //var a = "from: "+startPoint.toUrlValue(9) + " to: " + endPoint.toUrlValue(9);
     //var a = "from: "+startPoint + " to: " + endPoint;

     var s = startAddress + "@" + startPoint.toUrlValue(6);
     var e = endAddress   + "@" + endPoint.toUrlValue(6);
     var a =  "from: "+s+" to: "+e;
      
     gdir.load(a, {locale:"de",getPolyline:true,getSteps:true});
  }


  //
  //
  //
  //
  // From: http://maps.forum.nu/gm_driving_directions2.html
  //

  function getRouteInfo()
  {

	var copyrightHTML = gdir.getCopyrightsHtml();
	var summaryHTML   = gdir.getSummaryHtml();
	var distance      = gdir.getDistance();
	var duration      = gdir.getDuration();
	var numRoutes     = gdir.getNumRoutes();

	//var oDriveFrom    = startAddress ;
	//var oDriveTo      = endAddress;
        var startP        = gdir.getGeocode(0);
        var endP          = gdir.getGeocode(gdir.getNumGeocodes()-1);

	var polyline      = gdir.getPolyline();
	pLine             = copyPolyline(polyline);

        //var dirHead =  "&nbsp;&nbsp;<b>"+oDriveFrom+"</b> to <b>"+oDriveTo+"</b><br/>";
        var dirHead = "";
	dirHead += '<div class="globalSummaryDiv">';
	dirHead += '<table cellspacing="0" cellpadding="2" width="100%">';
	dirHead += '<tr><td valign="top"> <b>' + startP.address + '</b> nach <b>' + endP.address + '</b></td></tr>';
	//dirHead += '<tr><td valign="top">'+summaryHTML+'</td></tr>';
        dirHead += '<tr><td valign="top">Entfernung: '+distance.html+'</td></tr>';
	dirHead += '</table></div>';
        var routeTable = '<table cellspacing="0" cellpadding="0" id="routeTable">';

        for (var r = 0 ; r < numRoutes ; r++ ) {
	   var route = gdir.getRoute(r);
	   var startGeoCode = gdir.getGeocode(r);//route.getStartGeocode();
	   var endGeoCode = gdir.getGeocode(r+1);//route.getEndGeocode();
	   var endLatLng = route.getEndLatLng();
	   var routeSummaryHTML = route.getSummaryHtml();
	   var routeDistance = route.getDistance();
	   var routeDuration = route.getDuration();
           var numSteps = route.getNumSteps();

           
  	   for (var s = 0 ; s < numSteps ; s++ ) {
	      var step = route.getStep(s);
	      var stepPolylineIndex = step.getPolylineIndex();
	      var stepDescriptionHTML = step.getDescriptionHtml();
	      var stepDistance = step.getDistance();
	      var stepDuration = step.getDuration();
              routeTable += '<tr class="stepRow" onclick="showStep('+r+','+s+')" style="border-top:1px dotted #333;"><td class="stepRouteInfo">&nbsp;&nbsp;' +(s+1)+'. '+ 
                              stepDescriptionHTML + '</td><td class="distance">' + stepDistance.html +'</td></tr>';

//              routeTable += '<tr class="stepRow" onclick="showStep('+r+','+s+')"><td>&nbsp;&nbsp;' + (s+1) + '.</td><td class="stepRouteInfo"> ' + 
//                            stepDescriptionHTML + '</td><td>' + stepDistance.html +'(ca. '+stepDuration.html+ ')</td></tr>';
           }
           routeTable += '</table>';
        }
        document.getElementById("side_bar").innerHTML += dirHead + routeTable;
        document.getElementById("routeTable").style.cursor="pointer";
        $('#routeTable tr').hover(function(){$(this).addClass("routeTableHover")},function(){$(this).removeClass("routeTableHover")});
      }

 //------------------------------------------------------------------------------------------------------------------------------------------------ 
function copyPolyline(p) {
	pLinePoints = Array();
	for (var n = 0 ; n < p.getVertexCount() ; n++ ) {
		pLinePoints.push(p.getVertex(n));

	}
	var pLine = new GPolyline(pLinePoints,'#F7098A');
	return pLine;
}
 //------------------------------------------------------------------------------------------------------------------------------------------------ 


function showStep(r,s) {
	map.closeInfoWindow();
	var step = gdir.getRoute(r).getStep(s);
	var stepLatLng = step.getLatLng();
	var stepDescriptionHTML = step.getDescriptionHtml();
	var stepDistance = step.getDistance();
	var stepDuration = step.getDuration();

	var infoHTML = '<div id="bubble_info_tab" class="bubble">';
	infoHTML += '<div style="{margin-top:1px dotted #eee}">' + (s+1) + '.' + stepDescriptionHTML + '&nbsp;&nbsp;' + stepDistance.html + '</div>';
	infoHTML += '<div>' + stepLatLng + '</div>';

	infoHTML += '</div>';

	var tab1 = new GInfoWindowTab("Location", '<div id="bubbleMap"></div>');
	var tab2 = new GInfoWindowTab("Info", infoHTML);
	var infoTabs = [tab1,tab2];

	map.openInfoWindowTabsHtml(stepLatLng,infoTabs);
// Minimap for driving directions
	var dMapDiv = document.getElementById("bubbleMap");
	detailmap = new GMap2(dMapDiv);
	detailmap.setCenter(stepLatLng,15);

	detailmap.addOverlay(pLine);

	var CopyrightDiv = dMapDiv.firstChild.nextSibling;
	var CopyrightImg = dMapDiv.firstChild.nextSibling.nextSibling;
	CopyrightDiv.style.display = "none"; 
	CopyrightImg.style.display = "none"; 

	detailmap.addControl(new GSmallMapControl());


 }
 //------------------------------------------------------------------------------------------------------------------------------------------------ 



// UTILITY FUNCTIONS 


   function trimStringLength(element,type,length){
      var maxLength = length || 20;
      $(element).each(function(i){
         var titleText = $(this).text();
	 if(titleText.length>=maxLength){
	    // find next space after the max length
  	    var index = titleText.indexOf(" ",maxLength);
	    // replace the existing length
	    if(index!=-1){
               if(type=="...")
                  $(this).text(titleText.substring(0,index)+type);
               else
	          $(this).html("<span>"+titleText.substring(0,index)+"</span><br/><span>"+titleText.substring(index+1)+"</span>");
            }
            else
               index = titleText.search(/^\w/);
	 }
      });
   }