/*====================================================================
Filename:	videoFFOnDemand.js
Author: 	Didi Alamsaputra
Date: 		7/23/2009
Purpose: 	Viewing JS module for Fantasy Fishing On Demand page
=======================================================================*/


/* ================
	INITIALIZATION
   ================*/
divName = "";
mediaItemAreaId = 13;// This is for Fantasy Fishing On demand page
showAd = 0;	
var gaPlugin = "";
var messageContentWidth = "";


/* =========================================
	FUNCTIONS FOR STYLING THE VIDEO PLAYER
   =========================================*/
function instantiateVideoPlayerStyle(){
	var controlPlugin = $f("player").getControls();
	
	if (controlPlugin){
		controlPlugin.css("height","30px"); 
		
	}

	var playPlugin = $f("player").getPlugin("play");
	if (playPlugin && !subscriptionTypeId){
		playPlugin.css({opacity:0});
	}
	
}


/* =========================================
	FUNCTIONS FOR VIEWING THE CHANNEL VIDEOS
   =========================================*/
   
// Viewing the videos of the current channel
function viewChannel(channelId){
	for (i=0;i<=aVideoChannel.length-1;i++){
		divName = "divTab" + aVideoChannel[i];
		changeStyle(divName, "videoTabItem");
	}
	divName = "divTab" + aVideoChannel[channelId];
	changeStyle(divName, "videoTabItem hilite");
	getVideosInChannel(aVideoChannel[channelId],0);
	
}

//Create the html dynamically for the channels and the videos
function buildChannelVideos(numOfVideo,currentChannel){
	videosHTML = "";
	var divChannelVideos = document.getElementById("divChannelVideos");
	if (!playVideoId || playVideoId == 0){
		playVideoId = aVideoId[0];
	}
	
	for (var counter=0;counter<numOfVideo;counter++){
		if (aVideoId[counter] == playVideoId){
			currentVideoId = counter;
			document.getElementById("flowPlayerDiv").innerHTML = "<a href=\"\" style=\"background: transparent url(" + aVideoThumbnail[counter] + ") no-repeat scroll center center;display:block;width:480px;height:300px;z-index:4;position:relative;\" id=\"player\" onclick=\"return false;\"><img style=\"padding-top:100px; padding-left:195px;\" src=\"/includes/flowplayer/play_large.png\" alt=\"Play Video\"/> </a>";
		}
		if (aVideoId[counter] == playVideoId){
			currentVideoId = counter;
		}
		// HTML for the links on the right side
		videosHTML += "<a id=\"videoLink" + counter + "\" href=\"\" onClick=\"loadVideo(" + counter + ",1);return false;\"><img class=\"\" style=\"width: 80px; height: 60px; display: block; float: left; margin-right: 4px;\" src=\"" + aVideoThumbnail[counter] + "\" />" + "<span class=\"linkVideoTitle\">" + newLineToBR(aVideoTitle[counter]) ; 
		if (aVideoDuration[counter].length){
			videosHTML += "<span class=\"linkVideoDuration\"> (" + formatDuration(aVideoDuration[counter]) + ")</span>";
		}
		videosHTML += "</span>";
		videosHTML += "<div class=linkVideoDescription>"  + newLineToBR(aVideoDescription[counter]) +  "</div><div class=\"fixFrame\"></div></a>";
	}
	if (divChannelVideos)
		divChannelVideos.innerHTML = "<div id=\"div" + currentChannel + "\" class=\"openBox\" >" + videosHTML +"</div>";
	playVideoId = 0;
}

/* =============================================
	FUNCTIONS FOR LOADING AND PLAYING THE VIDEOS 
   =============================================*/

