/**
 *  This is a heavily modified version of the jQuery Infinite Carousel
 *  http://jqueryfordesigners.com/jquery-infinite-carousel/
 *  Due to the modifications, this is not for re-use, nor does it belong in it's own extention file anymore.
 */
$.fn.infiniteCarousel = function () {
	function repeat(str, num) {
		return new Array( num + 1 ).join( str );
	}

	return this.each(function () {
		var $wrapper = $( this ).css('overflow', 'hidden'),
		$slider = $wrapper.find('#stage').css( "position", "absolute" ),
		$items = $slider.find('.slide'),
		$single = $items.filter(':first'),
		singleWidth = $single.outerWidth( true ),
		visible = Math.floor($wrapper.innerWidth() / singleWidth), // note: doesn't include padding or border
		currentPage = 2,
		pages = Math.ceil($items.length / visible) + 1,
		padding = parseInt( $wrapper.css( "padding-left" ) );

		if( $items.length == 1 )
			return;

		// 1. Pad so that 'visible' number will always be seen, otherwise create empty items
		if (($items.length % visible) != 0) {
			$slider.append(repeat('<div class="slide" />', visible - ($items.length % visible)));
			$items = $slider.find('.slide');
		}

		// 2. Top and tail the list with 'visible' number of items, top has the last section, and tail has the first
		$items.filter(':first').before($items.slice(- visible).clone().addClass('cloned').attr( "id", null ));
		$items.filter(':last').after($items.slice(0, visible).clone().addClass('cloned').attr( "id", null ));
		$items = $slider.find('.slide'); // reselect

		$items.filter(':first').before($items.slice(- visible).clone().addClass('cloned'));
		$items.filter(':last').after($items.slice(0, visible).clone().addClass('cloned'));
		$items = $slider.find('.slide'); // reselect

		// empty cloned items
		$items.parent().find(".cloned .infograph").remove();

		$slider.css( "width", ( ( singleWidth * 2 ) * $items.length ) + "px" );
		// 3. Set the left position to the first 'real' item
		$slider.css( "left", -( ( ( singleWidth * 2 ) * visible ) - padding ) );


		// 4. paging function
		function gotoPage(page, stay) {
		
			objPlayer = $( "#carousel" ).find("div.button.video:visible");
			if(objPlayer.length > 0)
			{
				oPlayers[objPlayer.attr("title")].stop();
			}
			$( "#carousel" ).removeClass( "info" );
			$( ".slide .visual" ).removeClass( "hide" );
			$( ".slide .info" ).addClass( "hide" );
			stay = typeof stay == "undefined" ? false : stay
			var dir = page < currentPage ? -1 : 1,
			n = Math.abs(currentPage - page),
			left = singleWidth * dir * visible * n;
			$slider.delay( 100 ).filter(':not(:animated)').animate({
				left : '-=' + left
			}, 500, function () {
				if (page == 1) {
					$slider.css( "left", -( ( ( singleWidth ) * visible * pages ) - padding ) );
					page = pages;
				} else if (page > pages) {
					$slider.css( "left", -( ( ( singleWidth * 2 ) * visible ) - padding) );
					// reset back to start position
					page = 2;
				}
				currentPage = page;
			});
			$items.animate( { marginTop : "0" }, 100 );
			$items.find( ".belt" ).animate( { opacity : 0 }, 100 );
			$( "#shade" ).animate( { opacity : 1 }, 100 );
			$items.removeClass( "onstage" );
			var current = currentPage + ( n * dir );
			if( stay )
				current = currentPage;
			if( current == 1 )
				current = pages;
			else if( current > pages )
				current = 2;
			$( $items[ current ] ).addClass( "onstage" ).delay( 500 ).animate( { marginTop : "+=13" }, 300 );
			$( $items[ current ] ).find( ".belt" ).delay( 700 ).animate( { opacity : 1 }, 100 );
			$( "#shade" ).delay( 700 ).animate( { opacity : 0 }, 100 );
			c=current;
			$( ".ball" ).removeClass( "active" ).slice( c-2, c-1).addClass( "active" );
			return false;
		}

		// 5. Bind to the forward and back buttons
		$wrapper.find('#goleft').hover( function()
		{
			$( this ).toggleClass( "hover" );
		} ).click(function ( e ) {
			e.preventDefault();
			return gotoPage(currentPage - 1);
		});

		$wrapper.find('#goright').hover( function()
		{
			$( this ).toggleClass( "hover" );
		} ).click(function ( e ) {
			e.preventDefault();
			return gotoPage(currentPage + 1);
		});

		// create a public interface to move to a specific page
		$wrapper.bind('goto', function (event, params ) {
			gotoPage( params.page, params.stay);
		});
	});
};

