//------------------------------------------------------------
//  This page uses some gnarly javascript...  Here's what's
//  basically happening.  10,000 foot view.
//------------------------------------------------------------
PLAYER = new Object();
CLICKED_VID = '';
PAGE = 1;
MEDIA_INDEX = 0;

//************************************************************
//  APPLICATION STATE
//************************************************************
//------------------------------------------------------------
//  Build URL so users can share video page state across links
//------------------------------------------------------------
function buildURL() {
	media = 'm=' + MEDIA_INDEX;
	tab = 't=' + TAB_FILTER;
	string = media + '&' + tab;
	window.location.hash = string;
}

//------------------------------------------------------------
//  jquery will load before the youTube player has loaded
//  which can throw some errors.  This global var helps
//  you check for player availability in a lightweight way
//------------------------------------------------------------ 
TUBE_LOADED = 0;

//------------------------------------------------------------
//  The youtube api and firefox don't get along.  This is
//  part of a hack to make it all work nice nice.
//------------------------------------------------------------
TUBE_VISIBLE = 0;

//------------------------------------------------------------
//  This has to run outside jquery 
//------------------------------------------------------------
function onYouTubePlayerReady( playerId ) {
  PLAYER = document.getElementById("playa_playa");
  PLAYER.addEventListener( 'onStateChange', 'player_events' );
  TUBE_LOADED = 1;
}

//------------------------------------------------------------
//  Start to play the video as soon as it's cued
//  This has to live outside document ready
//------------------------------------------------------------
//------------------------------------------------------------
//  onStateChange -- Got this from the YouTube javascript api
//  page.
//
//  This event is fired whenever the player's state changes. 
//  Possible values are unstarted (-1), ended (0), playing (1), 
//  paused (2), buffering (3), video cued (5). When the SWF 
//  is first loaded it will broadcast an unstarted (-1) event. 
//  When the video is cued and ready to play it will 
//  broadcast a video cued event (5).
//------------------------------------------------------------
function player_events ( state ) {
    switch( state ){
        case 5:
            if ( TUBE_LOADED && TUBE_VISIBLE ) {PLAYER.playVideo();}
        break;
        case -1:
            if ( TUBE_LOADED && TUBE_VISIBLE ) {
                PLAYER.cueVideoById( CLICKED_VID );
            }
        break;
    }
}