// Load Video using the video id
function loadVideo(vid,autoPlay){
	
	//Initialization
	var videoTitleBottom = document.getElementById("videoTitleBottom");
	var videoTitleBottomRunningTime = document.getElementById("videoTitleBottomRunningTime");
	var videoDescription = document.getElementById("videoDescription");
	var standardVideoLink = document.getElementById("standardVideoLink");
	var addThisVideo = document.getElementById("addThisVideo");
	var suffix = "";
	var videoTitleText = "";
	// Setting the current video id to what is playing currently	
	currentVideoId = vid;
	
	// We need to clean up the ad interval before we play another ad
	if (videoAdTimer && showAd == 1){
		clearInterval(videoAdTimer);
	}
	// if autoPlay equal to 1 then we want to play the video, otherwise we just set the clip property  but not play the video
	if (autoPlay == 1){
		autoPlay = true;
	}else{
		autoPlay = false;
	}
	
	//check if this video requires some subscription to be viewed
	// if no subscription required, we can just continue to play the video
	if (aVideoSubscriptionTypeId[vid] == 0){
		
		// check to make sure that the player is initialized then we want to make sure we don't show any message if any for restricted video that was played previously.
		if ($f("player").getState() != -1){
			var contentPlugin = $f("player").getPlugin("messageContent");
			if (contentPlugin) contentPlugin.css("opacity","0");
		}
	// If this video needs a subscription type to be viewed then we will check if the user has that subscription type, if the user doesn't have the subscription then we want to show a text message
	}else{
		
		// Check if the user has the correct subscription
		if (aVideoSubscriptionTypeId[vid] == subscriptionTypeId){
			
			
		
		}else{// the user doesn't have the correct subscription type to view the video, show the restriction message
			messageContentWidth = 480 + "px";
			if ($f("player").getState() != -1){
			
				var contentPlugin = $f("player").getPlugin("messageContent");
				if (contentPlugin) {
					contentPlugin.css({opacity:1,zIndex:30,height:'60px',width:messageContentWidth});
					contentPlugin.css({color:'#ffffff'});
					var textMessage = "<p><font size='14' >" + aVideoMessageText[vid] + "</font></p>";
					contentPlugin.setHtml(textMessage);
				}
			}
		}
		
	}
		
	// make sure we don't set the high quality to false when we start loading the video, but we want to make sure that the player has loaded before we do this
	if ($f("player").getState() != -1){
		var gaPlugin = $f("player").getPlugin("gatracker");
		if (gaPlugin) 
			gaPlugin.setHighQuality(false);
	}
	
	if (aVideoSubscriptionTypeId[vid] == 0 || aVideoSubscriptionTypeId[vid] == subscriptionTypeId){	
		playlist = [{'url':aVideoStreamingPath[vid], 'autoplay':autoPlay,'provider':provider,'scaling': 'fit'}];
		$f("player").setPlaylist(playlist);
	}else{
		playlist = [{'url':aVideoThumbnail[vid], 'autoplay':autoPlay,'scaling': 'fit'}];
		$f("player").setPlaylist(playlist);
	}
	if (autoPlay){
		$f("player").play(playlist);
	}
	
	videoTitleText = aVideoTitle[vid];
	if (aVideoDuration[vid].length){
		videoTitleText += " (" + aVideoDuration[vid] + ") ";
	}
	

	
	for (var i=0;i<aVideoFile.length;i++){
		videoLinkid = 'videoLink' + i;
		divCommentId = 'commentShow' + i;
		if (i == vid){
			changeStyle(videoLinkid,'currentlyPlaying');
		}else{
			changeStyle(videoLinkid,'videoLink');
		}
	}
	closeEmbeddedCode();
	setEmbeddedCode(currentVideoId, false);
	standardVideoLink.style.display = "none";
	checkHDVideo(currentVideoId);
	
}



