﻿// JS file contains all the main Javascript functions for the uabhealthTV video section

var objProgImgPrev = null;  // Global Image Object
var ProgFileNmPrev = null;  // Global file name that stores '.jpg' file name
var oldContents = null;		// Contents of the Program Info Object before we switch it.
var needToStore = true;
var nowPlaying = "1";		// Default program being played
var curPlaylistPos = 0;     // Position in playlist array of video currently playing
var channelID = "1"; 		// Default Channel ID
var flash = null;  			// Flash object
var videosAlreadyRated =""; // Global variable that keeps track of videos already rated; identical to Session variable("VideosAlreadyRated") on the server side
var	videoTitle = "";   		// Global video title so it can be displayed in Rate Video window

//Preload The Rollover Images

Rollimage = [ ];

// Original Image
Rollimage[0]= new Image(104,25);
Rollimage[0].src = "/images/graphics/bt_EmailVideo.gif";

// Swapped Image
Rollimage[1] = new Image(104,25);
Rollimage[1].src = "/images/graphics/bt_EmailVideo_ro.gif";

// Original Image
Rollimage[2]= new Image(104,25);
Rollimage[2].src = "/images/graphics/bt_AddtoFavorites.gif";

// Swapped Image
Rollimage[3] = new Image(104,25);
Rollimage[3].src = "/images/graphics/bt_AddtoFavorites_ro.gif";

// Original Image
Rollimage[4]= new Image(104,25);
Rollimage[4].src = "/images/graphics/bt_RateVideo.gif";

// Swapped Image
Rollimage[5] = new Image(104,25);
Rollimage[5].src = "/images/graphics/bt_RateVideo_ro.gif";

function setBookMark ( elem )
{
	
	elem.href = "/Bookmarks.asp?ChannelID=" + channelID + "&ProgramID=" + nowPlaying;
	

}


// On startup, makes nowPlaying and channelID global variables; also plays the video from a Bookmark 
function initProgID ( progID, chanID )
{
	//alert ("initProgID = " + chanID + " " + progID); 
	
	nowPlaying = progID;
	channelID = chanID;
	flash = getFlashMovieObject('player'); // Retrieving the Flash Movie Object; <object> tag id = "player" in default.asp  
	
	//setCurPlaylistPos ( progID, chanID ); used for Continuous play; comment for now 
	
	
	var strURL;
	var dateTime = new Date(); 
							  
	
		if (nowPlaying.length > 0) 
		{ 
            strURL = '/updateVideoRating.asp?DateTimeNow=' + escape(dateTime.valueOf()); //IE sometimes caches results from a previous AJAX request; therefore we need to append this unique value to the QueryString to make each AJAX request UNIQUE		
		    //alert (strURL);
		}
	   	   
	   	   	   
		var responseSuccess = function(o)
		{
			
			// REMINDER: o.responseText will always return results of typing 'strURL' above in your browser! (which in this case is the response.write Session variable			
			videosAlreadyRated = o.responseText;
			
			//alert ('JS initProgID; videosAlreadyRated = ' + videosAlreadyRated);
							
		};
	
		var responseFailure = function(o)
		{
			//alert('System Problem in initProgID -- Please notify avizon@photobooks.com');
		};
	
		var callback = 
		{
			success: responseSuccess,
			failure: responseFailure
		};
	
        LogVideo(progID);
		
		var transaction = YAHOO.util.Connect.asyncRequest('GET', strURL, callback, null);

}

// On startup, hides submit button if Javascript is turned ON; executed from Body Onload 
function hideSubmitButton(fld)
{ //This hides the submit button (located underneath Select box) when viewer has Javascript turned ON.
  //Submit button automatically is visible to user when Javascript is OFF, b/c this JS function won't work
  //when JS is OFF (duh)!
	
	
	
	var elem = document.getElementById(fld);
		
	elem.style.display = 'none';


}



function getFlashMovieObject(movieName)
{
		
    if (window.document[movieName]) 
    {
	    return window.document[movieName];
    }
  
    if (navigator.appName.indexOf("Microsoft Internet")== -1)
    {
    	if (document.embeds && document.embeds[movieName]){
    	  return document.embeds[movieName];} 
    	  
    }
    else // if (navigator.appName.indexOf("Microsoft Internet")!=-1)
    {
        return document.getElementById(movieName);
    }
}

function swap ( fld, index )
{
    var elem = document.getElementById(fld);

	elem.src = Rollimage[index].src;
}

