// YouTube.js for PSPTube20080224 (by FreePlay) -total and page number fix by zmathue

function YouTube_CheckURL( url, option )
{
	// ex. http://www.youtube.com/watch?v=oHg5SJYRHA0
	if(url.match( /youtube\.com\/watch\?v=.*/ )) {
		return 1;
	} else {
		return 0;
	}
}

/*
 Get a YouTube URL
*/
function YouTube_GetURL( url, option )
{
	// Grab video ID:
	// "movie=" video ID
	var video_id = url.match( /youtube\.com\/watch\?v=(.*)/ );
	if(video_id == null) { return null; /* ID not valid */ }
	video_id = video_id[1];

	var contents = GetContents( "http://www.youtube.com/watch?v=" + video_id );
	if(contents == null) { return null; /* error getting page */ }

	// get video file URL
	var reg = contents.match(/\/watch_fullscreen\?.+&video_id=[^&]*.*&t=([^&]*).*/);
	if(reg == null) { return null; } /* no match - invalid video watching page */
	var token = reg[1];
	var video_url = 'http://youtube.com/get_video?video_id='+video_id+'&t='+token;

	return video_url;
}

/*
 Video search
 
 keyword     : keyword to search
 start_index : starting index (based on 1)
 length      : number of videos to search for
 option      : The current search criteria, defaults to 0 (?)
 
 Return info
 
 .keyword                            : search string
 .total                              : total number of results
                                                -1 : error
                                                 0 : no results
                                                 >0: total results
 .start                              : starting number (based on 1)
 .end                                : ending number (based on 1)
 .VideoInfo                          : video sequence information
 .VideoInfo[n].Author                : Author (string)
 .VideoInfo[n].Title                 : Title (string)
 .VideoInfo[n].LengthSeconds         : LengthSeconds: total video playback time (in seconds) (integer)
 .VideoInfo[n].RatingAvg             : RatingAvg: rating (float)
 .VideoInfo[n].RatingCount           : RatingCount: number of votes (integer)
 .VideoInfo[n].Description           : Description (string)
 .VideoInfo[n].ViewCount             : ViewCount (integer)
 .VideoInfo[n].UploadTime            : UploadTime: Video upload time (UNIX style)
 .VideoInfo[n].CommentCount          : CommentCount (integer)
 .VideoInfo[n].MylistCount           : MylistCount: ? (integer)
 .VideoInfo[n].Tags                  : Tags: Space-delimited string of tags, e.g. "tag1 tag2 tag3"
 .VideoInfo[n].URL                   : URL: Link to viewing page (string)
 .VideoInfo[n].ThumbnailURL          : ThumbnailURL: URL to thumbnail (string)
 .VideoInfo[n].SaveFilename          : SaveFilename (string)
                                                "Movie deprecated set unique ID please."
 .VideoInfo [n]. Attr: Integer OR video attribute set to the following value
                                                 1: read-only (not delete)
                                                 2: download
                                                 4: Play is a need to connect to the network
                                                 Usually, 1 +2 +4, 7
                                                 MS is a directory, so one can not be removed
                                                 MS files, 0
 .VideoInfo[n].child				 : children
 .VideoInfo[n].parent				 : parents
*/
function YouTube_Search( keyword, start_index, length, option )
{
	var pattern = /<entry>((.|\r|\n)*?)<\/entry>/;
	var result = new Object();
    result.keyword   = keyword;		// Search
	result.VideoInfo = new Array();	// Results in sequence
	result.start     = start_index;	// Index of first result
	result.end       = 0;
	result.total     = -1;

	// API calls for searching
	var url_base = "http://gdata.youtube.com/feeds/api/videos?vq=" + PSPTube.encodeURI( keyword )+"&start-index="+start_index+"&max-results="+length;

	var nPage = Math.floor( (start_index - 1) / 24 ) + 1;	/* begin the search page */
	var nIndex = (nPage - 1) * 24 + 1;						/* begin index */
	while(nIndex < (start_index + length)) {
		var url = url_base;
		var contents = GetContents( url );
		if(contents.match( /<openSearch:totalResults>([^<]*)<\/openSearch:totalResults>/ )) { //totalResults>(1)<
			result.total = RegExp.$1;
		}
		if(contents == null) { return null; /* failed to get page */ }
		/* total number of results */
		var i = nIndex;
		while(contents.indexOf("<entry>") >= 0) {
//		while(pattern.exec( contents ) != null) {
			if((start_index <= i) && (i < (start_index + length))) {
				contents = contents.substring(contents.indexOf("<entry>"));
				var e_end = contents.indexOf("</entry>");
				var item = contents.substring(0, e_end+8);
				contents = contents.substring(item.length);
//				var item = RegExp.$1;	// <entry>?</entry> video information
				info = new Object();

				// Title
				if(item.match( /<title type=\'text\'>([^<]*)<\/title>/ )) {
					info.Title = RegExp.$1;
				}
				// Description
				if(item.match( /<content type=\'text\'>([^<]*)<\/content>/ )) {
					info.Description = RegExp.$1;
				}
				// Thumbnail
				if(item.match( /<media:thumbnail url='([^']*)'[^>]*>/ )) {
					info.ThumbnailURL = RegExp.$1;
				}
				// URL
				if(item.match( /<media:player url='([^']*)'[^>]*>/ )) {
					var video_id = (RegExp.$1.match( /youtube\.com\/watch\?v=(.*)/ ))[1];
					var tok_contents = GetContents('http://www.youtube.com/watch?v='+video_id);
					var reg = tok_contents.match(/\/watch_fullscreen\?.+&video_id=[^&]*.*&t=([^&]*).*/);
					var token = reg[1];
					info.URL = 'http://youtube.com/get_video?video_id='+video_id+'&t='+token;
				}
				// view count
				if(item.match( /<yt:statistics viewCount='([^']*)'[^>]*>/ )) {
					info.ViewCount = RegExp.$1 - 0;
				}
				// Length
				if(item.match( /<yt:duration seconds='([^']*)'[^>]*>/ )) {
					info.LengthSeconds = RegExp.$1 - 0;
				}
				// Rating / rating count
				if(item.match( /<gd:rating .* numRaters='([^']*)' average='([^']*)'[^>]*>/ )) {
					info.RatingCount = RegExp.$1 - 0;
					info.RatingAvg = RegExp.$2 - 0;
				}
				info.attr = 7;
				result.VideoInfo.push( info );
			}
			i++;
		}
		nIndex = nIndex + 24;
		nPage++;
	}

		result.end   = result.start + result.VideoInfo.length; //length should always be 10 as of 2/28/08


	return result;
}

// Service metadata
var YouTube = new Object();
YouTube.Name          = "YouTube";			/* Service name */
YouTube.Description   = "YouTube";			/* Service description */
YouTube.SearchDesc    = "YouTube";			/* Service search screen description */
YouTube.SearchOSKMode = 1;						/* OSK mode 1: English only  2: Japanese */
YouTube.CheckURL      = YouTube_CheckURL;	/* CheckURL function */
YouTube.GetURL        = YouTube_GetURL;		/* GetURL function */
YouTube.Search        = YouTube_Search;		/* Search function */

// add YouTube to site list
SiteList.push( YouTube );
