﻿/**
* 
* Author: 
* Email: 
* URL: 
* Version: 0.0.2
* Licensed under the MIT License: http://dillerdesign.com/experiment/DD_belatedPNG/#license
*
* Example usage:
* 
* 
**/
(function($){
	var markers = [];
	
	$.addMarkers = function(dirs, map)
	{
		addMarker = function(fullAddress, callback)
		{
			geocoder = new GClientGeocoder();
			if (!geocoder){ status={'error':2,'msg':'Browser no compatible'};callback(status);return;};
			geocoder.getLocations(fullAddress, function(response){
				if (!response || response.Status.code != 200) {  
				     status={'error':1,'msg':fullAddress+' no pudo ser encontrada'};  
				} 
				else 
				{  
					place = response.Placemark[0]; 					 
					point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);   
					marker = new GMarker(point);  
					markers[markers.length++] = marker;
					map.addOverlay(marker);
				    status={'error':0};  				     
				}
				callback(status);
			})
		}
		addMarkersRec = function(dirs, index)
		{
			if (index == dirs.length)
			{
				mark = markers[0];
				// map.setCenter(mark.getLatLng(), 13);					   	
				 $(markers).each(function(i,marker){
										   GEvent.addListener(marker, "click", function(){
											map.panTo(marker.getLatLng());
											map.openInfoWindowHtml(marker.getLatLng(), dirs[i].infoHtml);
											}); 
										   });				
			}
			else
			{
				dir = dirs[index];
				if (dir.latlng)
				{
				   latlng = dir.latlng.split(',');
				   if (latlng.length != 2)
				   		$('#jquerymapmarkersdebug').append('<span style="display:block">Las coordenadas para '+dir.address+' son incorrectas</span>');
				   else
				  	{
						   point = new GLatLng(latlng[0], latlng[1]);  					 
							 marker = new GMarker(point);  
							 markers[markers.length++] = marker;
							 map.addOverlay(marker);
						}
					 addMarkersRec(dirs, index+1);
				}
				else
				{
					fullAddress = dir.address+","+dir.city+","+dir.cp;					
					addMarker(fullAddress, function(status){
					if (status.error == 2){ 
						$('#jquerymapmarkersdebug').append('<span style="display:block">'+status.msg+'</span>');						
					}else{
						if (status.error == 1) 
							$('#jquerymapmarkersdebug').append('<span style="display:block">'+status.msg+'</span>');						
							addMarkersRec(dirs, index+1);
						}
					});
				}
			}
		}
		addMarkersRec(dirs, 0);
	}
})(jQuery);