// tweak fuer url-ermittlung
function getURL() {
}
function zoomButton() {
}
var map = null;
var mgr = null;
var theIcon = null;
var theClusterIcon = null;
var om = null;
var bLoaded = false;


function load(iLat, iLon, iZoom) 
{
	if (GBrowserIsCompatible()) 
	{
		om = new OverlayMessage(document.getElementById('map'));      
    om.Set('<b>Loading...</b>');
    
	  map = new GMap2(document.getElementById("map"));
 
 		// START additional Button //
	  getURL.prototype = new GControl();
		getURL.prototype.initialize = function(map) {
		  var container = document.createElement("div");
		
		  var urlDiv = document.createElement("div");
		  this.setButtonStyle_(urlDiv);
		  container.appendChild(urlDiv);
		  urlDiv.appendChild(document.createTextNode("Position"));
		  GEvent.addDomListener(urlDiv, "click", function() {
		  	var sLink = map.getCenter() + "";
		  	sLink = sLink.substr(1, sLink.length-2) + ", " + map.getZoom();
		  	document.getElementById('copyurl').style.display='block';
		  	document.urlcopyform.urlcopy.value = sLink;
		  	document.urlcopyform.urlcopy.select();
		  	document.urlcopyform.urlcopy.focus();
		  });
		
		  map.getContainer().appendChild(container);
		  return container;
		}
		
		getURL.prototype.getDefaultPosition = function() {
		  return new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(7, 47));
		}
		
		getURL.prototype.setButtonStyle_ = function(button) {
		  //button.style.textDecoration = "underline";
		  button.style.color = "#666";
		  button.style.backgroundColor = "#F5EFDF";
		  button.style.font = "small Tahoma";
		  button.style.border = "1px solid #C1A75A";
		  button.style.padding = "2px";
		  button.style.marginBottom = "3px";
		  button.style.textAlign = "center";
		  button.style.width = "4em";
		  button.style.cursor = "pointer";
		}
	  
	  zoomButton.prototype = new GControl();
		zoomButton.prototype.initialize = function(map) {
		  var container = document.createElement("div");
		
		  var urlDiv = document.createElement("div");
		  this.setButtonStyle_(urlDiv);
		  container.appendChild(urlDiv);
		  urlDiv.appendChild(document.createTextNode("Full-Screen"));
		  GEvent.addDomListener(urlDiv, "click", function() {
		  	//return GB_showFullScreen('Thermarium worldwide', '/referenzen/refs_full_screen.html')
		  	if (bFullScreen) window.close();
		  	else var fullScreenWindow = window.open('/referenzen/refs_full_screen.html', 'refsfullscreen', 'width='+screen.width+',height='+screen.height);
		  });
		
		  map.getContainer().appendChild(container);
		  return container;
		}
		
		zoomButton.prototype.getDefaultPosition = function() {
		  return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(207, 7));
		}
		
		// Sets the proper CSS for the given button element.
		zoomButton.prototype.setButtonStyle_ = function(button) {
		  //button.style.textDecoration = "underline";
		  button.style.color = "#000000";
		  button.style.backgroundColor = "#FFFFFF";
		  button.style.font = "small Arial";
		  button.style.border = "1px solid #000000";
		  //button.style.padding = "1px";
		  //button.style.marginBottom = "3px";
		  button.style.textAlign = "center";
		  button.style.width = "89px";
		  button.style.height = "17px";
		  button.style.cursor = "pointer";
		}
		// additional Button END//
		
		map.enableContinuousZoom();
		//map.enableScrollWheelZoom();
	  map.addControl(new GLargeMapControl());
	  map.addControl(new GMapTypeControl());
	  map.addControl(new GOverviewMapControl());
	  map.addControl(new getURL());
	  map.addControl(new zoomButton());
	  
	  map.setCenter(new GLatLng(iLat, iLon), iZoom, G_HYBRID_MAP);
	  
	  mgr = new GMarkerManager(map, {borderPadding:1});
	  
	  theIcon = new GIcon(G_DEFAULT_ICON);
		theIcon.image = "/img/refs/marker.png";
		theIcon.shadow = "/img/refs/transpi.png";
		theIcon.iconSize = new GSize(26, 26);
		theIcon.shadowSize = new GSize(1, 1);
		theIcon.iconAnchor = new GPoint(13, 26);
		theClusterIcon = new GIcon(theIcon, "/img/refs/marker_cluster.png");
		theShipIcon = new GIcon(theIcon, "/img/refs/marker_ship.png");
		setupMarkers();
	}
}

