// General v1.0
// Andrew Pettican (May 2011)
//
// Changelog:
// v1.0 - 17/05/2011 - Initial build
// v1.1 - 25/05/2011 - Integrated Dmitry's changes
// v1.2 - 27/05/2011 - Integrated Dmitry's changes (gallery)
// v1.3 - 13/06/2011 - Updated #features_home to load main content each time the carousel moves
//////////////////////////////////////////////////////////////////

// ---------------------------------------------------------------
// Parameters
// ---------------------------------------------------------------

var gs_carousel_home_interval = -1;	// The interval between automated home carousel animations
var gs_carousel_home_duration = 1000;	// The duration of a home carousel animation
var gs_carousel_home_interval_without_autoload = -1;	// The interval between automated home carousel animations (when autoloading of the main feature is disabled)
var gs_carousel_home_duration_without_autoload = 1000;	// The duration of a home carousel animation (when autoloading of the main feature is disabled)
var gs_video_load_prefix = "video-";
var gs_audio_load_prefix = "audio-";

// ---------------------------------------------------------------
// Parameters End
// ---------------------------------------------------------------



// ---------------------------------------------------------------
// Global Vars, Do not change anything below this line!
// ---------------------------------------------------------------

var gs_mouseX = 0;	// The current mouse position (x-coordinate)
var gs_mouseY = 0;	// The current mouse position (y-coordinate)
var gs_scrollX = 0;	// The last scroll position when the mouse was moved (x-coordinate)
var gs_scrollY = 0;	// The last scroll position when the mouse was moved (y-coordinate)

// ---------------------------------------------------------------
// Global Vars End, Do not change anything above this line!
// ---------------------------------------------------------------



// ---------------------------------------------------------------
// Functions Start
// ---------------------------------------------------------------

/**
 * Toggles the suffix on the given filename.
 * If the suffix is found, it will be removed, if it is not found
 * it will be added.
 */
function toggle_filename_suffix(source, suffix)
{
	// Find where the file extension index
	var file_extension_index = source.lastIndexOf('.');
	if(file_extension_index > 0)
	{
		// Determine the filename and extension of the current src
		var filename = source.substr(0, file_extension_index);
		var file_extension = source.substr(file_extension_index);
		
		// Do the last 3 chars of the filename == suffix?
		if(filename.length > suffix.length && filename.substr(filename.length-3) === suffix)
		{
			// Remove suffix
			filename = filename.substr(0, filename.length-suffix.length);
		}
		else
		{
			// Add suffix
			filename += suffix;
		}
		
		source = filename + file_extension;
	}
	
	return source;
}


/**
 * Determines if the specified subnav should remain active based on the current mouse position
 * mouseX			- Current mouse x-coordinate
 * mouseY			- Current mouse y-coordinate
 * node				- The node to test against
 * outerDimensions	- Should outer dimensions be calculated (i.e. include the node's padding/border)
 * margin			- If outer dimensions are used, should the margin also be included?
 */
function is_mouseover(mouseX, mouseY, $node, outerDimensions, margin)
{
	// outerDimensions/margin default to true
	outerDimensions = (typeof(outerDimensions) === "boolean" ? outerDimensions : true);
	margin = (typeof(outerDimensions) === "boolean" ? margin : true);
	
	var answer = false;
	if($node !== null && $node.length === 1)
	{
		// Calculate the boundaries that the mouse must stay within.
		var nodeTopCoord = $node.offset().top;
		var nodeLeftCoord = $node.offset().left;
		var nodeBottomCoord = nodeTopCoord + (outerDimensions ? $node.outerHeight(margin) : $node.height());
		var nodeRightCoord = nodeLeftCoord + (outerDimensions ? $node.outerWidth(margin) : $node.width());
		
		// Is the mouse within these bounds?
		answer = (mouseY >= nodeTopCoord && mouseX >= nodeLeftCoord && mouseY <= nodeBottomCoord && mouseX <= nodeRightCoord);
		//alert("("+mouseX +"x"+ mouseY+")" + nodeTopCoord + ", " + nodeRightCoord + ", " + nodeBottomCoord + ", " + nodeLeftCoord + " = " + answer);
	}
	
	return answer;
}


