
var infowindows = [];
var marker_list = [];

var ajaxRequestRunning = false;

var boundsNeverChanged = true;

// Create a Marker with an Infotext
function createMarker(myLatlng, map, restaurant_title, restaurant_info, custom_icon, custom_shadow){
	if(custom_icon && custom_shadow){
	  var marker = new google.maps.Marker({
	      position: myLatlng, 
	      map: map,
	      title:restaurant_title,
	      icon:custom_icon,
	      shadow:custom_shadow
	  });   
	}else{
	  var marker = new google.maps.Marker({
	      position: myLatlng, 
	      map: map,
	      title:restaurant_title
	  });   
	}

  var infowindow = new google.maps.InfoWindow({
      content:restaurant_info
  });

  infowindows[infowindows.length] = infowindow;
  marker_list[myLatlng.lat()+"-"+myLatlng.lng()] = true;

  google.maps.event.addListener(marker, 'click', function() {
		for(var i = 0; i < infowindows.length; i++){
			infowindows[i].close();
		}
		infowindow.open(map,marker);
  });
  
  return marker;

}

/**
*
*  Javascript trim, ltrim, rtrim
*  http://www.webtoolkit.info/
*
**/
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}


// get a POSH list of restaurants in bounds of a given map
function getRestaurantsInBounds(map){
	// get new restaurants
	var bounds = map.getBounds();
	var bounds_sw = bounds.getSouthWest();
	var bounds_ne = bounds.getNorthEast();
	
	$.ajax({
		type: "GET",
		url: '/restaurants/in_bounds/'+bounds_sw.lat()+','+bounds_sw.lng()+'/'+bounds_ne.lat()+','+bounds_ne.lng()+'.posh', 
		complete: function(transport){
			var response = transport.responseText || "";

			
			
			$("#restaurant_table_container").html(response);
			
			var restaurantlist = new Array();
			
			$("#restaurant_table ul").each(
				function(){

				restaurant = {
						"title": $(".title a", $(this)).html(),

						"street": $(".street", $(this)).html(),
						"number": $(".number", $(this)).html(),

						"zip": $(".zip", $(this)).html(),
						"city": $(".city", $(this)).html(),

						"link": $(".title a", $(this)).attr("href"),

						"lat": $(".lat", $(this)).html(),
						"lng": $(".lng", $(this)).html()
					}
					
					restaurantlist.push(restaurant);

				}
			);


			created = 0;
			for(var i=0; i < restaurantlist.length; i++){

				if(restaurantlist[i].lat !== 0 && restaurantlist[i].lng !== 0){
					if(!marker_list[restaurantlist[i].lat+"-"+restaurantlist[i].lng]){
						myLatlng = new google.maps.LatLng(restaurantlist[i].lat, restaurantlist[i].lng);
					
						info = 
							'<div style="overflow: auto; text-align: left;"><strong style="white-space:nowrap;">'+restaurantlist[i].title+'</strong><br/>'+
							restaurantlist[i].street+' '+restaurantlist[i].number+'<br/>'+
							restaurantlist[i].zip+' '+restaurantlist[i].city+'<br/>';
						
							info += '<a href="'+restaurantlist[i].link+'">Details anzeigen</a>';
							
						info += '</div>';
		
						title = 'Rauchfreies Lokal ' + restaurantlist[i].title;

					    createMarker(myLatlng, map, title, info, '/img/markers/blue-dot.png', '/img/markers/msmarker.shadow.png');
				
						created++;
					}
				}
			}
			
			// check if bounds have changed
			var new_bounds = map.getBounds();
			new_bounds_sw = new_bounds.getSouthWest();
			new_bounds_ne = new_bounds.getNorthEast();
			
			// if map moved during last request, send a new one
			var diffFromLastPosition = new_bounds_sw.lat()-new_bounds_sw.lat();
			if(diffFromLastPosition !== 0){
				getRestaurantsInBounds(map);
			}

			ajaxRequestRunning = false;
		},
		error: function(){
			//alert('Something went wrong...');
			ajaxRequestRunning = false;
		
		}
	});
}



