 var AJAX_Pulling = false;  
var playerReady = 0; 
var newPlayer = ""; 
var outputHTML = ""; 
var paginationHTML = "";  
var myPlaylist = new Array();
var fetchedID = 0;
           
function initialLoad(basketID, tabBasketID) {
	//alert("initial");   	
	loadBasket(basketID, 1); 
	 
	
	InSkinLoad.init(InSkinParams);
	 
		if (GetCookie('planetrugby_video_playlist')) { 
			//load the playlist into memory
			myPlaylist.load(GetCookie('planetrugby_video_playlist'));
		} else {
			//paint the default text into the playlist
			myPlaylist.refresh();
		}
	 if(tabBasketID) {
		loadTabBasket(tabBasketID, 1, ""+tabBasketID+"");
	}	
}     
       
function loadAbstract(storyId) { 
	if (storyId) {
		var clipAbstract = $("#clipAbstract"+storyId).val();
		var clipTitle = $("#clipTitle"+storyId).val();
		var clipDate = $("#clipDate"+storyId).val();  
		 
		if (clipTitle.match(/%20/)) clipTitle = unescape(clipTitle);
		if (clipDate.match(/%20/)) clipDate = unescape(clipDate);
		if (clipAbstract.match(/%20/)) clipAbstract = unescape(clipAbstract);
	   
		var clipHTML = "";
		//siteName: planetrugby 
			if (clipTitle) clipHTML += "<h2>" + clipTitle.escapeHTML() + "</h2>";
			if (clipDate) clipHTML += "<p class='text-caption'>" + clipDate.escapeHTML() + "</p>";
			if (clipAbstract) clipHTML += "<p>" + clipAbstract.escapeHTML() + "</p>"
		 $("#video-detail").html(clipHTML);
	}
}   
  
function loadBasket(vidBasketID, thisPageNum) {
	var myPageNum = thisPageNum;
	var numVids = 8; 
	 
	$("#page-list").empty(); 
	$("#video-list").empty(); 
	
	var domainName = window.location.hostname;
	
	if (domainName.match(/teamsky\.it/)) {
		$("#video-list").html('<div align="center" style="width:300px;color:#000000"><img src="/Images/skysports/site/loadingAnimation.gif" border="0" /><br/><br/>Trova il video</div>');
	} else {
		$("#video-list").html('<div align="center" style="width:300px;color:#000000"><img src="/Images/skysports/site/loadingAnimation.gif" border="0" /><br/><br/>Finding Video Clips</div>');
	}	
	 
	paginationHTML ="";  
	outputHTML ="";  

	var loadBasketURL = "/video_clip_list_xml/0,25682,thisisnotanoid_thisisnotapagenum_thisisnotavidnum,00.xml";
	
	if (typeof vidBasketID == "undefined") {vidBasketID = 15715;}
	if (typeof myPageNum == "undefined") {myPageNum = 1;}
 
	loadBasketURL = loadBasketURL.replace("thisisnotanoid", vidBasketID);
	loadBasketURL = loadBasketURL.replace("thisisnotapagenum", myPageNum);
	loadBasketURL = loadBasketURL.replace("thisisnotavidnum", numVids);
	
	if (AJAX_Pulling != true) {
		AJAX_Pulling = true;
		
		$.get(loadBasketURL, {}, function(xmlData) {
			var vLength = $(xmlData).find('clip').length;
			var basketName = $(xmlData).find('clipList').attr("basketName");
			 
			if (vLength > 0) {	
			    
			   
					outputHTML += "<ul>";
				 $('clip',xmlData).each(function(i) {
				  
					i++; //i starts on 0, we need it to start with 1
					var cStoryID = $(this).attr("storyID");
					var cDate = $(this).attr("clipDate");	
					var cTitle = $(this).attr("title");
					var cAbstract = $(this).attr("abstract"); 
					 
					var cID = $(this).attr("id");
					var cVidPath = $(this).attr("vidPath");	
					var cThumb = $(this).attr("thumbPath");
					var cOrigin = $(this).attr("origin");
					      
					if ((i%4) == 0) {   
						 var clipClass = "no-bdr"
					} else { 
						var clipClass = ""	
					} 
					var stuffedId = vidBasketID+"_"+cStoryID;
					
					if (cOrigin == "skyplayer") {
						var cAction = "playSPVideo('"+ cVidPath +"')"
						var cLinkText = "Sign in to watch";
						var cLinkClass = "sign-in";
					} else {
						var cAction = "playBCVideo('"+ cID +"_"+ cStoryID +"', '"+stuffedId+"')"
						var cLinkText = "Watch now";
						var cLinkClass = "free-to-watch";
					}
					
					var cLinktag = " href=\"#\" onclick=\"javascript: "+ cAction +"; return false;\" "
					var cPlaylistTag = " href=\"javascript:;\" onclick=\"javascript:myPlaylist.addClip('"+ cID +"', '"+ cStoryID +"'); return false;\" "

					
						outputHTML += "<li class=\"" + clipClass + "\">";
						outputHTML += "<a "+ cLinktag +" title=\""+ cTitle +"\"><img src=\""+ cThumb +"\" alt=\""+ cTitle +"\" /></a>";
						outputHTML += "<p>"+ cDate +"</p>";
						outputHTML += "<h3>"+ cTitle.escapeHTML() +"</h3>";

						outputHTML += "<ul class=\"pr-clip-btns\">";						
	        			outputHTML += "<li><a "+ cLinktag +" title=\"Watch Now\">Watch Now<img src=\"/Images/PlanetRugby/Icons/pr-clip-btns-watch.gif\"></a></li>";
	    				outputHTML += "<li class=\"playlist\"><a "+ cPlaylistTag +" title=\"Add to playlist\">Add to playlist<img src=\"/Images/PlanetRugby/Icons/pr-clip-btns-add.gif\"></a></li>";
	        			outputHTML += "</ul>";						
						outputHTML += "</li>"; 
					 //Hidden values used as temp store for loadAbstract func 		
					outputHTML += "<input type=\"hidden\" id=\"clipAbstract" + cStoryID + "\" value=\"" + cAbstract.escapeHTML() + "\" />";
					outputHTML += "<input type=\"hidden\" id=\"clipTitle" + cStoryID + "\" value=\"" + cTitle.escapeHTML() + "\" />";
					outputHTML += "<input type=\"hidden\" id=\"clipDate" + cStoryID + "\" value=\"" + cDate.escapeHTML() + "\" />";
					outputHTML += "<input type=\"hidden\" id=\"clipImage" + cStoryID + "\" value=\"" + cThumb + "\" />";
				});	 
				
				 
						outputHTML += "</ul>";	
				  } else {
				outputHTML = "<div style='color:#000000;font-size:16px;'>There are currently no video clips in '"+ basketName +"'</div>"
			}  
			
			
			//////// PAGINATION ////////////////
			var pLength = $(xmlData).find('page').length;
			var pCurrent = $(xmlData).find('pagination').attr("currentPage");
			var pTotal = $(xmlData).find('pagination').attr("totalPages");
			
			if (pLength > 0) {     
			
			
				if (thisPageNum != 1) {
					
						var trackLink = "";
					 paginationHTML += "<li><a href=\"javascript:;\" onclick=\"javascript:loadBasket('"+ vidBasketID + "', '1'); "+trackLink+" return false;\" title=\"Go to First Page\">&laquo; First</a></li>";
				}
				if (pCurrent > 1) {
					
						var trackLink = "";
					 paginationHTML += "<li><a href=\"javascript:;\" onclick=\"javascript:loadBasket('"+ vidBasketID + "', '" + (eval(pCurrent)-1) + "'); "+trackLink+" return false;\" title=\"Go to Previous Page\">Prev</a></li>";
				} 
			 $('page',xmlData).each(function(i) {
					var pNumber = $(this).attr("pageNumber");
					var pIsCurrent = $(this).attr("isCurrent");
					
					
						var trackLink = "";
					 
						  var pLink = " href=\"javascript:;\" onclick=\"javascript:loadBasket('"+ vidBasketID +"', '"+ pNumber +"'); "+trackLink+" return false;\" title=\"Page "+ pNumber +"\"";
					
					 if(pIsCurrent == 1) { 
						paginationHTML += "<li>"+ pNumber +"</li>";
					} else {
						paginationHTML += "<li><a "+ pLink +">"+ pNumber +"</a></li>";
					}
				});   

			
				if (eval(pCurrent)+1 <= pTotal) {
					
						var trackLink = "";
					 paginationHTML += "<li class=\"\"><a href=\"javascript:;\" onclick=\"javascript:loadBasket('"+ vidBasketID + "', '" + (eval(pCurrent)+1) + "'); "+trackLink+" return false;\" title=\"Go to Next Page\" class=\"pag-next\" >Next</a></li>";
				}
				if (pCurrent != pTotal) {
					
						var trackLink = "";
					 paginationHTML += "<li class=\" no-bdr\"><a href=\"javascript:;\" onclick=\"javascript:loadBasket('"+ vidBasketID + "', '" + pTotal + "'); "+trackLink+" return false;\" title=\"Go to Last Page\" >Last &raquo;</a></li>";
				}	
			 }    
			
				
				$("#video-list").html(outputHTML);
				$("#page-list").html(paginationHTML);
			 }, "xml");
		
		if( typeof videoPageLoadCallback == 'function' ) {
			videoPageLoadCallback();
		} 
		
		AJAX_Pulling = false;
	}  
}   

