// JavaScript Document
//<![CDATA[

// Global Variables:
var TVS = null;			// The global variable for the TruveoVideoSearch object used in this application.
var VIDEO_PANEL = null;		// The global variable for the view object used to display the video search results.
var TITLE_BAR = null; 		// The global variable for the view object used to display a title bar for a set of video search results.
//var CATEGORY_MENU = null; 	// The global variable for the view object used to display a menu of related categories.
var CHANNEL_MENU = null; 	// The global variable for the view object used to display a menu of related channels.
var TAG_MENU = null; 		// The global variable for the view object used to display a menu of related tags.
var USER_MENU = null; 		// The global variable for the view object used to display a menu of related users.
var LOGIN_BUTTON = null;	// The global variable for the stateful login button.

// The following functions are handlers for the buttons and links provided in the application.
// Function getVideos() submits the given query to the AOL video search engine.  The optional argument
// start specifies the position of the first video in the total set of matching videos.
function getVideos(query, start) { 
	VIDEO_PANEL.displayMessage('Please wait...');
	if (arguments.length < 1) { TVS.getVideos(); }
	else if (arguments.length < 2) { TVS.getVideos(query); }
	else { TVS.getVideos(query, start); }
}
// Function getVideosByCategory() modifies the current query to include the provided category filter and retrieves a new set of videos.
function getVideosByCategory(category) {
	if (category.toLowerCase() == 'all') { 
		var query = TVS.query;
		query = query.replace(/\s?category:"[^"]*"/gi, "");
		query = query.replace(/\s?category:\S*/gi, "");
		getVideos(query); 
	}
	else { 
		var query = TVS.query;
		var theRegExp = new RegExp('\\s?category:"\\s*'+VSUTIL.escapeRegExp(category)+'\\s*"', "gi");
		query = query.replace(theRegExp, "");
		theRegExp = new RegExp('\\s?category:'+VSUTIL.escapeRegExp(category), "gi");
		query = query.replace(theRegExp, "");
		getVideos(query + ' category:"' + category + '"'); 
	}
}
// Function getVideosByChannel() modifies the current query to include the provided channel filter and retrieves a new set of videos.
function getVideosByChannel(channel) {
	if (channel.toLowerCase() == 'all') { 
		var query = TVS.query;
		query = query.replace(/\s?channel:"[^"]*"/gi, "");
		query = query.replace(/\s?channel:\S*/gi, "");
		getVideos(query); 
	}
	else { 
		var query = TVS.query;
		var theRegExp = new RegExp('\\s?channel:"\\s*'+VSUTIL.escapeRegExp(channel)+'\\s*"', "gi");
		query = query.replace(theRegExp, "");
		theRegExp = new RegExp('\\s?channel:'+VSUTIL.escapeRegExp(channel), "gi");
		query = query.replace(theRegExp, "");
		getVideos(query + ' channel:"' + channel + '"'); 
	}
}
// Function getVideosByTag() modifies the current query to include the provided tag filter and retrieves a new set of videos.
function getVideosByTag(tag) {
	if (tag.toLowerCase() == 'all') { 
		var query = TVS.query;
		query = query.replace(/\s?tag:"[^"]*"/gi, "");
		query = query.replace(/\s?tag:\S*/gi, "");
		getVideos(query); 
	}
	else { 
		var query = TVS.query;
		var theRegExp = new RegExp('\\s?tag:"\\s*'+VSUTIL.escapeRegExp(tag)+'\\s*"', "gi");
		query = query.replace(theRegExp, "");
		theRegExp = new RegExp('\\s?tag:'+VSUTIL.escapeRegExp(tag), "gi");
		query = query.replace(theRegExp, "");
		getVideos(query + ' tag:"' + tag + '"'); 
	}
}
// Function getVideosByUser() modifies the current query to include the provided user filter and retrieves a new set of videos.
function getVideosByUser(user) {
	if (user.toLowerCase() == 'all') { 
		var query = TVS.query;
		query = query.replace(/\s?user:"[^"]*"/gi, "");
		query = query.replace(/\s?user:\S*/gi, "");
		getVideos(query); 
	}
	else { 
		var query = TVS.query;
		var theRegExp = new RegExp('\\s?user:"\\s*'+VSUTIL.escapeRegExp(user)+'\\s*"', "gi");
		query = query.replace(theRegExp, "");
		theRegExp = new RegExp('\\s?user:'+VSUTIL.escapeRegExp(user), "gi");
		query = query.replace(theRegExp, "");
		getVideos(query + ' user:"' + user + '"'); 
	}
}
// Function nextPage() displays the next page of videos in the current VideoSet.
function nextPage() {
	VIDEO_PANEL.displayMessage('Please wait...');
	TVS.nextPage()
}
// Function previousPage() displays the previous page of videos in the current VideoSet.
function previousPage() {
	VIDEO_PANEL.displayMessage('Please wait...');
	TVS.previousPage()
}
// Function goToPage() displays the page of videos, specified by pageNum, in the current VideoSet.
function goToPage(pageNum) {
	VIDEO_PANEL.displayMessage('Please wait...');
	TVS.goToPage(pageNum)
}
// Function hasNextPage() returns true if a next page of video results is available.
function hasNextPage() { return(TVS.hasNextPage()); }
// Function hasNextPage() returns true if a previous page of video results is available.
function hasPreviousPage() { return(TVS.hasPreviousPage()); }
// Function sortBy() modifies the query string to include the provided sort option and retrieves a new set of videos.
function sortBy(sortOption) { getVideos(TVS.query.replace(/\s?sort:\S*/gi, "") + " sort:" + sortOption); }
// Function filterType() modifies the query string to include the provided type filter and retrieves a new set of videos.
function filterType(type) { 
	var query = TVS.query.replace(/\s?type:\S*/gi, "");
	if (type == 'all') { getVideos(query); }
	else { getVideos(query + " type:" + type); }
}
// Function filterRuntime() modifies the query string to include the specified runtime filter and retrieves a new set of videos.
function filterRuntime(runtime) { 
	var query = TVS.query.replace(/\s?runtime:\S*/gi, "");
	switch(runtime) {
		case 'short': getVideos(query + " runtime:<2"); break;
		case 'medium': getVideos(query + " runtime:>2 AND runtime:<10"); break;
		case 'long': getVideos(query + " runtime:>10"); break;
		default: getVideos(query); break;
	}
}
// Function filterQuality() modifies the query string to include the provided quality filter and retrieves a new set of videos.
function filterQuality(quality) { 
	var query = TVS.query.replace(/\s?quality:\S*/gi, "");
	if (quality == 'all') { getVideos(query); }
	else { getVideos(query + " quality:" + quality); }
}
// Function filterFormat() modifies the query string to include the provided format filter and retrieves a new set of videos.
function filterFormat(format) { 
	var query = TVS.query.replace(/\s?format:\S*/gi, "");
	if (format == 'all') { getVideos(query); }
	else { getVideos(query + " format:" + format); }
}
// Function setStyle() sets the CSS style to apply to the video results.
function setStyle(styleName) {
	document.getElementById('bodyDiv').className = styleName; 
	setStyleBtn();
}
// Function setView() sets the type of view (e.g. grid, list or detail) of the video results to display.
function setView(value) {
	VIDEO_PANEL.setView(value); 
	setViewBtn();
	VIDEO_PANEL.refresh(TVS);
}
// Function setVideosPerPage() sets the number of videos to retrieve in each page of results.
function setVideosPerPage(numVideos) {
	TVS.results = numVideos;
	setVideosPerPageBtn();
	getVideos(TVS.query, TVS.start);
}
// Function setShowAdult() turns on or off the family filter and retrieves a new set of videos.
function setShowAdult(value) { 
	TVS.showAdult = value;
	setShowAdultBtn();
	getVideos(TVS.query);
}
// Function submitRating() submits the rating integer (1-5) for the video with the specified id value.
function submitRating(videoId, rating) { TVS.submitRating(videoId, rating); }
// Function login() signs the user into the AOL video search service.
function login() {
	saveState();
	TVS.login(window.location.href);
}
// Function logout() signs the user out of the AOL video search service.
function logout() { 
	saveState();
	TVS.logout(window.location.href);
}
// Function getFavoriteVideos() retrieves the user's favorite videos, if any have been saved.
function getFavoriteVideos() { TVS.getFavoriteVideos(); }
// Function addFavorite() adds the video with the submitted id to the user's favorites list.
function addFavorite(id) { TVS.addFavorite(id); }
// Function removeFavorite() removes the video with the submitted id from your favorites list.
function removeFavorite(id) { TVS.removeFavorite(id); }
// Function getRecentVideos() retrieves the user's recently viewed videos.
function getRecentVideos() { TVS.getRecentVideos(); }
// Function addRecentVideo() adds the video with the submitted id to your recent videos list.
function addRecentVideo(id) { TVS.addRecentVideo(id); }
// Function clearRecentVideos() removes all videos from the recent videos list.
function clearRecentVideos() {
	if (confirm("Click 'OK' to confirm that you would like to delete all of your recent videos.")) {
		TVS.clearRecentVideos();
	}
}
// Function getWatchlists() retrieves the user's watchlists, if any have been saved.
function getWatchlists() { TVS.getWatchlists(); }
// Function addWatchlist() adds the specified search query to the user's watchlists.
function addWatchlist(query) { TVS.addWatchlist(query); }
// Function removeWatchlist() removes the specified query from your watchlists.
function removeWatchlist(query) { TVS.removeWatchlist(query); }
// Function playVideo() adds the video with the specified id to the recent videos list (if logged in) and then
// opens a new browser window to load the specified videoUrl.
function playVideo(videoUrl, id) {
	addRecentVideo(id);
	window.open(videoUrl, '', 'width=800,height=800,location=no,menubar=no,resizable=yes,scrollbars=yes');
}

