//------------------------------------------------------------
//  Global vars, baby!  You can call them class vars if you're nasty.
//------------------------------------------------------------
var player = new Object();
SEARCH_FILTER = '';
TAB_FILTER = 'ALL';
VIDEO_ID = '';

//------------------------------------------------------------
//  What are we going to do about link clicking at the end
//  of the video.
//------------------------------------------------------------
function onStateChange( state ){
	if ( state == 1) {
//		console.log( player.getVideoUrl() );
	}
}

//------------------------------------------------------------
//  This has to run outside jquery's ready() to work properly
//  It is called by swfObject.
//------------------------------------------------------------
function onYouTubePlayerReady( playerId ) {
  player = document.getElementById("ytplayer");
	if ( ! VIDEO_ID ) {
  		VIDEO_ID = $('#entertainment_center #video_id').html(); //this is sort of a hackey way to get the video's first id.
	}
	
	//------------------------------------------------------------
	//  Play the first video
	//------------------------------------------------------------
	player.cueVideoById( VIDEO_ID );
	
	//------------------------------------------------------------
	//  Subscribe to the onStateChange Event
	//------------------------------------------------------------
	player.addEventListener("onStateChange", "onStateChange");
}

$(document).ready(function() {
	//------------------------------------------------------------
	//  Restore page state if it's included in the URL
	//------------------------------------------------------------
	if ( window.location.hash ) {restoreState();}
	
	//------------------------------------------------------------
	//  Build the filters
	//------------------------------------------------------------
	buildFilter();
	hideTabs();
	
	//------------------------------------------------------------
	//  If a tab filter is defined highlight it.
	//------------------------------------------------------------
	showTab( $('#subcategories #' + TAB_FILTER ) );
	
		
	//*************************************************************
	//  YOUTUBE LOADING
	//************************************************************
	//------------------------------------------------------------
	//   update the video player area with the proper info
	//------------------------------------------------------------
	$('#product_grid .product').each( function() {
		
		//------------------------------------------------------------
		//  Set up video thumbnail clickability
		//------------------------------------------------------------
		$(this).click( function( event ) {
			event.preventDefault();
						
			$('#entertainment_center #title').html( 
				$(".name_full", this ).html() );
			$('#entertainment_center #summary').html( 
				$(".summary_full", this ).html() );
			$('#entertainment_center #yt_play').html( "<a href='https://www.youtube.com/watch?v=" +
				$(".video_url_id", this ).html() + "' data-lity><img id='youtube_play_button' src='/images/video/youtube_play_button.png'/></a>" );
			
			//------------------------------------------------------------
			//  Store the video's id for other functions
			//------------------------------------------------------------	
			VIDEO_ID = $(".video_url_id", this).html();
			
			//------------------------------------------------------------
			//  Load the video
			//------------------------------------------------------------
			//player.loadVideoById( VIDEO_ID );
			
			//------------------------------------------------------------
			//  Build the url to maintain state in hyperlinks
			//------------------------------------------------------------
			buildURL();
		});
	});

	//************************************************************
	//  SEARCHING
	//************************************************************
	//------------------------------------------------------------
	//  If a user types somethingin the box store it
	//------------------------------------------------------------
	$("#video_search #box input")
	
		.change( function(event) {
		})
		
		.keyup( function( event) {
			SEARCH_FILTER = escape( $(this).val() );
		})
		
		.bind( 'keypress', function(event) {
			if ( event.keyCode == 13 ){filter();}
		});
	
	//------------------------------------------------------------
	//   If a user clicks the search icon filter the videos.
	//------------------------------------------------------------
	$("#video_search #icon").click( function(event) {filter();});
	
	//------------------------------------------------------------
	//   Filter product names base on search
	//------------------------------------------------------------
	function filter() {
		
		$( "#product_grid .product").each ( function() {
			$(this).hide();
			show=false;
			
			if ( TAB_FILTER == 'ALL' || $(this).hasClass( TAB_FILTER ) ) {show=true}
			
			//------------------------------------------------------------
			//   If you don't pass the search filter you stay hidden, son.
			//------------------------------------------------------------
			if ( ! productCheck( $(this) ) ) {show=false;}
			
			if ( show ) {$(this).show();}
		});
		
		//------------------------------------------------------------
		//  Update the URL
		//------------------------------------------------------------
		buildURL();
	}
	
	//------------------------------------------------------------
	//  Compares a video name to the search filter.
	//------------------------------------------------------------
	function productCheck( product ){
		//------------------------------------------------------------
		//  Clean up the product name
		//------------------------------------------------------------
		name = $( ".name_full", product ).html().toUpperCase();
		name = htmlClean( name );
		name = escape( name );
		
		//------------------------------------------------------------
		//  Clean up the search filter
		//------------------------------------------------------------
		search = '';
		if ( SEARCH_FILTER ) {
		    search = SEARCH_FILTER.toUpperCase();
		    search = search.replace( ' ', '' );
	    }
					
		// If the name doesn't contain any of the letters
		// don't hide it.
		if ( search == '' ) {
			return true;
		}
		
		// indexOf is funky.  It returns the index
		// of the first occurence of the string.  This is 0
		// if it's the first letter of the string.  It returns
		// -1 if no match is found.  A +1 will fix a match of
		// the first letter throwing a negative.
		else if ( name.indexOf( search ) + 1 ) {
			return true;
		}
		else {
			$( product ).hide();
			return false;
		}
	}
	
	//*************************************************************
	//  TAB FILTERING
	//************************************************************
	//------------------------------------------------------------
	//  Get started
	//------------------------------------------------------------
	$('#subcategories .subcategory').each( function() {
		$(this).click( function( event ) {
			showTab( $(this) );
			event.preventDefault();
			TAB_FILTER = $( 'a', this).html();
			filter();
		});
	});
    
	//------------------------------------------------------------
	//  Build the subcategory filter headers
	//------------------------------------------------------------
	function buildFilter() {
		filt = [];
		$('#product_grid .product').each( function() {
			subs = $(this).attr('class').split(' ');
			for( sub in subs ){
				if ( subs[sub] != '' && subs[sub] != 'product' ){

				    // $.inArray is a jquery function...
				    // it's strange it return 0 on true and -1 on false
				    // This just ensures there aren't multiples of the
				    // same filter value
				    if ( $.inArray( subs[sub], filt ) == -1 ) {
				        filt.push( subs[sub] );
			        }
				}
			}
		});
		for( i in filt ){
			div = "<div class=\"subcategory\" id=\"" + filt[i] + "\"><a href=\"#" + filt[i] + "\">" + filt[i].toUpperCase() + "</a></div>"
			$('#subcategories').append( div );
			$('#subcategories').add( $('#subcategories .subcategory #' + filt[i]) );
		}
	}

	//------------------------------------------------------------
	//  Show 'tab' shape
	//------------------------------------------------------------
	function showTab( tabName ) {
		hideTabs();
		$( tabName ).css( "background-color","#282d33" );
		$( "a", tabName ).css( 'color', '#d1143e' );
	}
    
	//------------------------------------------------------------
	//  Hide 'tab' shape
	//------------------------------------------------------------
	function hideTabs() {
		$("#subcategories .subcategory").each ( function() {
			$(this).css( 'background-color', '' );
			$("a",this).css( 'color', '' );
		});
	}
	
	//************************************************************
	//  APPLICATION STATE
	//************************************************************
	//------------------------------------------------------------
	//  Build URL so users can share video page state across links
	//------------------------------------------------------------
	function buildURL() {
		search = 's=' + SEARCH_FILTER;
		video = 'v=' + VIDEO_ID;
		tab = 't=' + TAB_FILTER;
		string = video + '&' + search + '&' + tab;
		window.location.hash = string;
	}
	
	//------------------------------------------------------------
	//  Replace common html ascii char codes with actual char
	//------------------------------------------------------------
	function htmlClean( str ) {
	    return String( str ).replace( /&amp;/ig, '&' ).replace( /&lt;/ig, '<' ).replace( /&gt;/ig, '>' ).replace( /&quot;/ig, '"' );
	}

	//------------------------------------------------------------
	//  Restore program state.
	//------------------------------------------------------------
	function restoreState() {
		//------------------------------------------------------------
		//  Parse the URL
		//------------------------------------------------------------
		params = getHashParams( window.location.hash );
		//------------------------------------------------------------
		//  Get the page looking like it should
		//------------------------------------------------------------
		SEARCH_FILTER = params['s'];
		$("#video_search #box input").val( SEARCH_FILTER );

        if ( params['t'] ) {
		    TAB_FILTER = params['t'];
	    }
		
		//------------------------------------------------------------
		//  Don't call player.loadVideoById() here...
		//  That can be done in onYouTubePlayerReady()
		//  Just set VIDEO_ID
		//------------------------------------------------------------
        VIDEO_ID = params['v'];
        
		
		//------------------------------------------------------------
		//  Find the video
		//------------------------------------------------------------
        video = $("#product_grid .product .video_url_id:contains(" + VIDEO_ID + ")").parent();
        $('#entertainment_center #title').html( $( '.name_full', video ).html() );
        $('#entertainment_center #summary').html( $( '.summary_full', video ).html() );
        // $('#entertainment_center #vide_id').html( $('.video_url_id', video).html() );
        $('#entertainment_center #yt_play').html( "<a href='https://www.youtube.com/watch?v=" +
				$(".video_url_id", video ).text() + "' data-lity><img id='youtube_play_button' src='/images/video/youtube_play_button.png'/></a>" )
		
		
		//------------------------------------------------------------
		//  Filter the video grid
		//------------------------------------------------------------
		filter();		
	}
	
	//------------------------------------------------------------
	//  Custom video info and summary scrollbars!
	//------------------------------------------------------------
//	$('#entertainment_center #info').jScrollPane();
	
	//------------------------------------------------------------
	//  Get your hash params... pulled this from stackoverflow
	//  The code is ugly.
	//------------------------------------------------------------
	function getHashParams() {

	    var hashParams = {};
	    var e,
	        a = /\+/g,  // Regex for replacing addition symbol with a space
	        r = /([^&;=]+)=?([^&;]*)/g,
	        d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
	        q = window.location.hash.substring(1);

	    while (e = r.exec(q))
	       hashParams[d(e[1])] = d(e[2]);

	    return hashParams;
	}
});