function addNowPlaying(fld)
{
	// Function Adds the Currently Playing Video's image to the Send/Rate Video Form

	var elem = document.getElementById(fld);

	elem.nowPlaying.value = nowPlaying;
	elem.channelID.value = channelID;
	
}

function DisplayTitleNDescription (fld, title, shortDescription, longDescription, progID)
{ //Displays Title and Description in box to right of playing video
   var dispmessage;

	if (title !== null && title !== "")
	{
		dispmessage = '<p>' + title + '<\/p>';
	}
	
	if (shortDescription !== null && shortDescription !== "")
	{
		dispmessage = dispmessage + '<h3>' + shortDescription + '<\/h3>';
	}

	if (longDescription !== null && longDescription !== "")
	{
		dispmessage = dispmessage + '<h4>' + longDescription + '<\/h4>';
	}
	
	
    // dispmessage = '<p>' + title + "<\/p><br \/>" + "<h3>" + shortDescription + "<\/h3>" + "<h4>" + longDescription + "<\/h4>"; 
		
    var elem = document.getElementById(fld);
	
    elem.innerHTML = URLDecode(dispmessage);
	
	var linkelem = document.getElementById('links');
	
	if (progID > 0)
	{
    	DisplayLinks('links', progID);   //Display Helpful Links
	}
	else
	{
		
		linkelem.innerHTML = 'No Helpful Links Found';

	}
}



function DisplayLinks(fld, progID)
{   // displays links located in box to the right of video player 
	var elem = document.getElementById(fld);
	var strLinks = "";
	var strURL;
	var dateTime = new Date(); 
							  
		
		if (progID.length > 0) 
		{ 
            strURL = '/displayLinks.asp?ProgramID=' + escape(progID) + '&DateTimeNow=' + escape(dateTime.valueOf()); //IE sometimes caches results from a previous AJAX request; therefore we need to append this unique value to the QueryString to make each AJAX request UNIQUE		
		    //alert (strURL);
		}
	   	   
	   	   	   
		var responseSuccess = function(o)
		{
			
			// REMINDER: o.responseText will always return results of typing 'strURL' above in your browser! (which in this case is the response.write Session variable			
								
			elem.innerHTML = o.responseText;
			//alert (o.responseText);
										
		};
	
		var responseFailure = function(o)
		{
			alert('System Problem with Links -- Please notify avizon@photobooks.com');
		};
	
		var callback = 
		{
			success: responseSuccess,
			failure: responseFailure
		};
	
		
		var transaction = YAHOO.util.Connect.asyncRequest('GET', strURL, callback, null);
	
}

 
// Video Search is a form, and we need to reference the input box. This function references the video search input box.
// If the input box exists, it is passed to DisplayResults.  If it does not exist, then this returns false.
function fnVideoSearch(oForm) {

   oInput = oForm.strVideoSrch;
   if (!oInput) { return false; }
	
   return DisplayResults(oInput);
}

