var tilesCurrent = 0;
var tilesTimer = null;
var tilesTotal = null;
var tilesTube = false;
var tilesTubeId = null;
var tilesTubeLaunched = null;
var tilesTubeWidth = 0;
var tilesTubeHeight = 0;
var tilesDefaultInterval = 7000;
var tilesInterval = tilesDefaultInterval;

var layout_tilesPrevious = function()
{
   tilesNext = tilesCurrent - 1;
   if( tilesNext < 0 )
       tilesNext = tilesTotal - 1;
   layout_tilesSkip( tilesNext );
}

var ytplayer;

/**
 * Given an identifier string, go through each homepage tile and attempt to find one
 * with "data-identifier" matching the string
 * 
 */
var layout_findTileByIdentifier = function( identifier )
{
    var tileNumber = null;
    
    $( "#bd_home-splash" ).find( "div.splash-tile" ).each( function(index){
        if( $(this).find("div.hero-tile-container").attr("data-identifier") == identifier )
        {
            tileNumber = index;
        }
    });
    return tileNumber;
}

var layout_tilesSkip = function( newId, noAutoRotate )
{
//    $( "span#splash-control-buttons-youtube" ).css( 'display', 'none' );
    $( "div#tile-ytplayer-overlay" ).hide();
    $( "div#tile-ytplayer" ).css( 'width', 1 );
    $( "div#tile-ytplayer" ).css( 'height', 1 );
    
    // Stop Video, Hide Video etc.
    if( ytplayer != undefined )
    {
        ytplayer = document.getElementById( "movytplayer" );
        ytplayer.stopVideo();
        ytplayer.clearVideo();
        
        // Remove the launched state...
        $('#splash-control-buttons-play').removeClass('launched');
    }
    
    // Hide Old tile, if there is one
    if( tilesCurrent >= 0 )
    {
        var current_tile = $( "#bd_home-splash" ).find( "div.splash-tile" ).get( tilesCurrent );
        $( current_tile ).hide();
    }
    
    if( noAutoRotate != true )
    {
        tilesNext = tilesCurrent + 1;
    } else {
        tilesNext = newId;
        clearTimeout( tilesTimer ); // Kill the auto timer, as they request this specificaly..
    }
    
    // Cycle back to start of list (exclude first-time slide)
    if( tilesNext >= tilesTotal )
        tilesNext = 1;
    
    // Display new tile
    var next_tile = $( "#bd_home-splash" ).find( "div.splash-tile" ).get( tilesNext );
    $( next_tile ).show();


    // Update Tile Numbering
    $( "ul#splash-control-links" ).find( "a" ).removeClass( 'active' );
    nextLink = $( "ul#splash-control-links" ).find( "a" ).get( tilesNext );
    $( nextLink ).addClass( 'active' );

    // Detect YouTube...
    var img = $( next_tile ).find( "img[src*='youtube-']" ).get(0);
    if( img ) // Its a tube, so lets get the id and setup the player...
    {
        var url = $(img).attr('src');
        var tubeId = url.substring( url.indexOf( 'youtube-' ) + 8 );
        tubeId = tubeId.substring( 0, tubeId.indexOf( '.' ) );
        tilesTubeId = tubeId;
//        $( "span#splash-control-buttons-youtube" ).show();
        $( "div#tile-ytplayer-overlay" ).show();
        
        $('#splash-control-buttons-play').removeClass('disabled');
        $('#splash-control-buttons-mute').removeClass('disabled');
        $('#splash-control-buttons-youtube a').css('cursor','pointer');
        $('#splash-control-buttons-play').parent().attr('href','javascript:layout_tilePlay();');
        $('#splash-control-buttons-mute').parent().attr('href','javascript:layout_mute();');
    }
    else
    {
        $('#splash-control-buttons-play').addClass('disabled');
        $('#splash-control-buttons-mute').addClass('disabled');
        $('#splash-control-buttons-youtube a').css('cursor','default');
        $('#splash-control-buttons-play').parent().attr('href','javascript:return false;');
        $('#splash-control-buttons-mute').parent().attr('href','javascript:return false;');
    }

    tilesCurrent = tilesNext;

    // See if the current tile has a "delay" html attribute. If so, we'll use that for the
    // next interval
    if( $(next_tile).find("div.hero-tile-container").attr("data-delay"))
    {
        tilesInterval = $(next_tile).find("div.hero-tile-container").attr("data-delay");
    }
    else if( newId == undefined )
    {
        // If this is a general skip (ie. no particular index given) reset the interval to default
        tilesInterval = tilesDefaultInterval;
    }
    
    // If we are calling tileSkip without a particular slide index in mind, set off
    // a timer to be able to skip to the next one after X milliseconds
    if( noAutoRotate != true )
    {
        // console.log("Hero Tile delay: "+tilesInterval);
        clearInterval( tilesTimer );
        tilesTimer = setInterval( "layout_tilesSkip()", tilesInterval );
    }
}