// Function handleUpdate() handles all response messages from the TruveoVideoSearchAPI.  Whenever the TruveoVideoSearchAPI
// receives a response to an AJAX request, it fires the onupdate event.  This method handles each onupdate event.
function handleUpdate(methodName) {
	if ((methodName == 'getVideos') || (methodName == 'getFavoriteVideos') || (methodName == 'getRecentVideos')) {
		TITLE_BAR.refresh(TVS);
		if(document.getElementById('searchBox') != null)
			document.getElementById('searchBox').value = TVS.query;
		
		// If there are not videos in the returned VideoSet, then display a helpful message.
		// Otherwise, if this is a 'show details' query for a single video, then show the full view of the video record.  
		// Otherwise, display the standard grid, list or detail view.
		if ((TVS.VideoSet) && (TVS.VideoSet.totalResultsReturned == 0) || !(TVS.VideoSet.Video) || (TVS.VideoSet.Video.length == 0)) {
			VIDEO_PANEL.displayMessage('There are no videos available.');
			//CATEGORY_MENU.clear();
			//CHANNEL_MENU.clear();
			//TAG_MENU.clear();
			//USER_MENU.clear();
		}
		else if ((TVS.VideoSet) && (TVS.VideoSet.totalResultsAvailable == 1) && (TVS.query) && (TVS.query.indexOf("id:") >= 0)) {
			VIDEO_PANEL.displayFullView(TVS, TVS.previousQuery);
			//CATEGORY_MENU.clear();
			//CHANNEL_MENU.clear();
			//TAG_MENU.clear();
			//USER_MENU.clear();
		}
		else {
			VIDEO_PANEL.refresh(TVS);
			if ((methodName == 'getFavoriteVideos') || (methodName == 'getRecentVideos')) {
				//CATEGORY_MENU.clear();
				//CHANNEL_MENU.clear();
				//TAG_MENU.clear();
				//USER_MENU.clear();
			}
			/*else {
				CATEGORY_MENU.refresh(TVS.CategorySet);
				CHANNEL_MENU.refresh(TVS.ChannelSet);
				TAG_MENU.refresh(TVS.TagSet);
				USER_MENU.refresh(TVS.UserSet);
			}*/
		}
	}
	else if (methodName == 'submitRating') {
		alert(TVS.Result.message + " (User rating: " + TVS.Result.userRating + ", User rating count: " + TVS.Result.userRatingCount +")");
	}
	else if (methodName == 'addFavorite') {
		alert(TVS.Result.message);
	}
	else if (methodName == 'removeFavorite') {
		getFavoriteVideos();
	}
	else if (methodName == 'clearRecentVideos') {
		getRecentVideos();
	}
	else if (methodName == 'getWatchlists') {
		TITLE_BAR.displayTitle('My Watchlists');
		VIDEO_PANEL.displayWatchlists(TVS);
		//CATEGORY_MENU.clear();
		//CHANNEL_MENU.clear();
		//TAG_MENU.clear();
		USER_MENU.clear();
	}
	else if (methodName == 'addWatchlist') {
		alert(TVS.Result.message);
	}
	else if (methodName == 'removeWatchlist') {
		getWatchlists();
	}
	//LOGIN_BUTTON.refresh(TVS.isLoggedIn());
}

