var ytvbp = {};
ytvbp.MAX_RESULTS_LIST = 16;
ytvbp.PREVIOUS_PAGE_BUTTON = 'previousPageButton'; // dom ID
ytvbp.NEXT_PAGE_BUTTON = 'nextPageButton';
ytvbp.VIDEO_LIST_CONTAINER_DIV = 'searchResultsVideoList';
ytvbp.VIDEO_PLAYER_DIV = 'videoPlayer';
ytvbp.MAIN_SEARCH_CONTAINER_DIV = 'mainSearchBox';
ytvbp.TOP_SEARCH_CONTAINER_DIV = 'searchBox';
ytvbp.nextPage = 2;
ytvbp.previousPage = 0;
ytvbp.previousSearchTerm = '';
ytvbp.previousQueryType = 'all';

/**
 * Retrieves a list of videos matching the provided criteria.  The list of
 * videos can be restricted to a particular standard feed or search criteria.
 * @param {String} queryType The type of query to be done - either 'all'
 *     for querying all videos, or the name of a standard feed.
 * @param {String} searchTerm The search term(s) to use for querying as the
 *     'vq' query parameter value
 * @param {Number} page The 1-based page of results to return.
 */
ytvbp.listVideos = function(queryType, searchTerm, page) {
	searchTerm = "vuezone -TechViShow " + searchTerm;
  ytvbp.previousSearchTerm = searchTerm; 
  ytvbp.previousQueryType = queryType; 
  var maxResults = ytvbp.MAX_RESULTS_LIST;
  var startIndex =  (((page - 1) * ytvbp.MAX_RESULTS_LIST) + 1);
  ytvbp.presentFeed(queryType, maxResults, startIndex, searchTerm);
  ytvbp.updateNavigation(page);
};

/**
 * Sends an AJAX request to the server to retrieve a list of videos or
 * the video player/metadata.  Sends the request to the specified filePath
 * on the same host, passing the specified params, and filling the specified
 * resultDivName with the resutls upon success.
 * @param {String} filePath The path to which the request should be sent
 * @param {String} params The URL encoded POST params
 * @param {String} resultDivName The name of the DIV used to hold the results
 */
ytvbp.sendRequest = function(filePath, params, resultDivName, callback) {
  if (window.XMLHttpRequest) {
    var xmlhr = new XMLHttpRequest();
  } else {
    var xmlhr = new ActiveXObject('MSXML2.XMLHTTP.3.0');
  }
  var resultDiv = document.getElementById(resultDivName);
  resultDiv.innerHTML = '<div class="loading"><b>loading...</b></div>'; 
  xmlhr.open('POST', filePath, true);
  xmlhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); 
  xmlhr.onreadystatechange = function() {
    var resultDiv = document.getElementById(resultDivName);
    if (xmlhr.readyState == 1) {
    } else if (xmlhr.readyState == 4 && xmlhr.status == 200) {
      if (xmlhr.responseText) {
        resultDiv.innerHTML = xmlhr.responseText;
		if( callback )
			callback();
      }
    } else if (xmlhr.readyState == 4) {
      alert('Invalid response received - Status: ' + xmlhr.status);
    }
  }
  xmlhr.send(params);
}

/**
 * Uses ytvbp.sendRequest to display a YT video player and metadata for the
 * specified video ID.
 * @param {String} videoId The ID of the YouTube video to show
 */
ytvbp.presentVideo = function(videoId) {
  var params = 'queryType=show_video&videoId=' + videoId;
  var filePath = '/YouTube/process.php';
  ytvbp.sendRequest(filePath, params, ytvbp.VIDEO_PLAYER_DIV, videoRating);
}

/**
 * Uses ytvbp.sendRequest to display a list of of YT videos.
 * @param {String} queryType The name of a standard video feed or 'all'
 * @param {Number} maxResults The maximum number of videos to list
 * @param {Number} startIndex The first video to include in the list
 * @param {String} searchTerm The search terms to pass to the specified feed
 */
/*	
	uploaded=
		today - d
		this week - w
		this month - m
		anytime - ''
	search_query=vuezone
	search_type=videos
	search_sort=
		newest - video_date_uploaded
		oldest - video_date_uploaded_reverse
		video_view_count
		video_avg_rating
		Relevance - ''
		
		
		orderby parameter, which is only supported for video feeds, specifies the value that will be used to sort videos in the search result set. Valid values for this parameter are relevance, published, viewCount and rating
*/

