// SU College of Law Media Player
// Craig Waterman @ Mindshare, LLC
// Enjoy...

var _playerShellUri = "/_internal/support/mediaplayer.aspx";
var _ensembleUri = "/_assets/js/ensembleProxy.aspx";
var _ensembleVideoUri = "/_assets/js/ensembleProxyVideo.aspx";
var _ensembleListPath = _ensembleUri + "?list={id}";
var _ensembleVideoPath = _ensembleVideoUri + "?video={id}";
var _blockHtml = '<div><h2></h2><img /><h3></h3><p class="mptitle"></p></div>';
var _ensembleListId = "";
var _ensembleList = new Array();
var _playlist = new Array();
var _plID = 0;

$(window).load( initMediaPlayer );

function initMediaPlayer() {

	$("#mpshell").load( _playerShellUri, null, playerHtmlReady );
	$(".tdTab").click( navigateViaTab );
	$(".photo_image a").colorbox();
}

function playerHtmlReady() {
        var divContent = $("div#mediablock a");
        if( divContent.size() > 0 ) {
	  var xmlPath = $("div#mediablock a").attr("href").split(".aspx").join(".xml");
          $.get( xmlPath, cascadeXmlLoaded, "xml" );
        }
}


function cascadeXmlLoaded( data, text, xhr ) {
	
	var json = $("content", data).text();
	var o = $.parseJSON( json );

	var mediaBlock = $("div#mediablock");
	var newBlock = $(_blockHtml);
	
	//$("h2", newBlock).text( "Media");
        $("h2", newBlock).addClass("hide");
	$("h3", newBlock).text( o.playlist.title );
	$("p", newBlock).html( o.playlist.blurb );
	$("img", newBlock).attr( "src", o.playlist.thumb );
	
	mediaBlock.empty();
	mediaBlock.append( newBlock );
	mediaBlock.click( launchMediaPlayer );	

	for( var loop = 0; loop < o.playlist.entries.length; loop++ ) {
		var entry = o.playlist.entries[loop];
		
		// Load remote ensemble listings.
		if( entry.ensembleList != "" ) {
			var uri = _ensembleListPath.split("{id}").join( entry.ensembleList );
			_ensembleList[ entry.ensembleList ] = new Array();
			_ensembleListId = entry.ensembleList;

			$.get( uri, null, ensembleListLoaded );
		}

		if( entry.gallery.photos.length > 0 ) {
			createPlaylistEntry( "gallery", entry.title, entry.gallery.photos.length + " photos.", entry, entry.gallery_thumb );
			
		}
		
	}

}

function ensembleListLoaded( data, text, xhr ) {
		
	// Ensemble doesn't return real JSON, it returns a chunk of javascript. We'll clean that up here
	// rather than eval'ing it.
	var json = data.split("var _xsajax$transport_status = 200; var data = ").join("");
	json = json.substring(0, json.length-1);
	
	// Make the "json" into JSON
	json = json.split("videos:").join('"videos":').split("video:").join('"video":').split("metaData:").join('"metaData":');
	
	try {
		var o = $.parseJSON( json );
	}
	catch( e ) {
		db( e );
	}

	// Exit out if there are no videos to process.
	if( o.videos.metaData.recordCount == 0 ) { return; }

	for( var loop = 0; loop < o.videos.video.length; loop++ ) {
		var _video = o.videos.video[ loop ];

		// Retrive and store videos into the array for this ensemble playlist..
		var _element = _ensembleList[ _ensembleListId ];
		_element.push( _video );
		createPlaylistEntry( "video", _video.videoTitle, "Length: " + _video.videoDuration, _video, _video.thumbnailUrl );

	}
	
}


function ae( data, xhr, ao, te ) {
	db( te );
}