var gmarkers = [];
var iMarker = 0;
var side_bar_html = "";
var markersA = [];
var markersB = [];
var markersC = [];
var markersD = [];

// This function picks up the click and opens the corresponding info window
function myclick(iMarker) {
	mgr.addMarker(gmarkers[iMarker],4,7);
  GEvent.trigger(gmarkers[iMarker], "click");
}
function str_replace(c) {
	var s = Array('#a#','#o#','#u#','#A#','#O#','#U#','#s#');
	var r = Array('ä','ö','ü','Ä','Ö','Ü','ß');

	for(i=0; i < s.length; i++) {
		c = c.split(s[i]).join(r[i]);
	}
	return c;
}
function getRefs(iWhich)
{
	if (bLoaded)
	{
		getBreadcrumbs(iWhich);
		document.getElementById("ref_refs").innerHTML = "";
		//setupMarkers();
		
		var sRefs = "";
		//var urlstr="http://thermarium.com/refs.php?type=referenzen&iWhich="+iWhich+"&lng="+iLang;
		var urlstr="/refs.php?type=referenzen&iWhich="+iWhich+"&lng="+iLang;
		
		var request = creat_Object();

		request.open('POST', urlstr , true);
		request.onreadystatechange = function () 
		{
			if (request.readyState == 1) 
			{
				document.getElementById("ref_refs").innerHTML = "Loading...";
			}
			else if (request.readyState == 4) 
			{
				var xmlDoc = request.responseXML;
				refs = xmlDoc.documentElement.getElementsByTagName("ref");
				if (refs.length)
				{
					
					for (var i = 0; i < refs.length; i++)
					{
						sRefs += '<a href="javascript:void(0);" onmouseover="myclick(' + refs[i].getAttribute("id") + ')" alt="' + str_replace( refs[i].getAttribute("name") ) + '" title="' + str_replace( refs[i].getAttribute("name") ) + '">' + str_replace( refs[i].getAttribute("name") ) + '</a> - ' + str_replace( refs[i].getAttribute("ort") ) + '<br>';
					}
				}
				document.getElementById("ref_refs").innerHTML = sRefs;
			}
		}
		request.send(null);
	}
}



function setupMarkers() {
 
	var request = GXmlHttp.create();
	side_bar_html = "";
  request.open("POST", "/refs.php?type=markers2&lng="+iLang, true);
  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      var xmlDoc = GXml.parse(request.responseText);
      // obtain the array of markers and loop through it
      var testo = xmlDoc.documentElement;
      var markers = xmlDoc.documentElement.getElementsByTagName("marker");
      var sTmp = "";
      if (markers.length)
      {
	      for (var i = 0; i < markers.length; i++) {
	        // obtain the attribues of each marker
	        var lat = parseFloat(markers[i].getAttribute("lat"));
	        var lng = parseFloat(markers[i].getAttribute("lon"));
	        var point = new GLatLng(lat,lng);
	        var html = markers[i].getAttribute("html");
	        var label = markers[i].getAttribute("label");
	        var theid = markers[i].getAttribute("id");
	        var cluster = markers[i].getAttribute("cluster");
	        // create the marker
	        if (cluster == '0')
	        {
		        var marker = createMarker(point,label,html,theid,1);
		        markersA.push(marker);
		      }
		      else if (cluster == 'referenz')
	        {
		        var marker = createMarker(point,label,html,theid,theIcon);
		        markersC.push(marker);
		      }
		      else if (cluster == 'ship')
	        {
		        var marker = createMarker(point,label,html,theid,3);
		        markersD.push(marker);
		      }
		      else
		      {
		        var marker = createMarker(point,label,html,theid,2);
		        markersB.push(marker);
		      }
	      }
	    }
	       
	    mgr.addMarkers(markersA,0,2);
	    mgr.addMarkers(markersD,0,17);
	    mgr.addMarkers(markersB,3,3);
	    mgr.addMarkers(randomEntries(markersC, 40, false, -1), 4,7);
	    mgr.addMarkers(markersC,8,17);
			mgr.refresh();
			setLoaded();
	  }
  }
  request.send(null);
  
}

