var map;
var iconHaendlerSmall;
var iconHaendlerBig;
var iconReparaturSmall;
var iconReparaturBig;
var iconServiceSmall;
var iconServiceBig;

var smallIcon;
var markerManager = null;

var debug = false;
var tmpMarker;

var loadEvent = null;

var circle = null;

var serverUrlAdressen = window.location.protocol+"//"+window.location.host+"/cms/php/";
var imageUrlAdressen = window.location.protocol+"//"+window.location.host+"/cms/images/";

var markerArray = new Array();

var UTF8 = {
	encode: function(s){
		for(var c, i = -1, l = (s = s.split("")).length, o = String.fromCharCode; ++i < l;
			s[i] = (c = s[i].charCodeAt(0)) >= 127 ? o(0xc0 | (c >>> 6)) + o(0x80 | (c & 0x3f)) : s[i]
		);
		return s.join("");
	},
	decode: function(s){
		for(var a, b, i = -1, l = (s = s.split("")).length, o = String.fromCharCode, c = "charCodeAt"; ++i < l;
			((a = s[i][c](0)) & 0x80) &&
			(s[i] = (a & 0xfc) == 0xc0 && ((b = s[i + 1][c](0)) & 0xc0) == 0x80 ?
			o(((a & 0x03) << 6) + (b & 0x3f)) : o(128), s[++i] = "")
		);
		return s.join("");
	}
};

function load() 
{
    if (GBrowserIsCompatible()) 
    {
    	var params = window.location.search.toQueryParams();
		
	    if(params.debug)
	    {
		    if(params.debug == "true")
		    {
		        debug = true;
		    }
	    }
		
	    
		var mapDivision = $("mapDivision");
       
        map = new GMap2(mapDivision);
		
		loadEvent = GEvent.addListener(map,"load",loadMarkers);
        
        var icon = new GIcon();
        icon.iconSize=new GSize(32,32);
        icon.shadowSize=new GSize(56,32);
        icon.iconAnchor=new GPoint(16,32);
        icon.infoWindowAnchor=new GPoint(16,16);
        
        var icon2 = new GIcon();
        icon2.iconSize=new GSize(16,16);
        icon2.shadowSize=new GSize(29,22);
        icon2.iconAnchor=new GPoint(8,16);
        icon2.infoWindowAnchor=new GPoint(8,8);
        
        iconHaendlerBig = new GIcon(icon, imageUrlAdressen +"icon49red.gif", null, null);
        iconHaendlerSmall = new GIcon(icon2, imageUrlAdressen +"icon49redsmall.gif", null,null);   
        
        iconReparaturBig = new GIcon(icon, imageUrlAdressen +"icon49black.gif", null, null);
        iconReparaturSmall = new GIcon(icon2, imageUrlAdressen +"icon49blacksmall.gif", null,null);   
		
		iconHPDBig = new GIcon(icon, imageUrlAdressen +"iconhpd.gif", null, null);
        iconHPDSmall = new GIcon(icon2, imageUrlAdressen +"iconhpdsmall.gif", null,null);   
        
        iconServiceBig = new GIcon(icon, imageUrlAdressen +"iconservice.gif", null, null);
        iconServiceSmall = new GIcon(icon2, imageUrlAdressen +"iconservicesmall.gif", null,null);   
        
        map.addControl(new GLargeMapControl());
        map.addControl(new GScaleControl());
        map.addControl(new GMapTypeControl());
        map.addControl(new GOverviewMapControl());
        
        map.setCenter(new GLatLng(51.0,11.0),5);
        
        markerManager = new GMarkerManager(map);
        
       
    }
}



function createMarker(point,id,title,icon,z) 
{
  function importanceOrder (marker,b) 
  {
      return marker.importance*1000000;
  }

  var marker = new GMarker(point,{icon : icon,title : title,zIndexProcess : importanceOrder});
  marker.importance = z;
  GEvent.addListener(marker, "click", function() 
  {
    getInfoWindowText(id);
  });
  
  markerArray[parseInt(id)] = marker;
  return marker;
}

function loadMarkers()
{
   if(debug)
   {
	  GLog.write(serverUrlAdressen + "adressen.php");
   }

   GEvent.removeListener(loadEvent);
   var myAjax = new Ajax.Request
   (
		serverUrlAdressen + "adressen.php", 
		{
			method: 'post', 
			parameters: "functionId=0&constraint=" + constraint + "&mode=" + mode, 
			onComplete: callbacklLoadMarkers
		}
	);
}

