window.onunload = GUnload;
 
var map;
var minHeight;
var maxHeight;
var markers = new Array();
var labels = new Array();
var anzeige = 'aktuell';
var infoWindow;
var searchID = -1;
var base_url ="http://www.wetterwolke.de/";

 
Event.observe(window, 'load', function() {

	maxHeight = windowHeight() - 192;
	minHeight = maxHeight - 233;
	$('map').style.height = maxHeight+'px';
	
  if (GBrowserIsCompatible()) {
		if(!map.getCenter()){
			var initLat = parseFloat(getParm('lat'));
	    var initLon = parseFloat(getParm('lng'));
	    if (isNaN(initLat) ||
	        isNaN(initLon))
	      var initCenter = new GLatLng(52, 14);
	      
	    else
	      var initCenter = new GLatLng(initLat, initLon);
	    var initZoom = parseInt(getParm('z'));
	    if (isNaN(initZoom))
	      var initZoom = 2;
			map.setCenter(initCenter, initZoom, G_PHYSICAL_MAP);
			
		}
		
		G_PHYSICAL_MAP.getMinimumResolution = 
    function() {return 4};
		G_PHYSICAL_MAP.getMaximumResolution = 
    function() {return 10};
    GEvent.addListener(map,"dragend",function(){updateMap();});
 		GEvent.addListener(map,"zoomend",function(){updateMap();});
		GEvent.addListener(map,"moveend",function(){updateMap();});
		//GEvent.addListener(map,"resize",function(){updateMap();});
		map.setMapType( G_PHYSICAL_MAP );
		map.disableScrollWheelZoom();
		var topRight = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(10,20));
		var mapControl = new GLargeMapControl3D();
		map.addControl(mapControl, topRight);
		//map.addOverlay(new GLayer("com.google.webcams"));
		
  }
	$$('ul#navigation li a').each(function(elm, index) {
		++index; // Now it's 1-based
		elm.observe('click', function(event) {
	  	$$('a.active').invoke('removeClassName','active');
			anzeige = elm.id;
			elm.addClassName("active")
			updateMap();
	  });
	});
	$('search').observe("click",function(){
		this.style.backgroundPosition = "0 0";
	});
	$('location_city').observe("focus",function(){
		if(this.value == "Stadtnamen eingeben"){
			this.value = "";
		}
	});
	$('location_city').observe("blur",function(){
		if(this.value == ""){
			this.value = "Stadtnamen eingeben";
		}
	});
	
	if($('forecast')){ 
		$('map').style.height= minHeight+"px";
		map.checkResize();
		$('zugeklappt').show();
	}else{
		if(searchID > 0){
			$('aufgeklappt').show();
		}else{
			$('aufgeklapptgrau').show();
		}
	}
	$('slide_button').observe("click", function(){
		if(searchID > 0){
			if($('forecast') == null){
				open_forecast();
			}else{
				close_forecast();
			}
		}
	});
	updateMap();
});


function open_forecast(){
	
		new Ajax.Request('/details/'+searchID, {
	    method:'get',
	    parameters: {},
	    onSuccess: function(transport){
				if($('forecast')){
					$('forecast').remove();
					$('slide_button').insert({after: transport.responseText});
				}else{
					$('slide_button').insert({after: transport.responseText});
					$('map').morph('height:'+minHeight+'px');
					$('forecast').hide();
					$('forecast').slideDown();
					$('zugeklappt').show();
					$('aufgeklappt').hide();
				}
				facebox = new Facebox();
    	}
	  });
	
	
	map.checkResize();
}

