//Written by Erik White
//http://erikwhite.net
//erikwhite@gmail.com
(function($){ //Allow functioning in no-conflict mode

	$(document).ready(function(){ //Start script when ready
		
		//Enhanced suckerfish navigation menu
		//Main navigation
		$("ul#nav").superfish({
			pathClass:     'active',            // the class you have applied to list items that lead to the active page 
			pathLevels:    1,                   // the number of levels of submenus that remain open or are restored using pathClass 
			delay:         3000,                // the delay in milliseconds that the mouse can remain outside a submenu without it closing 
			animation:     {opacity:'show'},    // an object equivalent to first parameter of jQuery’s .animate() method 
			speed:         'medium',            // speed of the animation. Equivalent to second parameter of jQuery’s .animate() method 
			autoArrows:    false                // if true, arrow mark-up generated automatically = cleaner source code at expense of initialisation performance     
		});
		//User bar navigation
		$("#user_bar ul.sf-menu").superfish({
			delay:         3000,                // the delay in milliseconds that the mouse can remain outside a submenu without it closing 
			animation:     {opacity:'show'},    // an object equivalent to first parameter of jQuery’s .animate() method 
			speed:         'fast',            // speed of the animation. Equivalent to second parameter of jQuery’s .animate() method 
			autoArrows:    false                // if true, arrow mark-up generated automatically = cleaner source code at expense of initialisation performance     
		}); 
 
		//Focus search box on page load
		//Disabled for the time being as it may be preferrable to use the default text instead.
		/*
		var input = document.getElementById ('s'); //Focus on the input field for easy access
		input.focus ();
		document.onkeydown = function (e) { //But if someone wishes to go back in their history, let them
			if (!e) {
				var e = window.event;
			}
			if (e.keyCode === 8 && !input.value) {
				history.back();
			}
		};
		*/
		
		//Tabbed navigation
		//Store nav elements in an array
		var tab_nav = new Array('#matches', '#fixtures_image', '#store');
		
		//Loop through array and assign events
		$.each(tab_nav,function(i,el){
			$(el + ' div').hide(); // Hide all divs
			$(el + ' div:first').show(); // Show the first div
			$(el + ' div div').show(); // Show the first div
			$(el + ' .tab_nav li:first').addClass('active'); //Set the first link's class to active
			$(el + ' .tab_nav li a.tab_link').click(function(){ //When any link is clicked
				$(el + ' .tab_nav li').removeClass('active'); // Remove active class from all links
				$(this).parent().addClass('active'); //Set clicked link class to active
				var currentTab = $(this).attr('href'); // Set variable currentTab
				$(el + ' div:visible').fadeOut('normal',function(){ //fade out visible div, speed set to normal
					$(currentTab).fadeIn('normal') //fade in target div, speed set to normal
				});return false;
			});
		});
 
		//Hover effect when over link text of top news item
		$(function() {
			$('div #news_top').hover( function(){ //On hover of #news_top
				$(this).find('a.top_read_more').css('background-image', 'url(/img/site/news_overlay_h.png)'); //Change background image of link
			},
			function(){
				$(this).find('a.top_read_more').css('background-image', 'url(/img/site/news_overlay.png)'); //Restore previous state on mouse out
			});
		});

		//Hover effect for news module link text
		$(function() {
			$('li.news_title').hover( function(){ //On hover of news title
				$(this).find('h2 a').css('color', '#2064b5'); //Change text colour
				//$(this).children('a.read_more').css('background-position', '0 -22px'); //Change background image of link if image sprite
				$(this).children('a.read_more').css('background-image', 'url(/img/site/read_more_h.png)'); //Change background image of link
			},
			function(){
				$(this).find('h2 a').css('color', '#3a3a3a'); //Restore previous state on mouse out
				//$(this).children('a.read_more').css('background-position', '0 0'); //Restore previous state on mouse out if image sprite
				$(this).children('a.read_more').css('background-image', 'url(/img/site/read_more.png)'); //Change background image of link
			});
		});

		//Hover effect when over recent news link text
		$(function() {
			$('#news_latest li').hover( function(){ //On hover of recent news list item
				$(this).find('h4 a').css('background-image', 'url(/img/site/news_overlay_h.png)'); //Change background image of link
			},
			function(){
				$(this).find('h4 a').css('background-image', 'url(/img/site/news_overlay.png)'); //Restore previous state on mouse out
			});
		});

		//Hover effect when over gallery list images
		$(function() {
			$('.gallery_list li').hover( function(){ //On hover of gallery list
				$(this).find('a').css('color', '#363636');
				$(this).find('.gallery_wrapper').css('background-color', '#A2A2A2');
			},
			function(){
				$(this).find('a').css('color', '#D3D3D3'); //Restore previous state on mouse out
				$(this).find('h3 a').css('color', '#CBE9FC');
				$(this).find('.gallery_wrapper').css('background-color', '#4A4A4A');
			});
		});
		
		//Show more profiles
		$(".squad_toggle").toggle(function () {
			$(".squad_extra li").fadeIn("slow");
			$(".squad_extra").slideDown("slow");
			$(this).html("Hide &uarr;");
			return false;
		},function() {
			$(".squad_extra li").fadeOut("slow");
			$(".squad_extra").slideUp("slow");
			$(this).html("Show more &darr;");
			return false;
		});

		//Horizontal nav
		var firstItem = $('.hor_nav li:first a');
		$('#nav_move').css({ 
			width: firstItem.width()+14, 
			height: firstItem.height()+14 
		});
		firstItem.addClass('cur');
      
		$('.hor_nav a').click(function() {
			var offset = $(this).offset();
			var offsetBody = $('#main').offset();//Find the offset of the wrapping div  
			
			$('#nav_move').animate(
				{
					width: $(this).width()+14, 
					height: $(this).height()+14, 
					left: (offset.left - offsetBody.left)
				}, 
				{ duration: 400, easing: 'swing' }
			);
		
			$('.cur').removeClass('cur');
			$(this).addClass('cur');
			return false;
		});

		//Filtering for fixtures listings
		if (document.getElementById("fixtures_list")) {
		
			//Fade up all elements except those passed to the function
			//Prevents elements going to opacity 1 and then fading again
			function showAll(el){
				$('.fixtures_title').not(el).fadeTo('normal', 1);
			}
			//Fade element to 0.5 opacity
			function fadeHalf(el){
				$(el).animate({
						opacity: 0.5
				});
			}
		
			//Set all opacities to 1 and do not exclude any items
			$('#fixtures_all').click(function() {
				showAll('');
			});
		
			//Store nav options in an array
			var nav_fixtures = new Array();
				nav_fixtures[0] = new Array('#fixtures_home', '.away');
				nav_fixtures[1] = new Array('#fixtures_away', '.home');
				nav_fixtures[2] = new Array('#fixtures_win', '.draw, .loss');
				nav_fixtures[3] = new Array('#fixtures_draw', '.win, .loss');
				nav_fixtures[4] = new Array('#fixtures_loss', '.draw, .win');
		
			//Loop through array and assign events
			$.each(nav_fixtures,function(i,fixture){
				$(fixture[0]).click(function() {
					//Exclude these items from fading up and fade them to 0.5 opacity
					showAll(fixture[1]);
					fadeHalf(fixture[1]);
				});
			});
			
		}//End if fixtures_list exists

		//Filtering for fixtures image listings
		if (document.getElementById("fixtures_image")) {
		
			//Hide future matches on load
			$('#fixtures_image #match_prev').hide();
		
			//Store nav options in an array
			var nav_fixtures = new Array();
				nav_fixtures[0] = new Array('#fixtures_home', '.away');
				nav_fixtures[1] = new Array('#fixtures_away', '.home');
				nav_fixtures[2] = new Array('#fixtures_win', '.draw, .loss');
				nav_fixtures[3] = new Array('#fixtures_draw', '.win, .loss');
				nav_fixtures[4] = new Array('#fixtures_loss', '.draw, .win');
		
			//Loop through array and assign events
			$.each(nav_fixtures,function(i,fixture){
				$(fixture[0]).click(function() {
					//Exclude these items from fading up and fade them to 0.5 opacity
					showAll(fixture[1]);
					fadeHalf(fixture[1]);
				});
			});
			
		}//End if fixtures_list exists
		
		//Animate training info pulldowns
		if (document.getElementById("training_schedule")) {
		
			var sourceEl = $('#training_schedule li');
			var targetEl = $('#training_info li');
			$(targetEl).hide();
			
			//Show or hide
			function showActive(el){
				$(el).slideDown("slow", function() { $(this).fadeTo(400, 1); } );
			}
			function hideActive(){
				$(targetEl).slideUp(450, function() { $(this).fadeTo(400, 0); } );
			}
			//Add or remove 'active' class from target element
			function setActive(el, addRemove){
				if( addRemove == 'add'){
					$(el).addClass('active');
				}else{
					$(el).removeClass('active');
				}			
			}
			//Fade in or out 
			function fadeEl(el, notEl, opacity){
				//Fade all except the clicked item
				$(el).not(notEl).animate({
					opacity: opacity
				}, 800 );
			}
			
			//Hide extra information, fade all menu items to 1 and remove 'active' classes
			$(sourceEl).not('.training_day').click(function(){
				hideActive();
				fadeEl(sourceEl, '', 1);
				setActive( sourceEl, 'remove');
			});
			
			//Cycle through information with effects on load
			$(sourceEl).filter('.training_day').each(function(i, el){
			
				//Append '_info'
				var day = "li[id='" + $(el).attr('id') + "_info']";
				setTimeout(function(){
					showActive(day);
					fadeEl(sourceEl, el, 0.45);					
					//Delay for a set time
					$(el).animate({ opacity: 1 }, 2000, function(){
						hideActive();
						fadeEl(sourceEl, '', 1);
					}); 
				}, i*3000);
			});
			
			//Show and hide extra information with fade effects
			$(sourceEl).filter('.training_day').click(function(){
				//Get the clicked item id and append '_info'
				var day = "li[id='" + $(this).attr('id') + "_info']";
				
				//Toggle visibilty of items when clicked
				if( $(this).hasClass('active') ){
					hideActive();
					setActive( sourceEl, 'remove');
					fadeEl(sourceEl, '', 1);
					var hideSwitch = 1;
				}else{
					hideActive();
					showActive(day);
					fadeEl(sourceEl, this, 0.45);
				}
				
				//Only continue with displaying the extra info if an item is clicked that is not currently visible
				if( hideSwitch != 1){
					//Clear all active classes and set this active
					setActive( sourceEl, 'remove');
					setActive( this, 'add');
					//Set the clicked item visible and fade the rest
					fadeEl(this, '', 1);
					fadeEl(sourceEl, this, 0.45);
				}					
			});
		}//End if training_schedule exists

		//Google maps with jQuery effects
		if (document.getElementById("map_overview")) {
				
			//Default map center location
			var defaultLat = 50.5;
			var defaultLon = -1.4;
			
			//Locations data
			var markers = new Array();
               markers[0] = new Array(new GMarker(new GLatLng(51.264949, -1.117666)), "Basingstoke", "<strong>Basingstoke Ice Rink</strong><br/>West Ham Leisure Pk, Basingstoke<br />Hampshire, RG22 6PG<br />01256 355266<br /><a href='http://www.planet-ice.co.uk'>planet-ice.co.uk</a>");
               markers[1] = new Array(new GMarker(new GLatLng(51.308124, -0.656756)), "Bisley", "<strong>Lord Roberts Centre</strong><br/>Bisley Camp, Pirbright<br />Woking, Surrey GU24 0NP<br />0845 130 6772");
               markers[2] = new Array(new GMarker(new GLatLng(50.82719221187368, -1.1597442626953125)), "Gosport", "<strong>Gosport Ice Rink</strong><br/>Forest Way, Gosport<br />Hampshire, PO13 0ZX<br />023 92511217<br /><a href='http://www.planet-ice.co.uk'>planet-ice.co.uk</a>");
               markers[3] = new Array(new GMarker(new GLatLng(50.933883, -1.397458)), "Southampton", "<img src='/img/site/logo_footer.png' width='43' height='42' class='fr' /><strong>University of Southampton</strong><br/>University Road<br />Southampton, SO17 1BJ<br />023 8059 5000<br /><a href='http://www.soton.ac.uk/'>soton.ac.uk</a>");

			var map = new google.maps.Map2($("#map_overview").get(0));//Initialise google maps
			map.setCenter(new GLatLng(defaultLat, defaultLon), 8);//Set location to the default and zoom level to 8
			map.disableDoubleClickZoom();//Disable zooming

			//This section works fine but does not animate on load
			/*
			$(markers).each(function(i,marker){
				  map.addOverlay(marker[0]);
				$("<li />")
					.html(markers[i][1])//Use list item label from array
					.click(function(){
						displayPoint(marker[0], i);
						setActive(this);//Show active state
						if ($('#map_message').is(':hidden')) {//Allow toggling of active state
							setActive();
						}
					})
					.appendTo("#map_list");
					
				   GEvent.addListener(marker[0], "click", function(){
					displayPoint(marker[0], i);
					   setActive(i);//Show active location
					if ($('#map_message').is(':hidden')) {//Allow toggling of active state
						setActive();
					}
				});
			});
			*/
				
			$.each(markers,function(i,marker){
				var delayTime = ((i * 3000) / (0.5 * markers.length));//Delay time decreases as number of markers increases
				
				setTimeout(function(){ 
					map.addOverlay(marker[0]);
					$("<li />")
						.html(markers[i][1])//Use list item label from array
						.click(function(){
							displayPoint(marker[0], i);
							setActive(this);//Show active state
						})
						.appendTo("#map_list");
					
					GEvent.addListener(marker[0], "click", function(){
						displayPoint(marker[0], i);
						setActive(i);//Show active location
					});
						
					displayPoint(marker[0], i);
					setActive(i);//Show active location
					if (i == (markers.length - 1)) {//If last item in array
						setTimeout(function(){//Fade marker after delay
							$("#map_message").fadeOut();
							//setActive();
						}, 3500);
					}
				}, delayTime);
			});
				
			$("#map_list").css("opacity","0.2").animate({opacity: 1}, 1100);//Fade in menu
			$("#map_message").appendTo(map.getPane(G_MAP_FLOAT_SHADOW_PANE));

			function displayPoint(marker, index){
				if ($('#map_message').is(':hidden')) {//Allow toggling of markers
					$('#map_message').fadeIn();
				}
				else{//Remove all .active classes and hide markers
					$('#map_message').hide();
					$("#map_list .active").removeClass();
				}
				//$("#map_message").hide();//Default behaviour, doesn't allow toggling of markers
					
				var moveEnd = GEvent.addListener(map, "moveend", function(){
					var markerOffset = map.fromLatLngToDivPixel(marker.getLatLng());
					$("#map_message")
						.html(markers[index][2])//Use information from array
						.fadeIn()
						.css({ top:markerOffset.y, left:markerOffset.x });
				GEvent.removeListener(moveEnd);
				});
				map.panTo(marker.getLatLng());
			}	
				
			function setActive(el){
				$("#map_list .active").removeClass();//Remove all .active classes
				$("#map_list").find('li').eq(el).addClass('active');//Find list element equal to index number and set active
				$(el).addClass('active');//Set active if list element clicked directly
			}
			
			//Unload google maps in case of memory leaks
			$(document).unload(
				function() {
					GUnload();
				}
			);
		}//End if map_overview exists
		
	}); //End document ready

})(jQuery);//End allow functioning in no-conflict mode

//Remember to remove trailing commas in arrays to prevent IE7 JS errors