/*
 * jQuery uTube Script v1.0
 * http://www.emarketed.com/
 *
 * Made for usage with the YouTube API
 *
 * Copyright (c) 2010 emarketed.
 *
 * PARAMETERS:
 * 	(string) flickrApiKey - your Flickr API Key.
 * 	(string) flickrPhotosetId - your Flickr Photoset ID.
 *  (int) width - a number in pixels of the width of the gallery.
 *  (int) imageWidth - the main photo image width in pixels.
 *  (int) imageHeight - the main photo image height in pixels.
 *  (int) thumbs - the number of thumbnails to show in the slider.
 *  (string) speed - set the thumbnail slider speed to: "normal", "slow", or "fast".
 *  (string) easing - set the thumbnail slider transition effect to: "linear", or "swing".
 *
 * USAGE/EXAMPLE:
 *
 * <div id="uTube"></div>
 *
 * $(document).ready(function() {
 *    $("div#uTube").uTube({
 *							   username : 'worldgympr',
 *							   width : 600,
 *							   height: 400,
 *							   videoWidth : 400,
 *							   videoHeight : 300
 * 							   });
 * });
 */

var constants;
var durationInterval;
var mainDivId = '';
var ytplayer;

//FUNCTIONS
function formatTime(secs){
	var times = new Array(3600, 60, 1);
	var time = '';
	var tmp;
	for(var i = 0; i < times.length; i++){
		tmp = Math.floor(secs / times[i]);
		if(tmp < 1){ tmp = '00'; }
		else if(tmp < 10){ tmp = '0' + tmp; }
		time += tmp;
		if(i < 2){ time += ':'; }
		secs = secs % times[i];
	}
	return time;
}

function ytplayerReadyCheck(url,_mainDivId, _constants) {
	var ready = !!ytplayer;
	if(!ready) { window.setTimeout(function() { ytplayerReadyCheck(url,_mainDivId,_constants); },50); }
	else {
		ytplayer.cueVideoByUrl(url);
		mainDivId = _mainDivId;
		constants = _constants;
	}
}

function onYouTubePlayerReady(playerId) {
	ytplayer = document.getElementById("myytplayer");
	ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
}

function onytplayerStateChange(newState) {
	//unstarted (-1), ended (0), playing (1), paused (2), buffering (3), video cued (5).
	switch(newState) {
		case -1:
		case 0:
		case 2:
		case 3:
		case 5:
			var imgPlayPause = $("div#" + mainDivId + " > div#" + mainDivId + "-left > div#" + mainDivId + "-controller > div#" + mainDivId + "-controller-playpause > a > img");
			imgPlayPause.attr('src',constants.yt_play);
			clearInterval(durationInterval);
			break;
		case 1:
			var imgPlayPause = $("div#" + mainDivId + " > div#" + mainDivId + "-left > div#" + mainDivId + "-controller > div#" + mainDivId + "-controller-playpause > a > img");
			var divDuration = $("div#" + mainDivId + " > div#" + mainDivId + "-left > div#" + mainDivId + "-controller > div#" + mainDivId + "-controller-duration");
			var divPosition = $("div#" + mainDivId + " > div#" + mainDivId + "-left > div#" + mainDivId + "-controller > div#" + mainDivId + "-controller-duration > div#" + mainDivId + "-controller-duration-position");
			imgPlayPause.attr('src',constants.yt_pause);
			durationInterval = setInterval(function() {
				var percentPlayed = ytplayer.getCurrentTime()/ytplayer.getDuration();	
				divPosition.css('width', Math.ceil(divDuration.width()*percentPlayed) + 'px');
			},50);
			break;
	}
}