// Display the videos in Related Videos box
function DisplayResults(obj)
{
		
		var sType = obj.type;

		var dateTime = new Date(); //IE sometimes caches results from AJAX requests; therefore we need to append this unique value to the QueryString to make each AJAX request UNIQUE
		var channelNbr;
		var strVideoSrch;
		var strURL; 
		var SrchResultsArr;
		var strMsg = '';

		switch (sType) {		//"select-one" is the property type for a Select box; 'text' is property type for the search input box
			case 'select-one' :
				channelNbr = obj[obj.selectedIndex].value;
				strVideoSrch = '';
				break;
			default :
				channelNbr = 0;
				strVideoSrch = obj.value;
		}

	    //alert ('In display results; channelNbr= ' + channelNbr + ' selectedindex = '+ obj.selectedIndex + ' search = ' + obj.value);

	    channelNbr = channelNbr.toString();

        var elem = document.getElementById('relatedVideos');
       
      
		var elemSrchDisplay = document.getElementById('srchResultsDisplay');
		if (elemSrchDisplay.firstChild) {
			elemSrchDisplay = elemSrchDisplay.firstChild;
			elemSrchDisplay.nodeValue = '';
		} else {
			elemSrchDisplay = elemSrchDisplay.appendChild(document.createTextNode(''));
		}


		if (sType != 'text' && obj.selectedIndex === 0)
		{// Do nothing if selected option is the "-pull to select-" option. 
			return;
		}

		strURL = '/Default.asp?AJAX=True&DateTimeNow=' + escape(dateTime.valueOf());
		if (channelNbr.length > 0) { strURL += '&ChannelID=' + escape(channelNbr); }
		if (strVideoSrch.length > 0) { strURL += '&strVideoSrch=' + escape(strVideoSrch); }
		

		var responseSuccess = function(o)
		{
	
			// REMINDER: o.responseText will always return results of typing 'strURL' above in your browser! 			
			elem.innerHTML = o.responseText; // display o.responseText in id='progInfo' section 
			
			if (strVideoSrch.length > 0) 
			{	// function is in include yahoo-dom-event.js;  Get all div elements named progInfoRow in div id=relatedVideos
				SrchResultsArr = Dom.getElementsByClassName('progInfoRow', 'div', document.getElementById('relatedVideos'));			
								
				if (SrchResultsArr.length == 1) {strMsg = 'result'; }
				if (SrchResultsArr.length > 1)  {strMsg = 'results'; }
				
				elemSrchDisplay.nodeValue = 'Your search for "' + strVideoSrch + '" has returned ' + SrchResultsArr.length + ' ' + strMsg + ' under RELATED VIDEOS below.';
				fnHighlightSearchResults('RELATED VIDEOS');   //highlight text so that it catches viewers eye
			}
			
			if (sType == 'select-one')
			{	//highlight text so that it catches viewers eye that RELATED VIDEOS section changed with new content 
				fnHighlightSearchResults('RESULTS FOR VIDEO TOPIC: ' + obj[obj.selectedIndex].innerHTML);
				elemSrchDisplay.nodeValue = 'Your video topic search results can be found under RELATED VIDEOS below.';

			}
						
		};
	
		var responseFailure = function(o)
		{
			alert('System Problem with Display Results -- Please notify avizon@photobooks.com');
		};
	
		var callback = 
		{
			success: responseSuccess,
			failure: responseFailure
		};
	
		
		var transaction = YAHOO.util.Connect.asyncRequest('GET', strURL, callback, null);
		return false;

}


function fnHighlightSearchResults(sTitle) {
	var oRelated = $('relatedvideostitle');
	var oRelLink = $('Related');
	var oRelText = oRelLink.firstChild;
	var oAnim    = new YAHOO.util.ColorAnim(oRelLink, {
		color: { to: '#FF1700' },							//red: #FF0000
		backgroundColor: { to: '#FFFF00' }   				//yellow background
	}, .5, YAHOO.util.Easing.easeOut);						//fade to red & yellow in .5 second
	
	var oAnimPause = new YAHOO.util.ColorAnim(oRelLink, 
	{
		color: { to: '#FF0000' },
		backgroundColor: { to: '#FFFF00' }
	}, 5);			//Pause red for 5 seconds	
		
	
	
	var oAnimBack = new YAHOO.util.ColorAnim(oRelLink, {
		color: { to: '#007550' },							//text color changes back to green
		backgroundColor: { to: '#FFFFFF' }
	}, .5, YAHOO.util.Easing.easeOut);						//fade to green & white in .5 second
	
	oAnim.onComplete.subscribe(oAnimPause.animate, oAnimPause, true);     //executes this after first animation completes
	oAnimPause.onComplete.subscribe(oAnimBack.animate, oAnimBack, true);
	oRelText.nodeValue = sTitle;
	oAnim.animate();                                     //starts first animation
}


