jQuery(function($){
	var map = new GMap2(document.getElementById("offices-map"));
	map.setCenter(new GLatLng(56.052868, 12.700195), 12);
	map.addControl(new GSmallMapControl());
	
	var geocoder = new GClientGeocoder();
	
	var tags = {};
	
	for(var i = 0; i < offices.length; i++)
	{
		addOffice(offices[i], i);
	}
	
	function addOffice(office, index)
	{
		for(var tag, i = 0; i < office.tags.length; i++)
		{
			tag = office.tags[i].toLowerCase();
			if(tags[tag])
			{
				tags[tag]++;
			}
			else
			{
				tags[tag] = 1;
			}
		}
		geocoder.getLatLng(
			office.address + ", Sweden",
			function(point) {
				if (point) {
					var marker = new GMarker(point);
					offices[index].marker = marker;

					map.addOverlay(marker);
					//marker.openInfoWindowHtml(address);
					GEvent.addListener(marker, "click", function(overlay, latlng) {
						marker.openInfoWindow('<h3>' + office.name + '</h3><p class="address">' + office.address + '</p><p class="link"><a href="?office=' + office.id + '">Läs mer om ' + office.name + ' »</a></p>');
					});
				}
			}
		);
	}
	
	function filterMapsByTags()
	{
		var sortByTags = new Array();
		$('#tag-chooser li.selected').each(function(){
			sortByTags.push($(this).text());
		});
		for(office in offices)
		{
			var office = offices[office], 
				visible = false;
			if(sortByTags.length == 0)
			{
				visible = true;
			}
			else
			{
				for(key in sortByTags)
				{
					if(inArray(sortByTags[key], office.tags))
					{
						visible = true;
						break;
					}
				}
			}

			if(visible)
			{
				office.marker.show();
			}
			else
			{
				office.marker.hide();
			}
		}
	}
	
	function inArray(needle, haystack)
	{
		for(key in haystack)
		{
			if(haystack[key].toLowerCase() == needle)
			{
				return true;
			}
		}
		return false;
	}
	
	tagArray = new Array();
	
	for(tag in tags)
	{
		tagArray.push({name: tag, count: tags[tag]});
	}
	
	tagArray.sort(function(a, b) {
		return (a.count > b.count ? -1 : (a.count < b.count ? 1 : 0));
	});

	for(var tag, i = 0; i < tagArray.length; i++)
	{
		tag = tagArray[i];
		$('#tag-chooser').append('<li title="' + (tag.count > 1 ? tag.count : 'Ett') + ' kontor har kompetens inom &quot;' + tag.name + '&quot;">' + tag.name + '</li>');
	}
	
	$('#tag-chooser li').click(function() {
		$(this).toggleClass('selected');
		filterMapsByTags();
	});

});