var layout_tilePlay = function()
{
	ytplayer = document.getElementById( "movytplayer" );
	
	// Is the video paused?
	if ( ytplayer.getPlayerState() === 2 ) {
		// Yes, it is paused... so unpause
		ytplayer.playVideo();
		$('#splash-control-buttons-play').removeClass('paused').addClass('launched');
	} else if ( ytplayer.getPlayerState() === 1 ) {
		// Pause the clip
		ytplayer.pauseVideo();
		$('#splash-control-buttons-play').addClass('paused').removeClass('launched');
	} else {
		// Wasn't paused and wasn't playing so launch the clip
		//if( tilesTubeLaunched != tilesTubeId )
	    //{
	        layout_tileLaunchVideo( tilesTubeId );
	    //} else {
	    //    ytplayer.playVideo();
	    //}
		$('#splash-control-buttons-play').addClass('launched').removeClass('paused');
	    tilesTubeLaunched = tilesTubeId;
	}
}

var layout_tileStop = function()
{
    //ytplayer.seekTo( 0, true );
    ytplayer.stopVideo();
    ytplayer.clearVideo();
    tilesTubeLaunched = null; // force it to restart the video..
}

var layout_mute = function()
{
	// is the player muted?
	ytplayer = document.getElementById( "movytplayer" );
	if ( ytplayer.isMuted() ) {
		ytplayer.unMute();
		$('#splash-control-buttons-mute').removeClass('muted');
	} else {
		ytplayer.mute();
		$('#splash-control-buttons-mute').addClass('muted');
	}
}

var layout_tileLaunchVideo = function( youtube_videoId )
{
    if( tilesTube == false )
    {
        alert( 'YouTube player still loading, or failed to load...' );
        return;
    }
    $( "div#tile-ytplayer-overlay" ).css( 'display', 'none' );

    // Clear timeout
    clearTimeout( tilesTimer );

    // Hide Image
    var current_tile = $( "#bd_home-splash" ).find( "div.splash-tile" ).get( tilesCurrent );
    $( current_tile ).css( 'display', 'none' );

    // Show player
    $( "div#tile-ytplayer" ).css( 'width', tilesTubeWidth );
    $( "div#tile-ytplayer" ).css( 'height', tilesTubeHeight );

    // Play video
    ytplayer = document.getElementById( "movytplayer" );
    ytplayer.stopVideo();
    ytplayer.clearVideo();
    ytplayer.loadVideoById( youtube_videoId, 0 );
    
    //TODO - double check this jt
    pageTracker._trackPageview( '/homepage-video/' + youtube_videoId );
}

/**
 *
 * @param int width
 * @param int height
 * @param bool showFirstTime   If true, first slide will be treated differently
 * @param string startTileId   String that contains the 'name' of a particular tile to begin with
 */