/**
 *  These need to be available in the global scope so both the document.ready as the jquery.extention can modify them
 */
var s = 2,
c = 2;
var oPlayers = new Object();
$( document ).ready( function()
{
	// prepare the UI balls
	$( "#carousel .slide" ).each( function()
	{
		var x = s++;
		$( "#ui" ).append( $( "<div class=\"ball\"><div class=\"preview\"><img class=\"image\" src=\"" + 
			$( this ).find( ".visual" ).css( "backgroundImage" ).replace(/url\((\"| )?(.*?)(\"| )?\)/g, "$2" ) + 
			"\" alt=\"\" /><img class=\"overlay\" src=\"/media/images/layout/carousel_preview_cutout.png\" alt=\"\" /><div class=\"title\"><span>" + $( this ).find( ".visual .belt span:not(.platform)" ).text() + "</span></div></div></div>" ).hover( function()
		{
			$( this ).toggleClass( "hover" );
			var oPreview = $( this ).find( ".preview" ).toggle();
			if( !$( this ).hasClass( "shrunk" ) )
			{
				oPreview.find( "div.title span" ).fit();
				$( this ).addClass( "shrunk" );
			}
		} ).click( function()
		{
			if( c == x )
				return;
			$( "#carousel" ).trigger( "goto", { page : x, stay : false } );
			c=x;
		} ) );
	} ).click( function()
	{
		$this = $( this );
		$( "#carousel" ).addClass( "info" );
		$this.find( ".visual" ).addClass( "hide" );
		$this.find( ".info" ).removeClass( "hide" );


		oParent = $this.find( ".info .entry .title" );
		if( !oParent.hasClass( "shrunk" ) )
		{
			oTarget = oParent.find( "p.h1" );
			oTarget.fit();
			oParent.addClass( "shrunk" );
		}
		
		objPlayer = $(this).parent().find("div.button.video.active:visible");
		if(objPlayer.length > 0 && $.browser.msie && $this.data("clicked"))
		{
			oPlayers[objPlayer.attr("title")].play();
		}
		$this.data("clicked", true);

	} ).find( ".close" ).click( function( e )
	{
		e.stopPropagation();
		e.preventDefault();
		$( "#carousel" ).removeClass( "info" );
		$( this ).parents( ".slide" ).find( ".visual" ).removeClass( "hide" );
		$( this ).parents( ".slide" ).find( ".info" ).addClass( "hide" );
		
		if($(this).parent().find("div.button.video").length > 0)
		{
			oPlayers[$(this).parent().find("div.button.video").attr("title")].stop();
		}
	} );
	// perform carousellic actions
	$( "#carousel" ).infiniteCarousel().trigger( "goto", { page : 2, stay : true } );
	// stretch the ui holder so it can be properly positioned
	$( "#ui" ).css( "width", $( "#ui" ).find( ".ball" ).outerWidth( true ) * ( s - 2 ) );
	$( "#carousel .slide .info .graphui div.button" ).click( function( e )
	{
		e.stopPropagation();
		$( this ).parent().find( "div.button" ).removeClass( "active" );
		$( this ).addClass( "active" );
		var oParent = $( this ).parent().parent().find( ".graph" ),
		oChild = $( this ).find( "img:first" );
		if($(this).hasClass('video'))
		{
			oParent.find('img').hide();
			oParent.find('div').show();
			var sTitle = $(this).attr('title');
			oPlayers[sTitle].play();
		}
		else
		{
			var sTitle = $(this).siblings('.video').attr('title');
			if( oPlayers && oPlayers[sTitle])
				oPlayers[sTitle].stop();
			oParent.find('img').css( { "background" : "url( " + oChild.attr( "src" ) + " ) no-repeat center center" } ).show();
			oParent.find('div:not(.comingsoon)').hide();
		}
	} );
	$( "#carousel .slide .info .graphui" ).each( function()
	{
		$( this ).find( "div.button:first" ).addClass( "active" );
	} );
} );
