/**
 * @fileoverview Provides functions for browsing and searching 
 * videos in the BIKE video-center application. This file reclines to the
 * userClips.js file which drives a lot of the user clips functionality.
 */

/**
 * provides namespacing for the action clips
 */
var clips = {};

/** 
 * Clips to control
 * @type String
 */
clips.ACTION = 'actionClips';
clips.BIKE4STV = 'bike4StvClips';

/**
 * The flash player reference.
 * @type Object
 */
clips.PLAYER = null;

/**
 * maximum number of results to return for list of videos
 * @type Number
 */
clips.MAX_RESULTS_LIST = 10;

/**
 * navigation button id used to page to the previous page of
 * results in the list of videos list
 * @type String
 */
clips.VIDEOS_PREVIOUS_PAGE_BUTTON = 'videosPreviousPageButton';

/**
 * navigation button id used to page to the next page of
 * results in the list of videos list
 * @type String
 */
clips.VIDEOS_NEXT_PAGE_BUTTON = 'videosNextPageButton';

/**
 * container div ID used to hold list of action clips
 * @type String
 */
clips.VIDEO_LIST_CONTAINER_DIV = 'clipsList';

/**
 * container div ID used to hold the video player
 * @type String
 */
clips.ACTION_CLIP_PLAYER_DIV = 'video';

/**
 * container div ID used to hold the search box which displays when the page
 * first loads
 * @type String
 */
clips.MAIN_SEARCH_CONTAINER_DIV = 'mainSearchBox';

/** 
 * container div ID used to hold the search box displayed at the top of
 * the browser after one search has already been performed
 * @type String
 */
clips.TOP_SEARCH_CONTAINER_DIV = 'searchBox';

/**
 * the page number to use for the next page navigation button
 * @type Number
 */
clips.nextVideoPage = 2;

/**
 * the page number to use for the previous page navigation button
 * @type Number
 */
clips.previousVideoPage = 0;

/** 
 * the last search term used to query - allows for the navigation
 * buttons to know what string query to perform when clicked
 * @type String
 */
clips.previousSearchTerm = '';

/**
 * Gets the Flash Player reference.
 */
clips.getFlashPlayer = function() {
	if (Browser.Engine.trident) { // IEs
		clips.PLAYER = window.FLVPlayer;
	} else {
		clips.PLAYER = window.document.FLVPlayer;
	}
}

/**
 * Helper method that removes unwanted tokens from the searchTerm.
 * 
 * @param {String} searchTerm The search term entered by a user.
 * @return {String} searchTerm The sanitized string.
 */
clips.sanitizeSearchTerm = function(searchTerm) {	
	var sanitizedSearchTerm; 
	
	// Remove whitespaces from beginning and end
	sanitizedSearchTerm = searchTerm.strip();
	
	// Remove any HTMl tags
	sanitizedSearchTerm = sanitizedSearchTerm.stripTags();
	
	// Remove any scripts
	sanitizedSearchTerm = sanitizedSearchTerm.stripScripts();
	
	// Replace whitespaces
	sanitizedSearchTerm = sanitizedSearchTerm.gsub(' ', '+');
	
	return sanitizedSearchTerm;
}


/**
 * 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} type       The type of clips to list
 * @param {String} searchTerm The search term(s) to use for filtering the DB
 * @param {Number} page       The 1-based page of results to return
 */
clips.listVideos = function(type, searchTerm, page) {
	clips.previousSearchTerm = searchTerm; 
	
  var maxResults = clips.MAX_RESULTS_LIST;
  // var startIndex =  (((page - 1) * clips.MAX_RESULTS_LIST) + 1);
	
	// Sanitize search term a bit
	if (searchTerm && !searchTerm == '') {
		// Removes all extraneous whitespace from a string and trims it
		searchTerm = searchTerm.clean();
		
		// Strip any <script> tags and anything in between them
		searchTerm = searchTerm.stripScripts();
	}

	clips.presentFeed(type, searchTerm, maxResults, page);
  clips.updateVideoNavigation(page, 
		clips.VIDEOS_PREVIOUS_PAGE_BUTTON, 
		clips.VIDEOS_NEXT_PAGE_BUTTON
	);
};


/**
 * Sends an AJAX request to the server to retrieve a list of videos or a 
 * specific clip.  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
 * @param {Boolean} loadClip      If true, request a specific clip
 * @param {Boolean} loadList      If true, request a video feed 
 */
clips.sendRequest = function(filePath, params, resultDivName, loadClip, loadList) {	
	var resultDiv = $(resultDivName);
	var headlineDiv = $('videosHeadline');
	
	var options = {
		url : filePath,
		data : params,
		update : resultDiv,
		onRequest : function() {
			if (loadClip) {
				resultDiv.innerHTML = '<h2>Loading ... &nbsp;' + 
					'<img src="../gfx/loader.gif" alt="" /></h2>';
			}
			if (loadList) {
				resultDiv.innerHTML = '<b>Loading ...</b>&nbsp;' + 
					'<img src="../gfx/loader.gif" alt="" />';
			}
		},
		onSuccess : function(responseTree, responseElements, responseHTML, responseJavaScript) {
			var html = responseHTML;	
		},
		onComplete : function() {
			var scrollWindow = new Fx.Scroll(window);
			//if (params.searchTerm && !params.searchTerm == '') {
			//	headlineDiv.innerHTML = 'Suchergebnisse...';
			//	scrollWindow.toElement(headlineDiv);
			//}
			if (loadClip) {
				scrollWindow.toElement(resultDiv);
			}
		}
	};
	
	var request = new Request.HTML(options);
	request.send();
}


/**
 * Uses clips.sendRequest to display an action clip video player and 
 * some metadata for the specified video.
 *
 * @param {String} videoId The vid (of the local DB) of the action clip to show
 */