function loadTabBasket(vidBasketID, thisPageNum, tabName) {
	var myPageNum = thisPageNum;
	var numVids = 8; 
	
	$("#"+tabName).empty(); 
	 
	$("#"+tabName).html('<div align="center" class="finding-video-text" style="width:100%;margin-top:100px;color:#000000"><img src="/Images/skysports/site/loadingAnimation.gif" border="0" /><br/><br/>Finding Video Clips</div>');
	
	tabPaginationHTML ="";  
	tabOutputHTML ="";  

	var loadBasketURL = "/video_clip_list_xml/0,25682,thisisnotanoid_thisisnotapagenum_thisisnotavidnum,00.xml";

	if (typeof vidBasketID == "undefined") {vidBasketID = 15715;}
	if (typeof myPageNum == "undefined") {myPageNum = 1;}		

	loadBasketURL = loadBasketURL.replace("thisisnotanoid", vidBasketID);
	loadBasketURL = loadBasketURL.replace("thisisnotapagenum", myPageNum);
	loadBasketURL = loadBasketURL.replace("thisisnotavidnum", numVids);

	if (AJAX_Pulling != true) {
		AJAX_Pulling = true;
		 
		$.get(loadBasketURL, {}, function(xmlData) {
			var vLength = $(xmlData).find('clip').length;
			var basketName = $(xmlData).find('clipList').attr("basketName");

			if (vLength > 0) {	
			  
				tabOutputHTML += "<ul class='clips-wrapper'>";
				
				$('clip',xmlData).each(function(i) {
				 
					i++; //i starts on 0, we need it to start with 1
					var cStoryID = $(this).attr("storyID");
					var cDate = $(this).attr("clipDate");	
					var cTitle = $(this).attr("title");
					var cAbstract = $(this).attr("abstract");
					
					var cID = $(this).attr("id");
					var cVidPath = $(this).attr("vidPath");	
					var cThumb = $(this).attr("thumbPath");
		
					 var cOrigin = $(this).attr("origin");
					  
					if ((i%4) == 0) {
						 var clipClass = "no-bdr"
					} else { 
						var clipClass = ""	
					}
				  
					var cLinktag = " href=\"javascript:;\" onclick=\"javascript:playBCVideo('"+ cID +"_"+ cStoryID +"'); return false;\" "
					var cPlaylistTag = " href=\"javascript:;\" onclick=\"javascript:myPlaylist.addClip('"+ cID +"', '"+ cStoryID +"'); return false;\" "

					
						
						tabOutputHTML += "<li class=\"clip-box\">";
						tabOutputHTML += "<a "+ cLinktag +" title=\""+ cTitle +"\"><img src=\""+ cThumb +"\" alt=\""+ cTitle +"\" /></a>";
						tabOutputHTML += "<p class=\"text-caption\">"+ cDate +"</p>";
						tabOutputHTML += "<h3><a "+ cLinktag +" title=\""+ cTitle.escapeHTML() +"\">"+ cTitle.escapeHTML() +"</a></h3>";
						
						tabOutputHTML += "<ul class=\"pr-clip-btns\">";
	        			tabOutputHTML += "<li><a "+ cLinktag +" title=\"Watch Now\">Watch Now<img src=\"/Images/PlanetRugby/Icons/pr-clip-btns-watch.gif\"></a></li>";
	    				tabOutputHTML += "<li class=\"playlist\">";
						tabOutputHTML += "<a "+ cPlaylistTag +" title=\"Add to playlist\">";
						tabOutputHTML += "Add to playlist";
						tabOutputHTML += "<img src=\"/Images/PlanetRugby/Icons/pr-clip-btns-add.gif\">";
						tabOutputHTML += "</a></li>";
						tabOutputHTML += "</ul>";						
						
						tabOutputHTML += "</li>";
  
					 //Hidden values used as temp store for loadAbstract func 		
					tabOutputHTML += "<input type=\"hidden\" id=\"clipAbstract" + cStoryID + "\" value=\"" + cAbstract.escapeHTML() + "\" />";
					tabOutputHTML += "<input type=\"hidden\" id=\"clipTitle" + cStoryID + "\" value=\"" + cTitle.escapeHTML() + "\" />";
					tabOutputHTML += "<input type=\"hidden\" id=\"clipDate" + cStoryID + "\" value=\"" + cDate.escapeHTML() + "\" />";
					tabOutputHTML += "<input type=\"hidden\" id=\"clipImage" + cStoryID + "\" value=\"" + cThumb + "\" />";
				});	 
				
				tabOutputHTML += "</ul>";	
				 
			} else {
				tabOutputHTML = "<div class='no-video-text' style='color:#000000;font-size:16px;'>There are currently no video clips in '"+ basketName +"'</div>"
			}

			//////// PAGINATION ////////////////
			var pLength = $(xmlData).find('page').length;
			var pCurrent = $(xmlData).find('paginationTab').attr("currentPage");
			var pTotal = $(xmlData).find('paginationTab').attr("totalPages");
			
			if (pLength > 1) {     
 			    //Only want to see paging if there's more than one page
				
				if (thisPageNum != 1) {
				 	tabPaginationHTML += "<li><a href=\"javascript:;\" onclick=\"javascript:loadTabBasket('"+ vidBasketID + "', '1' , '"+ tabName + "'); return false;\" title=\"Go to First Page\">&laquo; First</a></li>";
				}
				
				if (pCurrent > 1) {
				 	tabPaginationHTML += "<li><a href=\"javascript:;\" onclick=\"javascript:loadTabBasket('"+ vidBasketID + "', '" + (eval(pCurrent)-1) + "' , '"+ tabName + "'); return false;\" title=\"Go to Previous Page\">Prev</a></li>";
				} 
				   
				$('page',xmlData).each(function(i) {
					var pNumber = $(this).attr("pageNumber");
					var pIsCurrent = $(this).attr("isCurrent");
					var pLink = " href=\"javascript:;\" onclick=\"javascript:loadTabBasket('"+ vidBasketID +"', '"+ pNumber +"', '"+ tabName +"'); return false;\" title=\"Page "+ pNumber +"\"";
						
					if(pIsCurrent == 1) {
						tabPaginationHTML += "<li>"+ pNumber +"</li>";
					} else {
						tabPaginationHTML += "<li><a "+ pLink +">"+ pNumber +"</a></li>";
					}
				}); 

				
					if (eval(pCurrent)+1 <= pTotal) {
						tabPaginationHTML += "<li class=\"\"><a href=\"javascript:;\" onclick=\"javascript:loadTabBasket('"+ vidBasketID + "', '" + (eval(pCurrent)+1) + "' , '"+ tabName + "'); return false;\" title=\"Go to Next Page\" class=\"pag-next\" >Next</a></li>";
					}
					if (pCurrent != pTotal) {
						tabPaginationHTML += "<li class=\" no-bdr\"><a href=\"javascript:;\" onclick=\"javascript:loadTabBasket('"+ vidBasketID + "', '" + pTotal + "' , '"+ tabName + "'); return false;\" title=\"Go to Last Page\" >Last &raquo;</a></li>";
					}	  
				 }// End Pagination    

			
			
				if(basketName.toLowerCase() == "highlights"){
					tabPaginationHTML += "<li class=\"tab-note\">*UK & ROI only.</li>";
				}
			 tabOutputHTML += "<ul class='paginationTab' id='page-list'>"+ tabPaginationHTML +"</ul>";
			$("#"+tabName).html(tabOutputHTML);
		}, "xml");
		
		AJAX_Pulling = false;
	}		

	   
}

 
String.prototype.escapeHTML = function () {                                       
return(                                                                 
    this.replace(/&/g,'&amp;').                                         
        replace(/>/g,'&gt;').                                           
        replace(/</g,'&lt;').                                           
        replace(/"/g,'&quot;').
		replace(/'/g,'&#39;')                                         
    );                                                                     
} 
function trim(str) {
	return str.replace(/^ss*/, '').replace(/ss*$/, '');
}



	var bcExp;
var modVP;
var modExp;
var modCon;
var modAd; 
var modMP;

function onTemplateLoaded(experienceID) {
	//alert("EVENT: The template has loaded");
	
	bcExp = brightcove.getExperience(experienceID);
	
	
	modExp = bcExp.getModule(APIModules.EXPERIENCE);
	modCon = bcExp.getModule(APIModules.CONTENT);
	modVP = bcExp.getModule(APIModules.VIDEO_PLAYER);
	modAd = bcExp.getModule(APIModules.ADVERTISING);
	modMP = bcExp.getModule(APIModules.MENU);
	 
	
	modExp.addEventListener(BCExperienceEvent.TEMPLATE_READY, onTemplateReady);
	modExp.addEventListener(BCExperienceEvent.CONTENT_LOAD, onPlayerLoad);
	
	modVP.addEventListener(BCVideoEvent.VIDEO_LOAD, onVideoLoad); 
	modVP.addEventListener(BCMediaEvent.BEGIN, onVideoBegin);
	modVP.addEventListener(BCMediaEvent.CHANGE, onVideoChange); 
	
	modAd.addEventListener(BCAdvertisingEvent.AD_START, onAdvertBegin);
}

function onTemplateReady(evt) {
	
    //alert("EVENT: The Player has loaded correctly"); 	
	playerReady = 1;
}

function onPlayerLoad(evt) {	
	
	var vID;
	if (fetchedID == 0) {
		//if we havent already fetched a video IE clicked it, play the current one.
		var currentVideo = modVP.getCurrentVideo();
		vID = currentVideo.id;
	} else {
		vID = fetchedID;
	}
	
	//debug("EVENT content_load - video id= <b>" +vID + "</b> fetched_id "+fetchedID);
	modVP.loadVideo(vID);
}

function onVideoLoad(evt) {
	//alert("videoload");
}

function onVideoBegin(evt) {
   // Event fired when video starts playback, only fired when video plays not before pre-roll
	
		//alert(evt.media.adKeys);
	}

function onVideoChange(evt) {

  	//when we change the media
	var currentid = evt.media.id;
	var adKeys = evt.media.adKeys;

	if (!adKeys) {
		adKeys = "General"; 
	}

	adKeys = adKeys.replace("Key=", "");
	adKeys = adKeys.replace("key=", "");
	//debug("JLH EVENT video_change - video id = <b>"+currentid + "</b> video keywords <b>"+ adKeys + "</b>");
	changeAdAlias(adKeys);
}

function changeAdAlias(adkey) {

	var newadPolicy = new Object();
	var adPolicy = modAd.getAdPolicy();

	newadPolicy.adServerURL =  adPolicy.adServerURL;
	
	var re = /alias=(.*?);/;
	var str = "alias="+adkey+";";   
	
	newadPolicy.adServerURL = newadPolicy.adServerURL.replace(re, str);  
	newadPolicy.prerollAds = true;

	//debug("ACTION change Ad alias <b>"+ newadPolicy.adServerURL + "</b>");	
	modAd.setAdPolicy(newadPolicy);
} 

var fetchedId = null; //this allows me to store the id i'm fetching for use in the onTitleLoad function
	
function playBCVideo(titleId, stuffedId) {
	

	// are we a smart phone? 
	var thisIsSmartPhone = DetectSmartphone();	

	if (thisIsSmartPhone) {
		
		if (document.location.href.match(/inline/)) {
			var videoPageURL = "/skysports/video/inline/0,26691,stuffedid,00.html";		
		} else if (document.location.href.match(/parkgame/)) {
			var videoPageURL = "/skysports/parkgame/0,28581,stuffedid,00.html";		
		} else if (document.location.href.match(/rydercup/)) {
			var videoPageURL = "/skysports/golf/rydercup/video/0,28792,stuffedid,00.html";		
		} else if (document.location.href.match(/ashes/)) {
			var videoPageURL = "/skysports/cricket/ashes/video/0,26596,stuffedid,00.html";
		} else if (document.location.href.match(/teamsky/)) {
			var videoPageURL = "/teamsky/video/0,27287,stuffedid,00.html";		
		} else if (document.location.href.match(/Golf365/)) {
			var videoPageURL = "/Golf365/video/0,25680,stuffedid,00.html";	
		} else {
			var videoPageURL = "/skysports/video/clips/0,23791,stuffedid,00.html";		
		} 
		videoPageURL = videoPageURL.replace("stuffedid", stuffedId);
		
		if (!stuffedId) {
			// no id - just send to clips home
			//alert("no stuffedId, going home");
			return false;
			// window.location = videoPageURL;
		} else {
			
			// if the stuffedId has basketId_storyId and it's DIFFERENT to currStoryID (variable set on page) then we know 
			// it's a new video and we want to redirect.
			// if it's the SAME storyID, then we just want to play

			var match = stuffedId.match(/([0-9]+)_([0-9]+)/);
			if (match != null) {
				if (match[1] && match[2]) {
					// we have a storyID - check if it's the same as currStoryID
					if (currStoryID == match[2]) {
						//alert("same ID - we want to play this one");
					} else {
						//alert("different Story - about to redirect");
						window.location = videoPageURL;
					}
					return false;
				} else {
					//alert("we have basket " + match[1] + " only");
					return false; 
				}
			} else {
				// no match
				//alert("no match");
				return false;
			}  
			
			
		} 
		
	}
	
	
	var title_array=titleId.split("_");
	titleId = title_array[0];
	storyId = title_array[1];

	// Display the information box below player
	$("#video-detail").show();
	
	// remove sky player code
	destroySkyPlayer();
	
	$("#bc-container").show();
	//if player has been intialised load selected video
	if (titleId) {
		fetchedID = titleId;
		
		if (playerReady == 1) {
			if( modMP.isMenuPageShowing() ) {
				modMP.closeMenuPage();
			}
			
			modVP.loadVideo(titleId);
			$("#video-detail").show();
		}
	}
		
	loadAbstract(storyId); 	// pulls in the story infobelow the player
}
//// SKY PLAYER FUNCTIONS/////
function initSP(videoPath, hideSignInPage) {
	
	//stop currently playing BC video
	if (modVP) {
		modVP.stop();
	} 
	
	//hide BC player
	$("#bc-container").hide();
	$("#video-detail").hide();
	
	//intialise SkyPlayer with passed video URL
	__spHost = new SPHost();
	__spHost.hostId = 'SKYSPORTS';
	__spHost.brandName = 'Sky Sports';
	__spHost.placeHolder = document.getElementById('sp-container');
	__spHost.startPageUrl =  videoPath;
	__spHost.createSyndicatedPlayer();
}

function destroySkyPlayer() {
	$("#sp-container").empty();
}

function playSPVideo(videoPath) {
	
	//remove current skyplayer code
	destroySkyPlayer();

	//Re-initialise skyplayer code
	initSP(videoPath);
	
	return false;
}

/**
 * Copyright (C) 2005 Brightcove, Inc.  All Rights Reserved.  No
 * use, copying or distribution of this work may be made except in
 * accordance with a valid license agreement from Brightcove, Inc.
 * This notice must be included on all copies, modifications and
 * derivatives of this work.
 *
 * Brightcove, Inc MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT
 * THE SUITABILITY OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
 * NON-INFRINGEMENT. BRIGHTCOVE SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED
 * BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS
 * SOFTWARE OR ITS DERIVATIVES.
 *
 * "Brightcove" is a trademark of Brightcove, Inc.
 **/

/*********************************************** CONFIGURATION ************************************************/

/**
 * This is the API Token assigned to each Brightcove customer that allows for the use of Brightcove's Media Read API.
 * Fill in your read API token (there are two versions, but you want the one that includes URL responses) here.
 */
var BCReadAPIToken = "FKf2-UXI9EvFQmSk77uLPw5oVfIcmNUcDTXD9Cl_oRc.";

var videoPlayerWidth = "640";
var videoPlayerHeight = "360";

/**
 * This value indicates whether or not your account is set-up for UDS. HTML5 requires that the files be delivered
 * over HTTP.  This is accomplished by having an account that is configured for HTTP (PD) delivery or that is set-up
 * for UDS. 
 */
var isUDS = true;

/* This variable is a dictionary that contains information about the location of each
 * Brightcove video object within the DOM of the page. Specifically, it is an associative array
 * where, for each stored mapping, the keys is the playerID of a given video, and the value is
 * the next sibling of that video object in the DOM. Keeping track of this sibling will allow
 * us to re-insert the mobile compatible <video> tag into the correct place (before this sibling)
 * in the DOM of the original page.
 */
var pagePlacementInfo = new Object();

/**********************************************************************************************************************/
/*********************************************** DOM MODIFICATION CODE ************************************************/
/**********************************************************************************************************************/

/* This is the main entry function. It goes through the list of all video objects that need to be removed,
 * and one by one, initiates a request that causes that object to be removed and replaced by the
 * appropriate <video> tag (if the JS detects that the browser is on a smartphone).
 */
function runMobileCompatibilityScript(bcExperienceID, videoTagID){
	
	//detect if this is a smartphone or not
	var thisIsSmartPhone = DetectSmartphone();
	
	if (!thisIsSmartPhone) {
	    return;
	}
	makeMobileCompatible(bcExperienceID, videoTagID);
}

/* This method works on a specific object, represented by id "strObjID". The method retrieves the
 * element with the given ID from the DOM, and then extracts the player ID from the video
 * object. Then, it removes the video object from the page's DOM and stores its location in the page
 * in a global dictionary variable (this will be useful when we want to add the corresponding
 * video tag back in the page in the appropriate place).
 *
 * Finally, the method submits an API Read request to the Brightcove server through the initiateMobileVideoRetrieval()
 * method in order to retrieve the sepcific Video URL corresponding to the given object.
 */
function makeMobileCompatible(strObjID, videoTagID){
	//our video object (which we need to remove)
	var vidObj = document.getElementById(strObjID);
	
	//extract the playerID of this video object before deleting it
	var vidPlayerID = getParamValueForVidObject(vidObj, 'playerID');
	var programmedVideo = getParamValueForVidObject(vidObj, '@videoPlayer');
	
	videoPlayerWidth = getParamValueForVidObject(vidObj, 'width');
	videoPlayerHeight = getParamValueForVidObject(vidObj, 'height');

	//if the video player ID could not be extracted from the Source Code, for some reason,
	//then refer to the dictionary provided by the user
	if (vidPlayerID == null || typeof vidPlayerID == 'undefined'){
			vidPlayerID = BCVidObjects[strObjID];
	}

	//store the parent of the node we wish to remove
	var parentObj = vidObj.parentNode;
	
	//this is the object before which our vidObj element occurs in the parent element's DOM.
	//likewise, when we insert our <video> tag, we will insert it BEFORE this element,
	//in order to maintain the look of the page (this is the best that we can do...)
	var nextAdjacentNode = vidObj.nextSibling;
	
	//if there are no nodes after this node that was removed, then store 'null' to indicate that this was the last
	//child.
	if (nextAdjacentNode == null){
		pagePlacementInfo[""+strObjID] = null;
	}
	//otherwise store the next sibling
	else {
		pagePlacementInfo[""+strObjID] = nextAdjacentNode;	
	}
	
	//now, dynamically remove the video object from the DOM
	parentObj.removeChild(vidObj);

	//this procedure will make the appropriate API calls to get the first video corresponding to the player ID 
	//of the object we just removed.
	
	initiateMobileVideoRetrieval(vidPlayerID, programmedVideo, BCReadAPIToken, videoTagID, strObjID);
}


/** 
 * This function takes an object representing a Brigthcove video embed and a particular 'parameter' that was
 * passed to the Brightcove video object and returns the parameter.
 */
function getParamValueForVidObject(vidObj, paramName) {
	//these are the children nodes of the given object in the DOM
	var childrenNodes = vidObj.childNodes;
	var tagName;
	
	//loop through all children of the video object, searching for <param> tags.
	//each time we find a <param> tag, we check whether its name is 'flashVars'.
	//if so, we store the param's value and break from the loop, otherwise we
	//continue
	for (var i = 0; i < childrenNodes.length; i++){
	    if (childrenNodes[i].nodeType != 1) {
		continue;
	    }

	    tagName = childrenNodes[i].tagName.toLowerCase();
	    if (tagName == "param"){
		if (childrenNodes[i].getAttribute("name") == paramName){
		    return childrenNodes[i].getAttribute("value");
		}
	    }
	}

	return null;
}

/**
 * Takes a string 'str' that consists of multiple arguments separated by ampersands (&),
 * and breaks it down so that it can extract and return the paramName from the string.
 */
function parseParamFromString(str, paramName) {
	var params = str.split("&"); //array of strings
	for (var i = 0; i < params.length; i++){
		if (params[i].indexOf(paramName) != -1){
			return params[i].substr(params[i].indexOf("=")+1);
		}
	}
	
	// if we could not find the param then return null
	return null;
}



/**********************************************************************************************************************/
/****************************************** MEDIA API CALLS & VIDEO TAG INSERTION *************************************/
/**********************************************************************************************************************/

/* This method calls the Brightcove Media API to get all playlists included within a particular
 * playerID.
 */
function initiateMobileVideoRetrieval(playerID, programmedVideoID, readAPIToken, videoTagID, strObjID) {
    var APICall;
    var scriptNode;
    var scriptText;
    var callbackMethodName;

    if (programmedVideoID) {
		if (programmedVideoID.indexOf('ref:') != -1) {
		    APICall = "http://api.brightcove.com/services/library?command=find_video_by_reference_id&reference_id="+programmedVideoID.substring(4)+"&token="+readAPIToken;
		}
		else {
		    APICall = "http://api.brightcove.com/services/library?command=find_video_by_id&video_id="+programmedVideoID+"&token=" +readAPIToken;
		}
	
		//when we make the API call, we specify a response handler (known as a callback method) that will deal with the response from
		//the Brightcove server. However, we create a customized 'callback' method for each playerID, so that when we are 'inside' the
		//callback method (after receiving the server's reponse), we will know which playerID the response corresponds to. This variable
		//stores the name (which includes the playerID) of that callback method.
		
		callbackMethodName = "handleJSONResponseForID"+new Date().getTime();
		scriptNode = document.createElement("script");
		scriptNode.setAttribute("language", "javascript");
		scriptText = 
			"function "+callbackMethodName+"(JSONResponse){\n" + 
				"\thandleVideoResponse(JSONResponse, '"+playerID+"', '"+videoTagID+"', '"+strObjID+"');\n"+
			"}\n";
    }
    else {
		APICall = "http://api.brightcove.com/services/library?command=find_playlists_for_player_id&player_id="+playerID+"&token="+readAPIToken;
		callbackMethodName = "handleJSONResponseForID"+ new Date().getTime();
		scriptNode = document.createElement("script");
		scriptNode.setAttribute("language", "javascript");
		scriptText = 
			"function "+callbackMethodName+"(JSONResponse){\n" + 
				"\thandlePlaylistResponse(JSONResponse, '"+playerID+"', '"+videoTagID+"', '"+strObjID+"');\n"+
			"}\n";
    }

    if (isUDS) {
	APICall += "&media_delivery=http";
    }
	
	//NOTE: we add to the end of the body, so that we do not disrupt any of the order of the children
	//at the top of the body's DOM tree
	var scriptTextNode = document.createTextNode(scriptText);
	scriptNode.appendChild(scriptTextNode);
	document.body.appendChild(scriptNode);
	
	//make the API call, specifying the unique callback method for this request
	addScriptTag("getMobileRendition",  APICall, callbackMethodName);
}

/* Methods needed to make API Calls to the Brightcove server*/
function addScriptTag(id, url, callback) {
	var scriptTag = document.createElement("script");
	var noCacheIE = '&noCacheIE=' + (new Date()).getTime();
   
   // Add script object attributes
   scriptTag.setAttribute("type", "text/javascript");
   scriptTag.setAttribute("charset", "utf-8");
   scriptTag.setAttribute("src", url + "&callback=" + callback + noCacheIE);
   scriptTag.setAttribute("id", id);
	
	var head = document.getElementsByTagName("head").item(0);	
	head.appendChild(scriptTag);
}

/**
 * This is the general response-handler for the JSON response from the Brightcove server for playlist based players.
 * The arguments to the method include the response object, as well as the playerID of the 
 * object which this response pertains to.
 *
 */
function handlePlaylistResponse(JSONResponse, playerID, videoTagID, strObjID) {
	//obtain first playlist in Brightcove Player given corresponding to this playerID
	var firstPlaylist = JSONResponse.items[0];
	
	//obtain the first video from our first playlist
	var firstVideo = firstPlaylist.videos[0];

	embedHTML5PlayerForVideo(firstVideo, playerID, videoTagID, strObjID);
}

/**
 * This is the general response-handler for the JSON response from the Brightcove server for playlist based players.
 * The arguments to the method include the response object, as well as the playerID of the 
 * object which this response pertains to.
 *
 */
function handleVideoResponse(JSONResponse, playerID, videoTagID, strObjID) {
    embedHTML5PlayerForVideo(JSONResponse, playerID, videoTagID, strObjID);
}

/** 
 * For a given video object (from the BC APIs) we will embed an HTML 5 'video' tag.
 * Requires searching through the renditions associated with the video object
 * for a rendition that is a 'best' match and passing the URL to the video
 * tag.
 *
 * In this handler, we explore the JSON object in search of the first video in the
 * first playlist that is returned by the Brightcove server. Then, once we identify
 * this first video, we examine the various renditions of the video and search
 * for the rendition that is most appropriate for a mobile (H.264 encoding 
 * and 256 kbps). 
 */
function embedHTML5PlayerForVideo(video, playerID, videoTagID, strObjID) {
	//obtain the array of various renditions that exist for this video.
	//NOTE: a rendition, from our perspective, has a certain encoding rate,
	//      and a certain encoding format. We wish to find the best rendition for
	//      a smartphone.
	var renditions = video.renditions;
	
	//In the for-loop that follows, we traverse all renditions of this first video, searching
	//for the H.264 (mobile-compatible) rendition whose encoding rate is closest to 256kbps
	var bestRenditionIndex = -1;
	var bestEncodingRateSoFar = -1;
	
	for (var i = 0; i < renditions.length; i = i+1){
		//if this rendition is not H264, skip it and move on to the next
		if (renditions[i].videoCodec != "H264"){
			continue;
		}
		
		//if best rendition index variable is uninitialized, then initialize it to
		//this rendition (which is H.264) - we need this because it's possible that
		//there are no H264 renditions at all, and starting our bestRenditionIndex at
		//an invalid value will help us figure out whether we came across any H264 renditions
		//as we were looping.
		if (bestRenditionIndex == -1){
			bestRenditionIndex = i;
			bestEncodingRateSoFar = renditions[i].encodingRate;
		}
		
		//otherwise check to see if this rendition has a better encoding rate than the best one before this
		else if (betterEncodingForMobile(renditions[i].encodingRate, bestEncodingRateSoFar) == renditions[i].encodingRate){
			//if so, then record this rendition as the best one so far
			bestRenditionIndex = i;
			bestEncodingRateSoFar = renditions[i].encodingRate;
		}
	}
	
	//after the for-loop has terminated, if best rendition index still == -1,
	//then that means we don't have ANY H264 renditions. so let the user know,
	//and don't add anything to the page
	if (bestRenditionIndex == -1){
	    bestRendition = video.videoFullLength;
	}
	else {
		bestRendition = renditions[bestRenditionIndex];
	}


	var bestRenditionURL = bestRendition.url;
	

	var vidName = video.name;
	var vidHeight = bestRendition.frameHeight;
	var vidWidth = bestRendition.frameWidth;
	
	var vidHeight = videoPlayerHeight;
	var vidWidth = videoPlayerWidth;
	
	var vidStillURL = video.videoStillURL;
		
	//construct the <video> tag as a DOM element
	var videoScriptTag = formVideoTagFromInfo(videoTagID, vidName, bestRenditionURL, vidWidth, vidHeight, vidStillURL);
	
	//retrieve the component before which this video tag needs to be inserted
	var nextSiblingOfVideo = pagePlacementInfo[strObjID];
	var videoTagParent = nextSiblingOfVideo.parentNode; //the sibling and this video share the same parent node!
		
	//if 'nextSibling' value is null, then we want to add our video as the last child of the parent,
	//so we use the append() method; if 'nextSibling' is defined, then we use insertBefore() to add our video tag
	//into the appropriate location in our page.
	if (nextSiblingOfVideo == null){
		videoTagParent.appendChild(videoScriptTag);
	}
	else{
		videoTagParent.insertBefore(videoScriptTag, nextSiblingOfVideo);
	}
}

/* This function takes two encoding rates and returns the one that
 * is more apprporiate for mobile phones.
 */
function betterEncodingForMobile(encoding1, encoding2){
	IDEAL_ENCODING_RATE = 256000; //bits per second; equivalent to 256 kbps
	
	diff1 = Math.abs(encoding1 - IDEAL_ENCODING_RATE);
	diff2 = Math.abs(encoding2 - IDEAL_ENCODING_RATE);
	
	return ((diff1 <= diff2) ? encoding1 : encoding2);
}

/**
 * This method takes properties of a video, its dimensions, and its poster (still image),
 * inserts them into an HTML 5.0 <video> tag. This <video> object is then returned.
 */
function formVideoTagFromInfo(videoTagID, videoID, videoURL, vidWidth, vidHeight, vidImageURL){
	var videoTag = document.createElement("video");
	if (videoTagID) {
	    videoTag.setAttribute("id", videoTagID);
	}
	else {
	    videoTag.setAttribute("id", videoID);
	}
	videoTag.setAttribute("style", "position:relative; z-index:1;");
	videoTag.setAttribute("poster", vidImageURL);
	videoTag.setAttribute("width", vidWidth);
	videoTag.setAttribute("height", vidHeight);
	videoTag.setAttribute("controls", "true");
	videoTag.setAttribute("src", videoURL);
	
	return videoTag;
}


/**********************************************************************************************************************/
/****************************************** MOBILE BROWSER DETECTION CODE *********************************************/
/**********************************************************************************************************************/

// JavaScript Document

// Anthony Hand, ahand@hand-interactive.com
// Web: www.hand-interactive.com
// 
// License info: http://creativecommons.org/licenses/by/3.0/us/

//Initialize some initial string variables we'll look for later.
var deviceIphone = "iphone";
var deviceIPad = "ipad";
var deviceIpod = "ipod";
var devicePlaystation = "playstation";
var deviceWap = "wap";

var deviceWinMob = "windows ce";
var enginePie = "wm5 pie";
var deviceIeMob = "iemobile";

var deviceS60 = "series60";
var deviceSymbian = "symbian";
var deviceS60 = "series60";
var deviceS70 = "series70";
var deviceS80 = "series80";
var deviceS90 = "series90";

var deviceBB = "blackberry";

var deviceAndroid = "android";

var deviceMidp = "midp";
var deviceWml = "wml";
var deviceBrew = "brew";

var devicePalm = "palm";
var engineXiino = "xiino";
var engineBlazer = "blazer"; //Old Palm

var devicePda = "pda";
var deviceNintendoDs = "nitro";

var engineWebKit = "webkit";
var engineNetfront = "netfront";


var manuSonyEricsson = "sonyericsson";
var manuericsson = "ericsson";
var manuSamsung1 = "sec-sgh";

var svcDocomo = "docomo";
var svcKddi = "kddi";
var svcVodafone = "vodafone";

//Due to the flexibility of the S60 OSSO Browser, 
//   you may wish to let new S60 devices get the regular pages instead.
var s60GetsMobile = false;


//Due to the flexibility of the iPhone/iPod Touch Browser, 
//   you may wish to let new S60 devices get the regular pages instead.
var iphoneIpodGetsMobile = false;


//Initialize our user agent string.
var uagent = navigator.userAgent.toLowerCase();


//**************************
// Detects if the current device is an iPhone.
function DetectIphone()
{
   if (uagent.search(deviceIphone) > -1)
   {
      //The iPod touch says it's an iPhone! So let's disambiguate.
      if (uagent.search(deviceIpod) > -1)
         return false;
      else 
         return true;
   }
   else
      return false;
}

//**************************
// Detects if the current device is an iPhone.
function DetectIPad()
{
	if (uagent.search(deviceIPad) > -1) {
	return true;       
	} else {
	return false;
	}
}

//**************************
// Detects if the current device is an iPod Touch.
function DetectIpod()
{
   if (uagent.search(deviceIpod) > -1)
      return true;
   else
      return false;
}

//**************************
// Detects if the current device is an iPhone or iPod Touch.
function DetectIphoneOrIpodOrIPad()
{
   //We repeat the searches here because some iPods 
   //  may report themselves as an iPhone, which is ok.
   if (uagent.search(deviceIphone) > -1 ||
       uagent.search(deviceIpod) > -1 ||
       uagent.search(deviceIPad) > -1)

       return true;
    else
       return false;
}

//**************************
// Detects if the current device is an Android OS-based device.
function DetectAndroid()
{
   if (uagent.search(deviceAndroid) > -1)
      return true;
   else
      return false;
}


//**************************
// Detects if the current device is an Android OS-based device and
//   the browser is based on WebKit.
function DetectAndroidWebKit()
{
   if (DetectAndroid())
   {
     if (DetectWebkit())
        return true;
     else
        return false;
   }
   else
      return false;
}

//**************************
// Detects if the current browser is based on WebKit.
function DetectWebkit()
{
   if (uagent.search(engineWebKit) > -1)
      return true;
   else
      return false;
}

//**************************
// Detects if the current browser is the Nokia S60 Open Source Browser.
function DetectS60OssBrowser()
{
   if (DetectWebkit())
   {
     if ((uagent.search(deviceS60) > -1 || 
          uagent.search(deviceSymbian) > -1))
        return true;
     else
        return false;
   }
   else
      return false;
}

//**************************
// Detects if the current device is any Symbian OS-based device,
//   including older S60, Series 70, Series 80, Series 90, and UIQ, 
//   or other browsers running on these devices.
function DetectSymbianOS()
{
   if (uagent.search(deviceSymbian) > -1 ||
       uagent.search(deviceS60) > -1 ||
       uagent.search(deviceS70) > -1 ||
       uagent.search(deviceS80) > -1 ||
       uagent.search(deviceS90) > -1)
      return true;
   else
      return false;
}


//**************************
// Detects if the current browser is a BlackBerry of some sort.
function DetectBlackBerry()
{
   if (uagent.search(deviceBB) > -1)
      return true;
   else
      return false;
}

//**************************
// Detects if the current browser is a Windows Mobile device.
function DetectWindowsMobile()
{
   //Most devices use 'Windows CE', but some report 'iemobile' 
   //  and some older ones report as 'PIE' for Pocket IE. 
   if (uagent.search(deviceWinMob) > -1 ||
       uagent.search(deviceIeMob) > -1 ||
       uagent.search(enginePie) > -1)
      return true;
   else
      return false;
}

//**************************
// Detects if the current browser is on a PalmOS device.
function DetectPalmOS()
{
   //Most devices nowadays report as 'Palm', 
   //  but some older ones reported as Blazer or Xiino.
   if (uagent.search(devicePalm) > -1 ||
       uagent.search(engineBlazer) > -1 ||
       uagent.search(engineXiino) > -1)
      return true;
   else
      return false;
}

//**************************
// Sets whether S60 devices running the 
//   Open Source Browser (based on WebKit)
//   should be detected as 'mobile' or not.
//   Set TRUE to be detected as mobile.
//   Set FALSE and it will not be detected as mobile.
function SetS60GetsMobile(setMobile)
{
   s60GetsMobile = setMobile;
};

//**************************
// Sets whether iPhone/iPod Touch devices running the 
//   Open Source Browser (based on WebKit)
//   should be detected as 'mobile' or not.
//   Set TRUE to be detected as mobile.
//   Set FALSE and it will not be detected as mobile.
function SetS60GetsMobile(setMobile)
{
   iphoneIpodGetsMobile = setMobile;
};


//**************************
// Check to see whether the device is a 'smartphone'.
//   You might wish to send smartphones to a more capable web page
//   than a dumbed down WAP page. 
function DetectSmartphone()
{
   //First, look for iPhone and iPod Touch.
   if (DetectIphoneOrIpodOrIPad())
      return true;

   //Now, look for S60 Open Source Browser on S60 release 3 devices.
   if (DetectS60OssBrowser())
      return true;

   //Check for other Symbian devices - older S60, UIQ, other.
   if (DetectSymbianOS())
      return true;

   //Check for Windows Mobile devices.
   if (DetectWindowsMobile())
      return true;

   //Next, look for a BlackBerry
   if (DetectBlackBerry())
      return true;

   //PalmOS.
   if (DetectPalmOS())
      return true;

   //Otherwise, return false.
   return false;
};


//**************************
// Detects if the current device is a mobile device.
//  This method catches most of the popular modern devices.
function DetectMobileQuick()
{
   //Attempt to detect most mobile devices, 
   //   especially mass market feature phones.
   // NOTE: Doesn't usually work reliably...
   if (uagent.search(deviceWap) > -1   || 
	uagent.search(deviceMidp) > -1 ||
	uagent.search(deviceWml) > -1  ||
	uagent.search(deviceBrew) > -1  )
   {
      return true;
   }

   //Detect for most smartphones.
   if (DetectSmartphone())
      return true;

   //Check for a NetFront browser
   if (uagent.search(engineNetfront) > -1)
      return true;

   //Check for a Playstation
   if (uagent.search(devicePlaystation) > -1)
      return true;

   //Check for a generic PDA
   if (uagent.search(devicePda) > -1)
      return true;

   return false;
};


//**************************
// Detects in a more comprehensive way if the current device is a mobile device.
function DetectMobileLonger()
{
   //Run the quick check first.
   if (DetectMobileQuick())
      return true;

   //Check for NTT Docomo
   if (uagent.search(svcDocomo) > -1)
      return true;

   //Check for KDDI
   if (uagent.search(svcKddi) > -1)
      return true;

   //Check for Nintendo DS
   if (uagent.search(deviceNintendoDs) > -1)
      return true;

   //Check for Vodafone 3G
   if (uagent.search(svcVodafone) > -1)
      return true;

   //Finally, detect for certain very old devices with stupid useragent strings.
   if (uagent.search(manuSamsung1) > -1 ||
	uagent.search(manuSonyEricsson) > -1 || 
	uagent.search(manuericsson) > -1)
   {
      return true;
   }

   return false;
};


	/***************************************
	 Playlist funcs
**************************************/

Array.prototype.refresh=function() {

	var playlistClearHTML = "";
	var thePlaylistHTML = "";

	//re-paint the playlist on the page
	if ($("#vid-playlist")) {

		//re-add the clips in the current order
		if (this.length>0) {
		
			for (var p = 0;p< this.length;p++) {
			
				var pImg = this[p].getImg();
				var pAbs = this[p].getAbstr();
				var pDate = this[p].getPubdate();
				var pSid = this[p].getSid();
				var pTitle = this[p].getTitle();
				
				var pPlayLink = " href=\"javascript:;\" onclick=\"javascript:myPlaylist.playClip(" + p + "); return false;\" title=\"" + pTitle + "\"";
				var pRemoveLink = " href=\"javascript:;\" onclick=\"javascript:myPlaylist.removeClip(" + p + "); return false;\" title=\"Remove from playlist\"";
										
					
					thePlaylistHTML += "<div class=\"pr-playlist-clip no-bdr\">";
					if(pImg) {
					thePlaylistHTML += "<a "+ pPlayLink +"><img src=\"" + pImg + "\" alt=\"" + pTitle + "\" title=\"" + pTitle + "\" /></a>";
					}
					thePlaylistHTML += "<h3><a "+ pPlayLink +">"+ pTitle +"</a></h3>";
					
					thePlaylistHTML += "<ul class=\"pr-playlist-clip-btns\">";
					thePlaylistHTML += "<li><a "+ pPlayLink +"><img src=\"/Images/PlanetRugby/Icons/pr-clip-btns-watch.gif\" alt=\"Watch Now\" title=\"Watch Now\" /> Watch Now</a></li>";
					thePlaylistHTML += "<li><a "+ pRemoveLink +"><img src=\"/Images/PlanetRugby/Icons/pr-clip-btns-remove.gif\" alt=\"Remove from playlist\" title=\"Remove from playlist\" /> Remove</a></li>";
					thePlaylistHTML += "</ul>";
					thePlaylistHTML += "</div>";
					
					thePlaylistHTML += '<input type="hidden" id="clipAbstract' + pSid + '" value="' + pAbs.escapeHTML() + '" />';
					thePlaylistHTML += '<input type="hidden" id="clipDate' + pSid + '" value="' + pDate + '" />';
					thePlaylistHTML += '<input type="hidden" id="clipTitle' + pSid  + '" value="' + pTitle + '" />';
				 }
			playlistClearHTML = "<div class=\"clear-playlist\"><a href=\"javascript:;\" onclick=\"javascript:myPlaylist.clear(); return false;\"><img src=\"/Images/PlanetRugby/Icons/pr-clip-btns-clear.gif\" />Clear playlist</a></div>";

		} else {
			thePlaylistHTML = "<p>Click the plus sign to add clips to your playlist.</p>";
		}

			
			thePlaylistHTML = "<div class=\"pr-tabs-container-scroll\">" + playlistClearHTML + "" + thePlaylistHTML + "</div>";
		 $("#vid-playlist").empty();
		$("#vid-playlist").append(thePlaylistHTML);

	}
}

Array.prototype.save=function() {
		//save the playlist to a session cookie
		var thePlaylistCookieText = '';

		for (var p = 0;p< this.length;p++) {
			//get the clipObject and save its contents to a string to save in the cookie
			if (p < 10) {
			thePlaylistCookieText += "this.push(new Clip(unescape(\"" +
			escape(this[p].getTitle()) + "\"),unescape(\"" +
			escape(this[p].getAbstr()) + "\"),\"" +
			this[p].getPubdate() + "\",\"" +
			this[p].getCid() + "\",\"" +
			this[p].getSid() + "\",\"" +
			this[p].getImg() + "\"));|";
			}
		}
		SetCookie('planetrugby_video_playlist',thePlaylistCookieText);
}

Array.prototype.load=function(cookietext) {
	
	//load the playlist from the session cookie
	var myPlaylistTextAry = cookietext.split("|");
	if (myPlaylistTextAry.length>0) {
		for (var p = 0;p< myPlaylistTextAry.length;p++) {
			if (myPlaylistTextAry[p]) {
				eval(myPlaylistTextAry[p]);
			}
		}
		myPlaylist.refresh();
	}
}

Array.prototype.addClip=function(cId,sId,src) {
	
	
	var cAbstract = $("#clipAbstract"+sId).val();
	var cTitle = $("#clipTitle"+sId).val();
	var cDate = $("#clipDate"+sId).val();
	var cImg = $("#clipImage"+sId).val();   
	
	//Create a clip object on the fly and add it to the playlist array
	this.push(new Clip(cTitle, cAbstract, cDate, cId, sId, cImg));
	
	this.refresh();
	this.save();
	
	//if the list is now of size 1, there will be no onComplete event for the current video
	//so add one now
	
	if (this.length==1) {
		onMediaComplete = function() {myPlaylist.playClip(0)}
		modVP.addEventListener(BCVideoEvent.VIDEO_COMPLETE, onMediaComplete);
	}
	
}
Array.prototype.removeClip=function(i) {
	//removes a clip from the playlist array

	this.splice(i,1);
	this.refresh();	
	this.save();
}

Array.prototype.clear=function(i) {
	//removes all clips from the playlist array
	if (this.length>1) {
		modVP.removeEventListener(BCVideoEvent.VIDEO_COMPLETE, onMediaComplete);
	}
	this.splice(i,this.length);
	this.refresh();	
	this.save();
	
}
	
Array.prototype.playClip=function(i) {
	//plays a clip at index i from the playlist array
	//defaults to the 'next' clip
	
	if (this.length > 0) {

		if (!i) i=0;
		
		var clipTitle = this[i].getTitle();
		var clipId = this[i].getCid();
		var Sid = this[i].getSid();
		var clipPubdate = this[i].getPubdate();	
		var clipAbstract = this[i].getAbstr();
		
		modVP.loadVideo(clipId);
		
		fetchedId = clipId; //stores the titleId in a global variable so that i can use it in the onTitleLoad function
		
		this.removeClip(i);		
		
		if (this.length > i+1) {
			//as we have just removed this clip, the index stays the same
			var nextClip = i;
		} else if (this.length > 0) {
			//wrap round to the start of the list
			var nextClip = 0;
		} else {
			var nextClip = -1
		}	
		
		if (nextClip > -1) {
			modVP.removeEventListener(BCVideoEvent.VIDEO_COMPLETE, onMediaComplete); 
			
			onMediaComplete = function() {myPlaylist.playClip(nextClip)}
			modVP.addEventListener(BCVideoEvent.VIDEO_COMPLETE, onMediaComplete); 		
		} else {
			//no more clips in the playlist, remove the event listener
			modVP.removeEventListener(BCVideoEvent.VIDEO_COMPLETE, onMediaComplete); 
		}
	
		//do this after the call to act more as a companion...
		if (document.getElementById("liveBANFrame")) document.getElementById("liveBANFrame").src = bannerIFRAME;
	
		loadAbstract(Sid, '');
	}

}
Array.prototype.moveClipUp=function() {
	//moves a selected clip up/forward in the list. tbc
}
Array.prototype.moveClipDown=function() {
	//moves a selected clip down/backwards in the list. tbc
}

/***************************************
	 Clip funcs
**************************************/

function Clip(cTitle, cAbstract, cDate, cId, sId, cImg) {
	this.title = cTitle;	
	this.abstract = cAbstract;	
	this.pubdate = cDate;	
	this.cid = cId;
	this.sid = sId;
	this.img = cImg
	
	this.getTitle = function () { return this.title; }
	this.getAbstr = function () { return this.abstract; }
	this.getPubdate = function () { return this.pubdate; }
	this.getCid = function () { return this.cid; }
	this.getSid = function () { return this.sid; }
	this.getImg = function () { return this.img; }
}

function clearRelatedClips() {
	$("#nextup").html('');
}

<!--

//
// "Internal" function to return the decoded value of a cookie
//
function getCookieVal (offset) {
  var endstr = document.cookie.indexOf (";", offset);
  if (endstr == -1)
    endstr = document.cookie.length;
  return unescape(document.cookie.substring(offset, endstr));
}
//
//  Function to correct for 2.x Mac date bug.  Call this function to
//  fix a date object prior to passing it to SetCookie.
//  IMPORTANT:  This function should only be called *once* for
//  any given date object!  See example at the end of this document.
//
function FixCookieDate (date) {
  var base = new Date(0);
  var skew = base.getTime(); // dawn of (Unix) time - should be 0
  if (skew > 0)  // Except on the Mac - ahead of its time
    date.setTime (date.getTime() - skew);
}
//
//  Function to return the value of the cookie specified by "name".
//    name - String object containing the cookie name.
//    returns - String object containing the cookie value, or null if
//      the cookie does not exist.
//
function GetCookie (name) {
  var arg = name + "=";
  var alen = arg.length;
  var clen = document.cookie.length;
  var i = 0;
  while (i < clen) {
    var j = i + alen;
    if (document.cookie.substring(i, j) == arg)
      return getCookieVal (j);
    i = document.cookie.indexOf(" ", i) + 1;
    if (i == 0) break; 
  }
  return null;
}
//
//  Function to create or update a cookie.
//    name - String object containing the cookie name.
//    value - String object containing the cookie value.  May contain
//      any valid string characters.
//    <expires> - Date object containing the expiration data of the cookie.  If
//      omitted or null, expires the cookie at the end of the current session.
//    <path> - String object indicating the path for which the cookie is valid.
//      If omitted or null, uses the path of the calling document.
//    <domain> - String object indicating the domain for which the cookie is
//      valid.  If omitted or null, uses the domain of the calling document.
//    <secure> - Boolean (true/false) value indicating whether cookie transmission
//      requires a secure channel (HTTPS).  
//
//  The first two parameters are required.  The others, if supplied, must
//  be passed in the order listed above.  To omit an unused optional field,
//  use null as a place holder.  For example, to call SetCookie using name,
//  value and path, you would code:
//
//      SetCookie ("myCookieName", "myCookieValue", null, "/");
//
//  Note that trailing omitted parameters do not require a placeholder.
//
//  To set a secure cookie for path "/myPath", that expires after the
//  current session, you might code:
//
//      SetCookie (myCookieVar, cookieValueVar, null, "/myPath", null, true);
//
function SetCookie (name,value,expires,path,domain,secure) {
  document.cookie = name + "=" + escape (value) +
    ((expires) ? "; expires=" + expires.toGMTString() : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    ((secure) ? "; secure" : "");
}

//  Function to delete a cookie. (Sets expiration date to start of epoch)
//    name -   String object containing the cookie name
//    path -   String object containing the path of the cookie to delete.  This MUST
//             be the same as the path used to create the cookie, or null/omitted if
//             no path was specified when creating the cookie.
//    domain - String object containing the domain of the cookie to delete.  This MUST
//             be the same as the domain used to create the cookie, or null/omitted if
//             no domain was specified when creating the cookie.
//
function DeleteCookie (name,path,domain) {
  if (GetCookie(name)) {
    document.cookie = name + "=" +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}


// -->