function HomeControl(controlDiv, map) {

  // Set CSS styles for the DIV containing the control
  // Setting padding to 5 px will offset the control
  // from the edge of the map
  controlDiv.style.padding = '5px';

  // Set CSS for the control border
  var controlUI = document.createElement('DIV');
  controlUI.style.backgroundColor = 'white';
  controlUI.style.borderStyle = 'solid';
  controlUI.style.borderWidth = '2px';
  controlUI.style.cursor = 'pointer';
  controlUI.style.textAlign = 'center';
  controlUI.title = 'Alle rauchfreien Lokale in Österreich anzeigen';
  controlDiv.appendChild(controlUI);

  // Set CSS for the control interior
  var controlText = document.createElement('DIV');
  controlText.style.fontFamily = 'Arial,sans-serif';
  controlText.style.fontSize = '12px';
  controlText.style.paddingTop = '1px';
  controlText.style.paddingLeft = '4px';
  controlText.style.paddingRight = '4px';
  controlText.innerHTML = 'Ganz Österreich';
  controlUI.appendChild(controlText);

  // Setup the click event listeners: simply set the map to
  // Chicago
  google.maps.event.addDomListener(controlUI, 'click', function() {
  
  	boundsNeverChanged = false;
  	
	var austria = new google.maps.LatLng(47.61357,13.084717);

	map.setCenter(austria)
	map.setZoom(7);
  });
}

function PositionControl(controlDiv, map) {

  // Set CSS styles for the DIV containing the control
  // Setting padding to 5 px will offset the control
  // from the edge of the map
  controlDiv.style.padding = '5px';

  // Set CSS for the control border
  var controlUI = document.createElement('DIV');
  controlUI.style.backgroundColor = 'white';
  controlUI.style.borderStyle = 'solid';
  controlUI.style.borderWidth = '2px';
  controlUI.style.cursor = 'pointer';
  controlUI.style.textAlign = 'center';
  controlUI.title = 'Rauchfreie Lokale in der Nähe anzeigen';
  controlDiv.appendChild(controlUI);

  // Set CSS for the control interior
  var controlText = document.createElement('DIV');
  controlText.style.fontFamily = 'Arial,sans-serif';
  controlText.style.fontSize = '12px';
  controlText.style.paddingTop = '1px';
  controlText.style.paddingLeft = '4px';
  controlText.style.paddingRight = '4px';
  controlText.innerHTML = 'Aktuelle Position';
  controlUI.appendChild(controlText);

  // Setup the click event listeners: simply set the map to
  // Chicago
  google.maps.event.addDomListener(controlUI, 'click', function() {
  
  	boundsNeverChanged = false;
  
	var lat = google.loader.ClientLocation.latitude;
	var lng = google.loader.ClientLocation.longitude;

	var myLatlng = new google.maps.LatLng(lat, lng);

	map.setZoom(10);
	map.panTo(myLatlng);
  });
}


