var map;
var arrMarkers = [];
var arrInfoWindows = [];

$(document).ready(function() {
	var groupId;
	// initialize map (create markers, infowindows and list)
	if ($('#mapgroup').length) { // implies *not* zero
	    groupId 				= $('#mapgroup').html();
	  } else {
	    groupId					= 23;
	  }
	  
	mapInit(groupId);
	
	// "live" bind click event
	$("#maplist a").live("click", function(){
		var i = $(this).attr("rel");
		// close open windows before opening the selected one
		for(x=0; x < arrInfoWindows.length; x++){ arrInfoWindows[x].close(); }
		// open window
		arrInfoWindows[i].open(map, arrMarkers[i]);
	});
});

function mapInit(groupId){
	var setZoom,setLat,setLng;
	
	if (groupId == '23'){
		setZoom			= 7;
		setLat			= 46.428087;
		setLng			= -122.277832;
		
	} else {
		setZoom			= 4;		
		setLat			= 40;
		setLng			= -100;
	}
	var centerCoord = new google.maps.LatLng(setLat,setLng);
	var mapOptions = {
		zoom: 			setZoom,
		center: 		centerCoord,
		mapTypeId: 		google.maps.MapTypeId.ROADMAP
	};
	map = new google.maps.Map(document.getElementById("map"), mapOptions);
	
	$.ajax({ 
			type: "GET",
			dataType: "json",
			url: "/share/api/1/index.php/group/" + groupId + "/contact",
			success: dataLoop
	});

}

function dataLoop(data)
{	
	var count = data.ContactList.Contact.length;
	
	$("#maplist").append('<ul id="markers">');
	
	$.each(data.ContactList.Contact, function(i, contact){
		//console.log(contact);
		var address = contact.MailingAddressIDObject;
		if (contact.PhoneWork)
			var phone	= contact.PhoneWork;
		else
			var phone	= '';
			
		if (contact.Email)
			var email 	= contact.Email;
		else
			var email	= '';
		
		if (contact.Website)
			var website = contact.Website;
		else
			var website	= '';
				
		$("#maplist").append('<li><a href="#maplink" rel="' + i + '">' + contact.OrganizationName + '</a></li>');
		var marker = new google.maps.Marker({
			position: new google.maps.LatLng(address.Lat, address.Lng),
			map: map,
			title: address.FullName
		});
		arrMarkers[i] = marker;
		var infowindow = new google.maps.InfoWindow({
			content: "<div style='width:250px;height:150px'><b>"+ contact.OrganizationName +"</b><br />"+ address.Line1 +"<br />"+ address.City + ", " + address.State + " " + address.Zip + "<br />" + phone + "<br />" + email + "<a href='http://" + website + "'>" + website +"</a><br /><a target='_blank' href='http://maps.google.com/maps?q="+ address.Line1 + "%20" + address.City + "%20" + address.State + "%20" + address.Zip + "'>Click here for directions</a></div>"
		});
		arrInfoWindows[i] = infowindow;
		google.maps.event.addListener(marker, 'click', function() {
			infowindow.open(map, marker);
		});
		
		if (count == i+1) $("#maplist").append('</ul>');
	});
}