(function($) {

	$.fn.uTube = function(options) {
		//DEFAULT SETTINGS
		var settings = $.extend({
			username : 'worldgympr',
			width : 600,
			height: 400,
			videoWidth : 400,
			videoHeight : 300
		},options);

		//CONSTANTS/REFERENCE
		var constants = {
			'yt_player' : 'http://www.youtube.com/apiplayer?enablejsapi=1&playerapiid=ytplayer&hd=1&showsearch=showsearch=0&showinfo=0&cc_load_policy=0&iv_load_policy=0&version=3',
			'yt_userFeed' : 'http://gdata.youtube.com/feeds/api/videos?author=' + settings.username + '&alt=json-in-script&callback=?',
			'yt_play' : 'tpl/js/uTube/play.jpg',
			'yt_pause' : 'tpl/js/uTube/pause.jpg',
			'yt_fullscreen' : 'tpl/js/uTube/full-screen.jpg',
			'yt_durationBackground' : 'tpl/js/uTube/duration-background.jpg',
			'yt_durationPlayed' :'tpl/js/uTube/duration-played.jpg'
		};

		//PROPERTIES
		var originalHTML = '';
		var mainDivId = '';
		var mainVideo = new Array();
		var allVideos = new Array();

		//START CONSTRUCT
		return this.each(function() {
			obj = $(this);
			mainDivId = obj.attr('id');
			
			//BEGIN FETCH USER UPLOADS
			jQuery.getJSON(constants.yt_userFeed,function(data) {
				//BEGIN FOR EACH VIDEO
				$.each(data.feed.entry,function(i,item) {
					var currItem = {
						'id' : item.id.$t,
						'title' : item.title.$t,
						'published' : item.published.$t,
						'content' : item.content.$t,
						'thumbnail' : '',
						'media' : ''
					};
					$.each(item.media$group.media$thumbnail,function(j,thumbnail) {
						if(j==0) {
							currItem.thumbnail = {
								'url' : thumbnail.url,
								'width' : thumbnail.width,
								'height' : thumbnail.height
							}
							return false;
						}
					});
					$.each(item.media$group.media$content,function(k,content) {
						if(content.yt$format==5) {
							currItem.media = {
								'duration' : content.duration,
								'medium' : content.medium,
								'type' : content.type,
								'url' : content.url,
								'format' : content.yt$format
							};
						}
					});
					if(i==0) { mainVideo = currItem; } //SET MAIN DEFAULT VIDEO
					allVideos.push(currItem);
				});
				//END FOR EACH VIDEO
				var divLeft = $("<div />")
					.attr('id',mainDivId + '-left')
					.css({
						 'float' : 'left',
						 'width' : settings.videoWidth + 'px'
					})
					.appendTo(obj);
					var embedPlayer = '<object id="myytplayer" width="' + settings.videoWidth + '" height="' + settings.videoHeight + '" type="application/x-shockwave-flash" data="' + constants.yt_player + '">';
					embedPlayer += '<param name="allowScriptAccess" value="always" />';
					embedPlayer += '<param name="movie" value="' + constants.yt_player + '" />';
					embedPlayer += '<param name="quality" value="high" />';
					embedPlayer += '<param name="wmode" value="transparent" />';
					embedPlayer += '<embed src="' + constants.yt_player + '" quality="high" width="' + settings.videoWidth + '" height="' + settings.videoHeight + '"></embed>';
					embedPlayer += '</object>'
					divLeft.append(embedPlayer);
					var divController = $("<div />")
						.attr('id',mainDivId + '-controller')
						.css({
							 'width' : settings.videoWidth,
							 'height' : '20px',
							 'background-color' : '#000000',
							 'color' : '#ffffff',
							 'padding-top' : '5px',
							 'padding-bottom' : '5px',
							 'margin-bottom' : '10px'
						})
						.appendTo(divLeft);
						var divPlayPause = $("<div />")
							.attr('id',divController.attr('id') + '-playpause')
							.css({
								 'float' : 'left',
								 'width' : '40px',
								 'height' : '20px',
								 'text-align' : 'center',
								 'margin-left' : '10px',
								 'margin-right' : '10px'
							})
							.appendTo(divController);
							var anchorPlayPause = $("<a />")
								.css({
									 'display' : 'block',
									 'width' : divPlayPause.css('width'),
									 'height' : divPlayPause.css('height')
								})
								.attr('href','#')
								//BEGIN ON PLAY/PAUSE CLICK
								.click(function() {
									switch(ytplayer.getPlayerState()) {
										case -1:
										case 2:
										case 3:
										case 5:
											ytplayer.playVideo();
											
											break;
										case 0:
										case 1:
											ytplayer.pauseVideo();
											break;
									}
									return false;
								})
								//END ON PLAY/PAUSE CLICK
								.appendTo(divPlayPause);
								var imgPlayPause = $("<img />")
									.css({
										 'margin-top' : divPlayPause.height()*0.25 + 'px'
									})
									.attr('src',constants.yt_play)
									.appendTo(anchorPlayPause);
						var divDuration = $("<div />")
							.attr('id',divController.attr('id') + '-duration')
							.css({
								 'float' : 'left',
								 'width' : (divController.width()-divPlayPause.width()-40) + 'px',
								 'height' : divController.css('height'),
								 'background-image' : 'url(' + constants.yt_durationBackground + ')',
								 'background-repeat' : 'repeat-x',
								 'background-position' : 'top left'
							})
							.appendTo(divController);
							var divPosition = $("<div />")
								.attr('id',divDuration.attr('id') + '-position')
								.css({
									 'width' : '0px',
									 'height' : divDuration.css('height'),
									 'background-image' : 'url(' + constants.yt_durationPlayed + ')',
									 'background-repeat' :'repeat-x',
									 'background-position' : 'top left'
								})
								.appendTo(divDuration);
					var divTitle = $("<div />")
						.attr('id',mainDivId + '-title')
						.css({
							 'margin-bottom' : '10px',
							 'font-size' : '20px',
							 'font-weight' : 'bold'
						})
						.html(mainVideo.title)
						.appendTo(divLeft);
					var divDescription = $("<div />")
						.attr('id',mainDivId + '-description')
						.css({
							 'margin-bottom' : '10px'
						})
						.html(mainVideo.content)
						.appendTo(divLeft);
					ytplayerReadyCheck(mainVideo.media.url,mainDivId,constants);
				var divRight = $("<div />")
					.attr('id',mainDivId + '-right')
					.css({
						 'float' : 'left',
						 'width' : (settings.width-settings.videoWidth-10) + 'px',
						 'height' : settings.height + 'px',
						 'padding-left' : '10px',
						 'overflow' : 'hidden'
					})
					.appendTo(obj);
					var divScrollPane = $("<div />")
						.attr('id',divRight.attr('id') + '-scrollPane')
						.css({
							 'width' : divRight.css('width'),
							 'height' : settings.height + 'px',
							 'overflow' : 'auto'
						})
						.appendTo(divRight);
						//BEGIN FOR EACH PHOTOS
						if(allVideos.length) {
							$.each(allVideos,function(i,video) {
								var divPlaylistVideo = $("<div />")
									.attr('id','playlist_' + i)
									.css({
										 'clear' : 'both',
										 'width' : divRight.css('width'),
										 'margin-bottom' : '10px',
										 'overflow' : 'auto'
									})
									.appendTo(divScrollPane);
									var anchorVideoImage = $("<a />")
										.attr('href','#')
										.click(function() {
											ytplayer.loadVideoByUrl(video.media.url);
											divTitle.html(video.title);
											divDescription.html(video.content);
											return false;
										})
										.appendTo(divPlaylistVideo);
										var videoImage = $("<img />")
											.css({
												 'float' : 'left',
												 'width' : Math.ceil(divRight.width()*0.4) + 'px'
											})
											.attr('src',video.thumbnail.url)
											.attr('width',Math.ceil(divRight.width()*0.4))
											.appendTo(anchorVideoImage);
									var divVideoInfo = $("<div />")
										.css({
											 'float' : 'left',
											 'width' : (divRight.width()-videoImage.attr('width')-30) + 'px',
											 'margin-left' : '10px',
											 'margin-right' : '20px',
											 'color' : '#999999'
										})
										.appendTo(divPlaylistVideo);
										if(video.title.length > 20) { shortenTitle = video.title.substring(0,19) + '...'; }
										else { shortenTitle = video.title; }
										$("<div />")
											.css({
											 'text-transform' : 'uppercase',
											 'font-weight' : 'bold',
											 'margin-bottom' : '5px'
											})
											.html(shortenTitle)
											.appendTo(divVideoInfo);
										$("<div />")
											.html(formatTime(video.media.duration))
											.appendTo(divVideoInfo);
							});
						}
						else { divScrollPane.html("No videos available."); }
						//END FOR EACH PHOTOS
						divScrollPane.ready(function() {
							divScrollPane.jScrollPane();
						});
			});
			//END FETCH USER UPLOADS
		});

	};

}) (jQuery);