ytvbp.presentFeed = function(queryType, maxResults, startIndex, searchTerm){
  var params = 'queryType=' + queryType + 
               '&maxResults=' + maxResults +
               '&startIndex=' + startIndex + 
               '&searchTerm=' + searchTerm;
  var filePath = '/YouTube/process.php';
  ytvbp.sendRequest(filePath, params, ytvbp.VIDEO_LIST_CONTAINER_DIV, fixRating);
}

/**
 * Updates the variables used by the navigation buttons and the 'enabled' 
 * status of the buttons based upon the current page number passed in.
 * @param {Number} page The current page number
 */
ytvbp.updateNavigation = function(page) {
  ytvbp.nextPage = page + 1;
  ytvbp.previousPage = page - 1;
  document.getElementById(ytvbp.NEXT_PAGE_BUTTON).style.display = 'inline';
  document.getElementById(ytvbp.PREVIOUS_PAGE_BUTTON).style.display = 'inline';
  if (ytvbp.previousPage < 1) {
    document.getElementById(ytvbp.PREVIOUS_PAGE_BUTTON).disabled = true;
  } else {
    document.getElementById(ytvbp.PREVIOUS_PAGE_BUTTON).disabled = false;
  }
  document.getElementById(ytvbp.NEXT_PAGE_BUTTON).disabled = false;
};

/**
 * Hides the main (large) search form and enables one that's in the
 * title bar of the application.  The main search form is only used
 * for the first load.  Subsequent searches should use the version in
 * the title bar.
 */
ytvbp.hideMainSearch = function() {
  document.getElementById(ytvbp.MAIN_SEARCH_CONTAINER_DIV).style.display = 
      'none';
  document.getElementById(ytvbp.TOP_SEARCH_CONTAINER_DIV).style.display = 
      'inline';
};

/**
 * Method called when the query type has been changed.  Clears out the
 * value of the search term input box by default if one of the standard
 * feeds is selected.  This is to improve usability, as many of the standard
 * feeds may not include results for even fairly popular search terms.
 * @param {String} queryType The type of query being done - either 'all'
 *     for querying all videos, or the name of one of the standard feeds.
 * @param {Node} searchTermInputElement The HTML input element for the input
 *     element.
 */
ytvbp.queryTypeChanged = function(queryType, searchTermInputElement) {
  if (queryType != 'all') {
    searchTermInputElement.value = '';
  }
};


Date.prototype.setUTC = function (string) {
	// ISO8601
	// var date = new Date();
	// date.setUTC("2005-03-26T19:51:34Z");

	var regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" +
        "(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?" +
        "(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?";
    var d = string.match(new RegExp(regexp));

    var offset = 0;
    var date = new Date(d[1], 0, 1);

    if (d[3]) { date.setMonth(d[3] - 1); }
    if (d[5]) { date.setDate(d[5]); }
    if (d[7]) { date.setHours(d[7]); }
    if (d[8]) { date.setMinutes(d[8]); }
    if (d[10]) { date.setSeconds(d[10]); }
    if (d[12]) { date.setMilliseconds(Number("0." + d[12]) * 1000); }
    if (d[14]) {
        offset = (Number(d[16]) * 60) + Number(d[17]);
        offset *= ((d[15] == '-') ? 1 : -1);
    }

    offset -= date.getTimezoneOffset();
    time = (Number(date) + (offset * 60 * 1000));
    this.setTime(Number(time));
}

function showVideo(videoId)
{
	var opts = {
		onHide: function(h) { 
			if(h.o)h.o.remove();
			h.w.fadeOut(200, function(){$('#videoPlayer').html('');} );
		}
	}
	showModal('modalPlayer',opts);
	ytvbp.presentVideo(videoId);
}

function fixRating()
{
	$('#searchResultsVideoList p.rating').each(function(i){
		var o = $(this);
		var rate = o.html().substr(8);
		var star = Math.floor(64*rate/5);
		o.html("<div style=\"width:"+star+"px\"></div><span>("+rate+")</span>");
		o.css('visibility','visible');
	});
}

function videoRating()
{
	$('#videoPlayer .rating').each(function(i){
		var o = $(this);
		var rate = o.html().substr(15);
		var star = Math.floor(64*rate/5);
		o.html("<b>Rating:</b> <div style=\"width:"+star+"px\"></div><span>("+rate+")</span>");
		o.css('visibility','visible');
	});
}