function DisplayForm(fld, formType)
{ // This displays the "send video" e-mail form i.e. HTML rendered by sendVideo.asp  or rate video form (ratethisVideo.asp)
	    var elem = document.getElementById(fld); // fld = 'progInfo' 
	  
    	var restoreFlag = false;
    	
    	var blnAlreadyRated = false; 
    	
    	var dateTime = new Date(); // Unique value appended to AJAX request to ensure the request is unique every time; resolves IE caching issue

		var strURL;
		
		if (needToStore === true)    
		{
		oldContents = elem.innerHTML; // Save current video program info into oldContents before sendVideo email form gets displayed 
		needToStore = false;
		}

	
        if (formType == 'SendVideo')
        {
		    strURL = '/sendVideo.asp?AJAX=True&ProgramID='+ nowPlaying + '&DateTimeNow=' + escape(dateTime.valueOf()); //IE sometimes caches results from a previous AJAX request; therefore we need to append this unique value to the QueryString to make each AJAX request UNIQUE		;
		}
		else
		{
		    if (formType == 'RateVideo')
		    {
		        //alert ('Now Playing = ' + nowPlaying + 'Video Title = ' + videoTitle);
		        blnAlreadyRated = VideoAlreadyRated(nowPlaying); // check if video has already been rated; returns boolean value 
			
				//alert ('blnAlreadyRated = ' + blnAlreadyRated);
		        strURL = '/ratethisVideo.asp?VideoTitle=' + videoTitle + '&DateTimeNow=' + escape(dateTime.valueOf()); 
		    }
		}
				
		var responseSuccess = function(o)
		{
			
			// REMINDER: o.responseText will always return results of typing 'strURL' above in your browser! 			
			elem.innerHTML = o.responseText; // display o.responseText in id='progInfo' section 
			
							
		};
	
		var responseFailure = function(o)
		{
			alert('System Problem with Display Form -- Please notify avizon@photobooks.com');
		};
	
		var callback = 
		{
			success: responseSuccess,
			failure: responseFailure
		};
	
		
		if (blnAlreadyRated === true)
		{
			if (videoTitle.length > 0) {alert('You have already rated video: ' + URLDecode(videoTitle));}
			else {alert('You have already rated this video!');}
		}
		else
		{
		var transaction = YAHOO.util.Connect.asyncRequest('GET', strURL, callback, null);
		}
	
}    



function restoreProgramInfo(fld)
{ // replaces "send video" email form with video program info 
	
	var elem = document.getElementById(fld);
	//alert(needToStore);
	//alert('oldContents = ' + oldContents);
	
	if (oldContents !== null)
	{
		elem.innerHTML = oldContents;
		oldContents = null;
		needToStore = true;
	}
}

function restoreImage ( fld )
{
	var patternNPjpg;
	var srcString;
	var elem = document.getElementById(fld);
	//alert ('restoreImage = ' + elem);
	if (elem !== null)
	{
		patternNPjpg = /NP.jpg$/;
				
		srcString = elem.src;
			
		// replaces NP.jpg ("now playing") with .jpg image if it finds a NP.jpg at the end of filename // 	
		if (srcString.match(patternNPjpg))
		{
			
			elem.src = srcString.replace(patternNPjpg, ".jpg");	
			
		}
		
	}
	
}


function PlayFlashMovie(VideoFileName)    // PlayUABVideo is a Flash method defined in videoplayer.swf
{
				
//		var o = getFlashMovieObject('player');
//		o.PlayUABVideo(VideoFileName);
		//alert ('PFM: ' + VideoFileName);
		flash.PlayUABVideo(VideoFileName);

}





function PlayVideo(objProgImgCurr, progID, chanID, ProgFileNmCurr, VideoFileNm ,title, shortDescription, longDescription)
{  // Values passed into this function:    
   // 1) Image Object of selected program  
   // 2) Filename of Selected Program (ex. /images/HealthTV    
		
				
		//alert ('In Play Video - nowPlaying = ' + nowPlaying);
		restoreImage('prog' + nowPlaying); // when click on a new video, this replaces NP.jpg ("now playing") with .jpg image if it finds a NP.jpg at the end of filename  	
		       
        needToStore = true;
        nowPlaying = progID;
        channelID = chanID;
        //alert('In PlayVideo ' + nowPlaying + '; '+ channelID + '; ' + ProgFileNmCurr + '; ' +title); 

		videoTitle = title; //  save video title in a global variable to be used within Javascript 

        if (objProgImgPrev === null)
        {  // first time through 
        	
            objProgImgPrev = objProgImgCurr;
            ProgFileNmPrev = ProgFileNmCurr + '.jpg';
            objProgImgPrev.src = ProgFileNmCurr + 'NP.jpg';
            
         }
         else
         {
            objProgImgPrev.src = ProgFileNmPrev;            // set 'src' to display '.jpg' file of previous selected image 
            objProgImgPrev = objProgImgCurr;                // save image object of the currently selected image
            objProgImgPrev.src = ProgFileNmCurr + 'NP.jpg'; // Now, set 'src' to display 'NP.jpg' of current selected image
            ProgFileNmPrev = ProgFileNmCurr + '.jpg';       // save '.jpg' file name of current image
	        
 
         }
         
         restoreProgramInfo('progInfo');  // If I have something to restore in top right hand box, then do the switch (i.e. replace email or rate video forms with previous program info)
         DisplayTitleNDescription ('ProgramInfo', title, shortDescription, longDescription, progID);  // Displays Title and Description in the box located to right of playing video

              
        
                  
         //alert('Video File Name = ' + VideoFileNm + ' short desc = ' + shortDescription);
         
		 if (shortDescription == 'No Video File')
		 {
		 	return;
		 }
		 else
		 {        
		 	
		 	//PlayFlashMovie(playList[curPlaylistPos].videoFileName + '.flv'); use this for Continuous Play
         	PlayFlashMovie(VideoFileNm + '.flv');				// play video
           
           
           	LogVideo(progID);
         	
         }
         
        
}

