// Note that using Google Gears requires loading the Javascript
// at http://code.google.com/apis/gears/gears_init.js

var aedRequestSent = 0;

var currentLocation = null;
var currentLocationMarker = null;
var geolocationTimeout = null;
var currentLocationTimeout = null;

var errorMsgTimeout = null;

var markers = [];

var zurich = new google.maps.LatLng(47.366667, 8.55);

var browserSupportFlag =  new Boolean();

var aed_gmap = null;
var mmgr = null;
var dService = null;
var dDisplay = null;

var fromAddress = '';

var gmap_options = {
	zoom: 13,
	mapTypeId: google.maps.MapTypeId.ROADMAP
}

$(function() {
  /* init GMap */
  initGMap();

  /* Event handler  */
  $("#autoCL").click(getCurrentLocation);
  
  $("#showaed").submit(getLocFromAddress);
  
  $("#reset").click(resetForm);
  
  $("#aed_locations").delegate(".directions", "click", requestDirections);
  
  $("#showlocations").click(showLocations);
  
  /* try to get current location */
  getCurrentLocation();

});

function getLocFromAddress() {
  
  if(geolocationTimeout) {
    clearTimeout(geolocationTimeout);
  }
  
  var street = $("#str").val();
  var city = $("#ct").val();
  
  if(street == '' || city == "") {
    alert("Bitte geben Sie die Strasse und den Ort Ihres aktuellen Standortes ein");
    return false;
  }

  var geocoder = new google.maps.Geocoder();
  geocoder.geocode( { 'address': street + ", " + city + " Switzerland"},
    function(results, status) {

      if(status == "OK") {
        var position = {
          'coords': {
            'latitude': results[0].geometry.location.lat(),
            'longitude': results[0].geometry.location.lng()
          }
        };

        applyCurrentLocation(position);
        
        if(results[0].geometry.location_type == google.maps.GeocoderLocationType.APPROXIMATE) {
          $("#approxLocation").css("display", "block");
        }
        
        loadNearbyAEDS();
        
      }else if(status == "ZERO_RESULTS") {
        $("#clLoader").css("display", "block");
        $(".search_form").css("display", "none");

        $("#addressNotFound").css("display", "block");
        fadeErrorMsg("addressNotFound", 3000);
      }
    }
  );
    
  return false;
}

function handleNoAnswer() {
	$("#clLoader").slideUp();
  $(".search_form").slideDown();
  $("#noGeolocationPossible").css("display", "block");
  fadeErrorMsg("noGeolocationPossible", 3000);
}

function loadNearbyAEDS() {
	
  if(aedRequestSent) {
    return;
  }
  
	if(!currentLocation) {
		alert("bitte geben Sie zuerst Ihren aktuellen Standort an");
		return;
	}
	
	var getData = {lat: currentLocation.coords.latitude, lng: currentLocation.coords.longitude};

  aedRequestSent = 1;

  $.ajax({
  	url: base_url + 'getNearByAEDs.php',
  	type: 'GET',
  	data: getData,
  	dataType: 'json',
  	success: function(data) {
      aedRequestSent = 0;
  		if(data.status == 'ok') {

  			if(data.locations.length > 0) {

          var bounds = new google.maps.LatLngBounds(),
							marker = null,
							latlng = null,
							article = null,
							artcontent = '';
					
					var aed_locations = $("#aed_locations");
          

  				for(var x = 0;x<data.locations.length;x++) {
  				
  					article = $('<article>' + data.locations[x].html + '</article>');
  					//+ '<span class="small aedLocation">' + data.locations[x].title + ', ' + data.locations[x].strasse + '</span><br />' + data.locations[x].anmerkungen + '</article>');
  					aed_locations.append(article);
  					
  					latlng = new google.maps.LatLng(data.locations[x].latitude, data.locations[x].longitude);
						
						marker = new google.maps.Marker({
								position: latlng, 
								map: aed_gmap
						});
            
						markers.push(marker);
						bounds.extend(latlng);
  				}

					aed_gmap.fitBounds(bounds);
          
          $("#clLoader").slideUp();
          $(".search_form").slideUp();
          $("#locations").slideDown();
  					
  			}else {
  				alert("no nearby AEDs found");
  			}
  		}
  	}
  });
}
  
