jQuery(document).ready(function($) {
	var params = { allowScriptAccess: 'always', bgcolor: '#222' };
	var atts = { id: 'bwinytplayer' };
	
	function getScrollX(){
		var scrOfX = 0, scrOfY = 0;
		if ( typeof( window.pageXOffset ) == 'number' ) {
			//Netscape compliant
			scrOfX = window.pageXOffset;
		} else if ( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
			//DOM compliant
			scrOfX = document.body.scrollLeft;
		} else if ( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
			//IE6 standards compliant mode
			scrOfX = document.documentElement.scrollLeft;
		}
		return scrOfX;
	}
	
	function getVolumeOffset(e, $ctrl) {
		var x = e.clientX + getScrollX();
		var offset = $ctrl.offset();
		return x - offset.left;
	}
	
	function get_x_y_pos($obj) {
	    var pos = $obj.css("background-position");
	    if (pos == 'undefined' || pos == null) { // IE
	        var posX = $obj.css("background-position-x"); 
			var posY = $obj.css("background-position-y");
			pos = posX + " " + posY;
	    }
	    return pos || "0 0";
	}
	
	function set_x_y_pos($obj, pStr) {
		var pos = $obj.css("background-position");
		if (pos == 'undefined' || pos == null) { // IE
			var parts = pStr.split(" ");
			$obj.css("background-position-x", parts[0]);
			$obj.css("background-position-y", parts[1]);
		} else {
			$obj.css("background-position", pStr);
		}
	}
	
	function insertPlayer() {
		if (!window.ytplayer) {
			// Flash player
			swfobject.embedSWF('http://www.youtube.com/apiplayer?key=AI39si57D3hI59dzpL-seQeAa0hgwBQubUn0llya3SWtm3O7eizNhAJ1aORrWMYNJqhVziUwOhCzG7AX3RYOKwAywn2Pp1mCFA&amp;enablejsapi=1&amp;playerapiid=ytplayer','ytapiplayer',video_width,video_height,'8',null,null,params,atts);

			// Video controls
			var controls = '<a id="videoPlay" href="#" title="' + video_play + '">' + video_play + '</a><a id="videoPause" href="#" title="' + video_pause + '">' + video_pause + '</a><div id="videoSeeker"><div id="videoTimebar"></div></div><div id="videoTime"><span id="videoCurrentTime">00:00</span>/<span id="videoDuration">00:00</span></div><div id="videoVolume"><label for="volumeInput">Volume (0 - 100)</label><input id="volumeInput" type="text" value="100" size="3" maxlength="3"/></div>';
			$(controls).appendTo('#videoControls');

			// Video player volume control
			$('#videoVolume').mousedown(function(e) {
				if ($('#volumeInput', this).css('display') == 'none') {
					var vx = getVolumeOffset(e, $(this));
					if (vx < 18) {
						if (window.getVolume() > 0 ) {
							window.setVolume(0);
							set_x_y_pos($(this), "0 -96px");
						} else {
							window.setVolume(100);
							set_x_y_pos($(this), "0 0");
						}
					} else if (vx < 21) {
						window.setVolume(13);
						set_x_y_pos($(this), "0 -84px");
					} else if (vx < 24) {
						window.setVolume(25);
						set_x_y_pos($(this), "0 -72px");
					} else if (vx < 27) {
						window.setVolume(38);
						set_x_y_pos($(this), "0 -60px");
					} else if (vx < 30) {
						window.setVolume(50);
						set_x_y_pos($(this), "0 -48px");
					} else if (vx < 33) {
						window.setVolume(63);
						set_x_y_pos($(this), "0 -36px");
					} else if (vx < 36) {
						window.setVolume(75);
						set_x_y_pos($(this), "0 -24px");
					} else if (vx < 39) {
						set_x_y_pos($(this), "0 -12px");
						window.setVolume(88);
					} else {
						set_x_y_pos($(this), "0 0");
						window.setVolume(100);
					}
				}
			});
			$('#videoVolume').mousemove(function(e) {
				if ($('#volumeInput', this).css('display') == 'none') {
					var vx = getVolumeOffset(e, $(this));
					var pos = get_x_y_pos($(this)).split(' ');
					if (vx < 18) {
						set_x_y_pos($(this), "-46px " + pos[1]);
					} else {
						set_x_y_pos($(this), "0 " + pos[1]);
					}
				}
			});
			$('#videoVolume').mouseout(function(e) {
				if ($('#volumeInput', this).css('display') == 'none') {
					var vx = getVolumeOffset(e, $(this));
					var pos = get_x_y_pos($(this)).split(' ');
					set_x_y_pos($(this), "0 " + pos[1]);
				}
			});
			// Available when CSS is turned off
			$('#volumeInput').change(function() {
				var val = $(this).val();
				if (parseInt(val, 10) > -1 && parseInt(val, 10) < 101) {
					window.setVolume($(this).val());
				}
			});

			// Play and pause buttons
			$('#videoPlay').click(function(e) {
				e.preventDefault();
				play();
			});
			$('#videoPause').click(function(e) {
				e.preventDefault();
				pause();
			});
		}
	}
	
	// Clicking on the placeholder div before the player exists in the page
	// embeds the player in the page and then cues and plays the first video
	// in the linked playlist
	$('#ytapiplayer').html('');
	$('#ytapiplayer').css('cursor', 'pointer').click(function() {
		insertPlayer();
		function cueAndPlayVideo() {
			if (window.ytplayer) {
				clearInterval(cueInt);
				loadNewVideo(first_video_id, 0);
			}
		}
		cueInt = setInterval(cueAndPlayVideo, 250);
	});
	
	// Clicking on a thumbnail in the playlist linked to the smallFormat player
	// should embed the player in the page (if it's not there already) and then
	// cue and play the video for the clicked thumbnail
	$('.smallFormat #youtubePlaylist a').click(function(e) {
		var video_id = $(this).attr('href').substring(31); // remove http://www.youtube.com/watch?v=
		e.preventDefault();
		if ($('#ytapiplayer').length > 0) {
			insertPlayer();
			function cueAndPlayVideo() {
				if (window.ytplayer) {
					clearInterval(cueInt);
					loadNewVideo(video_id, 0);
				}
			}
			cueInt = setInterval(cueAndPlayVideo, 250);
		} else {
			loadNewVideo(video_id, 0);
		}
	});
	
	// Automatically embed the largeFormat player in the page
	var largeFormat = $('.largeFormat');
	if (largeFormat.length > 0) {
		insertPlayer();
		function cueVideo() {
			if (window.ytplayer) {
				clearInterval(cueInt);
				cueNewVideo(first_video_id, 0);
			}
		}
		cueInt = setInterval(cueVideo, 250);
		$('.largeFormat #youtubePlaylist .youtube-item:first').addClass('current');
	}
	
	// Clicking on a thumbnail in the carousel linked to the largeFormat player
	// should scroll the carousel to "centre" the clicked thumbnail, then cue 
	// and play the video for the clicked thumbnail and update the info in the 
	// column beside the player
	$('.largeFormat #youtubePlaylist .youtube-item').click(function() {
		var item = $(this);
		var index = scrollable.getClickIndex();
		scrollable.click(index);
		$('.video-thumbnails .youtube-item').removeClass('current');
		var video_id = item.find('a').attr('href').substring(31); // remove http://www.youtube.com/watch?v=
		var html = '<h2>' + item.find('h4').text() + '</h2>' + $(item.find('.nowPlaying')).html();
		$('#nowPlaying').html(html);
		loadNewVideo(video_id, 0);
	});
	
	// Clicking on a thumbnail in the sorted list
	$('.video-thumbnails .youtube-item').click(function() {
		var item = $(this);
		$('.youtube-item').removeClass('current');
		item.addClass('current');
		var video_id = item.find('a').attr('href').substring(31); // remove http://www.youtube.com/watch?v=
		var html = '<h2>' + item.find('h4').text() + '</h2>' + $(item.find('.nowPlaying')).html();
		$('#nowPlaying').html(html);
		loadNewVideo(video_id, 0);
	});
	
	// Mouseover and mouseout effects for largeFormat thumbnails and thumbnails 
	// shown elsewhere on a page (not those linked to the smallFormat player)
	$('.largeFormat #youtubePlaylist .youtube-item, .video-thumbnails .youtube-item').mouseover(function() {
		$(this).find('h4, .background').show();
	});
	$('.largeFormat #youtubePlaylist .youtube-item, .video-thumbnails .youtube-item').mouseout(function() {
		$(this).find('h4, .background').hide();
	});
});
