var geocoder;
var map;
var bounds = new google.maps.LatLngBounds();
var infoWindow = new google.maps.InfoWindow();
$(document).ready(function(){
	if ($('#map_canvas').length > 0){
		$('#map_canvas').one('inview', function (event, visible) {
		  if (visible == true) {
		    initialize();
		  } else {
		    // element has gone out of viewport
		  }
		});
	}
});
function initialize() {
	geocoder = new google.maps.Geocoder();
	var latlng = new google.maps.LatLng(-34.397, 150.644);
	var myOptions = {
	  zoom: 8,
	  center: latlng,
	  mapTypeId: google.maps.MapTypeId.HYBRID,
	  disableDefaultUI: true,
	  navigationControl: true
	}
	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	
	var locationData = $('.location-data li', $('.location'));
	var length = locationData.length;
	var counter = 0;
	locationLoop(counter);
	function locationLoop(i){
		locationData.eq(i).animate({'opacity':0},1000, function(){
			codeAddress($(this));
			if (i < length) {
				i++
				locationLoop(i);
			}
		});
	}
}

function codeAddress(data) {
	var address = data.children('.loc').text();
	var image = data.children('.image').text();
	var name = data.children('.sn').text();
	var description = data.children('.desc').text();
	if (geocoder) {
	  geocoder.geocode( { 'address': address}, function(results, status) {
	    if (status == google.maps.GeocoderStatus.OK) {
	    	bounds.extend(results[0].geometry.location);
			map.fitBounds(bounds);
			var marker = new google.maps.Marker({
			  map: map, 
			  position: results[0].geometry.location,
			  icon: new google.maps.MarkerImage(image, new google.maps.Size(48,48), new google.maps.Point(0,0), new google.maps.Point(30,60), new google.maps.Size(48,48))
			});

			google.maps.event.addListener(marker, 'click', function() {
				$('.description', $('#map_canvas')).remove();
				$('#map_canvas').append('<div class="description"><h1>' + name + '</h1>' + '<p>' + description + '</p><small>' + address + '</small></div>');
				//infoWindow.open(map, marker);
				
			});

	    } else {
	      //console.log("Geocode was not successful for the following reason: " + status);
	    }
	  });
	}
}
