		var currentVidId = null; //Stores the current video id
		var videoTitleArr = new Array(); //Stores array of titles with video id as index 
		var playerState = null;
		var numberOfComments;
		var numberOfCommentPages;
		var seekWithVideo = true; //LOOK! Added by Aaron for video slider
		var noOfVidsInChannel = 0; // Number of videos from the channel obtained from database.
		
		/**
		 * Load the video accepting the player URL and auto play parameter.
		 * @param playerUrl
		 * @param autoplay
		 * @return
		 */

		function loadVideo(playerUrl, autoplay) {
			swfobject.embedSWF(
			playerUrl + '&rel=1&border=0&fs=1&autoplay=' +
			(autoplay?1:0), 'player', '543', '323', '9.0.0', false,
			false, {allowfullscreen: 'true'});
		}
		
		/**
		 * Show the full screen of the player.
		 * @return
		 */
		
		function showFullScreen(){
		$('#overlay').overlay({	
				effect: 'apple',
				expose: '#123448',
				onLoad: function() {
					var embed = $('#mainPlayer');
					var embedPlayer = $('#ytapiplayer');
					var el = this.getContent();
					var height = el.height(); 
					embed.css({
						width:parseInt(el.width()) -80,
						height:parseInt(height) -80,
						left: parseInt(el.css('left')) + 40,
						top: parseInt(el.css('top')) + 40});
					embed.css("z-index",10001);
					embedPlayer.attr({
						width:"100%",
						height:"100%"});
						}, 
				onClose: function() { 
					var embed = $('#mainPlayer');
					embed.css({
						width:580,
						height:300,
						left: null,
						top: null});
					embed.css("z-index",1);
				//$('#mainPlayer').css({width: 580, height: 300, left:null, top:null, position: null});
				}}).load();
		}
		
		var urlVideoID = null;
		var urlChannelId = null;
		var currentChannel = null; // Stores the id of the video that is playing currently
	
		
		/**
		 * First function called after the page loads. 
		 * @return
		 */		
		function showCBTvVideos(){
			checkAndSplitURL(); //Split and set the URL of video and channel id
			if(urlVideoID!=null && urlChannelId!=null){ //If the videoId and channel is from URL then process differently
				showVideosByChannel(urlChannelId); //Take the channel id from the URL
			}else{
				showVideosByChannel(DEFAULT_CHANNEL); //Take the channel id from the CBTV Properties file
			}
		}
		
		/**
		 * Split the URL for share the video. It extracts the video from the URL.
		 * @return
		 */
		
		function checkAndSplitURL(){	 
			 if((window.parent.location.href).match("channel=")!=null) //Spliting the URL parameters from the URL
			{
				//var testUrl = "http://www.uat.citybeach.com.au/webapp/wcs/stores/servlet/StaticPageDisplay?storeId=10551&identifier=CBTV_Channel&langId=-1&catalogId=10101&channel=SURFv=Obw9dYsTh-Q"; //For testing
				urlChannelId = getURLVar("channel",window.parent.location.href);
				urlVideoID = getURLVar("v",window.parent.location.href);
			}
		}
		 
		
		
		/**
		 * Show the default channel videos
		 */
		
		function showVideosOfDefaultChannel(data){
			currentChannel = DEFAULT_CHANNEL; 
			var feed = data.feed;
			var entries = feed.entry || [];
			var html = ['<table id="allvids">'];
			var vidIDArr = new Array();
			document.getElementById("playpause").className = "playbtn"; //Change the button to be play by default once the channel loads
			resetNavigationButtons();  //Resetting the up down right left buttons.									
			showNavigationButtons(); //Show the social video icons	
			for (var i = 0; i < entries.length; i++) {
				var entry = entries[i];
				var title = entry.title.$t;
				var thumbnailUrl = (entries[i].media$group!=null)?entries[i].media$group.media$thumbnail[0].url:"";
				var playerUrl = (entries[i].media$group!=null)?entries[i].media$group.media$content[0].url:"";
				var splitUrl = playerUrl.split("/v/");
				var videoId = (splitUrl[1].split("?"))[0]; 	//Removing the unwanted datas after the video id
				var viewcount = (entries[i].yt$statistics!=null)?entries[i].yt$statistics.viewCount:0; //View count
				var viewCntStr = addCommas(viewcount)+" views"; //Converting view count to comma separated String

				vidIDArr[videoId] = title; //Adding all the video title with video id in the array

				if(videoId == urlVideoID){
					updateHTML("headtitle", title);				
				}			

				if(i==0){
					vidId = (urlVideoID!=null)?urlVideoID:videoId; //Setting the current video ID. If from URL take it.
					setVideoId(vidId);
					updateHTML("headtitle", title);										
				}
				var truncatedTitle =  truncateStr(title, MAXIMUM_TITLE_LENGTH); //Truncate the title to a maximum of 40.
				
				html.push('<tr><td>','<br /><table width="292"><tr><td width="80" class="listvideoborder"><img onclick="loadNewVideo(\'', videoId, '\', 0)" style="cursor:pointer; vertical-align:middle;" src="', thumbnailUrl, '" width="85" height="57"/></td>', '<td valign="top"><span onclick="loadNewVideo(\'', videoId, '\', 0)" class="titlec">', truncatedTitle , '</span><br/><span class="veiwcount">',viewCntStr,'</span></td></tr><tr><td colspan="2" class="videoLine"></td></tr></table></td></tr>');
				}
				setVideoArr(vidIDArr); //Setting the video array as a global variable.
				html.push('</table>');
				document.getElementById('videos2').innerHTML = html.join('');
				allPager.init();
				allPager.showPage(1);

				if (entries.length > 0) {
					loadVideo(entries[0].media$group.media$content[0].url, false);
				}
						
			if(defaultChannelCall){ //Queue the current video
				cueNewVideo(currentVidId, 0);
				defaultChannelCall = false;
			}
			updateHTML("videoComments", "");  //Clear off the comments table
			urlVideoID = null;
			loadComments(currentVidId);  //Load current comments video id	
			changeSkateBgColor();  // Change the BG color of the Skate button
				
		}
		 
		/**
		 * Show the navigation buttons and the social networking icons
		 * @return
		 */
	
		function showNavigationButtons(){
			document.getElementById('socialButtons').style.visibility='visible';
			document.getElementById('addNewCommentBtn').style.visibility='visible';
			document.getElementById('rightLeftNav').style.visibility='visible';
			document.getElementById('upDownNav').style.visibility='visible';			
		}
		
		 /**
		  * This method accepts the string as a parameter and truncates to 40 characters.
		  * @param str
		  * @return
		  */
		 function truncateStr(str, maxChars){
			 return (str.length)>parseInt(maxChars)?(str.substr(0,parseInt(maxChars))+"..."):str;
			 
		 }		 
		
		 /**
		  * Shows the ajax loader by accepting the div as parameter.
		  * @param divName
		  * @return
		  */
		 
		function showLoader(divName){
			document.getElementById(divName).innerHTML = "<br/><br/><br/><table align=\"center\"><tr><td>Loading please wait</td></tr><tr><td align=\"center\"><img src=\"images/ajax-loader.gif\" alt=\"Loading videos\" /></td></tr></table>";
		}

		/**LOOK! ADDED BY AARON!!!
		 * Updates the timer bar. Moves the icon along the x axis.
		 * @return
		 */
		function updateTimebar() {
		    /** removed for new jquery slider
			var all = ytplayer.getDuration();
		    var part = ytplayer.getCurrentTime();
		    var percent = getPercent1(all, part);
		    var timebarWidth = 100;
		    document.getElementById('timebarIndicator').style.left = percent * (timebarWidth / 100) + "%";
			*/	
			if(seekWithVideo) {
				$("#slider").slider('option', 'value', percentageComplete());
				adjustCacheBar();
			}
		}
		
		/*
		 * Works out percentage of video played.
		 * @return
		 */	  
		/*LOOK! ADDED BY AARON!!!*/
		function percentageComplete(){
			var percentage;
			if(ytplayer && ytplayer.getDuration) {
				if ( ytplayer.getCurrentTime() > 0 ) {
				percentage = (ytplayer.getCurrentTime() / ytplayer.getDuration()) *100;
				return percentage;
				}
			}
		}


		function getPercent1(all, part) {
			return (all > 0) ? (100 / all) * part : 0;
		}

		/***
		 * Change the bg color of the default channel on load
		 * @return
		 */
		function changeSkateBgColor(){
			//Change the left image too	
			document.getElementById("vidmenuright").style.background = "url(images/btn_bgMenuChannelBlueRight.gif)";
			//Change the bg image to blue
			document.getElementById("tdtube").style.background = "url(images/btn_bgMenuChannelBlue.gif)";			
		}

		/**
		 * This method retrives the given input variable (<name>) value from  the current page HTTP URL.
		 * @param name - This is the name of the variable whose value needs to be retrieved from the current page HTTP URL
		 */

		function getURLVar(name, URL){
				name = name.replace( /[\[]/, '\\\[' ).replace( /[\]]/ , '\\\]' );
				var regexS = '[\\?&]' + name + '=([^&#]*)';
				var regex = new RegExp( regexS );
				var results = regex.exec( URL );
				var result = (results == null) ? null : results[1];
				return result;				
			}
		
		/***
		 * Pagination for the videos and comments
		 */
		
		function Pager(tableName,itemsPerPage) {
			this.tableName=tableName;
			this.itemsPerPage=itemsPerPage;
			this.currentPage=1;
			this.pages=0;
			this.inited=false;

			this.showRecords=function(from, to) {
				var rows = document.getElementById(this.tableName).rows;
				for (var i = 1; i < rows.length; i++) {
					if (i < from || i > to)
					rows[i].style.display = 'none';
					else
					rows[i].style.display = '';
				}
			}

			this.init = function() {
				var rows = document.getElementById(this.tableName).rows;
				var records = (rows.length);
				this.pages = Math.ceil(records / itemsPerPage);				
				this.inited = true;
			}

			this.prev = function() {
				if (this.currentPage > 1)
				this.showPage(this.currentPage - 1);
				if(this.currentPage == 1){
					if(this.tableName=="allvids"){		
						var numberOfPagesInChannel = Math.ceil(noOfVidsInChannel/VIDEOS_PER_PAGE);
						if(numberOfPagesInChannel == 1){
							document.getElementById("btnUp").src=IMG_UP_BUTTON_DISABLED;
							document.getElementById("btnDown").src=IMG_DOWN_BUTTON_DISABLED;
						}else{
							document.getElementById("btnUp").src=IMG_UP_BUTTON_DISABLED;
							document.getElementById("btnDown").src=IMG_DOWN_BUTTON;
						}						
					}else if(this.tableName=="vidcomments"){
						if(numberOfCommentPages == 1){
							document.getElementById("btnLeft").src=IMG_LEFT_BUTTON_DISABLED;
							document.getElementById("btnRight").src=IMG_RIGHT_BUTTON_DISABLED;
						}else{
							document.getElementById("btnLeft").src=IMG_LEFT_BUTTON_DISABLED;
							document.getElementById("btnRight").src=IMG_RIGHT_BUTTON;	
						}						
					}
				}else{
					if(this.tableName=="allvids"){
						document.getElementById("btnUp").src=IMG_UP_BUTTON;
						document.getElementById("btnDown").src=IMG_DOWN_BUTTON;
					}else if(this.tableName=="vidcomments"){
						
						document.getElementById("btnLeft").src=IMG_LEFT_BUTTON;
						document.getElementById("btnRight").src=IMG_RIGHT_BUTTON;
					}
				}
				
			}

			this.next = function() {
				if (this.currentPage < this.pages)
					this.showPage(this.currentPage + 1);
				
				if(this.currentPage == this.pages){
					this.showPage(this.currentPage);
					if(this.tableName=="allvids"){		
						var numberOfPagesInChannel = Math.ceil(noOfVidsInChannel/VIDEOS_PER_PAGE);
						if(numberOfPagesInChannel == 1){
							document.getElementById("btnUp").src=IMG_UP_BUTTON_DISABLED;
							document.getElementById("btnDown").src=IMG_DOWN_BUTTON_DISABLED;
						}else{
							document.getElementById("btnUp").src=IMG_UP_BUTTON;
							document.getElementById("btnDown").src=IMG_DOWN_BUTTON_DISABLED;
						}						
						
					}else if(this.tableName=="vidcomments"){
						if(numberOfCommentPages == 1){
							document.getElementById("btnLeft").src=IMG_LEFT_BUTTON_DISABLED;
							document.getElementById("btnRight").src=IMG_RIGHT_BUTTON_DISABLED;
						}else{
							document.getElementById("btnLeft").src =IMG_LEFT_BUTTON;
							document.getElementById("btnRight").src = IMG_RIGHT_BUTTON_DISABLED;	
						}						
					}
										
				}else{
					if(this.tableName=="allvids"){
						document.getElementById("btnUp").src=IMG_UP_BUTTON;
						document.getElementById("btnDown").src=IMG_DOWN_BUTTON;
					}else if(this.tableName=="vidcomments"){						
						document.getElementById("btnLeft").src=IMG_LEFT_BUTTON;
						document.getElementById("btnRight").src=IMG_RIGHT_BUTTON;
					}
				}
					
			}

			this.showPage = function(pageNumber) {
				//Change the selected number color in the page
				if(this.tableName=="vidcomments"){
					changeSelPageNumberColor(pageNumber);
				}
				if (! this.inited) {
					alert("not inited");
					return;
				}

			this.currentPage = pageNumber;
				var from = (pageNumber - 1) * itemsPerPage + 0;
				var to = from + itemsPerPage - 1;
				this.showRecords(from,to);
			}

			this.showRecords=function(from, to) {
				var rows = document.getElementById(tableName).rows;
				for (var i = 0; i < rows.length; i++) {
					if (i < from || i > to)
						rows[i].style.display = 'none';
					else
						rows[i].style.display = '';
				}
			}
			
		}
		
		var allPager = new Pager("allvids",VIDEOS_PER_PAGE); // Initializing the pagination for the video widget.
		var commentPager = new Pager("vidcomments",COMMENTS_PER_PAGE); // Initializing the pagination for the comments widget. 
		
		
		
		/**
		 * Accepts the page number as parameter and changes the color of selected text.
		 * @param pageNumber
		 * @return
		 */
		function changeSelPageNumberColor(selpageNumber)
		{		
			for (var i=1; i <= numberOfCommentPages; i++) {
				if(i==selpageNumber){
					document.getElementById("cp_"+selpageNumber).style.color = "#000000";	
				}else{
					document.getElementById("cp_"+i).style.color = "#3737F7";	
				}				
			}			
		}
		
		/**
		*  Reset the navigation buttons.
		**/	

		function resetNavigationButtons(){
			document.getElementById("btnUp").src=IMG_UP_BUTTON_DISABLED;
			document.getElementById("btnDown").src=IMG_DOWN_BUTTON;
	
			document.getElementById("btnLeft").src=IMG_LEFT_BUTTON_DISABLED;
			document.getElementById("btnRight").src=IMG_RIGHT_BUTTON;				
		}
		 
		
	  /**
	   * Load the channl videos by querying the database using AJAX request.
	   * @param channelName
	   * @return
	   */	
	  function loadChannelVideos(channelName)
		{
		var channelVideosRequest = null;
		channelVideosRequest = new XMLHttpRequest();
		
		if (channelVideosRequest==null){
			try {
				channelVideosRequest = new ActiveXObject("Msxml2.XMLHTTP");
			} catch(e){
				try{
					channelVideosRequest = new ActiveXObject("Microsoft.XMLHTTP");
				}
				catch(ex)
				{
					channelVideosRequest = new XMLHttpRequest();
				}
		
			}
		}		
	
	   var myURL = "/CityBeach/ProcessRequestServlet?type=Action.View.FetchVideosList&channelName="+channelName;
	   //var myURL = "/CityBeach/ProcessRequestServlet";
	   channelVideosRequest.open("GET", myURL, false);
	   //channelVideosRequest.setRequestHeader('RequestType','Action.View.FetchVideosList');
  	   //channelVideosRequest.setRequestHeader('VideoCategoryID',channelName); //TODO set this dynamically
  	   channelVideosRequest.send(null);
  	   
  	   var xmlDoc; //XML document object	
	  
	   if (window.DOMParser) {
		 	parser=new DOMParser();
		 	xmlDoc=parser.parseFromString(channelVideosRequest.responseText,"text/xml");		 
	   	}else // Internet Explorer
	  	{	
	   	  	xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
		  	xmlDoc.async = false;
		  	xmlDoc.loadXML(channelVideosRequest.responseText);
	  	}  
	   
		return xmlDoc;
		}
		
		var defaultChannelCall = false;

		/***
		 * Shows the videos based on the channel name. Video ids are obtained from either feeds or from database.
		 * @param channelName
		 * @return
		 */
		
		function showVideosByChannel(channelName) {
			currentChannel = channelName;   			 
			changeButtonImage(channelName); // Change the button bg image
			resetNavigationButtons(); //Resetting the up down right left buttons.

			if(channelName==DEFAULT_CHANNEL || channelName=="DEFAULT"){ //This will be the city beach surf channel				
				showLoader('videos2');  //Show Ajax loader
				defaultChannelCall = true;
				var feedUrl = "http://gdata.youtube.com/feeds/users/"+DEFAULT_CHANNEL+"/uploads?";
				var getParams = '&alt=json-in-script&format=5' + '&callback=showVideosOfDefaultChannel' + '&max-results='+MAXIMUM_NO_VIDEOS;
				feedUrl += getParams;
				var scriptTag = document.createElement('script');
				scriptTag.src = feedUrl;
				document.body.appendChild(scriptTag);
					
			}else{
				showLoader('videos2');
				var vidXmlDocument=loadChannelVideos(channelName);				
				var count;
				var videoNode;
				document.getElementById('videos2').innerHTML = "";
				var html = ['<table id="allvids">'];
				var vidIDArr = new Array();
				var videoId = null;
				var title = null;
				var thumbnailUrl = null;				
				var viewCntStr = null;
				
				document.getElementById("playpause").className = "playbtn"; //Change the button to be play by default once the channel loads				
				if(vidXmlDocument==null || vidXmlDocument.getElementsByTagName("count").length == 0 || vidXmlDocument.getElementsByTagName("count")[0].childNodes[0].nodeValue == 0){
					html.push('<br/><br/><br/><tr><td align="center">Sorry! No videos are present under this channel.</td></tr>');
					cueNewVideo(0, 0);
					clearVideo();
					clearVideoInfo(); //Clear the comments, title, pagination						
					
				}else{
					count = vidXmlDocument.getElementsByTagName("count")[0].childNodes[0].nodeValue;
					noOfVidsInChannel = count;  //Set the number of videos in the channel.
					videoNode = vidXmlDocument.getElementsByTagName("video");
				}
				for(var start=0; start < count ; start ++ ){
					videoId = videoNode[start].childNodes[0].childNodes[0].nodeValue;
					title = videoNode[start].childNodes[1].childNodes[0].nodeValue;					
					thumbnailUrl = videoNode[start].childNodes[2].childNodes[0].nodeValue;
					viewCntStr = addCommas(videoNode[start].childNodes[4].childNodes[0].nodeValue)+" views";
				
					if(videoId == urlVideoID){
						updateHTML("headtitle", title);	
						defaultChannelCall = true;			
					}				

					if(start==0){
						vidId = (urlVideoID!=null)?urlVideoID:videoId; //Setting the current video ID. Get the video id from URL if present
						setVideoId(vidId);
						updateHTML("headtitle", title);	// Update the title of the video				
					}					
					vidIDArr[videoId] = title; //Adding all the video id in the array		
					
					var truncatedTitle =  truncateStr(title, MAXIMUM_TITLE_LENGTH); //Truncate the title to a maximum of 40.
					html.push('<tr><td>','<br /><table width="292"><tr><td width="80" class="listvideoborder"><img onclick="loadNewVideo(\'', videoId, '\', 0)" style="cursor:pointer; vertical-align:middle;" src="', thumbnailUrl, '" width="85" height="57"/></td>', '<td valign="top"><span onclick="loadNewVideo(\'', videoId, '\', 0)" class="titlec">', truncatedTitle, '</span><br/><span class="veiwcount">',viewCntStr,'</span></td></tr><tr><td colspan="2" class="videoLine"></td></tr></table></td></tr>');					
				}	
				
				
				setVideoArr(vidIDArr); //Setting the video array as a global variable
				urlVideoID = null;
				//document.getElementById("tdsurf").style.background = "url(images/btn_bgMenuChannel.gif)";				
				html.push('</table>');
				document.getElementById('videos2').innerHTML = html.join('');			
				allPager.init();
				allPager.showPage(1);	
			}
						
			if(count>0){
				loadComments(currentVidId); //Load current comments video id
				cueNewVideo(currentVidId, 0);
				if(!defaultChannelCall){ //Queue the current video
					cueNewVideo(currentVidId, 0);
				}	
				showNavigationButtons(); //Show all the navigation buttons				
			}
		}
		
		/**
		 * Append the script tag dynamically for Share the video.
		 * @return
		 */
		function addShareTheVideoScript(){
			var shareDiv = document.getElementById("shareVideo");
			var link = getCityBeachVideoURL(true);
			shareDiv.innerHTML = "<a class='a2a_dd' onclick='openSocialNetSite(\"http://www.addtoany.com/share_save?linkname=&amp;linkurl=\")'><img src='images/share-video.png' alt='Share video' alt='Share this video' border='0'/></a>";
			//shareDiv.innerHTML = "<a class='a2a_dd' href='http://www.addtoany.com/share_save?linkname=&amp;linkurl="+link+"'><img src='images/share-video.png' alt='Share video' alt='Share this video' border='0'/></a>";
			a2a_linkname=document.title;
			a2a_linkurl= link;
			a2a_init('page');
		}	
		 
		
		/**
		 * Creates a dynamic script and inserts the script in the body of the HTML page.
		 * @param scriptSrc
		 * @return
		 */
				
		function createDynamicScriptElement(scriptSrc){
			var scriptTag = document.createElement('script');
			scriptTag.src = scriptSrc;
			document.body.appendChild(scriptTag);			
		}
		
		/**
		 * Clear the video information on load.
		 * @return
		 */
		
		function clearVideoInfo(){			
			updateHTML("headtitle", ""); //Clear off the title	
			updateHTML("videoComments", ""); //Clear off the comments table
			updateHTML("numberpaging", ""); //Clear off the pagination 		
			document.getElementById('rightLeftNav').style.visibility='hidden'; //Clear the right left comment navigation
			document.getElementById('upDownNav').style.visibility='hidden'; //Clear the up down navigation buttons
			document.getElementById('addNewCommentBtn').style.visibility='hidden'; //Clear the add new comment and adding social n/w button
			document.getElementById('socialButtons').style.visibility='hidden';		
		}
		
		/***
		 * This method changes the background image of the channel.
		 * TODO Very important: Optimize the function reuse it by removing repeated code.
		 */
		
		function changeButtonImage(channelName){
			if(channelName=="SURF"){					
				document.getElementById("vidmenuleft").style.background = "url(images/btn_bgMenuChannelBlueLeft.gif)"; //Change the left image too
				document.getElementById("tdsurf").style.background = "url(images/btn_bgMenuChannelBlue.gif)"; //Change the bg image to blue
				document.getElementById("tdskate").style.background = "url(images/btn_bgMenuChannel.gif)"; //Change other images to black
 			    document.getElementById("tdmoto").style.background = "url(images/btn_bgMenuChannel.gif)";
				document.getElementById("tdmusic").style.background = "url(images/btn_bgMenuChannel.gif)";
				document.getElementById("tdbmx").style.background = "url(images/btn_bgMenuChannel.gif)";
				document.getElementById("tdstuff").style.background = "url(images/btn_bgMenuChannel.gif)";
				document.getElementById("tdtube").style.background 	= "url(images/btn_bgMenuChannel.gif)";
				document.getElementById("vidmenuright").style.background = "url(images/btn_bgMenuChannelRight.gif)";				
			}else if(channelName=="SKATE"){					
				document.getElementById("vidmenuleft").style.background = "url(images/btn_bgMenuChannelLeft.gif)"; //Change the left image too
				document.getElementById("tdsurf").style.background = "url(images/btn_bgMenuChannel.gif)";
				document.getElementById("tdskate").style.background = "url(images/btn_bgMenuChannelBlue.gif)"; //Change the bg image to blue
 			    document.getElementById("tdmoto").style.background = "url(images/btn_bgMenuChannel.gif)";
				document.getElementById("tdmusic").style.background = "url(images/btn_bgMenuChannel.gif)";
				document.getElementById("tdbmx").style.background = "url(images/btn_bgMenuChannel.gif)";
				document.getElementById("tdstuff").style.background = "url(images/btn_bgMenuChannel.gif)";
				document.getElementById("tdtube").style.background 	= "url(images/btn_bgMenuChannel.gif)";
				document.getElementById("vidmenuright").style.background = "url(images/btn_bgMenuChannelRight.gif)";											
			}else if(channelName=="MOTO"){					
				document.getElementById("vidmenuleft").style.background = "url(images/btn_bgMenuChannelLeft.gif)"; //Change the left image too
				document.getElementById("tdsurf").style.background = "url(images/btn_bgMenuChannel.gif)";
				document.getElementById("tdskate").style.background = "url(images/btn_bgMenuChannel.gif)";
				document.getElementById("tdmoto").style.background = "url(images/btn_bgMenuChannelBlue.gif)"; //Change the bg image to blue
				document.getElementById("tdmusic").style.background = "url(images/btn_bgMenuChannel.gif)";
				document.getElementById("tdbmx").style.background = "url(images/btn_bgMenuChannel.gif)";
				document.getElementById("tdstuff").style.background = "url(images/btn_bgMenuChannel.gif)";
				document.getElementById("tdtube").style.background 	= "url(images/btn_bgMenuChannel.gif)";
				document.getElementById("vidmenuright").style.background = "url(images/btn_bgMenuChannelRight.gif)";				
			}else if(channelName=="MUSIC"){
				document.getElementById("vidmenuleft").style.background = "url(images/btn_bgMenuChannelLeft.gif)"; //Change the left image too
				document.getElementById("tdsurf").style.background = "url(images/btn_bgMenuChannel.gif)";
				document.getElementById("tdskate").style.background = "url(images/btn_bgMenuChannel.gif)";
				document.getElementById("tdmoto").style.background = "url(images/btn_bgMenuChannel.gif)";				
				document.getElementById("tdmusic").style.background = "url(images/btn_bgMenuChannelBlue.gif)"; //Change the bg image to blue
				document.getElementById("tdbmx").style.background = "url(images/btn_bgMenuChannel.gif)";
				document.getElementById("tdstuff").style.background = "url(images/btn_bgMenuChannel.gif)";
				document.getElementById("tdtube").style.background 	= "url(images/btn_bgMenuChannel.gif)";
				document.getElementById("vidmenuright").style.background = "url(images/btn_bgMenuChannelRight.gif)";				
			
			}else if(channelName=="BMX"){					
				document.getElementById("vidmenuleft").style.background = "url(images/btn_bgMenuChannelLeft.gif)"; //Change the left image too
				document.getElementById("tdsurf").style.background = "url(images/btn_bgMenuChannel.gif)";
				document.getElementById("tdskate").style.background = "url(images/btn_bgMenuChannel.gif)";				
 			    document.getElementById("tdmoto").style.background = "url(images/btn_bgMenuChannel.gif)";
				document.getElementById("tdmusic").style.background = "url(images/btn_bgMenuChannel.gif)";				
				document.getElementById("tdbmx").style.background = "url(images/btn_bgMenuChannelBlue.gif)"; //Change the bg image to blue
				document.getElementById("tdstuff").style.background = "url(images/btn_bgMenuChannel.gif)";
				document.getElementById("tdtube").style.background 	= "url(images/btn_bgMenuChannel.gif)";
				document.getElementById("vidmenuright").style.background = "url(images/btn_bgMenuChannelRight.gif)";				
			
			}else if(channelName=="STUFF"){					
				document.getElementById("vidmenuleft").style.background = "url(images/btn_bgMenuChannelLeft.gif)"; //Change the left image too
				document.getElementById("tdsurf").style.background = "url(images/btn_bgMenuChannel.gif)";
				document.getElementById("tdskate").style.background = "url(images/btn_bgMenuChannel.gif)";				
 			    document.getElementById("tdmoto").style.background = "url(images/btn_bgMenuChannel.gif)";
				document.getElementById("tdmusic").style.background = "url(images/btn_bgMenuChannel.gif)";
				document.getElementById("tdbmx").style.background = "url(images/btn_bgMenuChannel.gif)";				
				document.getElementById("tdstuff").style.background = "url(images/btn_bgMenuChannelBlue.gif)";  //Change the bg image to blue
				document.getElementById("tdtube").style.background 	= "url(images/btn_bgMenuChannel.gif)";
				document.getElementById("vidmenuright").style.background = "url(images/btn_bgMenuChannelRight.gif)";					
			}else if(channelName==DEFAULT_CHANNEL || channelName=="DEFAULT"){					
				document.getElementById("vidmenuleft").style.background = "url(images/btn_bgMenuChannelLeft.gif)"; //Change the left image too
				document.getElementById("tdsurf").style.background = "url(images/btn_bgMenuChannel.gif)";
				document.getElementById("tdskate").style.background = "url(images/btn_bgMenuChannel.gif)";				
 			    document.getElementById("tdmoto").style.background = "url(images/btn_bgMenuChannel.gif)";
				document.getElementById("tdmusic").style.background = "url(images/btn_bgMenuChannel.gif)";
				document.getElementById("tdbmx").style.background = "url(images/btn_bgMenuChannel.gif)";
				document.getElementById("tdstuff").style.background = "url(images/btn_bgMenuChannel.gif)";				
				document.getElementById("tdtube").style.background 	= "url(images/btn_bgMenuChannelBlue.gif)"; //Change the bg image to blue
				document.getElementById("vidmenuright").style.background = "url(images/btn_bgMenuChannelBlueRight.gif)";				
			}
	
		}
			
		/***
		 * This method accepts the video id as parameter and loads the comments based on it. 
		 * @param vidId
		 * @return
		 */
		
		function loadComments(vidId) {
			 
			var videoURL = "http://gdata.youtube.com/feeds/api/videos/"+vidId+"/comments"; // Create a feed instance that will grab Digg's feed.
			var feed = new google.feeds.Feed(videoURL);
			feed.setNumEntries(MAXIMUM_NO_COMMENTS);	//Setting the number of entries to 50
			feed.setResultFormat(google.feeds.Feed.MIXED_FORMAT); //Setting the result format to MIXED to get the comment ids
			updateHTML("videoComments", ""); //Clear off the comments table
			feed.load(feedLoaded); // Calling load sends the request off. It requires a callback function.
			resetNavigationButtons(); //Resetting the up down right left buttons.
		}

		 
		/**
		 * Set the player state
		 * @param plyrState
		 * @return
		 */ 
		function setPlayerState(plyrState){
			playerState = plyrState;
		}
		
		/**
		 * Set the video id
		 * @param videoId
		 * @return
		 */

		function setVideoId(videoId){
			currentVidId = videoId;
		}
		
		/**
		 * Set the video title array
		 * @param vidArr
		 * @return
		 */
		
		function setVideoArr(vidArr){
			videoTitleArr = vidArr;
		}
		
		/**
		 * Update the HTML element in the HTML page
		 * @param elmId
		 * @param value
		 * @return
		 */

		function updateHTML(elmId, value) {
			document.getElementById(elmId).innerHTML = value;
		}
		
		/**
		 * Set the player state
		 * @param newState
		 * @return
		 */
		
		function setytplayerState(newState) {
			updateHTML("playerstate", newState);
		}
		
		/**
		 * This function is called once the player is ready. First function called for the player.
		 * @param playerId
		 * @return
		 */
		function onYouTubePlayerReady(playerId) {
			ytplayer = document.getElementById("ytapiplayer");
			setInterval(updateytplayerInfo, 250);
			updateytplayerInfo();
			ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
			ytplayer.addEventListener("onError", "onPlayerError");
			cueNewVideo(currentVidId, 0);
			createDynamicScriptElement('http://static.addtoany.com/menu/page.js'); //Importing the javascript source for Share the video button
			addShareTheVideoScript(); //Adding dynamic script for share the video
		}
		
		/**
		 * Fires the onplayerstate change event. 
		 * @param newState
		 * @return
		 */
		 
		function onytplayerStateChange(newState) {
			setPlayerState(newState);
			updateTimeAndPercentage(newState);  //Update time and percentage every time the state of the player changes	
			if(playerState==0){
				document.getElementById("playpause").className = "playbtn";				
			}
		}

		/**
		 * Called when the player throws an error.
		 * Possible error codes are: 100, 101 and 150
		 * 
		 * @param errorCode
		 * @return
		 */
		function onPlayerError(errorCode) {
			if(errorCode==150){
				if (confirm("Embedding disabled by request. Please click Ok to play the video in youtube.\nNote: Please enable pop-ups to open the video in new window."))
				{
					window.open("http://www.youtube.com/watch?v="+currentVidId,"_blank","toolbar=yes, location=yes, directories=no, status=no, menubar=yes, scrollbars=yes, resizable=no, copyhistory=yes, fullscreen=yes");
					
				}
				else{
					
				}
			}
		}
		
		/**
		 * Updates the player information every 500ms.
		 * @return
		 */
		function updateytplayerInfo() {
			var bytesLoaded = (getBytesLoaded()/1024);
			var totalBytes = (getBytesTotal()/1024);
			var videoDuration = getDuration();
			var videotime = getCurrentTime();
			//Updating the percentage and time
			updateTimeAndPercentage(playerState);			
			setVolume(document.getElementById('volume').value);
			//Show the timer bar
			updateTimebar();
		}
		
		/***
		 * Updates the time and the percentage based on the player state.
		 * @param playerState
		 * @return
		 */

		function updateTimeAndPercentage(playerState){
			var bytesLoaded = (getBytesLoaded()/1024);
			var totalBytes = (getBytesTotal()/1024);
			var videoDuration = getDuration();
			var videotime = getCurrentTime();

			if((playerState==1 || playerState==2 || playerState==3)&&(videotime>0 && bytesLoaded>0))
				{
					//Showing the time
					var formattedTime = (getMinutesSecond(videotime))+"/"+(getMinutesSecond(videoDuration));
					updateHTML("formattedTime", formattedTime);

					var loadedPercentage = parseInt((bytesLoaded/totalBytes)*100); //Setting progress bar value
					//pb.set('value',loadedPercentage);
					/**  LOOK: ADDED BY AARON*/
					adjustCacheBar();

				}else{
					updateHTML("formattedTime", "00:00/00:00");
					//pb.set('value',0);
					/**  LOOK: ADDED BY AARON*/
					adjustCacheBar();
				}

		}		
		
		/**
		 * Accepts the time as parameter and then it converts to days ago or months ago or minutes ago.
		 * @param time_value
		 * @return
		 */

	   function relative_time(time_value) {

			  var values = time_value.split(" ");
			  time_value = values[1] + " " + values[2] + ", " + values[3] + " " + values[4];
			  var parsed_date = Date.parse(time_value);
			  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
			  var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
			  delta = delta + (relative_to.getTimezoneOffset() * 60);

			  var r = '';
			  if (delta < 60) {
				r = 'a minute ago';
			  } else if(delta < 120) {
				r = 'couple of minutes ago';
			  } else if(delta < (45*60)) {
				r = (parseInt(delta / 60)).toString() + ' minutes ago';
			  } else if(delta < (90*60)) {
				r = 'an hour ago';
			  } else if(delta < (24*60*60)) {
				r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
			  } else if(delta < (48*60*60)) {
				r = '1 day ago';
			  } else {
				r = (parseInt(delta / 86400)).toString() + ' days ago';
			  }

			  return r;
	    }
	  	
		/**
		 * Opens the social network site based on the URL.
		 * 
		 * @param theURL
		 * @return
		*/
	  	function openSocialNetSite(theURL) {
	  		window.open((theURL+getCityBeachVideoURL(false)), '', 'fullscreen=yes, scrollbars=yes');
		}

		/**
		* Get the URL for social network site. Returns the parent URL with the video parameter embedded.
		* Eg: http://localhost:8080/CityBeach/?channel=GoogleDevelopersv=Xjt-CZsyLBQ
		**/
		
		function getCityBeachVideoURL(addAny){
			var currentVidURLId = getURLVar("v", ytplayer.getVideoUrl());
			var parentURL =  window.parent.location.href; 
			var splitVidURL;
			
			var ampStr = addAny?"&":"%26"; //For add to any & and for other buttons %26
			var qstnStr = ((parentURL).indexOf("?")== -1)?"?":ampStr; //If URL has ? assign ampStr value else assign ?. Used for Test Env and UAT url change.
			
			if((parentURL).indexOf("?channel")!= -1){ //Check if the channel already has extra parameters if channel is first parameter.
				splitVidURL = parentURL.split("?channel");
				parentURL = splitVidURL[0];
				qstnStr = "?";
			}
			
			if((parentURL).indexOf("&channel")!= -1){ //Check if the channel already has extra parameters if channel is last parameter.
				splitVidURL = parentURL.split("&channel");
				parentURL = splitVidURL[0];
				qstnStr = ampStr;
			}
			
			var channelParam = qstnStr+"channel="+currentChannel+ampStr+"v="+currentVidURLId;
			var fullUrl = parentURL+channelParam;
			return addAny?fullUrl:replaceAmpersand(fullUrl);
		}
		/**
		 * Replace the ampersand with the %26.
		 * @param url
		 * @return
		 */
		function replaceAmpersand(url){
			return url.replace("&","%26");
		}
		
		
		/**
		 * Clear the time and the progressbar on the first time load.
		 * @return
		 */
		function clearTimeAndProgress(){
			//Update player status.
			updateHTML("formattedTime", "00:00/00:00");
			//pb.set('value',0);
			/**  LOOK: ADDED BY AARON*/
			adjustCacheBar();
		}

		 /**
		  * Converts the seconds to minutes.
		  * @param seconds
		  * @return
		  */
		
		function getMinutesSecond(seconds){
			var numminutes = parseInt(Math.floor(((seconds % 86400) % 3600) / 60));
			var numseconds = parseInt(((seconds % 86400) % 3600) % 60);

			if(numminutes <= 9){
				numminutes = "0"+numminutes;
			}
			if(numseconds <= 9){
				numseconds = "0"+numseconds;
			}
			return (numminutes)+":"+(numseconds);
		}
		
		/** Player function for the Youtube. **/
		
		/**
		 * Loads the new video by accepting the id and the start seconds
		 * @param id
		 * @param startSeconds
		 * @return
		*/
		function loadNewVideo(id, startSeconds) {
			if (ytplayer) {
				ytplayer.loadVideoById(id, parseInt(startSeconds));
				clearTimeAndProgress();
				updateHTML("headtitle", videoTitleArr[id]);	//Setting the title
				loadComments(id); //Load comments for the video
				setVolume(DEFAULT_VOLUME);
				document.getElementById("playpause").className = "pausebtn";
				currentVidId = id; //Setting the current video ID
				addShareTheVideoScript(); //Adding dynamic script for share the video
				
			}
		}
		
		/**
		 * Queue's the new video by accepting the id and the start seconds
		 * @param id
		 * @param startSeconds
		 * @return
		 */
		function cueNewVideo(id, startSeconds) {
			if (ytplayer) {
				ytplayer.cueVideoById(id, startSeconds);
				clearTimeAndProgress();
				setVolume(DEFAULT_VOLUME);
			}
		}
		 
		/**
		 * Plays the video once this method is called
		 * @return
		 */ 
		function play() {
			if (ytplayer) {
			ytplayer.playVideo();
			}
		}
		
		/**
		 * Pauses the video once this method is called
		 * @return
		 */ 

		function pause() {
			if (ytplayer) {
			ytplayer.pauseVideo();
			}
		}
		
		/**
		 * Stops the video once this method is called
		 * @return
		 */
		function stop() {
			if (ytplayer) {
			ytplayer.stopVideo();
			}
		}
		
		/**
		 * Gets the state of the player
		 * Possible states are unstarted (-1), ended (0), playing (1), paused (2), buffering (3), video cued (5)  
		 * @return
		 */
		function getPlayerState() {
			if (ytplayer) {
			return ytplayer.getPlayerState();
			}
		}
		
		/**
		 * Seeks the video in the time sent as parameter
		 * @param seconds
		 * @return
		 */

		function seekTo(seconds) {
			if (ytplayer) {
			ytplayer.seekTo(seconds, true);
			}
		}
		
		/**
		 * Returns the bytes loaded
		 * @return
		 */
		function getBytesLoaded() {
			if (ytplayer) {
				return ytplayer.getVideoBytesLoaded();
			}
		}
		
		/**
		 * Returns the total size of the video in bytes
		 * @return
		 */

		function getBytesTotal() {
			if (ytplayer) {
				return ytplayer.getVideoBytesTotal();
			}
		}

		/**
		 * Get the current playing time
		 * @return
		 */
		function getCurrentTime() {
			if (ytplayer) {
				return ytplayer.getCurrentTime();
			}
		}
		
		/**
		 * Gets the total duration of the video
		 * @return
		 */

		function getDuration() {
			if (ytplayer) {
				return ytplayer.getDuration();
			}
		}
		
		/**
		 * Mute the player
		 * @return
		 */
		
		function mute() {
			if (ytplayer) {
				ytplayer.mute();
			}
		}
		
		/**
		 * Unmute the player
		 * @return
		 */
		function unMute() {
			if (ytplayer) {
				ytplayer.unMute();
			}
		}

		/**
		 * Gets the embed code of the video that is currently playing
		 * @return
		 */
		function getEmbedCode() {
			alert(ytplayer.getVideoEmbedCode());
		}
		
		/**
		 * Gets the player URL of the video that is played currently
		 * @return
		 */
		function getVideoUrl() {
			alert(ytplayer.getVideoUrl());
		}
		
		/**
		 * Sets the volume for the playing video
		 * @param newVolume
		 * @return
		 */

		function setVolume(newVolume) {
			if (ytplayer) {
				ytplayer.setVolume(newVolume);
			}
		}

		/**
		 * Returns the volume as integer of the currently playing video
		 * @return
		 */
		function getVolume() {
			if (ytplayer) {
				return ytplayer.getVolume();
			}
		}
		
		/**
		 * Clears the video by removing the buffer data
		 * @return
		 */
		function clearVideo() {
			if (ytplayer) {
				ytplayer.clearVideo();
			}
		}
		 
		 function startBytes() {
				if (ytplayer) {
					return ytplayer.getVideoStartBytes();
				}
			}
		
		/***
		 *  Toggle the play pause buttons
		 *  unstarted (-1), ended (0), playing (1), paused (2), buffering (3), video cued (5) 
		*/
		 
		function contolPlayPause(){
		    var playerState = getPlayerState();		   
			if(playerState == -1 || playerState == 3){  //Unstarted Ended Buffering
				document.getElementById("playpause").className = "playbtn";
			
			}else if(playerState == 0){
				var btClass = document.getElementById("playpause").className;
				changeBtnBasedOnClass(btClass);
				
			}else if(playerState == 1 || playerState == 2){  //Player state playing or paused
				var btClass = document.getElementById("playpause").className;
				changeBtnBasedOnClass(btClass);
			
			}else if(playerState == 5){  //Que video
				play();
				document.getElementById("playpause").className = "pausebtn";
			}

		}
		 
		/***
		 * Change the play pause button based on the event triggered.
		 * @param btClass
		 * @return
		 */ 
		function changeBtnBasedOnClass(btClass){			
			if(btClass=="playbtn"){
				play();
				document.getElementById("playpause").className = "pausebtn";
			}else{
				document.getElementById("playpause").className = "playbtn";
				pause();
			}			
		}
		 

		/**
		 * Posts comments to youtube. Calls a new page, sends the video id to it.
		 */
		
		function addNewComment(){
		    var url = "YoutubeComments.html?videoid="+currentVidId;
			window.open(url,'mywindow','width=900,height=500,left=100,top=100,screenX=500,screenY=100');
			//postCommentsToYoutube(currentVidId, null);
		}
		
		 

		function appendReplies(replyArr, commentId){
			alert(replyArr[commentId]);
			var replies = "";
			for ( var indvCommentId in replyArr){
				if(commentId==indvCommentId){
					replies += replyArr[indvCommentId];
				}
			}
			return replies;
		}

		/**
		  * Our callback function, for when a feed is loaded.
		  * @param result
		  * @return
		  */
		 
		function feedLoaded(result) {
		  if (!result.error) {
			// Grab the container we will put the results into
			var container = document.getElementById("videoComments");
			container.innerHTML = '';
			var html = ['<table id="vidcomments" cellpadding="0" cellspacing="0" width="100%">'];
		
			// Loop through the feeds, putting the titles onto the page.
			// Check out the result object for a list of properties returned in each entry.
			// http://code.google.com/apis/ajaxfeeds/documentation/reference.html#JSON
			var replyStr = "";
			numberOfComments = result.feed.entries.length;
			
			var comments = new Array();
			var reply = new Hashtable();
			
			var j=0;
			for (var i = 0; i < numberOfComments; i++) {				
			  var entry = result.feed.entries[i];
			  
			  var publishedDate = relative_time(entry.publishedDate);
			    
			  
			  
			  if(getLinkAttributeValue(entry)!=""){  //Checking whether the comment is reply or not.
			  //alert(getLinkAttributeValue(entry));
			  //reply.put(getLinkAttributeValue(entry), "<tr id="+commentId+"><td><table width=\"94%\" class=\"commentReply\"><tr><td height=\"30\"><span class=\"titlec\">"+entry.author+"</span> <span style=\"color:#898989;\">"+publishedDate+"</span></td></tr><tr><td><span class=\"veiwcount\">"+commentChars+"</span></td></tr><tr><td><img src=\"images/btn_reply.png\" style=\"cursor:pointer\" onclick=\"addReplyToComments('"+commentId+"')\"/></td></tr><tr><td class=\"commentsLine\"></td></tr></table></td></tr>");  //Add all the replies to the string
			  reply.put(getLinkAttributeValue(entry),entry);
			  }else{
				  //comments[commentId] = "<tr id="+commentId+"><td><table width=\"99%\"><tr><td height=\"30\"><span class=\"titlec\">"+entry.author+"</span> <span style=\"color:#898989;\">"+publishedDate+"</span></td></tr><tr><td><span class=\"veiwcount\">"+commentChars+"</span></td></tr><tr><td><img src=\"images/btn_reply.png\" style=\"cursor:pointer\" onclick=\"addReplyToComments('"+commentId+"')\"/></td></tr><tr><td class=\"commentsLine\"></td></tr></table></td></tr>";
				  comments[j]=entry;
				  j++;
			  }
			}
			
			for ( var commId=0;commId<comments.length;commId++){
				var entry = comments[commId];
				
				var commentId = getCommentId(entry.xmlNode.getElementsByTagName("id")[0].childNodes[0].nodeValue);
				var commentChars = truncateStr(entry.content, MAXIMUM_COMMENT_LENGTH);   //Truncate the comment values
				html.push("<tr id="+commentId+"><td><table width=\"99%\"><tr><td height=\"30\"><span class=\"titlec\">"+entry.author+"</span> <span style=\"color:#898989;\">"+publishedDate+"</span></td></tr><tr><td><span class=\"veiwcount\">"+commentChars+"</span></td></tr><tr><td><img src=\"images/btn_reply.png\" style=\"cursor:pointer\" onclick=\"addReplyToComments('"+commentId+"')\"/></td></tr><tr><td class=\"commentsLine\"></td></tr></table></td></tr>");
				var key=entry.xmlNode.getElementsByTagName("id")[0].childNodes[0].nodeValue;
				while(true){
					
					if (reply.containsKey(key)){
						entry= reply.get(key);
						commentId = getCommentId(entry.xmlNode.getElementsByTagName("id")[0].childNodes[0].nodeValue);
						commentChars = truncateStr(entry.content, MAXIMUM_COMMENT_LENGTH);   //Truncate the comment values
						html.push("<tr id="+commentId+"><td><table width=\"94%\" class=\"commentReply\"><tr><td height=\"30\"><span class=\"titlec\">"+entry.author+"</span> <span style=\"color:#898989;\">"+publishedDate+"</span></td></tr><tr><td><span class=\"veiwcount\">"+commentChars+"</span></td></tr><tr><td><img src=\"images/btn_reply.png\" style=\"cursor:pointer\" onclick=\"addReplyToComments('"+commentId+"')\"/></td></tr><tr><td class=\"commentsLine\"></td></tr></table></td></tr>");  //Add all the replies to the string
						key=entry.xmlNode.getElementsByTagName("id")[0].childNodes[0].nodeValue;
					}
					else
					{
						break;
					}
				
			}

				//html.push(comments[commId]);
				
				//html.push(appendReplies(reply, commId));
			}
			html.push('</table>');			
			container.innerHTML = html.join('');
			updateNumberPaging(numberOfComments); //Update the number paging div
			commentPager.init();
			commentPager.showPage(1);			
			
		  }
		}

		
		/**
		 * Update the number paging div, show the page numbers and navigate on click.
		 * @param numberOfComments
		 * @return
		 */
		
		function updateNumberPaging(numberOfComments){
			 numberOfCommentPages = Math.ceil(numberOfComments/COMMENTS_PER_PAGE);
			var pagingDiv = document.getElementById("numberpaging");
			var pageStr = "<b>P a g e . . .</b>";
			for ( var i = 1; i <= numberOfCommentPages; i++) {
				pageStr += "<a id="+("cp_"+i)+" class=\"replyNumber\" onClick=\"javascript:commentPager.showPage("+i+");\">"+i+"</a>";
			}
			pagingDiv.innerHTML = pageStr+"     <b>. . .</b>";	
			if(numberOfComments==0){
				pagingDiv.innerHTML = "";
			}
			 
			if(numberOfCommentPages==1){ //if the number of pages is 1, change the right button too.
				document.getElementById("btnRight").src = IMG_RIGHT_BUTTON_DISABLED;
			}
			
		}
		 
		/**
		 * Gets the attribute value of the link tag by sending the parameter as an entry feed object.
		 * @param entry
		 * @return
		 */ 
		 		 
		function  getLinkAttributeValue(entry){
			var replyAttr = ""
			var count = entry.xmlNode.getElementsByTagName("link").length;
			for (var i = 0; i < count; i++) {
				if(entry.xmlNode.getElementsByTagName("link")[i].getAttribute("rel").match("in-reply-to")){
					replyAttr =entry.xmlNode.getElementsByTagName("link")[i].getAttribute("href"); 					
				} 
			}
			return replyAttr;			
		}
		
		
		/**
		 * Reply for a comment. Sends videoid and comment id to the new page.
		 * @param commentId
		 * @return
		 */
		
		function addReplyToComments(commentId){
			var url = "YoutubeComments.html?videoid="+currentVidId+"&commentid="+commentId;
			window.open(url,'mywindow','width=900,height=500,left=100,top=100,screenX=500,screenY=100');
			//postCommentsToYoutube(currentVidId, commentId);
		}
		
	   /**  LOOK: ADDED BY AARON
		* Adjusts the cache bar the reprosent the currently cached content 
	    * @param commentId
		* @return
		*/		
		function adjustCacheBar() {
			//var totalLength = document.getElementById("timebar").style.width;
			var totalLength = $("#timebar").width(width);
			var total = getBytesTotal();
			var start = startBytes();
			var loaded = getBytesLoaded();
			
			if(ytplayer) {
				if(total > 0) {
					var width = ((loaded/total) * totalLength);
					var left = ((start/total) * totalLength);
					$("#cached").css("left",left);
					$("#cached").width(width);
				}
			}
		}
		
		/**
		 * This functions inserts the commas to the views count Note: Thousand separator as per foreign standards.
		 */
		 
		function addCommas(val) {
			var regEx = /(\d+)(\d{3})/;
			while (regEx.test(val)) {
				val = val.replace(regEx, '$1' + ',' + '$2');
			}
			return val;
		}
	
		/**
		 * Get the comment id accepting URL as parameter.
		 * @param nodeValue
		 * @return
		 */
		function getCommentId(nodeValue){
			var splitUrl = nodeValue.split("/comments/");
			return splitUrl[1];
		}
		
		/**
		 * On load this fetches the comments of the first video from the youtube.
		 * @return
		 */
		function OnLoad() {
			// Create a feed instance that will grab Digg's feed.
			var videoURL = "http://gdata.youtube.com/feeds/api/videos/"+currentVidId+"/comments";
			var feed = new google.feeds.Feed(videoURL);
			feed.setNumEntries(MAXIMUM_NO_COMMENTS);  //Set the number of feed entry results to 50	
			feed.setResultFormat(google.feeds.Feed.MIXED_FORMAT);  //Setting the result format.			
			feed.load(feedLoaded);  // Calling load sends the request off.  It requires a callback function.
		}		