// Load High Definition Video using the video id
function loadHDVideo(vid,autoPlay){
	var hdVideoStreamingPath = "";
	var pathEndPosition = 0;
	var hdVideoLink = document.getElementById("hdVideoLink");
	var standardVideoLink = document.getElementById("standardVideoLink");
	if ($f("player").getState() != -1){
		var contentPlugin = $f("player").getPlugin("messageContent");
		var gaPlugin = $f("player").getPlugin("gatracker");
	}
	if (contentPlugin) {
		contentPlugin.css({opacity:0})
	}
	pathEndPosition = aVideoStreamingPath[vid].lastIndexOf("/") + 1;
	hdVideoStreamingPath = aVideoStreamingPath[vid].substring(0,pathEndPosition) + aVideoHDFile[vid];
	if (showAd == 1){
		var playlist = [{'url':aVideoAdStreamingPath[currentVideoAdIndex], 'autoplay':true,'provider':provider,'scaling': 'fit'},{'url':hdVideoStreamingPath, 'autoplay':true,'provider':provider, 'scaling': 'fit'}];
		if (autoPlay == 1){
			$f("player").play(playlist);	
		}
		// For tracking we pass the high quality  flag
		if (gaPlugin) 
			gaPlugin.setHighQuality(true);

	}else{
		if (autoPlay == 1){
			clip = {'url':hdVideoStreamingPath, 'autoplay':true,'provider':provider,'scaling': 'fit'};
			$f("player").play(clip);
			
		}else{
			clip = {'url':hdVideoStreamingPath, 'autoplay':false,'provider':provider,'scaling': 'fit'};
		}
	}
	if (hdVideoLink) hdVideoLink.style.display = "none";
	if (standardVideoLink) standardVideoLink.style.display = "block";
	setEmbeddedCode(currentVideoId, true);
}

//Check if the High definition of the video is available
function checkHDVideo(vid){
	var hdVideoLink = document.getElementById("hdVideoLink");
	if (aVideoHDFile[vid].length > 0 && hdVideoLink){
		hdVideoLink.style.display = "block";
	}else{
		if (hdVideoLink) hdVideoLink.style.display = "none";
	}
}

// Load the caption using the video id
function loadText(vid){
	var videoTitleBottom = document.getElementById("videoTitleBottom");
	var videoDescription = document.getElementById("videoDescription");

	videoTitleBottom.innerHTML = aVideoTitle[vid];
	videoDescription.innerHTML = aVideoDescription[vid];
}



/* ====================================================
	FUNCTIONS FOR SEARCHING VIDEOS FOR CERTAIN CHANNELS
   ====================================================*/

// Search the videos
function searchVideos(searchKeywords,maxResultsReturned, tabSource){
	var searchChannels = "";
	if (tabSource == "search"){
		changeStyle("divTabsearch", "videoTabItem hilite");
	}
	//we want to search in all  channels
	for (i=1;i<=5;i++){
		divName = "divTab" + aVideoChannel[i];
		changeStyle(divName, "videoTabItem");
		if (i==1){
			searchChannels = aVideoChannel[i];
		}else{
			searchChannels = searchChannels + "," + aVideoChannel[i];
		}
	}
	searchMediaItems(searchChannels,searchKeywords,maxResultsReturned);
}

// If we can't find any video from the search then display this message
function showNoVideosFound(){
	document.getElementById("divChannelVideos").innerHTML = "<div style='color:#000000;padding:10px;'>No videos found using the specified keyword(s)</div>";
}

//clear the search text
function clearSearchText(){
	if (document.getElementById("keywordsField").value == 'Keyword(s)'){
		document.getElementById("keywordsField").value = "";
	}
}




/* ==================================
	FUNCTIONS FOR TRACKING THE VIDEOS 
   ==================================*/
   
// for tracking the video
function trackMedia(eventId){
	
	$.post(flwMediaAjaxPath, {
		method:				"trackMediaItem"
		,id: aVideoId[currentVideoId]
		,areaid:mediaItemAreaId
		,mediachannelid: aVideoChannelId[currentVideoId]
		,eventid:eventId
	}, function(response) {
	});
}


/* ======================================================
   FUNCTIONS FOR STRING/STYLE FORMATTING AND MANIPULATION 
   ======================================================
*/