/**
 * Function that preloads a defined list of images (arguments for the function).
 * Thanks: http://ppolyzos.com/2010/05/preload-images-with-jquery/
 */
jQuery.preloadImages = function()
{  
	//Loop through the images
	for(var i = 0; i<arguments.length; i++)
	{
		jQuery("<img>").attr("src", arguments[i]);
	}
}


/**
 * Sets the correct classes to all <li> elements in the navigation based on the current <a> node the mouse is over.
 * The classes set are as follows:
 *  - 'hover'		(the current <li> the mouse is over)
 *  - 'active'		(indicates any <li>'s which are always active -- this class is NOT set by javascript and will be preset in the html where necessary)
 *  - 'active_l'	(the <li> which is immediately to the left of the 'hover' <li>, unless that <li> is 'active')
 *
 * $target_link_node	- the current <a> node in the navigation that the mouse is over
 */
function set_nav_classes($target_link_node)
{
	// Fetch objects
	var $prev_target_li = $target_link_node.parents('li').prev('li');
	
	// Set classes
	$('ul#nav li a').each(function()
	{
		// Fetch objects
		var $this_li = $(this);
		var $parent_li = $this_li.parents('li');
		var $next_li = $parent_li.next('li');
		
		// If we are hovering over this li, or if its next sibling is inactive, remove 'active_l' class
		if($this_li.hasClass('hover') || !$next_li.hasClass('active'))
		{
			$parent_li.removeClass('active_l');
			
			// If we are hovering over this li, and the previous li that was targeted is inactive, add the 'active_l' class
			if($this_li.hasClass('hover') && !$prev_target_li.hasClass('active'))
			{
				$prev_target_li.addClass('active_l');
			}
		}
		
		// If we are not hovering over this li and its next sibling is active, add the 'active_l' class
		else if($next_li.hasClass('active'))
		{
			$parent_li.addClass('active_l');
		}
	});
}

/**
 * Stops all players except current
 * Incoming variables:
 *  - 'all_players'				array of selectors of all registered players
 *  - 'this_player'				selector id of current player
 *
 *  return boolean
 */
function stopOtherPlayers(all_players,this_player)
{
	var killEmAll = false;
	
	if(this_player == null){
		killEmAll = true;
	}
	//console.log(all_players);
	//alert(all_players);
	for(var i = 0; i<all_players.length;i++)
	{
		// stop the player if it is not current player
		if(!killEmAll)
		{
			if(all_players[i] != this_player)
			{
				$(all_players[i]).jPlayer("stop");				
			}
		}
		else {
			$(all_players[i]).jPlayer("stop");
		}		
	}	
}

var registered_players = new Array();

/**
 * Finds all players in the supplied container
 * Currenly created for 'judging panel', but could be expanded further.
 * 
 * Incoming variables:
 *  - 'carouselId'				id of the container  
 *
 *  return boolean
 */
function findAllPlayers(carouselId) {
			
	
	// get all players and their types					
	var number_of_players = $('ul.overview:first div.nonimage', carouselId).length;
	
	if(number_of_players != '')
	{
		var media_settings = new Array(number_of_players);
		for(var i = 0; i<media_settings.length; i++){
			media_settings[i] = new Array();
		}
		var m = 0;					
		
		$('ul.overview:first div.nonimage', carouselId).each(function(){
			var n = 0;			
			
			// get type of the media (video or audio)
			var media_type = "";
			media_type = (media_type == "" && $(this).hasClass('jp-video') ? "jp-video" : media_type);
			media_type = (media_type == "" && $(this).hasClass('jp-audio') ? "jp-audio" : media_type);
			media_settings[m][n++]= media_type;
			
			// get id of the media
			media_settings[m][n++]= "#"+$('div > div', this).eq(0).attr('id');
			
			//get interface id of the media
			media_settings[m][n++]= "#"+$('div > div', this).eq(1).attr('id');

			//get filename from the parent... (as on 'judging panel' page)
			if($(this).parent().attr('id')){
				media_settings[m][n++]= $(this).parent().attr('id');
			}
			else{
				media_settings[m][n++]= $('.current_entry:first').attr('id');
			}		
				
			m++;
			
			
		});	
		
		//console.log(media_settings);
		
		for(var i=0;i<number_of_players;i++)
		{
			// if player with such a name has been already created, destroy it, and create a new one
			
			var array_index = jQuery.inArray(media_settings[i][1],registered_players);
			if(array_index != -1)
			{
				//alert('not new!');
				$(media_settings[i][1]).jPlayer("destroy");										
				//also remove it from the currently registered players list	
				registered_players.splice(array_index,1);																						
			}			
			
			if(carouselId === "#carousel_box_judges")
			{
				registerPlayer(media_settings[i][3],media_settings[i][0],media_settings[i][1],media_settings[i][2], "judges");
			}
			else
			{
				registerPlayer(media_settings[i][3],media_settings[i][0],media_settings[i][1],media_settings[i][2]);
			}
		}
		
	}	
}