function handleNoGeolocation(errorFlag) {

  /* if (errorFlag == true) {
		alert("Geolocation service failed.");
	} else {
		alert("Your browser doesn't support geolocation.");
	} */
	handleNoAnswer();
  /*
	aed_gmap.setCenter(zurich);
	
	$("#clLoader").css("display", "none");
  $("#search_form").css("display", "block");*/
  
}

function getCurrentLocation() {
	if(!aed_gmap) {
    //if gmap is not ready, wait 2 seconds, then call yourself again
    geolocationTimeout = setTimeout(getCurrentLocation, 2000);
		return;
	}else if(currentLocationTimeout) {
    //check if a timeout for current location was set, and clear it
    clearTimeout(currentLocationTimeout);
  }

  $(".search_form").hide();
  $("#clLoader").show();

  //set a timeout for geolocation service (firefox workaround)
  geolocationTimeout = setTimeout(handleNoAnswer, 15000);  

	
  // Try W3C Geolocation (Preferred)
 
  if(navigator.geolocation) {
    browserSupportFlag = true;
    navigator.geolocation.getCurrentPosition(function(position) {
      clearTimeout(geolocationTimeout);
    	currentLocation = position;
      applyCurrentLocation(position);
     }, function() {
      handleNoGeolocation(browserSupportFlag);
    });
  // Try Google Gears Geolocation
  } else if (google.gears) {

    browserSupportFlag = true;
    var geo = google.gears.factory.create('beta.geolocation');
    geo.getCurrentPosition(function(position) {
    	clearTimeout(geolocationTimeout);
      
      currentLocation = position;
    	applyCurrentLocation(position);
    	
      //loadNearbyAEDS();
    }, function() {

      handleNoGeoLocation(browserSupportFlag);
    });
  // Browser doesn't support Geolocation
  } else {
    clearTimeout(geolocationTimeout);
    browserSupportFlag = false;
    handleNoGeolocation(browserSupportFlag);
  }
  
  return false;
}
 
function applyCurrentLocation(position) {
  // Create our "tiny" marker icon
  var blueIcon = new google.maps.MarkerImage(google.maps.G_DEFAULT_ICON);
  blueIcon.url = "http://gmaps-samples.googlecode.com/svn/trunk/markers/blue/blank.png";

	var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
	var marker = new google.maps.Marker({position: latlng, map: aed_gmap, icon: blueIcon});

	aed_gmap.setCenter(latlng);
	
	currentLocation = position;
  currentLocationMarker = marker;
    	
	// aed_gmap.panTo(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));

	//	$("#str").val(position.address.street + " " + position.address.streetNumber);
	//	$("#ct").val(position.address.city);
	loadNearbyAEDS();
}

function resetForm() {
  
  initGMap();
	
	$("#locations").hide();
  $("#directions").hide();
  $("#clLoader").hide();
  $(".search_form").show();
	
  $("#aed_locations").empty();
	$("#currLocation form input").not("input[type=submit]").val('');
  
  //applyCurrentLocation(currentLocation);
  
  return false;
}

function requestDirections(event) {

	var pos = $(event.target).attr("title").split(',');
	
	var request = {
		origin: new google.maps.LatLng(currentLocation.coords.latitude, currentLocation.coords.longitude),
		destination: new google.maps.LatLng(pos[0], pos[1]),
		provideRouteAlternatives: false,
    travelMode: google.maps.DirectionsTravelMode.WALKING,
    unitSystem: google.maps.DirectionsUnitSystem.METRIC		
  };
  
	dService.route(request, function(response, status) {
		if (status == google.maps.DirectionsStatus.OK) {
			
			dDisplay.setDirections(response);
      
      $("#locations").slideToggle(
        function() {
          $("#directions").show();
        }
      );
  	}
	});
	
	return false;
}

function removeMarkers() {
	for(var x = 0;x<markers.length;x++) {
		markers[x].setMap(null);
	}
}

function showLocations() {
	$("#directions").slideUp(
		function() {
			$("#locations").slideDown();	
		}
	);
}

function fadeErrorMsg(id, timeout) {
  setTimeout(
    function() {
      $("#" + id).fadeOut();
    }, timeout
  );
}

function initGMap() {

	aed_gmap = new google.maps.Map(document.getElementById("aed_gmap"), gmap_options);
	aed_gmap.setCenter(zurich);

	dService = new google.maps.DirectionsService();
	dDisplay = new google.maps.DirectionsRenderer();

	dDisplay.setMap(aed_gmap);
	dDisplay.suppressMarkers = true;
	dDisplay.setPanel(document.getElementById("gDisplayPanel"));
}