// Function handleLoad() handles the onload event, which is fired when the loading of the TruveoVideoSearch object is complete.
// This function has one argument, reloadStateFlag, which is set to true if the API state has been reloaded.  This occurs
// following a login, logout or a cancelled login attempt.
function handleLoad(reloadStateFlag) {
	if (reloadStateFlag) { 
		loadState();
		getVideos(TVS.query, TVS.start);
	}
	else { getVideos(); }
}

// Function handleError() handles all errors thrown by the TruveoVideoSearch API.  It displays an alert box with the
// error code and error message.
function handleError(errorCode, errorMessage) {
	alert("ERROR: Code " + errorCode + "; " + errorMessage);
}

// Function VSLoad() is called when the containing web page has completed loading.  This function instantiates a single TruveoVideoSearch
// object, sets the state of the object, attaches the appropriate event handlers to this object, and then initializes the object. 
// This function also instantiates any view objects that are used to display search results and other UI features.
function VSLoad() {
	VIDEO_PANEL = new VideoPanel1("VideoPanelViewDiv");
	TITLE_BAR = new TitleBar1("TitleBarDiv");
	//CATEGORY_MENU = new CategoryMenu1("CategoryMenuDiv");
	//CHANNEL_MENU = new ChannelMenu1("ChannelMenuDiv");
	//TAG_MENU = new TagMenu1("TagMenuDiv");
	//USER_MENU = new UserMenu1("UserMenuDiv");
	//LOGIN_BUTTON = new LoginButton1("LoginButton");
	//TVS = new TruveoVideoSearch('1x1jhj64466mi12ia');
	TVS = new TruveoVideoSearch('6aaa9293cdeb131eb');
	TVS.showRelatedItems = 1;
	TVS.results = 8;
	TVS.showAdult = 0;
	TVS.attachEvent('onerror', 'handleError(errorCode, errorMessage);');
	TVS.attachEvent('onupdate', 'handleUpdate(methodName);');
	TVS.attachEvent('onload', 'handleLoad(reloadStateFlag);');
	TVS.initialize();
	//VIDEO_PANEL.setVideosPerPage(8);
	VIDEO_PANEL.setView(0);
	VIDEO_PANEL.setView(0);
}

