/*
By: mhuang@joby.com
For: Joby Around the World site
Uses: jQuery, Google Maps API 3
*/


;(function($) {

	var map;
	var current_marker;

	$.fn.jobyGalleryMap = function(settings) {
		var config = {};
		
		if (settings) $.extend(config, settings);
		
		this.each(function() {
			initMap(this);
		});
		
		return this;
	}
	
	function initMap(elem) {
		var latlng = new google.maps.LatLng(0,0);
		var mapOptions = {
			zoom: 4,
			center: latlng,
			mapTypeId: google.maps.MapTypeId.TERRAIN,
			mapTypeControl: true,
			mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
			navigationControl: true,
			navigationControlOptions: {style: google.maps.NavigationControlStyle.ZOOM_PAN}
		};
		map = new google.maps.Map(elem, mapOptions); //document.getElementById("map_canvas")
		
		loadPictures();
	} 
	
	// add points to the map based 
	function loadPictures() {
		var latLngBounds = new google.maps.LatLngBounds( );
	  
		$(".thumbs .thumb").each(function(){
			var marker = readMarker(this, latLngBounds);
			if (marker != null) {			
				google.maps.event.addListener(marker, 'click', function() {
					//infowindow.open(map,marker);
					window.location.href = url;
				});
				// check to see if it's the current one
				if ($(this).hasClass('current')) {
					current_marker = marker;
					current_marker.setIcon('http://code.google.com/apis/maps/documentation/v3/examples/images/beachflag.png');
				}
			}
		});
		
		/*$(".pictureframe").each(function(){
			var current_marker = readMarker(this, latLngBounds);
			current_marker.setIcon('http://code.google.com/apis/maps/documentation/v3/examples/images/beachflag.png');
		});*/
		
		map.setCenter(latLngBounds.getCenter());
		map.fitBounds(latLngBounds);
	}

	function readMarker(elem, latLngBounds) {
		var lat = 	$(elem).find(".meta .lat").text();
		var lon = 	$(elem).find(".meta .lon").text();
		var title = $(elem).find("img").attr('title');
		var url = 	$(elem).find("a").attr('href');
		
		// check to see that both lat and lon are set
		if (lat != '' && lon != '') {
		
			var latLng = new google.maps.LatLng(lat, lon);
			
			latLngBounds.extend( latLng );
	
			var marker = new google.maps.Marker({
				position: latLng,
				map: map,
				title: title
			});
			
			return marker;
		}
		return null;
	}
	
})(jQuery);
 