function callbacklLoadMarkers(request)
{
	  if(debug){
	  	GLog.write(request.responseText);
	 }
	  
	  
	  
	  
	  var marker = eval('(' + request.responseText + ')');
	  
	  for (var i = 0; i < marker.length; i++) 
	  {
   		var bigMarker = null;
   		var smallMarker = null;
   		
		
		
		// Service
		if (mode == 1){
			//if(marker[i].rep == 1)
       
            if(marker[i].rep > 0)
	   		{			 
	 			 bigMarker = createMarker(new GLatLng(parseFloat(marker[i].lat),parseFloat(marker[i].lon)),marker[i].id,marker[i].name,iconHaendlerBig,1);
	                         smallMarker = createMarker(new GLatLng(parseFloat(marker[i].lat),parseFloat(marker[i].lon)),marker[i].id,marker[i].name,iconHaendlerSmall,1);  			
				 
				 
	   		}
	  /*		else if(marker[i].rep == 2)
	   		{			 
	 			 bigMarker = createMarker(new GLatLng(parseFloat(marker[i].lat),parseFloat(marker[i].lon)),marker[i].id,marker[i].name, iconServiceBig,2);
	                         smallMarker = createMarker(new GLatLng(parseFloat(marker[i].lat),parseFloat(marker[i].lon)),marker[i].id,marker[i].name,iconServiceSmall,2); 			
	   		}*/
		}
		
		
		else {
			if(marker[i].hdl == 2)
	   		{			 
	 			 bigMarker = createMarker(new GLatLng(parseFloat(marker[i].lat),parseFloat(marker[i].lon)),marker[i].id,marker[i].name, iconHPDBig,2);
	                         smallMarker = createMarker(new GLatLng(parseFloat(marker[i].lat),parseFloat(marker[i].lon)),marker[i].id,marker[i].name,iconHPDSmall,2);  			
	   		}
	   		else if(marker[i].hdl == 1)
	   		{			 
	 			 bigMarker = createMarker(new GLatLng(parseFloat(marker[i].lat),parseFloat(marker[i].lon)),marker[i].id,marker[i].name,iconHaendlerBig ,1);
	                         smallMarker = createMarker(new GLatLng(parseFloat(marker[i].lat),parseFloat(marker[i].lon)),marker[i].id,marker[i].name,iconHaendlerSmall,1 );  			
	   		}
		}
		
		
		
   		
 
   		markerManager.addMarker(bigMarker,7);
   		markerManager.addMarker(smallMarker,0,6);
	  }
	
	   markerManager.refresh();
}

function setErgebnis()
{
	Element.hide("haendlerdiv");
	Element.hide("ortediv");
	var cb = $("auswahl");
	
	if(cb.selectedIndex == -1) cb.selectedIndex = 0;
	
	var suche = cb.options[cb.selectedIndex].value;
	
	if(suche !="")
	{
	    var myAjax = new Ajax.Request
        (
		    serverUrlAdressen + "search.php", 
		    {
			    method: 'post', 
			    parameters: "action=0&bl=" + suche + "&constraint=" + constraint, 
			    onComplete: callbackSetErgebnis,
			    onLoading: showWaitDiv,
			    onLoaded: hideWaitDiv,
			    onFailure: hideWaitDiv
		  }
	    );
	}
}

function callbackSetErgebnis(request)
{
	var cb = $("orte").options;
	
	cb.length = 0;
    
    if(debug) GLog.write("callbackSetErgebenis : " + request.responseText);
	var resultArray = eval('(' + request.responseText + ')');

    if(resultArray.length <= 0) { alert("Es wurden leider keine Orte gefunden !");return;};
	
	for(var i =0;i< resultArray.length;i++)
	{
		var oOption = document.createElement("OPTION");
	    oOption.text=resultArray[i];
		oOption.value=resultArray[i];
		cb.add(oOption);
	}
	
	Element.show("ortediv");
}

function setHaendler()
{
	var cb = $("orte");
	
	if(cb.selectedIndex == -1) cb.selectedIndex = 0;
	
	var suche = UTF8.encode(cb.options[cb.selectedIndex].value);
	
	var myAjax = new Ajax.Request
    (
		  serverUrlAdressen + "search.php", 
		  {
			  method: 'post', 
			  parameters: "action=1&ort=" + suche + "&constraint=" + constraint, 
			  onComplete: callbackSetHaendler,
			  onLoading: showWaitDiv,
			  onLoaded: hideWaitDiv,
			  onFailure: hideWaitDiv
		  }
	 );
	
}


function callbackSetHaendler(request)
{
	var cb = $("haendler").options;
	
	cb.length = 0;

	if(debug) GLog.write("callbackSetHaendler.responseText : " + request.responseText);
	
	var resultArray = eval('(' + request.responseText + ')');
	
	if(resultArray.length <= 0) { alert("Es wurden leider keine Händler gefunden !");return;};
	
	for(var i =0;i< resultArray.length;i++)
	{
		var oOption = document.createElement("OPTION");
	 
	    oOption.text=resultArray[i].name;
		oOption.value=resultArray[i].id;
		cb.add(oOption);
	}
	
	Element.show("haendlerdiv");
}