/**
 * Initializes media players for currently displayed news item
 * Incoming variables:
 *  - 'oFname'					filename
 *  - 'oType'					media type (audio of video)
 *  - 'oId'						id of the media
 *  - 'oInterfaceId'			id of the media interface
 *
 *  return boolean
 */
function registerPlayer(oFname,oType,oId,oInterfaceId,directory)
{
	// Security check, base_url MUST begin with "http://www.barclaysfootball.com/"
	if(!(typeof(base_url) === "string" && base_url.indexOf("http://www.barclaysfootball.com/") === 0))
	{
		base_url = "http://www.barclaysfootball.com/";
	}
	
	// Determine the directory (default: media_asset)
	if(typeof(directory) !== "string")
	{
		directory = "media_asset";
	}
	else if(directory === "judges")
	{
		directory = "images/judges";
	}
	else if(directory === "features/home")
	{
		directory = "images/features/home";
	}
	else
	{
		directory = "media_asset";
	}
	
	oId;
	oInterfaceId;
	if(oType == 'jp-video'){
		
		$(oId).jPlayer({
			ready: function () {
				$(this).jPlayer("setMedia", {
					poster: base_url+directory+(directory === "media_asset" ? "/frame_400/" : "/")+oFname+".jpg",
					m4v: base_url+directory+(directory === "media_asset" ? "/video_mp4/" : "/")+oFname+".mp4",
					webmv: base_url+directory+(directory === "media_asset" ? "/video_webm/" : "/")+oFname+".webm",
					ogv: base_url+directory+(directory === "media_asset" ? "/video_ogv/" : "/")+oFname+".ogv"
				}).jPlayer("stop");
				
				// add player id if it is not in the array yet
				if(jQuery.inArray(oId,registered_players) == -1)
				{
					registered_players.push(oId);
					//alert(registered_players);	
				}
				
			},
			ended: function (event) {
				$(this).jPlayer("stop");
			},
			swfPath: "js",
			supplied: "m4v, webmv, ogv",
			cssSelectorAncestor: oInterfaceId
		}).bind($.jPlayer.event.play, function() { // Avoid jPlayers playing together.
			stopOtherPlayers(registered_players,oId);
			//$(this).jPlayer("pauseOthers"); Does not work as expected
		});
	
		return true;	
		
	}
	else if(oType == 'jp-audio')
	{
		$(oId).jPlayer({
			ready: function () {
				$(this).jPlayer("setMedia", {
					mp3: base_url+directory+(directory === "media_asset" ? "/audio/" : "/")+oFname+".mp3",
					poster: base_url+directory+(directory === "media_asset" ? "/club_400/" : "/")+oFname+".jpg" // NB: This has not been implemented in media_asset, it should return a 400x224 image of the club logo for this registration
				}).jPlayer("stop");
				
				// add player id if it is not in the array yet
				if(jQuery.inArray(oId,registered_players) == -1)
				{
					registered_players.push(oId);
				}
				
			},
			ended: function (event) {
				$(this).jPlayer("stop");
			},
			swfPath: "js",
			supplied: "mp3",
			cssSelectorAncestor: oInterfaceId
		}).bind($.jPlayer.event.play, function() { // Using a jPlayer event to avoid both jPlayers playing together.
				stopOtherPlayers(registered_players,oId);
				//$(this).jPlayer("pauseOthers");	 Does not work as expected
		});
		
		return true;	
	}
	return false;
}