$(document).ready(function() {
	
	//------------------------------------------------------------
	//  Carousel javascript done quick and dirty
	//------------------------------------------------------------
	    vidAndPhotoCount();
	    carouselStart();
	    showFirst();
	    
	    //------------------------------------------------------------
	    //  If you have only one thumbnail don't worry about controls
	    //  and all that jazz
	    //------------------------------------------------------------
	    if ( $( '#thumbs').children().length == 1 ) {
            $( '#controls' ).hide();
            $( '#carousel' ).css( "padding-bottom", "20px" );
        }
	
	//------------------------------------------------------------
	//  So for each video thumb get the youtube ID
	//------------------------------------------------------------
	$('#thumbs .video').each( function() {
		$(this).click( function( event ) {
			event.preventDefault();
			hideBigImage();
			
			//------------------------------------------------------------
			//  Play the appropriate video in the playlist
			//------------------------------------------------------------
			CLICKED_VID = $("a", this).attr('href');
			if ( TUBE_LOADED ) {
			    PLAYER.cueVideoById( CLICKED_VID );
			}
			showYouTube();
			
			//------------------------------------------------------------
			//  Build the url
			//------------------------------------------------------------
			MEDIA_INDEX = $(this).attr('id');
			//buildURL();
		});
		
	});
	
	function hideBigImage() {
		$('#big_image').hide();
        TUBE_VISIBLE = 0;
	}
		
	//------------------------------------------------------------
	//   Initiate the carousel
	//------------------------------------------------------------
	function carouselStart() {
		$('#controls').addClass('1');
		buildThumbs();
		hideShowButtons ( 1 );
		showThumbs();
		hideYouTube();
	}
	
	//------------------------------------------------------------
	//   Coefficient calculation
	//------------------------------------------------------------
	$('#carousel #controls #next').click( function( event ) {
		
		// Get the class name (coefficient) of thumbs and increase it by 1
		var coeff = $('#controls').attr('class');
		$('#controls').removeClass( coeff );
		
		// Don't make coeff more than max ... breaks functionality
		var max = $('#carousel #controls #next a').attr('class');
		if ( coeff < max ) {coeff++;}
		
		$('#controls').addClass( coeff.toString() );
		
		// Show the buttons as appropriate
		hideShowButtons( coeff );
		
		// Now show the appropriate thumbnails
		showThumbs();
		
		// Make the changes stick
		event.preventDefault();
	});
	
	$('#carousel #controls #back').click( function( event ) {
		
		// Get the class name (coefficient) of thumbs and increase it by 1
		var coeff = $('#controls').attr('class');
		$('#controls').removeClass( coeff );
		
		// Don't make coeff 0 or less ... breaks functionality
		if ( coeff > 1 ) {coeff--;}
		
		$('#controls').addClass( coeff.toString() );
		
		// Show the buttons as appropriate
		hideShowButtons( coeff );
		
		// Now show the appropriate thumbnails
		showThumbs();
		
		// Make the changes stick
		event.preventDefault();
	});
	
	
	function hideShowButtons ( coeff ) {
				
		//------------------------------------------------------------
		//  Make the back button appear
		//------------------------------------------------------------
		if ( coeff <= 1 ) {
			$('#carousel #controls #back').removeClass( 'on');
			$('#carousel #controls #back').addClass( 'off');
		}
		else {
			$('#carousel #controls #back').removeClass( 'off');
			$('#carousel #controls #back').addClass( 'on');
		}
		
		//------------------------------------------------------------
		//   If you're at the max next you don't need to see 
		//   the next button
		//------------------------------------------------------------
		var max = $('#carousel #controls #next a').attr('class');
		if ( coeff >= max ) {
			$('#carousel #controls #next').removeClass( 'on');
			$('#carousel #controls #next').addClass( 'off');
		}
		else {
			$('#carousel #controls #next').removeClass( 'off');
			$('#carousel #controls #next').addClass( 'on');
		}
	}
	
	function buildThumbs() {
		//------------------------------------------------------------
		//   So find out the number of thumbnail groups
		//------------------------------------------------------------
		var thumbsPer = $('#thumbs').attr( 'class' );
		var totalThumbs = $( '#thumbs').children().length;
		
		//------------------------------------------------------------
		//   Store the max next's in the dom
		//------------------------------------------------------------
		var maxNext = Math.ceil( totalThumbs / thumbsPer );
		$('#carousel #controls #next a').addClass( maxNext.toString() );
		
		//------------------------------------------------------------
		//   Store the thumbnail's index in the dom
		//------------------------------------------------------------
		$( '#thumbs' ).children().each ( function ( i, obj ) {
			$( this ).attr( 'id', i );
		});
	}
	
	function showThumbs() {
		var coeff = $('#controls').attr( 'class' );
		var thumbsPer = $('#thumbs').attr( 'class' );
		var topThumb = thumbsPer * coeff;
		var botThumb = topThumb - thumbsPer;
		topThumb--; // don't fall for plus one errors
		
		$( '#thumbs' ).children().each ( function ( i, obj ) {
			if ( i < botThumb || i > topThumb ) {
				$( this ).hide();
			}
			else {
				$( this ).show();
			}
		});
	}
	
	//------------------------------------------------------------
	//  Photo thumbnail filter
	//------------------------------------------------------------
	$('#photos a').click( function( event ) {
		filter('photos');
		event.preventDefault();
	});
	
	//------------------------------------------------------------
	//   Video thumbnail filter
	//------------------------------------------------------------
	$('#video a').click( function( event ) {
		filter('video');
		event.preventDefault();
	});
	
	//------------------------------------------------------------
	//  Filter carousel thumbnails Look at the stylesheet to see
	//  how the look of the switcher changes
	//------------------------------------------------------------
	function filter( name ) {
		
		if ( $('#' + name).hasClass('on') ) {
			$('#' + name).removeClass('on');
			$('#' + name).addClass('off');
		}
		else if ( $('#' + name).hasClass('off') ) {
			$('#' + name).removeClass('off');
			$('#' + name).addClass('on');
		}
    	

		$('#thumbs').children().each( function() {
			var className;
			if ( name == "photos") {
				className = "image";
			}
			else if ( name == "video" ) {
				className = "vid";
			}
			
			if ( $(this).hasClass( className ) ) {
				if ( $('#' + name).hasClass('on') ) {$(this).show();}
				
				if ( $('#' + name).hasClass('off') ) {$(this).hide();}
			}
		});
	}

    //------------------------------------------------------------
    //  Hiding the youtube DOM element does screws with
    //  swfObject and the youtube API.
    //  So using jquery to move the player out of site
    //  is the best alternative I know of... excuse my grammar...
    //  of which I know.
    //------------------------------------------------------------
	function hideYouTube() {
		$('#youtube_player').css( 'position', 'absolute' );
		$('#youtube_player').css( 'left', '-9999px' );
		if ( TUBE_LOADED ) {PLAYER.stopVideo();}
        TUBE_VISIBLE = 0;
	}
	
	function showYouTube() {
		$('#youtube_player').css( 'position', 'static' );
		$('#youtube_player').css( 'left', '0px' );
        TUBE_VISIBLE = 1;
        PLAYER.playVideo();
	}
	
	//------------------------------------------------------------
	//   How many of videos and how many images
	//------------------------------------------------------------
	function vidAndPhotoCount() {
		var vidCount = 0;
		var photoCount = 0;
		$('#thumbs').children().each( function() {
			var name = $(this);
			if ( $(this).hasClass( 'vid') ) {vidCount++;}
			else if ( $(this).hasClass( 'image') ) {photoCount++;}
		});
		$('#video_count').text( vidCount );
		$('#photo_count').text( photoCount );
	}
	
	//------------------------------------------------------------
	//   Show the first image in the list
	//------------------------------------------------------------
	function showFirst() {
		var src = $('#thumbs .image a').get(0);
		var big_link = $('#thumbs .image a').attr('name');
        $('#carousel #big_image img').attr({
            src: src,
            title: src,
            alt: src
        });
        $('#carousel #big_image a').attr({ href: big_link });
        $('#carousel #big_image a').lightBox();
	}

	
	//------------------------------------------------------------
	//  Thumbnail to big image
	//------------------------------------------------------------
    $('#thumbs .image img').each( function() {
        $(this).click( function(event) {
	
			hideYouTube();
			$('#big_image').show();
            
			var src = $(this).parent().attr('href');
			var big_link = $(this).parent().attr('name');
            $('#carousel #big_image img').attr({
                src: src,
                title: src,
                alt: src
            });
	        $('#carousel #big_image a').attr({ href: big_link });
            $('#carousel #big_image a').lightBox();
            
      		event.preventDefault();
      		
      		//------------------------------------------------------------
      		//  Store the id
      		//------------------------------------------------------------
      		MEDIA_INDEX = $(this).parents('.image').attr('id');
      		//buildURL();
        });
    });

});