clips.presentActionClip = function(videoId) {
  var params = { videoId : videoId };
  var filePath = '/actionclips/echovideoplayer';
  clips.sendRequest(
		filePath, params, clips.ACTION_CLIP_PLAYER_DIV, true, false
	);
	
	$('video').setStyle('display', 'block');
}

/**
 * Tracks the clicks on 4-Seasons.TV clips.
 *
 * @param {String} videoID The video ID of the 4STV clip.
 * @param {String} title   The title of the 4STV clip.
 */
clips.track4StvClip = function(videoID, clipTitle) {
	
	var params = {
		vid : videoID,
		title : clipTitle
	}
	
	var options = {
		url : '/bike4stv/trackclick',
		data : params,
		onRequest : function() {
		},
		onSuccess : function(responseTree, responseElements, responseHTML, responseJavaScript) {
			var html = responseHTML;	
		},
		onComplete : function() {
		}
	};
	
	var request = new Request(options);
	request.send();
}


/**
 * Uses clips.sendRequest to display a list of of clips.
 *
 * @param {String} type       The type of clips we want to present
 * @param {String} searchTerm The search terms to pass to the specified feed
 * @param {Number} maxResults The maximum number of videos to list
 * @param {Number} page       The page to be displayed
 */
clips.presentFeed = function(type, searchTerm, maxResults, page) {
	var params = {
		searchTerm : searchTerm,
    maxResults : maxResults,
		page : page
	}
	
	/** Define filepath for AJAX request */
	switch (type) {
		case clips.ACTION:
			var filePath = '/actionclips/echovideolist';
			break;
		case clips.BIKE4STV:
			var filePath = '/bike4stv/echovideolist';
			break;
	}

  clips.sendRequest(
		filePath, params, clips.VIDEO_LIST_CONTAINER_DIV, false, true
	);
}


/**
 * 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
 * @param {String} prevButton The DOM id of the previous button
 * @param {String} nextButton The DOM id of the next button
 */
clips.updateVideoNavigation = function(page, prevButton, nextButton) {
	clips.nextVideoPage = page + 1;
  clips.previousVideoPage = page - 1;
  document.getElementById(nextButton).style.display = 'inline';
  document.getElementById(prevButton).style.display = 'inline';
  if (clips.previousVideoPage < 1) {
    document.getElementById(prevButton).disabled = true;
  } else {
    document.getElementById(prevButton).disabled = false;
  }
  document.getElementById(nextButton).disabled = false;
};

/** 
 * Starts playing a bike clip video.
 *
 * @param {Number} vid The clip id.
 * @param {String} title The clip title.
 * @param {String} file The video src filename.
 */
clips.playBikeClip = function(vid, title, file) {
	//$('video').removeProperty('style');
	$('video').setStyles({
		'visibility' : 'visible',
		'height' : 'auto'
	});
	$('clipTitle').innerHTML = title;
	clips.PLAYER.playVideo(file);
	
	var scrollWindow = new Fx.Scroll(window);
	scrollWindow.toElement($('video'));
	
	/** Try to track the click */
	try {
		var params = {
			vid : vid,
			title : title
		}

		var options = {
			url : '/bikeclips/trackclick',
			data : params,
			onRequest : function() {
			},
			onSuccess : function() {	
			},
			onComplete : function() {
			}
		};

		var request = new Request(options);
		request.send();
	} catch (e) {
		// do nothing;
	}	
}

/**
 * loadBikeClip
 *
 * Embeds a Bike Clip into the page 
 * 
 * @param {String} video The filename of the video to load
 * @param {String} title The video title
 */
clips.loadBikeClip = function(video, title) {
	var requiredMajorVersion = 9;
	var requiredMinorVersion = 0;
	var requiredRevision = 45;

	if (AC_FL_RunContent == 0 || DetectFlashVer == 0) {
		alert("Diese Seite erfordert die Datei AC_RunActiveContent.js.");
	} else {
		var hasRightVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);
		if(hasRightVersion) {  // sofern eine akzeptable Version ermittelt wurde
			// Flash-Film einbetten
			AC_FL_RunContent(
				'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,45,0',
				'width', '640',
				'height', '480',
				'src', '/videos/' + video,
				'quality', 'high',
				'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
				'play', 'false',
				'loop', 'false',
				'scale', 'showall',
				'wmode', 'window',
				'devicefont', 'false',
				'id', '' + video,
				'name', '' + video,
				'menu', 'true',
				'allowScriptAccess','sameDomain',
				'allowFullScreen','true',
				'movie', '/videos/' + video,
				'salign', ''
				); //end AC code
		} else {  // Flash ist veraltet, oder das Plug-In wurde nicht ermittelt
			var alternateContent = ''
				+ 'Um das Video abzuspielen ist der Adobe Flash Player erforderlich. '
				+ '<a href=https://www.macromedia.com/go/getflash/>Flash installieren</a>';
			// document.write(alternateContent);  // Nicht aus Flash stammenden Inhalt einfügen
			$('clip').innerHTML = alternateContent;
		}
	}
	
	/** Track the click */
	var params = {
		vid : 'No unique ID yet!',
		title : title
	}
	
	var options = {
		url : '/bikeclips/trackclick',
		data : params,
		onRequest : function() {
		},
		onSuccess : function(responseTree, responseElements, responseHTML, responseJavaScript) {
			var html = responseHTML;	
		},
		onComplete : function() {
		}
	};
	
	var request = new Request(options);
	request.send();
	
	$('clipTitle').innerHTML = title;
	var scrollWindow = new Fx.Scroll(window);
	scrollWindow.toElement($('video'));
}
/** EOF function */