var layout_tilesInit = function( width, height, showFirstTime, startTileId )
{
    tilesTubeWidth = width;
    tilesTubeHeight = height;
    //google.load( "swfobject", "2.1" );
    //alert( 'set em up' );
    tilesTotal = $( "#bd_home-splash" ).find( "div.splash-tile" ).length;
//    var first_tile = $( "#bd_home-splash" ).find( "div.splash-tile" ).get(0);
//    $( first_tile ).css( 'display', 'block' );

   // $( "#tile-ytplayer" ).css( 'visibility', 'hidden' ); // Hide the player...make it invisible, don't display: none..

    // If we were given an identifier to select a tile from, find the tile index here
    // and set startTile so that we skip directly to it.
    var startTile = null;
    var noAutoRotate = true;
    
    if( startTileId )
        startTile = layout_findTileByIdentifier(startTileId);
    else if( showFirstTime )
        startTile = 0;
    else
    {
        startTile = 1;
        noAutoRotate = false;
    }
    
    var require_player = true;
    if( require_player )
    {
        var params = { allowScriptAccess: "always", bgcolor: "#cccccc", wmode: "transparent" };
        var atts = { id: "movytplayer" };
        swfobject.embedSWF("http://www.youtube.com/apiplayer?enablejsapi=1&playerapiid=ytplayer",
                         "ytapiplayer", "100%", "100%", "8", null, null, params, atts);
        //alert( 'i got here...' );
    }

    var interval = 7000;
    
    for( var x = 0; x < tilesTotal; x++ )
    {
        var label = x;
        var labelClass = "";

        // Treat the first-time slide differently
        if( x == 0 )
        {
            label = "i";
            labelClass = "info";
            tilesInterval = 10000; // Longer fixed interval for first-time tile
            $( "#splash-control-links" ).append( '<li class="'+labelClass+'"><a href="javascript:layout_tilesSkip(' + x + ',true)"></a></li>' );
        }
        else
        {
            label = x;
            $( "#splash-control-links" ).append( '<li class="'+labelClass+'"><a href="javascript:layout_tilesSkip(' + x + ',true)">' + label + '</a></li>' );
        }
    }
    
    // Jump to the first tile and start the timer
    // If startTile is set, skip to that one instead
    
    layout_tilesSkip(startTile, noAutoRotate);
}

var layout_update = function()
{
	$("#hd").height( 'auto' );
	headerHeight = $("#hd").height();

	//$("#ft").height( 'auto' );
	footerHeight = $("#ft").height();

	$("#bd").height( 'auto' );
	bodyHeight = $("#bd").height();

	$("#bd").height( bodyHeight ); // fix it again...
	contentHeight = bodyHeight + headerHeight + footerHeight;
	windowHeight = $( window ).height();
	//console.log( 'Layout HH: ' + headerHeight );
	//console.log( 'Layout BH: ' + bodyHeight );
	//console.log( 'Layout FH: ' + footerHeight );
	//console.log( 'Layout CH: ' + contentHeight );
	//console.log( 'Layout WH: ' + windowHeight );
	if( windowHeight > contentHeight )
	{
		var newBodyHeight = windowHeight - headerHeight - footerHeight; 
		$("#bd").height( newBodyHeight );
		//console.log( 'Layout NBH: ' + newBodyHeight );
		
		var actualBodyHeight = $("#bd").height();
		//console.log( 'Layout ABH: ' + actualBodyHeight );
	}
}

function onytplayerStateChange(newState) {
	if (newState == 0)
	{
		// video has stopped - reset the play button
		$('#splash-control-buttons-play').removeClass('launched');
		//
	}
}

function onYouTubePlayerReady( playerId )
{
    //$( "#tile-ytplayer" ).css( 'visibility', 'hidden' ); // Hide the player...make it invisible, don't display: none..
    ytplayer = document.getElementById( "movytplayer" );
    ytplayer.addEventListener('onStateChange', 'onytplayerStateChange')
    tilesTube = true;
}

$(document).ready(function(){
    //layout_update();
    //$(window).resize( function() {
    //        layout_update();
    //});
    $('html').addClass('has-js');
});