// this updates [log - video] table
function LogVideo(videoID)
{
	var strURL;
	var dateTime = new Date(); // Unique value appended to AJAX request to ensure the request is unique every time; resolves IE caching issue

	if (videoID.length > 0) 
	{ 
		
	    strURL = '/default.asp?LogVideo=True&ProgramID='+ escape(videoID) + '&DateTimeNow=' + escape(dateTime.valueOf());
	}

	var responseSuccess = function(o)
	{
		var strSuccess = o.responseText;
	};

	var responseFailure = function(o)
	{
	};

	var callback = 
	{
		success: responseSuccess,
		failure: responseFailure
	};
	
	var transaction = YAHOO.util.Connect.asyncRequest('GET', strURL, callback, null);
}

// The Flash player calls this function when a video plays to the very end.  Flash sends message "videoComplete".  
// This calls ASP page hitTheServer.asp, in which its only purpose is to make a hit to the web server for logging purposes!
// This will allow us to keep track of the length of the playing video when the user watches it to the very end.
function HitTheServer(messagefromFlash)
{

	var strURL;
	var dateTime = new Date(); // Unique value appended to AJAX request to ensure the request is unique every time; resolves IE caching issue

	if (messagefromFlash.length > 0) 
	{ 
	    strURL = '/hitTheServer.asp?DateTimeNow=' + escape(dateTime.valueOf());
	}

	var responseSuccess = function(o)
	{
		//console.log ("I made a Successful call! = ", o.responseText);
	};

	var responseFailure = function(o)
	{
	};

	var callback = 
	{
		success: responseSuccess,
		failure: responseFailure
	};
	
	var transaction = YAHOO.util.Connect.asyncRequest('GET', strURL, callback, null);
}



function VideoAlreadyRated(pgmID)   
{//  Check global variable (identical to Session variable("VideosAlreadyRated")) to see if a video's program ID has already been rated 

		var position=0; 
		var alreadyrated = false;
		
		position=0;
		var searchString = ',' + pgmID + ',';
		
		position = videosAlreadyRated.indexOf(searchString); // from the beginning

		//alert (' in videoAlreadyRated position = ' + position);
		if (position != -1)    // -1 means not found; position >=0 means found
		{
			alreadyrated = true;
				
		}	
		
		return alreadyrated;	
	
}


// Update rating on server by passing video's program ID and the rating chosen by the viewer to an ASP page 
function UpdateVideoRating(currVideoNbr, videoRating)   
{
				

		//alert ('Current video nbr is: ' + currVideoNbr + ' rate= ' + videoRating );
		var strURL;
		var dateTime = new Date();
		
		//var elem = document.getElementById('proginfo'); // fld = 'progInfo' 

		
		if (currVideoNbr.length > 0) {
			strURL = '/updateVideoRating.asp?ProgramID='+ escape(currVideoNbr) +'&Rating=' + escape(videoRating) + '&DateTimeNow=' + escape(dateTime.valueOf());		
			
		}
		

		var responseSuccess = function(o) {
			// REMINDER: o.responseText will always return results of typing 'strURL' above in your browser! 			
			//o.responseText is the list of already rated videos Session variable ("VideosRatedAlready") 
			//o.responseText should always return a string, not numeric; otherwise, this will return a failure msg
			videosAlreadyRated = o.responseText;
			
		};

		var responseFailure = function(o) {
			//alert('System Problem with Video Rating -- Please notify avizon@photobooks.com');
		};
	
		var callback = {
			success: responseSuccess,
			failure: responseFailure
		};
			
		var transaction = YAHOO.util.Connect.asyncRequest('GET', strURL, callback, null);

}





function URLDecode( str )
{
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   
   var HEXCHARS = "0123456789ABCDEFabcdef"; 
   var encoded = str;
   
   var plaintext = "";
   var i = 0;
   var ch;
   
   while (i < encoded.length) {
       ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2) 
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while
   return plaintext;
}