function setLoaded()
{
	bLoaded = true;
	om.Clear();
}

function createMarker(point,name,html,theid,cluster) {
	var sIcon = theIcon;
	if (cluster == 1 || cluster == 2) var sIcon = theClusterIcon;
	else if (cluster == 3) var sIcon = theShipIcon;
	var marker = new GMarker(point, {icon:sIcon, title:name});
	if (cluster == 1)
	{
		GEvent.addListener(marker, "click", function() {
		  setMap(point.lat(), point.lng(), map.getZoom()+1);
		  getRegions(theid);
		});
	}
	else if (cluster == 2)
	{
		GEvent.addListener(marker, "click", function() {
		  setMap(point.lat(), point.lng(), map.getZoom()+2);
		  getRefs(theid);
		});
	}
	else
	{
		GEvent.addListener(marker, "click", function() {
		  marker.openInfoWindowHtml(html);
		});
	}
	gmarkers[theid] = marker;
	iMarker++;
	return marker;
}

function setMap(iLat, iLon, iZoom)
{
	if (bLoaded)
	{
		if (bFullScreen) iZoom++;
		//load(iLat, iLon, iZoom);
		if (iZoom == map.getZoom()) map.panTo(new GLatLng(iLat, iLon));
		else map.setCenter(new GLatLng(iLat, iLon), iZoom);
	}
}

function getRegions(iWhich)
{
	if (bLoaded)
	{
		var urlstr="/refs.php?type=regions&iWhich="+iWhich+"&lng="+iLang;
		var request = creat_Object();
		request.open('POST', urlstr , true);
		
		request.onreadystatechange = function () 
		{
			if (request.readyState == 1) 
			{
				document.getElementById("ref_regions").innerHTML = "Loading...";
			}
			else if (request.readyState == 4) 
			{
				var xmlDoc = request.responseXML;
				regs = xmlDoc.documentElement.getElementsByTagName("region");
				regions = "<table width=\"252\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">";
				if (regs.length)
				{
					for (var i = 0; i < regs.length; i++)
					{
						if ((i % 2 == 0)) regions += "<tr>";
						regions += "<td width=\"126\" valign=\"top\">";
						//regions += "<a href=\"javascript:void(0);\" onclick=\"";
						regions += "<a alt=\"" + regs[i].getAttribute("fullname") + "\" title=\"" + regs[i].getAttribute("fullname") + "\" href=\"javascript:void(0);\" onclick=\"";
						if (regs[i].getAttribute("children")>0) regions += "getRegions(" + regs[i].getAttribute("id") + ");";
						else regions += "getRefs(" + regs[i].getAttribute("id") + ");";
						if (regs[i].getAttribute("link")) regions += " setMap(" + regs[i].getAttribute("link") + ");";
						regions += "\">" + regs[i].getAttribute("name") + "</a>";
						regions += "</td>";
						if ((i % 2 == 1)) regions += "</tr>";
					}
				
					if ((regs.length % 2) != 0)
					{
						for (var i=0; i<(2-(regs.length % 2)); i++)
						{
							regions += "<td></td>";
						}
						regions += "</tr>";
					}
					regions += "</table>";
				}
				else
				{
					regions = "keine Unterregion";
					
				}
				//alert(regions);
				//getRefs(iWhich);
				document.getElementById("ref_refs").innerHTML = "";
				document.getElementById("ref_regions").innerHTML = regions;
			}
		}
		request.send(null);
		getBreadcrumbs(iWhich);
	}
}

function getBreadcrumbs(iWhich)
{
	if (bLoaded)
	{
		var urlstr="/refs.php?type=breadcrumbs&iWhich="+iWhich+"&lng="+iLang;
		var request = creat_Object();
		request.open('POST', urlstr , true);
		
		request.onreadystatechange = function () 
		{
			if (request.readyState == 1) 
			{
				document.getElementById("ref_region_crumbs").innerHTML = "Loading...";
			}
			else if (request.readyState == 4) 
			{
				var xmlDoc = request.responseXML;
				bcs = xmlDoc.documentElement.getElementsByTagName("bc");
				
				document.getElementById("ref_region_crumbs").innerHTML = bcs[0].getAttribute("thebc");
			}
		}
		request.send(null);
	}
	
}

