var map;

$(function(){
	$('.kjo-link').remove();

	$('#player-spotlight h3 a').player_spotlight_refresh({ image: '/wordpress/wp-content/themes/scottish/images/silhouette.png' });
	
	$('#stats').setup_tabs();
	
	$('#filter a[href="#schedule"]').toggle_schedule();
	
	$('.gag').swap_images({
		hover: '/wordpress/wp-content/themes/scottish/images/silhouette-stache.png',
		normal: '/wordpress/wp-content/themes/scottish/images/silhouette.png'
	});

	$.show_directions_map();
});

$.fn.player_spotlight_refresh = function(settings) {
	settings = $.extend({
		image: 'normal.png'
	}, settings);

	$(this)
		.show()
		.click(function(e) {
			e.preventDefault();
			$.getJSON(
				'/players/spotlight/?player='+$('input[name=current_player_spotlight]').val(),
				function(data){
					var spotlight = $('#player-spotlight');
					spotlight.find('input[name=current_player_spotlight]').val(data.player.id);
					
					if(data.player.image)
						spotlight.find('.profile').attr('src', '/wordpress/wp-content/uploads/players/'+data.player.image);
					else
						spotlight.find('.profile').attr('src', settings.image);
					spotlight.find('h4').html(data.player.first_name + ' ' + data.player.last_name);
					spotlight.find('.height').html('<strong>Height:</strong> ' + data.player.height);
					spotlight.find('.weight').html('<strong>Weight:</strong> ' + data.player.weight);
					spotlight.find('.century').html('<strong>Century Club:</strong> ' + data.player.century_club + ' games played');
					spotlight.find('p a').attr('href', '/players/profile/?player=' + data.player.id);
				}
			);
		});
}

$.fn.setup_tabs = function() {
	$(this).each(function(t) {
		var tabsDiv = $(this);
		var list = '';
	
		//for the h2 in each tab div
		$(tabsDiv).find("h3").each(
			function(h){
				var tabId = "tab" + t + "-" + h;
				$(this).html('<a id="'+tabId+'" tabindex="-1">'+ $(this).text() + '</a>');
				list += '<li><a href="#' + tabId + '">' + $(this).text() + '</a></li>';
			}
		);
		$(tabsDiv).prepend('<ul class="tabsMenu">' + list + '</ul>').find(">div").addClass("tab").hide();
		var current = $('input[name="team"]').val();

		$(tabsDiv).find(".tab").eq(current).show();
		$(tabsDiv).find(".tabsMenu>li").eq(current).toggleClass("current");
		//for each tabs menu link
		$(tabsDiv).find(">ul>li>a").each(
			function(a){
				$(this).click(
					function(e){	
						e.preventDefault();
						var target = $(this).attr("href");
						$(tabsDiv).find(">ul>li.current").removeClass("current").find(">a>span").remove();
						$(this).blur();
						$(tabsDiv).find(".tab:visible").hide();
						$(tabsDiv).find(".tab").eq(a).show();
						$('input[name="team"]').val(a);
						$(this).parent().addClass("current");
						//set focus to target h2 anchor inside the relevant, previously hidden tab -- NOTE: focus is being set AFTER the span is written to the tabs menu li anchor
						$($(this).attr("href")).focus();
					}
				);
			}
		);
	});
}

$.fn.swap_images = function(images) {
	images = $.extend({
		hover: 'hover.png',
		normal: 'normal.png'
	}, images);
	
	$(this).hover(
		function() {
			$(this).attr('src', images.hover);
		},
		function() {
			$(this).attr('src', images.normal);
		}
	);
}

jQuery.fn.toggleText = function(needles) {
	return $(this).each(function() {
		if (typeof needles == 'string') { needles = [needles]; }
		
		for (var needleKey=0; len=needles.length,needleKey<len; needleKey++) {
			var text = $(this).text();
			var regex = new RegExp(needles[needleKey], 'i')
			
			if (text.match(regex)) {
				$(this).text(text.replace(regex, ''));
			} else {
				$(this).text(text+' '+needles[needleKey]);
			}
		}
	});
};

$.fn.toggle_schedule = function(e) {
	$('tr.past').toggle();
	$(this).click(function(e) {
		$('tr.past').toggle();
		$(this).toggleText(['Hide Past Matches','Show Past Matches']);
		e.preventDefault();
	});
}

jQuery.show_directions_map = function() {
	if(document.getElementById('map')) {
		var latlng = new google.maps.LatLng(0, 0);
		map = new google.maps.Map(document.getElementById("map_canvas"), {
			zoom: 12,
			center: latlng,
			disableDefaultUI: true,
			mapTypeId: google.maps.MapTypeId.ROADMAP      
		});
		$.create_map_controls();

		var icon = image = "/wordpress/wp-content/themes/scottish/images/maps/marker.png";
		var geocoder = new google.maps.Geocoder();
		var bounds = new google.maps.LatLngBounds();
		
		var addresses = [{ 'address': "700 Longfields Drive, Ottawa, Ontario", 'notes': ""}];
		
		$.each(addresses, function(){
			var location = this;
			geocoder.geocode({'address': location.address.toString()}, function(results, status) {
				if (status == google.maps.GeocoderStatus.OK) {
					var marker = new google.maps.Marker({
						position: results[0].geometry.location,
						map: map,
						icon: icon,
						title: location.address.toString()
					});
					bounds.extend(marker.position);
					
					var content = '<div class="window">' + 
						'<h3>Barrhaven Scottish Field</h3>' + 
						'<p>'+location.address.toString()+'</p>' + 
						'<p>'+location.notes.toString()+'</p>' + 
						'</div>';
					var infowindow = new google.maps.InfoWindow({ content: content });
					
					google.maps.event.addListener(marker, 'click', function() {
						infowindow.open(map,marker);
					});
				} else {
					alert("Geocoder failed due to: " + status);
				}
				map.setCenter(bounds.getCenter());
			});
		});
		
		$('#map').before('<p><em><a href="http://maps.google.ca/maps?q=700+Longfields+Drive,+Ottawa,+Ontario&hl=en&sll=45.281755,-75.744344&sspn=0.006945,0.007682&vpsrc=0&hnear=700+Longfields+Dr,+Ottawa,+Ottawa+Division,+Ontario&t=m&z=17">'+addresses[0].address+'</a></em></p>');
	}
}

jQuery.create_map_controls = function() {
	$('#mapcontrols button').click(function() { return false; });				
	$('#centerButton').click(function() { map.panTo(bounds.getCenter()); });
	$('#upButton').click(function() { map.panBy(0,-20); });
	$('#downButton').click(function() { map.panBy(0,20); });
	$('#rightButton').click(function() { map.panBy(20,0); });
	$('#leftButton').click(function() { map.panBy(-20,0); });
	$('#zoomInButton').click(function() { map.setZoom(map.zoom + 1); });
	$('#zoomOutButton').click(function() { map.setZoom(map.zoom - 1); });
}