function close_forecast(){

	$('map').morph('height:'+maxHeight+'px');
	$('forecast').remove();
	$('zugeklappt').hide();
	if(searchID > 0 ) {
		$('aufgeklappt').show();
	}else{
		$('aufgeklapptgrau').show();
	}
}

 
function updateMap() {
	
	map.checkResize();
	mapMove();
	
  var bounds = map.getBounds();
  var southWest = bounds.getSouthWest();
  var northEast = bounds.getNorthEast();
	var mapWidth = document.getElementById("map").offsetWidth;
	var mapHeight = document.getElementById("map").offsetHeight;
	var limit = Math.round(Math.sqrt(mapWidth*mapWidth + mapHeight* mapHeight)/200);
	
	$('loading').show();
  // Send an AJAX request for our locations
  new Ajax.Request('/locations.js', {
    method:'get',
    parameters: {sw: southWest.toUrlValue(), ne: northEast.toUrlValue(), max: limit},
    onSuccess: function(transport){
      // Remove all markers
			clearMap();
			map.closeExtInfoWindow();
 
      // Add our new markers to the map (unless they are already on the map.)
      var json = transport.responseText.evalJSON();
      json.each(function(i) {
        id = i.location.id;
				
        if(!markers[id] || markers[id] == null){
          // Marker doesnt exist, add it.
					labels[id] = createLabel(i.location);
					map.addTLabel(labels[id]);
          markers[id] = createMarker(i.location);
          map.addOverlay(markers[id]);
        }
      });      
			if(searchID > -1 ){
				if(!markers[searchID] || markers[searchID] == null){
					showCity(searchID);
				}else{
					GEvent.trigger(markers[searchID], "click");
				}
			}
			if($('forecast')){
				new Ajax.Request('/details/'+searchID.id, {
			    method:'get',
			    parameters: {},
			    onSuccess: function(transport){
			      // Add our new markers to the map (unless they are already on the map.)
						try{
							$('forecast').remove();
							$('slide_button').insert({after: transport.responseText});
						}catch(err	){
							$('slide_button').insert({after: transport.responseText});
							open_forecast();
						}
						facebox = new Facebox();
		    	}
			  });
			}
			$('loading').hide(); 
    }
  });

}
function clearMap() {
 	for(i in markers) {
    if(i > 0 && markers[i]) {
      map.removeOverlay(markers[i]);
			map.removeTLabel(labels[i]);
      markers[i] = null;
    }
  }
}

function showCity(id){
	searchID = id;
		new Ajax.Request('/locations/'+id+'.js', {
	    method:'get',
	    parameters: {id: id},
	    onSuccess: function(transport){
	      // Add our new markers to the map (unless they are already on the map.)
	      var json = transport.responseText.evalJSON();
				id = json.location.id;
				// Marker doesnt exist, add it.
				labels[id] = createLabel(json.location);
				map.addTLabel(labels[id]);
        markers[id] = createMarker(json.location);
        map.addOverlay(markers[id]);		
				removeMarkersOutsideOfMapBounds();
				if(markers[searchID] || markers[searchID] != null){
						GEvent.trigger(markers[searchID], "click");
				}else{
					searchID = -1;
					if($('forecast')){
						close_forecast();
					}else{
						$('aufgeklappt').hide();
						$('aufgeklapptgrau').show();
					}
				}	
    	}
	  });
	
}

function getWeatherIcon(location) {
	var icon = new GIcon();
	switch(anzeige){
		case "aktuell": 
	  	icon.image = base_url+"images/icons/" + location.weather.icon + ".png";
			break;
		case "morgen":
	  	icon.image = base_url+"images/icons/" + location.weather.tomorrow_icon + ".png";
			break;
		case "in2tagen": 
	  	icon.image = base_url+"images/icons/" + location.weather.in2days_icon + ".png";
			break;
	}
	icon.iconAnchor = new GPoint(38, 10);
	icon.infoWindowAnchor = new GPoint(24, 0);
	icon.iconSize = new GSize(48, 48);
  return icon;
}

function createLabel(p_location){
	var label = new TLabel();
	label.id = p_location.id;
	label.anchorLatLng = new GLatLng (p_location.lat, p_location.lng);
	label.markerOffset = new GSize (-10,-2);
	switch(anzeige){
		case "aktuell": 
	  	label.content =  '<div class="temp"><nobr>' +p_location.weather.temp +'°C</nobr></div>';
			break;
		case "morgen":
	  	label.content =  '<div class="temp"><nobr>' + p_location.weather.tomorrow_low +' /'+ p_location.weather.tomorrow_high +'</nobr></div>';
			break;
		case "in2tagen": 
	  	label.content =  '<div class="temp"><nobr>' + p_location.weather.in2days_low +' /'+ p_location.weather.in2days_high +'</nobr></div>';
			break;
	}
	return label;
}
 
