<!--
/*
VIDEO SELECTOR . JS

Video Selector by King Cow Interactive LLC (2009)

This pure javascript video selector works with Google's RESTful interface defined at
http://code.google.com/apis/ajaxsearch/documentation/reference.html#_restUrlBase

And the chomless YouTube Player at
http://code.google.com/apis/youtube/chromeless_player_reference.html

To use it in your website, see the example htm file.

*/

var VideoSelector = new Object();
VideoSelector.Interface = function( interfaceDiv, initialVideoUrl ) {
	//private
	var thisObj = this;		// this object
	var q = Array(); 		// query history	
	var start_results_at = 0 //default
	var google_api_key = '' //default
	var controller_url_base = 'http://ajax.googleapis.com/ajax/services/search/video?v=1.0';
	var results_el;
	
	var preview_el;
	var preview_control_screen_el;
	var preview_no_video_message_el;
	var preview_clear_link_el;
	var preview_pause_link_el;
	var yt_player_id = '';
	var google_player_div_id = '';
	var yt_player_div_id = ''
	var yt_player_outer_div_id = ''
	this.num_results_per_page = 'large' //default
	this.selectedVideo = '';
	this.createInterface = function() {
		interfaceDiv.ytPlayerReady = function() {
			if (initialVideoUrl) {
				thisObj.selectVideo({
					playUrl:initialVideoUrl,
					videoType:'DetermineFromUrl'
				});
			}
		}
		$(interfaceDiv).html('\
			<div class="vsi_search_area"> \
				<p>Enter video search keywords or a YouTube web address (URL).</p> \
				<input class="vsi_search_field" type="text" value="" /> \
				<input class="vsi_search_button" type="button" value="Find Video"/> \
			</div> \
			<div class="vsi_results_and_preview" > \
				<div class="vsi_search_results">&nbsp;</div> \
				<div class="vsi_preview_control_screen"> \
				</div> \
				<div id="'+interfaceDiv.id+'_vsi_search_preview'+'" class="vsi_search_preview"> \
					Preview \
				</div> \
				<div id="'+interfaceDiv.id+'_vsi_search_preview_controls'+'" class="vsi_search_preview_controls"> \
					<span class="vsi_preview_no_video_message">No Video Selected</span> \
					<span class="vsi_preview_clear_link">No Video Selected</span> \
					<span class="vsi_pause">Pause</span> \
				</div> \
			</div> \
		');
		$('#'+interfaceDiv.id+' .vsi_search_button' ).click( this.runNewSearch );
		$('#'+interfaceDiv.id+' .vsi_search_field' ).attr('value','').bind('keypress', function(e) {
			if(e.keyCode==13) {
				$('#'+interfaceDiv.id+' .vsi_search_button' ).click();
				return false;
			}
		});
		results_el = $('#'+interfaceDiv.id+' .vsi_search_results' );
		preview_el = $('#'+interfaceDiv.id+' .vsi_search_preview' );
		preview_control_screen_el = $('#'+interfaceDiv.id+' .vsi_preview_control_screen' );
		preview_no_video_message_el = $('#'+interfaceDiv.id+' .vsi_preview_no_video_message' );
		preview_clear_link_el = $('#'+interfaceDiv.id+' .vsi_preview_clear_link' );
		preview_pause_link_el = $('#'+interfaceDiv.id+' .vsi_pause' );
		
		//You Tube Player and Google Player
		yt_player_id = interfaceDiv.id+'_ytplayer';
		var yt_params = { allowScriptAccess: "always", bgcolor: "black", wmode:"transparent" };
		var yt_atts = { id: yt_player_id };
		yt_player_div_id = preview_el.attr('id')+'_ytplayer_div';
		yt_player_outer_div_id = preview_el.attr('id')+'_ytplayer_outer_div';
		google_player_div_id = interfaceDiv.id+'_gplayer_div';
		preview_el.html( '<div class="vsi_player_google" id="'+google_player_div_id+'">&nbsp;</div><div id="'+yt_player_outer_div_id+'" class="vsi_player_yt"><div id="'+yt_player_div_id+'">&nbsp;</div></div>' );
		$('#'+google_player_div_id).hide();
		swfobject.embedSWF("http://www.youtube.com/apiplayer?enablejsapi=1&playerapiid="+yt_player_id, 
			yt_player_div_id, "500", "375", "8", null, null, yt_params, yt_atts);
		
		//Clear Video Button
		$('#'+interfaceDiv.id+' .vsi_preview_clear_link' ).click( function() { thisObj.clearVideo() } );
		
		//Pause Video Button for YouTube
		$('#'+interfaceDiv.id+' .vsi_pause' ).click( function() { thisObj.pauseVideo() } );
		
	}
	this.runNewSearch = function() {
		var search_field = $('#'+interfaceDiv.id+' .vsi_search_field' );
			results_el.html('');
			start_results_at = 0;
		if ( search_field.val() ) {
			thisObj.getResults();
			results_el.css({backgroundColor:'white', overflowY:'scroll' });
		} else {
			results_el.css({backgroundColor:'black', overflowY:'hidden' }).html('');
		}
	}
	this.getResults = function() {
		var controller_url = controller_url_base;
		var search_field = $('#'+interfaceDiv.id+' .vsi_search_field' );
		if ( search_field.val() ) {
			if ( search_field.val().match(/^http:\/\/www.youtube.com\/watch\?v=/) || search_field.val().match(/^http:\/\/www.youtube.com\/v\//) ) {
				controller_url += '&q='+encodeURI( this.getYouTubeIdFromURL(search_field.val()) );
			} else {
				controller_url += '&q='+encodeURI( search_field.val() );
			}
		}
		if ( google_api_key ) {
			controller_url += '&key='+google_api_key;
		}
		controller_url += '&start='+start_results_at;
		controller_url += '&rsz='+this.num_results_per_page;
		$.ajax({
		  url: controller_url,
		  dataType: 'jsonp',
		  jsonp: 'callback',
		  success: function (data) { thisObj.loadResultsInDom(data); }
		});
	}
	this.loadResultsInDom = function( gsr ) {
		//alert( dump(gsr['responseData']['cursor']) );
		if ( gsr['responseStatus'] !== 200) {
			//should not happen if estimated results is correct.
			alert( 'Visit www.YouTube.com for more results.' );
		} else {
			var videos = gsr['responseData']['results'];
			var x;
			var video_div_el;
			var videohtml;
			var results_el_scroll_height = $(results_el).attr("scrollHeight");
			
			for (x in videos) {
				video_div_el = document.createElement('div');
				video_div_el.video = videos[x];
				video_div_el.onclick = function() { thisObj.selectVideo(this.video ) }
				results_el.append( $(video_div_el) )
				$(video_div_el).addClass('vsi_video_block');
				videohtml = '';
				videohtml += '<img class="vsi_video_block_image" src="'+videos[x]['tbUrl']+'" alt="'+videos[x]['titleNoFormatting']+'"/>';
				videohtml += '<span class="vsi_video_block_label">'+videos[x]['titleNoFormatting']+'</span>';
				$(video_div_el).append( videohtml );
			}
			
			if ( start_results_at > 0 ) {
				$(results_el).animate({ scrollTop: results_el_scroll_height }, 1000);
			} else {
				$(results_el).animate({ scrollTop: 0 }, 1000);
			}
			
			start_results_at = start_results_at+videos.length;
			if ( gsr['responseData']['cursor']['estimatedResultCount']-1 > start_results_at ) {
				//if there are more results....
				if (start_results_at <= 56) {
					//if you tube will allow us to show more results...
					results_el.append( '<div class="vsi_load_more">Load More Results</div>' );
					var more_el = $('#'+interfaceDiv.id+' .vsi_search_results .vsi_load_more' );
					more_el.click( function() {
						$(this).remove();
						thisObj.getResults();
					})
				} else {
					results_el.append( '<a target="_blank" href="'+gsr['responseData']['cursor']['moreResultsUrl']+'" class="vsi_visit_you_tube">Browse Google Video for more results.</a>' );
				}
			}
		}
	}
	this.getYouTubeIdFromURL = function(yt_url) {
		return yt_url.match(/^[^v]+v.(.{11}).*/)[1]; //FOR IE and FIREFOX
	}
	this.selectVideo = function(v) {
		this.selectedVideo = v;
		var ytplayer = document.getElementById(yt_player_id);
		if (ytplayer) {
			var video_preview_html = '';
			var playUrl = v['playUrl'];
			var videoType = v['videoType'];
			if (videoType == 'DetermineFromUrl') {
				if ( playUrl.match(/^http:\/\/www.youtube.com\//) ) videoType  = 'YouTube';
				else videoType  = 'Google';
			}
			if ( videoType == 'YouTube' ) {
				$('#'+yt_player_id).show();
				$('#'+google_player_div_id).hide().html( '' );
				playUrl = playUrl+'&rel=0'; //no external links
				if ( v['videoType'] == 'YouTube' ) { //if determin from url, then pause
					ytplayer.cueVideoById( this.getYouTubeIdFromURL(playUrl) ); 
					this.playVideo();
				} else {
					ytplayer.cueVideoById( this.getYouTubeIdFromURL(playUrl) ); 
					this.playVideo();
				}
				preview_no_video_message_el.hide();
				preview_clear_link_el.html('Clear Selected You Tube Video').show();
				preview_pause_link_el.show();
				preview_control_screen_el.css({
					backgroundColor:'transparent',
					width:'500px',height:'375px',
					marginTop:'15px', marginLeft:'219px'
				});
				this.custom_select_function();
			} else if ( videoType == 'Google' ) {
				ytplayer.stopVideo();
				ytplayer.clearVideo();
				video_preview_html = '<div id="'+google_player_div_id+'_flash">&nbsp;</div>';
				$('#'+google_player_div_id).show().html( video_preview_html );
				swfobject.embedSWF(playUrl, google_player_div_id+'_flash', "500", "375", "8", null, null, { allowScriptAccess: "always", bgcolor: "black", wmode:"transparent" }, { id: google_player_div_id+'_flash' } );
				preview_no_video_message_el.hide();
				preview_clear_link_el.html('Clear Selected Google Video').show();
				preview_pause_link_el.hide();
				preview_control_screen_el.css({
					backgroundColor:'transparent',
					width:'100px', height:'20px',
					marginTop:'370px', marginLeft:'619px'
				});
				this.custom_select_function();
			} else {
				preview_clear_link_el.html( 'Sorry, this video cannot be selected at this time. Please upload your video to youtube.');
			}
		} else {
			//player is not ready
		}
	}
	this.custom_select_function = function() {
		// define a custom select function if needed for each video selector, like:
		// test_control.custom_select_function = function() {
		// 	if (test_control.selectedVideo) {
		// 		$('#test_video_url_input_el').val(test_control.selectedVideo['playUrl']);
		// 	} else {
		// 		$('#test_video_url_input_el').val('');
		// 	}
		// }
	}
	this.clearVideo = function() {
		var ytplayer = document.getElementById(yt_player_id);
		ytplayer.stopVideo();
		ytplayer.clearVideo();
		preview_pause_link_el.hide();
		$('#'+google_player_div_id).hide().html( '' );
		preview_clear_link_el.hide();
		preview_no_video_message_el.show();
		preview_control_screen_el.css({
			backgroundColor:'red',
			width:'500px',height:'375px',
			marginTop:'15px', marginLeft:'219px'
		});
		this.selectedVideo = '';
		this.custom_select_function();
	}
	this.pauseVideo = function() {
		var ytplayer = document.getElementById(yt_player_id);
		ytplayer.pauseVideo();
		preview_pause_link_el.html('Play').click( function() { thisObj.playVideo() } );
	}
	this.playVideo = function() {
		var ytplayer = document.getElementById(yt_player_id);
		ytplayer.playVideo();
		preview_pause_link_el.html('Pause').click( function() { thisObj.pauseVideo() } );
	}
	this.populateKeywords= function( keywords ) {
		$('#'+interfaceDiv.id+' .vsi_search_field' ).attr('value',keywords);
	}
	this.createInterface();
}

//this is a special function that is called when the player is ready
onYouTubePlayerReady = function(playerid) {
	player_that_is_ready = playerid.substr(0,playerid.length-9); //_ytplayer is 9 chars
	document.getElementById(player_that_is_ready).ytPlayerReady();
}