// Create entries in mp-playlist-container
function createPlaylistEntry( type, title, meta, json, thumb ) {

	// Create new list item
	var listItem = $(".mpitem_template").clone();
	
	// Prep is
	var newID = getNewID();
	
	listItem.attr( "id", "pl_" + newID );
	listItem.removeClass("hide");
	listItem.removeClass("mpitem_template");
	
	var listEntry = new Object();
		listEntry.type = type;
		listEntry.id = "pl_" + newID;
		listEntry.json = json;

	_playlist.push( listEntry );	

	$(".mp-item-content dl dt", listItem).text( title );
	$(".mp-item-content dl dd", listItem).html( ( (type=='video') ? "Audio/Video" : "Gallery" ) + " | <em>" + meta + "</em>" );
	$("img", listItem).attr( "src", thumb )
	listItem.click( playlistItemClicked );
	
	$(".mp-playlist").append( listItem );

}

	
function launchMediaPlayer() {
	$.fn.colorbox({ innerWidth: 870, height: 590, scrolling: false, inline: true, href: "#mpshell .mediaplayer", transition: "none", speed: 650, open: true });
	
}


function getNewID() {
	return _plID++;
}
	
	
function playlistItemClicked( obj ) {
	var listItem = $(this);
	
	$("div.mp-item").removeClass("mpactive");
	listItem.addClass("mpactive");
	
	// Locate the playlist item that was selected.
	for( var loop = 0; loop < _playlist.length; loop++ ) {
		var _entry = _playlist[loop];
		if( _entry.id == listItem.attr("id") ) {
			break;
		}
	}
	
	// JSON data is not currently normalized or standardized as it may come from multiple sources. Custom logic ensues.
	if( _entry.type == "video" ) {
		$(".mp-description dt").text( _entry.json.videoTitle );
		$(".mp-description dd").text( ( _entry.json.videoDescription == null || _entry.json.videoDescription == "" ) ? "No description available." : _entry.json.videoDescription );
		
		if( _entry.json.videoID != "" ) {
			var uri = _ensembleVideoPath.split("{id}").join( _entry.json.videoID );
			$.get( uri, null, ensembleVideoLoaded );
		}		
		
	}
	else {
		$(".mp-description dt").text( _entry.json.title );
		$(".mp-description dd").text( ( _entry.json.description == null || _entry.json.description == "" ) ? "No description available." : _entry.json.description );
	}
	
	
}


function ensembleVideoLoaded( incoming, text, xhr ) {

	eval(incoming);
	var videoPath = data.videos.videoEncodings.absolutePath;
	$("a#flowplay").remove();
	$("#wmvPlay").remove();
	
db( incoming );
	
	if( data.videos.videoEncodings.videoFormat == "video/x-ms-wmv" ) {
		// Get the first preview or thumbnail; remove any ?width=100
		var imgUrl = data.videos.videoImages[0].imageUrl.split("\?width=100")[0] + "?width=450";
		var output = '<div id="wmvPlay"><img src="'+imgUrl+'" alt="Video Thumbnail"/><a href="'+videoPath+'" target="_blank">Launch Video (Windows Media Format)</a>';
		// Display a link to play the video in a new window;
		$(".mp-viewport").append( output );
		
	}
	else if( data.videos.videoEncodings.videoFormat == "video/x-flv" ) {
		// Load FLV player.
		db('<a href="'+videoPath+'" style="display:block;width:550px;height:358px" id="flowplay"></a>');
		$(".mp-viewport").append('<a href="'+videoPath+'" style="display:block;width:550px;height:358px" id="flowplay"></a> ');
		flowplayer("flowplay", "/_assets/swf/flowplayer-3.2.2.swf", {
			plugins: {
				rtmp: {
					url: '/_assets/swf/flowplayer.rtmp-3.2.1.swf'
				}
			}		
		
		});
	}

}


function db( text ) {
	/*if( console && console.debug ) {
		console.debug( text );
	}*/
}	


/* ########### Additional Global Functions Inserted Here to avoid another round-trip to the server ######## */


function navigateViaTab() {

	var anch = $("a", this);
	document.location.href = anch.attr("href");

}