function createMarker(location) {
  var latlng = new GLatLng(location.lat, location.lng);
  var marker = new GMarker(latlng, { icon: getWeatherIcon(location) });
	var clickhandler =  createMarkerClickHandler(marker, location);
	GEvent.addListener(marker, "click", function(){
		searchID = location.id;
		$('aufgeklapptgrau').hide();
		if(!$('forecast')){
			$('aufgeklappt').show();
		}
		switch(anzeige){
			case "aktuell": 
		  	content =  '<p><strong>' + location.city +'</strong></p><p>' + location.weather.condition +'</p><p>Wind: ' + location.weather.windspeed +' m/s</p>';
				break;
			case "morgen":
		  	content =  '<p><strong>' + location.city +'</strong></p><p>' + location.weather.tomorrow_condition +'</p>';
				break;
			case "in2tagen": 
		  	content =  '<p><strong>' + location.city +'</strong></p><p>' + location.weather.in2days_condition +'</p>';
				break;
		}
		marker.openExtInfoWindow(
	  	map,
	    "simple_example_window",
	    content,
	    {
		beakOffset: 60
		}
	  );
	if($('forecast')){
		new Ajax.Request('/details/'+location.id, {
	    method:'get',
	    parameters: {},
	    onSuccess: function(transport){
	      // Add our new markers to the map (unless they are already on the map.)
				try{
					$('forecast').remove();
					$('slide_button').insert({after: transport.responseText});
				}catch(err	){
					$('slide_button').insert({after: transport.responseText});
					open_forecast();
				}
				facebox = new Facebox();
    	}
	  });
	}
	return false;
	});
	//GEvent.addListener(marker, "click", clickhandler);
	return marker;
}

function createMarkerClickHandler(marker, location) {
  return function() {
		searchID = location.id;
		new Ajax.Request('/details/'+location.id, {
	    method:'get',
	    parameters: {},
	    onSuccess: function(transport){
	      // Add our new markers to the map (unless they are already on the map.)
				try{
					$('forecast').remove();
					$('slide_button').insert({after: transport.responseText});
				}catch(err	){
					$('slide_button').insert({after: transport.responseText});
					open_forecast();
				}
				facebox = new Facebox();
    	}
	  });
    return false;
  };
}

 
function removeMarkersOutsideOfMapBounds() {
  for(i in markers) {
    if(i > 0 && markers[i] && !map.getBounds().containsLatLng(markers[i].getLatLng())) {
      map.removeOverlay(markers[i]);
			map.removeTLabel(labels[i])
      markers[i] = null;
    }
  }
}

function search_error(error){
	location_city_auto_completer.updateChoices('<ul><li>Nicht gefunden</li></ul>');
	
	$('search').style.backgroundPosition = "0px -29px";
}
function setStandard(location_id) {
	setParm("location_id", location_id);
	$('standard').innerHTML = location_id > 0 ? "(Standard zurücksetzen)" : "(als Standard setzen)";
}

function getParm(name)
{
  var result = getCookie(name);
  if (result == '')
    result = getURLParm(name);
  return result;
}

function setParm(name, value)
{
  /**var nextYear = cookieDate(new Date(Number(new Date()) + 365 * _mSecPerDay)) + 'path=/clouds/';
  var expired = 'Sun, 24-Apr-05 00:00:00 GMT;path=/clouds/';
  if (value == null)
    document.cookie = name + '=;expires=' + expired;
  else
    document.cookie = name + '=' + value + ';expires=' + nextYear;**/
		document.cookie = name + '=' + value + ';path=/';
}

function mapMove()
{
  var center = map.getCenter();
  setParm('lat', center.lat());
  setParm('lng', center.lng());
  setParm('z',   map.getZoom());
}

function getCookie(name) 
{
  // thanks to http://www.quirksmode.org/js/cookies.html
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for (var i = 0; i < ca.length; i++) 
	{
		var c = ca[i];
		while (c.charAt(0) == ' ') 
		  c = c.substring(1, c.length);

		if (c.indexOf(nameEQ) == 0)
		  return c.substring(nameEQ.length, c.length);
	}
	return null;
}
function windowHeight()
{
  var myHeight = 0;
  if (typeof(window.innerWidth) == 'number') 
  {
    //Non-IE
    myHeight = window.innerHeight;
  } 
  else if (document.documentElement && 
           (document.documentElement.clientWidth || document.documentElement.clientHeight)) 
  {
    //IE 6+ in 'standards compliant mode'
    myHeight = document.documentElement.clientHeight;
  } 
  else if (document.body && 
           (document.body.clientWidth || document.body.clientHeight)) 
  {
    //IE 4 compatible
    myHeight = document.body.clientHeight;
  }
  
  return myHeight;
};