function suchePLZ()
{
	Element.hide("haendlerdiv2");
	var plz = $F("plz").strip();
	
	if(plz.length != 5)
	{
		alert("Ihre Postleitzahl muss aus 5 Ziffern bestehen !");
	}
	else
	{
	  if(circle != null)
	  {
	    map.removeOverlay(circle);
	  }
	
	  var distanceSelect = $("umkreisSelect").options;
	  
	  var selectedIndex = distanceSelect.selectedIndex;
	  
	  if(selectedIndex == -1)
	  {
	     selectedIndex = 0;
	  }
	  
	  var distance = distanceSelect[selectedIndex].value;

	  var myAjax = new Ajax.Request
      (
		    serverUrlAdressen + "search.php", 
		    {
			    method: 'post', 
			    parameters: "action=2&plz=" + plz + "&constraint=" + constraint + "&distance=" + distance, 
			    onComplete: callbackSuchePLZ,
			    onLoading: showWaitDiv,
     			onLoaded: hideWaitDiv,
			    onFailure: hideWaitDiv
		    }
	  );
	}
}

function callbackSuchePLZ(request)
{
	var cb = $("haendler2").options;
	
	cb.length = 0;

	if(debug) GLog.write("callbackSuchePLZ : " + request.responseText);

	var result = eval('(' + request.responseText + ')');

	if(result.haendler.length <= 0) { alert("Es wurden leider keine Händler gefunden !");return;};
	
	for(var i =0;i< result.haendler.length;i++)
	{
		var oOption = document.createElement("OPTION");
	   
	    oOption.text=result.haendler[i].name;
		oOption.value=result.haendler[i].id;
		oOption.title=result.haendler[i].name;
		cb.add(oOption);
	}
	
	var plzMiddle = new GLatLng(parseFloat(result.lat_middle),parseFloat(result.lon_middle));
	
	map.setCenter(plzMiddle,10);
	
	var distanceSelect = $("umkreisSelect").options;
	  
	var selectedIndex = distanceSelect.selectedIndex;
	  
	if(selectedIndex == -1)
	{
	   selectedIndex = 0;
	}
	  
	var distance = distanceSelect[selectedIndex].value;
	
	circle = new TGCircle(plzMiddle,distance,"#CC9999",1,0.7,"#CC9999",0.7);
	
	map.addOverlay(circle);
	
	if(circle.getBounds())
	{
	    map.setZoom(map.getBoundsZoomLevel(circle.getBounds()));
	}

	Element.show("haendlerdiv2");
}

function getInfoWindowText(id)
{
	var myAjax = new Ajax.Request
    (
		    serverUrlAdressen + "adressen.php", 
		    {
			    method: 'post', 
			    parameters: "functionId=1&id=" + id, 
			    onComplete: callbackGotoMarker,
			    onLoading: showWaitDiv,
     			onLoaded: hideWaitDiv,
			    onFailure: hideWaitDiv
		    }
	);
}

function gotoMarker(sid)
{
	var cb = $(sid);
	if(cb.selectedIndex > -1)
	{
	  var id = cb.options[cb.selectedIndex].value;
	  
	  getInfoWindowText(id);
	}
}

function callbackGotoMarker(request)
{
	if(debug) GLog.write("callbackGotoMarker : " + request.responseText);
	
	var result = eval('(' + request.responseText + ')');
	
	var latlon = new GLatLng(parseFloat(result.lat),parseFloat(result.lon));
	
	map.setCenter(latlon,10);
	  
	//marker Punkt verschieben
	
	/*var point = map.fromLatLngToDivPixel(latlon);
	point = new GPoint(point.x,point.y -16);
	latlon = map.fromDivPixelToLatLng(point);
	  
	map.openInfoWindowHtml(latlon,result.text);*/
	
	var marker = markerArray[result.id];
	
	marker.openInfoWindowHtml(result.text);
}

function showDiv()
{
	var cb = $("art").options;
	
	if(cb.selectedIndex == -1) cb.selectedIndex = 0;
	
	if(cb.selectedIndex == 0)
	{
		Element.hide("nsuche");
		Element.show("psuche");
	}
	else
	{
		Element.hide("psuche");
		Element.show("nsuche");
	}
}

function showWaitDiv()
{
	
	//var element = $("indicator1");
	//element.style.display='inline';
}

function hideWaitDiv()
{

	//var element = $("indicator1");
	//element.style.display='none';
}