// ---------------------------------------------------------------
// Functions End
// ---------------------------------------------------------------



// ---------------------------------------------------------------
// JS Events
// ---------------------------------------------------------------

$(document).ready(function()
{
	// Preload certain images
	// Thanks: http://engineeredweb.com/blog/09/12/preloading-images-jquery-and-javascript
	//////////////////////////////////////////////////////////////
	// Call the function:
	/*
	$.preloadImages(
		"assets/images/layout/cbox_bg.png", 
		"assets/images/layout/cbox_loading.gif", 
		"assets/images/layout/cbox_loading_bg.png", 
		"assets/images/layout/nav_item_bg_l_active.png", 
		"assets/images/layout/nav_item_bg_r_active.png", 
		"assets/images/layout/popup_nav-hover.gif", 
		"assets/images/layout/table_arrow_hl.gif", 
		"assets/images/layout/table_arrow_hl-asc.gif", 
		"assets/images/layout/table_arrow_hl-desc.gif"
	);
	*/
	
	
	// Keep track of the mouse position
	//////////////////////////////////////////////////////////////
	$(document).mousemove(function(event) {
		gs_mouseX = event.pageX;
		gs_mouseY = event.pageY;
		gs_scrollX = $(window).scrollLeft();
		gs_scrollY = $(window).scrollTop();
		//$('#mouse').html(gs_mouseX+"x"+gs_mouseY+" . "+gs_scrollX+"x"+gs_scrollY);
	});
	
	
	// Blur all anchors?
	//////////////////////////////////////////////////////////////
	$("a").bind("focus click", function(e)
	{
		//this.blur();
	});
	
	
	// Create a popup window
	//////////////////////////////////////////////////////////////
	$('a[data-link-mode^="popup"]').each(function()
	{
		// Update titles
		var old_title = $(this).attr("title");
		old_title = typeof(old_title) == "undefined" ? "" : old_title;
		if(old_title !== "")
		{
			$(this).attr("title", old_title+" ["+jslang['barclays.new_window']+"]");
		}
		else
		{
			$(this).attr("title", "["+jslang['barclays.new_window']+"]");
		}
		
		// Perform the popup when clicked
		$(this).bind("click", function()
		{
			// Default window attributes
			var window_width = 400;
			var window_height = 400;
			var window_resizable = 0;
			var window_status = 1;
			var scrollbars_status = 0;
			var d = new Date();
			var window_name = 'popup_'+d.getTime();
			
			// Determine window attributes
			// These should be attached to the "rel" attribute of the <a> tag in the format:
			// width=300; height=300; status=1; resizable=0; name=blahblah
			var window_attributes = $(this).attr("data-link-mode").split(";");
			var i=0;
			for(i=0; i<window_attributes.length; i++)
			{
				if(window_attributes.hasOwnProperty(i))
				{
					var attrib_parts = window_attributes[i].split("=", 2);
					if(attrib_parts.length === 2)
					{
						// Determine what the value of this attribute is.
						// NB: attributes should always be an integer
						var attribute_key = jQuery.trim(attrib_parts[0]);
						var attribute_value_str = jQuery.trim(attrib_parts[1]);
						var attribute_value = parseInt(attribute_value_str, 10);
						if(!isNaN(attribute_value))
						{
							if(attribute_key === "width" && attribute_value >= 100)
							{
								window_width = attribute_value;
							}
							else if(attribute_key === "height" && attribute_value >= 100)
							{
								window_height = attribute_value;
							}
							else if(attribute_key === "resizable" && attribute_value >= 0)
							{
								window_resizable = attribute_value;
							}
							else if(attribute_key === "status" && attribute_value >= 0)
							{
								window_status = attribute_value;
							}
							else if(attribute_key === "scrollbars" && attribute_value >= 0)
							{
								scrollbars_status = attribute_value;
							}
						}
						
						// For handling string attributes
						if(attribute_key === "name" && attribute_value_str !== "")
						{
							window_name = attribute_value_str;
						}
					}
				}
			}
			
			var output_attributes = "width="+window_width+", height="+window_height+", resizable="+window_resizable+", status="+window_status+", scrollbars="+scrollbars_status;
			//alert(output_attributes +'\n'+ window_name);
			
			window.open(this.href,window_name,output_attributes);
			return false;
		});
	});
	
	
	// Load a link in the parent window, and close the popup
	//////////////////////////////////////////////////////////////
	$('a.popup_to_parent').click(function()
	{
		window.opener.location.href = this.href;
		window.close();
	});
	
	
	// Load the page in a new window
	//////////////////////////////////////////////////////////////
	$('a[rel=external], a.external_link').each(function()
	{
		// Set target and update titles
		$(this).attr("target", "_blank");
		var old_title = $(this).attr("title");
		old_title = typeof(old_title) == "undefined" ? "" : old_title;
		if(old_title !== "")
		{
			$(this).attr("title", old_title+" ["+jslang['barclays.new_window']+"]");
		}
		else
		{
			$(this).attr("title", "["+jslang['barclays.new_window']+"]");
		}
	});
	
	
	// Toggle the src attribute on certain objects to add/remove '_hl'
	//////////////////////////////////////////////////////////////
	$('.toggle_hl').hover(
		function()
		{
			$(this).attr('src', toggle_filename_suffix($(this).attr('src'), '_hl'));
		},
		function()
		{
			$(this).attr('src', toggle_filename_suffix($(this).attr('src'), '_hl'));
		}
	);
	
	
	// Certain pngs must be replaced with gifs in IE6
	//////////////////////////////////////////////////////////////
	if(ie <= 6 && ie > 0)
	{
		$('img.replace_png').each(function()
		{
			// Replace the .png extension with a .gif
			var png_src = $(this).attr('src');
			var png_ext_pos = png_src.lastIndexOf(".png");
			if(png_ext_pos > 0)
			{
				var gif_src = png_src.substr(0, png_ext_pos)+".gif";
				$(this).attr('src', gif_src);
			}
		});
	}
	
	
	// Keep track of the active nav item
	//////////////////////////////////////////////////////////////
	// Reset classes
	$('ul#nav').children('li').removeClass('active_l');
	$('ul#nav li.active a').each(function()
	{
		$(this).parents('li').prev('li').addClass('active_l');
	});
	
	// Monitor mouse hovers
	$('ul#nav li a').hover(
		function()
		{
			//$('#debug').html("ovr "+$(this).text()+"<br />"+$('#mouse').html());
			$(this).addClass('hover');
			set_nav_classes($(this));
		}, 
		function()
		{
			//$('#debug').html("out "+$(this).text()+"<br />"+$('#mouse').html());
			$(this).removeClass('hover');
			set_nav_classes($(this));
		}
	);
	
	
	// Home Feature
	//////////////////////////////////////////////////////////////
	if(Modernizr.touch)
	{
		// This device supports touch gestures, do not autoload content on carousel movement
		$('#features_home').features(
		{
			carouselInterval:gs_carousel_home_interval_without_autoload,
			carouselDuration:gs_carousel_home_duration_without_autoload,
			autoLoadContentOnCarousel:false,
			touchDevice:true
		});
		
		// Touch devices should never show borders, it doesn't work properly in iOS
		$('#features_home .items ul li a').css(
		{
			border:'none',
			margin:'5px',
			textDecoration:'none'
		});
	}
	else
	{
		// This device does not support touch gestures, autoload content on carousel movement
		$('#features_home').features(
		{
			carouselInterval:gs_carousel_home_interval,
			carouselDuration:gs_carousel_home_duration,
			autoLoadContentOnCarousel:true,
			touchDevice:false
		});
	}
	
	
	// Home Carousel (Latest Entries)
	//////////////////////////////////////////////////////////////
	// Load tinycarousel with minimum settings
	var carousel_box_index = 0;
	if($('#carousel_box').length > 0)
	{
		$('#carousel_box').tinycarousel({
			display: 4, // how many blocks do you want to move at 1 time?
			axis: 'x', // vertical or horizontal scroller? ( x || y ).
			controls: true, // show left and right navigation buttons.
			pager: false, // is there a page number navigation present?
			interval: false, // move to another block on intervals.
			intervaltime: 3000, // interval time in milliseconds.
			rewind: false, // If interval is true and rewind is true it will play in reverse if the last slide is reached.
			animation: true, // false is instant, true is animate.
			duration: 1000, // how fast must the animation move in ms?
			callback: function(element, index)
			{
				// function that executes after every move
				carousel_box_index = index;					
			}
		});	
		
		// Move carousel on swipe (for iStuff)
		$('#carousel_box .viewport').touchwipe({
			wipeLeft: function() {
				$('#carousel_box').tinycarousel({shouldmove : 1, start : carousel_box_index+1, callback: function(element, index){carousel_box_index = index;}});
			},
			wipeRight: function() {
				$('#carousel_box').tinycarousel({shouldmove : -1, start : carousel_box_index+1, callback: function(element, index){carousel_box_index = index;}});
			}
		});
	}
	
	
	// Judges
	//////////////////////////////////////////////////////////////
	if($('#carousel_box_judges').length > 0)
	{
		// find and register all players
		findAllPlayers('#carousel_box_judges');
		
		// default carousel starting point
		var start_from_judge = 0;
		var active_judge;
		
		active_judge = $('#carousel_box_judges ul.pager li.active:first a.pagenum').data('tinycarousel');
		if(active_judge != 'undefined'){
			start_from_judge = active_judge; 
		}
		
		
		// activate the carousel
		$('#carousel_box_judges').tinycarouselplayer(
		{
			start: start_from_judge+1, // from which element to start?
			display: 1, // how many blocks do you want to move at 1 time?
			axis: 'y', // vertical or horizontal scroller? ( x || y ).
			controls: false, // show left and right navigation buttons.
			pager: true, // is there a page number navigation present?
			interval: false, // move to another block on intervals.
			intervaltime: 3000, // interval time in milliseconds.
			rewind: false, // If interval is true and rewind is true it will play in reverse if the last slide is reached.
			animation: false, // false is instant, true is animate.
			duration: 1000, // how fast must the animation move in ms?
			playonclick: false, //play video when it is selected?
			callback: function(element, index)
			{
				$('#carousel_box_judges ul.pager li').removeClass('active');
				$('#carousel_box_judges ul.pager li').eq(index).addClass('active');
			}
		});		
	}
	
	
	// Monitor PIE objects for IE8 and below
	//////////////////////////////////////////////////////////////
	if(typeof(PIE) == "object" && ie > 0 && ie <= 8)
	{
		setInterval(function()
		{
			// Apply PIE to all nodes which are visible and have not had PIE attached already
			$('.buttons > a:visible, .buttons > span:visible, .pie:visible').not('.pie_visible').each(function()
			{
				PIE.attach(this);
				$(this).addClass('pie_visible');
			});
			
			// Remove PIE from all nodes which are now invisible and still have PIE attached
			$('.buttons > a:hidden, .buttons > span:hidden, .pie:hidden').filter('.pie_visible').each(function()
			{
				PIE.detach(this);
				$(this).removeClass('pie_visible');
			});
		}, (ie <= 6 ? 1000 : 250)); // IE6 will have a slower polling loop due to its poor performance
	}
	

	// Button hover support (IE6)
	//////////////////////////////////////////////////////////////
	if(ie > 0 && ie <= 6)
	{
		$('.buttons span').hover(
			function()
			{
				$(this).addClass('hover');
			}, 
			function()
			{
				$(this).removeClass('hover');
			}
		);
	}
});

// ---------------------------------------------------------------
// JS Events End
// ---------------------------------------------------------------