function creat_Object()
{
	var xmlhttp;
	if (!xmlhttp && typeof XMLHttpRequest != 'undefined') 
	{
	try 
	{
	xmlhttp = new XMLHttpRequest();
	} 
	catch (e) 
	{
	alert("Your browser is not supporting XMLHTTPRequest");
	xmlhttp = false;
	}
	}
	else
	{
	xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	return xmlhttp; 
}

function randomEntries(array, number, noCycle, firstIndex)
{
  if(typeof number == 'object')    // int[] is a range - get random number
    number = number[0] + Math.floor(Math.random()* (number[1]-number[0]+1));
  
  var len = array.length;
  if(len == 0 || number < 1)
    return [];
  if(len == 1)
    noCycle = true;
  
  var entries = [];                // the random entries
  var count = 0;
  var rand;
  var lastIndex = -1;
  var mems = [];                   // boolean array controls cycle
  
  if(typeof firstIndex == 'number' && firstIndex > -1 && firstIndex < len)
  {
    number++;                      // add 1 to include the first 'fixed' value

    entries[count++] = array[firstIndex];        // store entry
    lastIndex = firstIndex;
    mems[firstIndex] = true;
  }
  
  if(noCycle)                      // get random indices - disregard duplicates
  {
    for(var i = count; i < number; i++)
    {
      rand = Math.floor(Math.random()*len);
      entries[i] = array[rand];
    }
    return entries;                // 'pure randoms' ready
  }
  
  // Two seperate loops to generate the random indices
  if(len == 2)
  {
    var forcedFinalIndex = -1;
    
    while(true)                    // len == 2 gives alternating singles and duos
    {
      // Create random index and store new entry
      rand = Math.floor(Math.random()*len);
      entries[count++] = array[rand];
      
      if(count == number)          // loop delimiter
        break;

      if(lastIndex == rand)        // two in a row?
      {
        rand = 1 - rand;           // toggle index
        
        // If we start with a row, force a more cyclic index at the end
        if(count == 2)
          forcedFinalIndex = rand;
        
        entries[count++] = array[rand];
        if(count == number)        // loop delimiter
          break;
      }
      
      lastIndex = rand;
      
      // If asked for at start, force final entry of binary array to differ
      if(count == number-1 && forcedFinalIndex != -1)
      {
        entries[count++] = array[forcedFinalIndex];
        break;
      }
    }
  }
  else                             // len > 2 follows 'random cycle' algorithm
  {
    var isFull = (number % len == 0);            // when all comes full circle
    
    while(count < number)          // loop delimiter
    {
      rand = Math.floor(Math.random()*len);
      
      if(count == 0)
        firstIndex = rand;         // keep the first random index
      else
        // If there are 2 more to go, and firstIndex has not yet come, but must come..
        if(isFull && count == number-2 && !mems[firstIndex])
          rand = firstIndex;       // ..then force it!
        else 
        {
          var toggle = ((rand + count) % 3 == 0);    // pseudo random toggle

          while(mems[rand] || rand == lastIndex ||   // check against duplicates
                (!isFull && count == number-1 && rand == firstIndex))
            if(toggle)
            {
              if(--rand < 0)
                rand = len-1;                        // shift rand back
            }
            else
              if(++rand > len-1)                     // shuffle card forward
                rand = 0; 
        }
  
      // Store random entry
      entries[count++] = array[rand];
      mems[rand] = true;           // keep cycle memory
      lastIndex = rand;
      
      if(count % len == len-1 && count != number)
      {
        // Take the last rand of a cycle to be the last 'still false' entry of mems
        for(var i = 0; i < len; i++)
          if(mems[i])
            mems[i] = false;       // clear cycle memory
          else
          {
            entries[count++] = array[i];
            lastIndex = i;
          }
      }
    }
  }
  return entries;                  // 'cyclic randoms' ready
} 