function da_stinkts_net_initialize() {
	
	
	// Find ALL <form> tags on your page and add onsubmit action
	$('form').submit(function(){
	    // On submit disable its submit button
	    $('input[type=submit]', this).attr('disabled', 'disabled').attr('value', 'Bitte warten ...').fadeTo(0, 0.5);
	    $('input', this).attr('readonly', 'readonly').fadeTo(0, 0.5);
	    $('textarea', this).attr('readonly', 'readonly').fadeTo(0, 0.5);
	});



	// Minimum Zoom
	var min_zoom = 6;
	
	var map_container = false;
	var data_container = false;
	
	// index.ctp
	if(document.getElementById("restaurant_table") && document.getElementById("google_map")){
		map_container = "google_map";
		data_container = "restaurant_data";


		parse_restaurant_table = true;
		parse_restaurant_detail = false;
	}
	
	// view.ctp
	if(document.getElementById("restaurant_data_view") && document.getElementById("google_map_detail")){
		map_container = "google_map_detail";
		data_container = "restaurant_data_view";


		parse_restaurant_table = false;
		parse_restaurant_detail = true;
	}

		
	// overview map
	// http://da.stinkts.net/{CITY}.html
	if(map_container && data_container){
	

		if(parse_restaurant_table){
			var restaurantlist = new Array();
			
			$("#restaurant_table ul").each(
				function(){

				restaurant = {
						"title": $(".title a", $(this)).html(),

						"street": $(".street", $(this)).html(),
						"number": $(".number", $(this)).html(),

						"zip": $(".zip", $(this)).html(),
						"city": $(".city", $(this)).html(),

						"link": $(".title a", $(this)).attr("href"),

						"lat": $(".lat", $(this)).html(),
						"lng": $(".lng", $(this)).html()
					}
					
					restaurantlist.push(restaurant);

				}
			);
		}

		if(parse_restaurant_detail){
			var restaurantlist = new Array();
			
				restaurant = {
					"title": $("h1 .restaurant_title").html(),

					"street": $(".restaurants_detail .street").html(),
					"number": $(".restaurants_detail .number").html(),

					"zip": $(".restaurants_detail .zip a").html(),
					"city": $(".restaurants_detail .city a").html(),

					"link": false,

					"lat": $(".restaurants_detail .lat").html(),
					"lng": $(".restaurants_detail .lng").html()
				};
					
				restaurantlist.push(restaurant);

		}
		
		eval(document.getElementById(data_container).innerHTML);
		
		
		var myZoom = 10;
		var maxLat = 0;
		var maxLng = 0;

		var minLat = 100000;
		var minLng = 100000;

		var avgLat = 0;
		var avgLng = 0;
	
		var fitBounds = false;
	


		if(override_position && google.loader.ClientLocation){
			avgLat = google.loader.ClientLocation.latitude;
			avgLng = google.loader.ClientLocation.longitude;



			if(document.cookie){

				cookie_lines = document.cookie.split(";");

				for(var c = 0; c < cookie_lines.length; c++){
					cookie_line_data = cookie_lines[c].split("=");
										
					if(trim(cookie_line_data[0]," ") == "last-position-lat"){
						avgLat = trim(cookie_line_data[1]," ")*1.0;
					}
					if(trim(cookie_line_data[0]," ") == "last-position-lng"){
						avgLng = trim(cookie_line_data[1]," ")*1.0;
					}
					if(trim(cookie_line_data[0]," ") == "last-position-zoom"){
						myZoom = trim(cookie_line_data[1]," ")*1.0;
					}
				}

			}
		}else{

			// get average latlng
			for(i=0; i < restaurantlist.length; i++){
				if(restaurantlist[i].lat && restaurantlist[i].lng && restaurantlist[i].lat != 0 && restaurantlist[i].lng != 0){
					maxLat = Math.max(maxLat, restaurantlist[i].lat);
					maxLng = Math.max(maxLng, restaurantlist[i].lng);

					minLat = Math.min(minLat, restaurantlist[i].lat);
					minLng = Math.min(minLng, restaurantlist[i].lng);
				}
			}
			avgLat = (maxLat+minLat)/2;
			avgLng = (maxLng+minLng)/2;
			
			fitBounds = true;
		}
		

		
		if(restaurantlist.length == 1){
			fitBounds = false;
			switch(restaurantlist[0].city){
				case "Wien": myZoom = 15; break;
				case "Linz": myZoom = 14; break;
				case "Graz": myZoom = 14; break;
				case "Salzburg": myZoom = 14; break;
				default: myZoom = 10; break;

			}
			
		}

	
	    var myLatlng = new google.maps.LatLng(avgLat,avgLng);

		var myOptions = {
	      zoom: myZoom,
	      center: myLatlng,
	      mapTypeId: google.maps.MapTypeId.ROADMAP,
	      scrollwheel:false
	    };
	    var map = new google.maps.Map(document.getElementById(map_container), myOptions);

		var homeControlDiv = document.createElement('DIV');
		var homeControl = new HomeControl(homeControlDiv, map);
		homeControlDiv.index = 1;
		map.controls[google.maps.ControlPosition.TOP_RIGHT].push(homeControlDiv);


		var positionControlDiv = document.createElement('DIV');
		var positionControl = new PositionControl(positionControlDiv, map);
		positionControlDiv.index = 2;
		map.controls[google.maps.ControlPosition.TOP_RIGHT].push(positionControlDiv);

		

		if(fitBounds){
			var southWest = new google.maps.LatLng(minLat,minLng);
			var northEast = new google.maps.LatLng(maxLat,maxLng);
			var bounds = new google.maps.LatLngBounds(southWest,northEast);
			map.fitBounds(bounds);
		}

		var title;
		var info;

		for(i=0; i < restaurantlist.length; i++){
		

			if(restaurantlist[i].lat !== 0 && restaurantlist[i].lng !== 0){
				myLatlng = new google.maps.LatLng(restaurantlist[i].lat, restaurantlist[i].lng);
		
				info = 
					'<div style="overflow: auto; text-align: left;"><strong style="white-space:nowrap;">'+restaurantlist[i].title+'</strong><br/>'+
					restaurantlist[i].street+' '+restaurantlist[i].number+'<br/>'+
					restaurantlist[i].zip+' '+restaurantlist[i].city+'<br/>';
				
					if(restaurantlist[i].link){
						info += '<a href="'+restaurantlist[i].link+'">Details anzeigen</a>';
					}
					
				info += '</div>';

				title = 'Rauchfreies Lokal ' + restaurantlist[i].title;
		
			    createMarker(myLatlng, map, title, info, false);
			}
		}

//		Event.observe('update_map_data', 'click', function(event) {

		google.maps.event.addListener(map, 'bounds_changed', function() {
			
			// dont do anything for the first bounds_changed
			if(boundsNeverChanged){
				boundsNeverChanged = false;
				// return true;
			}


			// update cookie of client position
			center = this.getCenter();
			var a = new Date();
			a = new Date(a.getTime() +1000*60*60*24*365);
			document.cookie = 'last-position-lat='+center.lat()+';expires='+a.toGMTString()+';'; 
			document.cookie = 'last-position-lng='+center.lng()+';expires='+a.toGMTString()+';'; 
			document.cookie = 'last-position-zoom='+this.getZoom()+';expires='+a.toGMTString()+';'; 

			var bounds = map.getBounds();

			bounds_sw = bounds.getSouthWest().lat()+','+bounds.getSouthWest().lng();
			bounds_ne = bounds.getNorthEast().lat()+','+bounds.getNorthEast().lng();

			document.cookie = 'last-position-bounds-sw='+bounds_sw+';expires='+a.toGMTString()+';'; 
			document.cookie = 'last-position-bounds-ne='+bounds_ne+';expires='+a.toGMTString()+';'; 


			
			// send AJAX-Request only if there is no running Request
			if(!ajaxRequestRunning){
				ajaxRequestRunning = true;
				getRestaurantsInBounds(this);
			}

			
		});

		google.maps.event.addListener(map, 'dragend', function() {
			// after dragging the map, restaurants in bounds should be updated
			//getRestaurantsInBounds(this);
		});

		
		
		$('set_client_position').click(function(event){
			var clientLatlng = new google.maps.LatLng(
				google.loader.ClientLocation.latitude,
				google.loader.ClientLocation.longitude
			);
			map.setCenter(clientLatlng);
			map.setZoom(12);
			Event.stop(event);
		});
		

	
		// set a min zoom level of 7 (austria)
		google.maps.event.addListener(map, 'zoom_changed', function() {
	    zoomLevel = map.getZoom();

	    if (zoomLevel < min_zoom) {
	      map.setZoom(min_zoom);
	    }      
	  });
  
	}
	
}


$(document).ready(da_stinkts_net_initialize);