// replace all the new line string with a <br /> tag for html
function newLineToBR(stringToConvert){
	return stringToConvert.replace(/\n/g, "<br />");
}


// Change the style of a specific element
function changeStyle(id, newClass) {
	var identity = document.getElementById(id);
	if (identity)
		identity.className=newClass;
}  

//Format the duration of the videos
function formatDuration(strDuration){
	
	strDuration = strDuration.substr(0,8);
	var strIndex = strDuration.length;
	do
	{
		if (strDuration.substr(0,1) == '0' || strDuration.substr(0,1) == ':'){
			strDuration = strDuration.substr(1);
		}
		strIndex = strIndex - 1;
	}
	while ((strDuration.substr(0,1) == '0' || strDuration.substr(0,1) == ':') && strIndex >= 5);
	return strDuration;
}

/* ======================================================
   FUNCTIONS FOR EMBEDDING THE VIDEO TO A DIFFERENT PAGE 
   ======================================================
*/

//Function for setting the embedded code
function setEmbeddedCode(vid,hq){
	
	var embedLink = "http://www.flwoutdoors.com/flwondemand.cfm?cs=" + aVideoChannelCallsign[vid] +"&vid=" + aVideoId[vid];
	var embedLinkObject = "";
	var embedLinkObject = document.getElementById("divEmbedLink");
	var embedCode = "";
	if (hq){
		embedLink = embedLink + "&hq=1";
	}
	if (embedLinkObject){
		
		embedLinkObject.innerHTML = embedLink;
	}
	// Determine where we should get the player and the configuration for the flowplayer embedded code
	if (location.hostname){
		hostURL = "http://" + location.hostname;
		flowplayerURL = hostURL + "/FLWMedia/FLWVideoPlayer.swf";
		configURL = hostURL + "/FLWMedia/config.cfm?vid=";
	}
	
	// Form the embed code then set the field to that embedded code
	embedCode = "<object width=\"464\" height=\"291\"><param name=\"movie\" value=\""+ flowplayerURL + "?config=" + configURL + aVideoId[vid] + "\"></param><param name=\"allowFullScreen\" value=\"true\"></param><param name=\"allowscriptaccess\" value=\"always\"></param><embed src=\"" + flowplayerURL + "?config=" + configURL + aVideoId[vid] + "\" type=\"application/x-shockwave-flash\" allowscriptaccess=\"always\" allowfullscreen=\"true\" width=\"464\" height=\"291\"></embed></object>";
	
	var embedCodeObject = document.getElementById("divEmbedCode");
	/*if (embedCodeObject){
		embedCodeObject.value = embedCode;
	}*/

}

//Function for viewing the embedded code/link
function viewEmbeddedCode(typeid){
	closeEmbeddedCode();
	if (parseInt(typeid)==2)
	var embedCodeObject = document.getElementById("divEmbedCode");
	else
	var embedCodeObject = document.getElementById("divEmbedLink");
	if(embedCodeObject) embedCodeObject.style.display = "inline";
	document.getElementById("divShareInstruction").style.display = "block";
	document.getElementById("linkCloseEmbed").style.display = "inline";
	embedCodeObject.focus();
	//embedCodeObject.select();
}

//Function for closing the embedded code/link
function closeEmbeddedCode(){
	var embedCodeObject = document.getElementById("divEmbedCode");
	if (embedCodeObject) embedCodeObject.style.display = "none";
	var embedLinkObject = document.getElementById("divEmbedLink");
	if (embedLinkObject) embedLinkObject.style.display = "none";
	var linkCloseEmbedObject = document.getElementById("linkCloseEmbed");
	if (linkCloseEmbedObject) linkCloseEmbedObject.style.display = "none";
	var divShareInstructionObject = document.getElementById("divShareInstruction")
	if (divShareInstructionObject) divShareInstructionObject.style.display = "none";
}