// Function setStyleBtn() sets the state of the style toggle button.
function setStyleBtn() {
	var styleName = document.getElementById('bodyDiv').className;
	switch(styleName) {
		case 'style1':
			document.getElementById('style1Btn').style.textDecoration = "underline"; 
			document.getElementById('style2Btn').style.textDecoration = "none"; 
			break;
		case 'style2': 
			document.getElementById('style1Btn').style.textDecoration = "none"; 
			document.getElementById('style2Btn').style.textDecoration = "underline"; 
			break;
	}
}

// Function setViewBtn() sets the state of the view toggle button.
function setViewBtn() {
	switch(parseInt(VIDEO_PANEL.getView())) {
		case 0: 
			document.getElementById('gridBtn').style.textDecoration = "underline"; 
			document.getElementById('listBtn').style.textDecoration = "none"; 
			document.getElementById('detailBtn').style.textDecoration = "none"; 
			break;
		case 1: 
			document.getElementById('gridBtn').style.textDecoration = "none"; 
			document.getElementById('listBtn').style.textDecoration = "underline"; 
			document.getElementById('detailBtn').style.textDecoration = "none"; 
			break;
		case 2: 
			document.getElementById('gridBtn').style.textDecoration = "none"; 
			document.getElementById('listBtn').style.textDecoration = "none"; 
			document.getElementById('detailBtn').style.textDecoration = "underline"; 
			break;
	}
}

// Function setVideosPerPageBtn() sets the state of the videos per page toggle button.
function setVideosPerPageBtn() {
	switch(parseInt(TVS.results)) {
		case 10: 
			document.getElementById('10Btn').style.textDecoration = "underline"; 
			document.getElementById('20Btn').style.textDecoration = "none"; 
			document.getElementById('50Btn').style.textDecoration = "none"; 
			break;
		case 20: 
			document.getElementById('10Btn').style.textDecoration = "none"; 
			document.getElementById('20Btn').style.textDecoration = "underline"; 
			document.getElementById('50Btn').style.textDecoration = "none"; 
			break;
		case 50: 
			document.getElementById('10Btn').style.textDecoration = "none"; 
			document.getElementById('20Btn').style.textDecoration = "none"; 
			document.getElementById('50Btn').style.textDecoration = "underline"; 
			break;
	}
}

// Function setShowAdultBtn() sets the state of the family filter toggle button.
function setShowAdultBtn() {
	if (TVS.showAdult == 1) {
		document.getElementById('familyFilterOffBtn').style.textDecoration = "underline";
		document.getElementById('familyFilterOnBtn').style.textDecoration = "none";
	}
	else {
		document.getElementById('familyFilterOffBtn').style.textDecoration = "none";
		document.getElementById('familyFilterOnBtn').style.textDecoration = "underline";
	}
}

// Function saveState() saves application state to a cookie, so that it can be reloaded later if the user returns to this page.
function saveState() {
	var stateCookie = new Cookie(document, "app1_state");
	stateCookie.style = document.getElementById('bodyDiv').className;
	stateCookie.view = VIDEO_PANEL.getView();
	stateCookie.store();
}

// Function loadState() restores the application state from the stateCookie.
function loadState() {

	// Load the state from the cookie and update the application state based on the cookie values.
	var stateCookie = new Cookie(document, "app1_state");
	if (stateCookie.load()) {
		document.getElementById('bodyDiv').className = stateCookie.style; 
		VIDEO_PANEL.setView(stateCookie.view); 
		stateCookie.remove();
	}

	// Update the display of the stateful toggle buttons.
	setStyleBtn();
	setViewBtn();
	setVideosPerPageBtn();
	setShowAdultBtn();
}

//]]>
