 var AJAX_Pulling = false; 
var playerReady = 0;
var newPlayer = "";
var autoUpdateStory = "1806217383";
var numVids = 8;
var currentPlayer;
var fetchedID = 0;

function loadBasket(vidBasketID, thisPageNum, offset) {

	var myPageNum = thisPageNum;
	var paginationHTML ="";  
	var outputHTML ="";  

	$("#video-list").empty(); 
	$("#video-list").html('<div class="v-box-lineups"><span class="ajax-loading"><img src="/Images/skysports/site/loadingAnimation.gif"></span></div>');
	
	
	var loadBasketURL = "/video/skysports_video_load_basket/0,20287,thisisnotanoid_thisisnotapagenum_thisisnotavidnum_thisisnotanoffset,00.xml";
	
	if (typeof vidBasketID == "undefined") {vidBasketID = 12602;}
	if (typeof myPageNum == "undefined") {myPageNum = 1;}
	if (typeof offset == "undefined") {offset = 0;}
 
	loadBasketURL = loadBasketURL.replace("thisisnotanoid", vidBasketID);
	loadBasketURL = loadBasketURL.replace("thisisnotapagenum", myPageNum);
	loadBasketURL = loadBasketURL.replace("thisisnotavidnum", numVids);
	loadBasketURL = loadBasketURL.replace("thisisnotanoffset", offset);
	
	//alert(loadBasketURL +""+ offset);
	
	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) {	
	
				$('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 cExpDate = $(this).attr("expiryDate");
					var cExp = $(this).attr("expiry");		
					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");
					cThumb = cThumb.replace('68x60','128x67');
					
					var cOrigin = $(this).attr("origin");
					
					var videoPageURL= "/video/clips/0,23791,thisisnotthebasketid_thisisnotthestoryid,00.html";
					videoPageURL = videoPageURL.replace("thisisnotthebasketid", vidBasketID);
					videoPageURL = videoPageURL.replace("thisisnotthestoryid", cStoryID);
					
					var cExpText = "";

					if (cOrigin == "skyplayer") {
						var cAction = "playSPVideo('"+ cVidPath +"')"
						var cLinkText = "Watch on Sky Player";
						if (cExpDate!="") {
							cExpText =  "<br><em>until " +cExpDate+ "</em>";
						}
						var cLinkClass = "v-link-skyplayer";
					} else {
						var cAction = "playBCVideo('"+ cID +"')"
						var cLinkText = "Watch now";
						var cLinkClass = "v-link-watch";
					}
					
					var cLinktag = " href=\"#\" onclick=\"javascript: "+ cAction +"; return false;\" "
					
					if (home == 1) {
						var cLinktag = " href=\""+ videoPageURL +"\"";
					}

					var cPlaylistTag = " href=\"#\" "
					
					outputHTML += "<div class=\"v-box\" clipid=\""+ cStoryID +"\" expiry=\""+ cExp +"\" action=\""+ cAction +"\">";
					outputHTML += "<a "+ cLinktag +" title=\""+ cTitle +"\" class=\"v-box-rollover\">";
					outputHTML += "<span><span>"+cLinkText+""+cExpText+"</span>";
					outputHTML += "<img src=\""+ cThumb +"\" alt=\""+ cTitle +"\" /></span>";
					outputHTML += "<p class=\"ss-text-caption\">"+ cDate +"</p>";
					outputHTML += "<h4 title=\""+ cAbstract +"\">"+ cTitle +"</h4>";
					outputHTML += "</a>";
        			outputHTML += "<ul>";
					outputHTML += "<li class=\""+ cLinkClass +"\"><a "+ cLinktag +"  >"+ cLinkText +"</a></li>";
    				outputHTML += "<li class=\"v-link-playlist\"><a "+ cPlaylistTag +"  >Add to my clips</a></li>";
					outputHTML += "</ul></div>";
				});	 

				 
			} else {
				outputHTML = "<div class='v-box-lineups'><span class='ajax-loading'>There are currently no video clips in '"+ basketName +"'</span></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) {     
				paginationHTML += "<li class='pag-key'>Page <span>"+pCurrent+"</span> of "+pTotal+"</li>";
			
				if (thisPageNum != 1) {
				 	//paginationHTML += "<li><a href=\"javascript:;\" onclick=\"javascript:loadBasket('"+ vidBasketID + "', '1', '"+offset+"'); return false;\" title=\"Go to First Page\">&laquo; First</a><li>";
				}
				if (pCurrent > 1) {
				 	//paginationHTML += "<li><a href=\"javascript:;\" onclick=\"javascript:loadBasket('"+ vidBasketID + "', '" + (eval(pCurrent)-1, '"+offset+"') + "'); return false;\" title=\"Go to Previous Page\">&laquo; Prev</a><li>";
				} 
				   
				$('page',xmlData).each(function(i) {
					var pNumber = $(this).attr("pageNumber");
					var pIsCurrent = $(this).attr("isCurrent");
					var pLink = " href=\"javascript:;\" onclick=\"javascript:loadBasket('"+ vidBasketID +"', '"+ pNumber +"', '"+offset+"'); return false;\" title=\"Page "+ pNumber +"\"";
					
					if(pIsCurrent == 1) {
						paginationHTML += "<li class='on'><a "+ pLink +">"+ pNumber +"</a></li>";
					} else {
						paginationHTML += "<li><a "+ pLink +">"+ pNumber +"</a></li>";
					}
				}); 

				if (eval(pCurrent)+1 <= pTotal) {
					//paginationHTML += "<li><a href=\"javascript:;\" onclick=\"javascript:loadBasket('"+ vidBasketID + "', '" + (eval(pCurrent)+1) + "', '"+offset+"'); return false;\" title=\"Go to Next Page\" class=\"pag-next\" >Next</a></li>";
				}
				if (pCurrent != pTotal) {
					//paginationHTML += "<li><a href=\"javascript:;\" onclick=\"javascript:loadBasket('"+ vidBasketID + "', '" + pTotal + "', '"+offset+"'); return false;\" title=\"Go to Last Page\" >Last &raquo;</a></li>";
				}	
			}   
			outputHTML += "<ul class='pagination'>" + paginationHTML + "</ul>";

			$("#video-list").html(outputHTML);
			SKYVID.playlist();
		}, "xml");
		
		AJAX_Pulling = false;
		
		//Turn off sub nav highlights
		$(".v-clips-nav li").removeClass("on");
		
		//Turn on current sub nav basket highlight
		$("#smitem-"+vidBasketID).addClass("on");
	}
}  

function loadTab(tabBasketID, forceBasketID, offset) {
	//hide all submenus
	$("#v-clips .v-clips-nav").addClass("js-hdn");
	
	if ($("#sm-"+tabBasketID).html()) {
		//if tab has submenu, show menu limit to 6 clips
		$("#sm-"+tabBasketID).removeClass("js-hdn");
		numVids = 6;
	} else {
		//no menu fill with 8 clips
		numVids = 8;
	}
	ssvPage = 1;
	
	if (forceBasketID == 0) {
		loadBasket(tabBasketID, ssvPage,  offset); 
	} else {
		loadBasket(forceBasketID, ssvPage, offset);
	}
}

// didn't want to break calls to loadLatest, but want an extra param to force a player refresh on 1st load
function loadLatest(vidBasketID) {
	loadLatestWithRefresh(vidBasketID, false);
}

function loadLatestWithRefresh(vidBasketID, forcePlayerRefresh) {

	var myPageNum = 1;
	var paginationHTML ="";  
	var outputHTML ="";  
	var numVids = 4;
	$("#v-lineup .v-box-lineups").empty(); 
	$("#v-lineup .v-box-lineups").html('<span class="ajax-loading"><img src="/Images/skysports/site/loadingAnimation.gif"></span>'); 
	
	var loadBasketURL = "/video/skysports_video_load_basket/0,20287,thisisnotanoid_thisisnotapagenum_thisisnotavidnum,00.xml";
	
	if (typeof vidBasketID == "undefined") {vidBasketID = 12602;}
	if (typeof myPageNum == "undefined") {myPageNum = 1;}
	if (typeof numVids == "undefined") {numVids = 4;}
 
	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");
			var parentID = $(xmlData).find('clipList').attr("parentBasket");
			 
			if (vLength > 0) {	
	
				$('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 cExpDate = $(this).attr("expiryDate");
					var cExp = $(this).attr("expiry");		
					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");
					cThumb = cThumb.replace('128x67','60x54');
					var cOrigin = $(this).attr("origin");
					
					var videoPageURL= "/video/clips/0,23791,thisisnotthebasketid_thisisnotthestoryid,00.html";
					videoPageURL = videoPageURL.replace("thisisnotthebasketid", vidBasketID);
					videoPageURL = videoPageURL.replace("thisisnotthestoryid", cStoryID);

					if (cOrigin == "skyplayer") {
						var cAction = "playSPVideo('"+ cVidPath +"')"
						var cLinkText = "Watch on Sky Player";
						if (cExpDate!="") {
							var cExpText = "<br><em>until " +cExpDate+ "</em>";
						}
						var cLinkClass = "v-link-skyplayer";
					} else {
						var cAction = "playBCVideo('"+ cID +"')"
						var cLinkText = "Watch now";
						var cLinkClass = "v-link-watch";
					}
					
					if( typeof(contentAlreadyLoaded) == 'undefined' ) {
						contentAlreadyLoaded = false;
					}
					
					if(!contentAlreadyLoaded && forcePlayerRefresh && i==1) {
						if(cOrigin == 'skyplayer' ) {
							playSPVideo( cVidPath );
						} else {
							playBCVideo( cID );
						}
					}
					
					var cLinktag = " href=\"#\" onclick=\"javascript: "+ cAction +"; return false;\" "
					
					if (home == 1) {
						var cLinktag = " href=\""+ videoPageURL +"\"";
					}

					var cPlaylistTag = " href=\"#\" "
					
					outputHTML += "<div class=\"v-box\" clipid=\""+ cStoryID +"\" expiry=\""+ cExp +"\" action=\""+ cAction +"\">";
					outputHTML += "<a "+ cLinktag +" title=\""+ cTitle +"\" class=\"v-box-rollover\">";
					outputHTML += "<span><span>"+cLinkText+" "+cExpText+"</span>";
					outputHTML += "<img src=\""+ cThumb +"\" alt=\""+ cTitle +"\" /></span>";
					outputHTML += "<p class=\"ss-text-caption\">"+ cDate +"</p>";
					outputHTML += "<h4 title=\""+ cAbstract +"\">"+ cTitle +"</h4>";
					outputHTML += "</a>";
        			outputHTML += "<ul>";
					outputHTML += "<li class=\""+ cLinkClass +"\"><a "+ cLinktag +"  >"+ cLinkText +"</a></li>";
    				outputHTML += "<li class=\"v-link-playlist\"><a "+ cPlaylistTag +"  >Add to my clips</a></li>";
					outputHTML += "</ul></div>";
				});	 
				
				$("#v-lineup .v-box-lineups").html(outputHTML);
				

				if (parentID.toString().match(/13312/)) {
					basketName = 'Latest Soccer AM Videos';
				} else if (parentID.toString().match(/13861/)) {
					basketName = 'Latest Fanzone Videos';
				} else if (vidBasketID != 12602) {
					basketName = basketName.replace('Premiership','Prem');
					basketName = 'Latest '+ basketName +' Videos';
				} 
				
				$("#v-lineup-desc").html(basketName);

				SKYVID.playlist();

				 
			} else {
				outputHTML = "<span class='ajax-loading'>There are currently no video clips in '"+ basketName +"'</span>"
				loadLatestWithRefresh(parentID, true);
			}
		}, "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*$/, '');
}

function msToDisplayTime(ms) {
	if (ms) {
		var x = ms / 1000;
		
		var seconds = x % 60;
		seconds = Math.ceil(seconds);
		seconds = pad(seconds, 2)
		
		x /= 60;
		var minutes = x % 60;
		minutes = Math.floor(minutes);		
		
		return ""+minutes+":"+seconds+"";
		//alert(displayTime);
	} else {
		return ""
	}
}

function pad(numNumber, numLength){     
	var strString = '' + numNumber;     
	while(strString.length < numLength){
	         strString = '0' + strString;     
	}     

	return strString; 
} 

function formatDate(myDate) {

	var d = myDate;
	var curr_date = d.getDate();
	var m_names = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
	var sup = "";
	
	if (curr_date == 1 || curr_date == 21 || curr_date ==31) {
	   sup = "st";
	} else if (curr_date == 2 || curr_date == 22) {
	   sup = "nd";
	} else if (curr_date == 3 || curr_date == 23) {
	   sup = "rd";
	} else {
	   sup = "th";
	}
	
	var curr_month = d.getMonth();
	var curr_year = d.getFullYear();
	
	var myFormattedDate = ""+curr_date + "" + sup + " " + m_names[curr_month] + " " + curr_year+ "";
	return myFormattedDate;
}

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

function onTemplateLoaded(experienceID) {
    //alert("EVENT: TEMPLATE_LOAD");
  
    bcExp = brightcove.getExperience(experienceID);
	
    //created references to API Modules
    modVP = bcExp.getModule(APIModules.VIDEO_PLAYER);
    modExp = bcExp.getModule(APIModules.EXPERIENCE);
    modCon = bcExp.getModule(APIModules.CONTENT);
	modAd = bcExp.getModule(APIModules.ADVERTISING);
  	modMP = bcExp.getModule(APIModules.MENU);

	//Attach intial listeners to modules
    modExp.addEventListener(BCExperienceEvent.TEMPLATE_READY, onTemplateReady);
    modExp.addEventListener(BCExperienceEvent.CONTENT_LOAD, onContentLoad);
    modCon.addEventListener(BCContentEvent.VIDEO_LOAD, onVideoLoad); 
	 
	modVP.addEventListener(BCMediaEvent.BEGIN, onVideoBegin); 
	modAd.addEventListener(BCAdvertisingEvent.AD_START, onAdvertBegin);
}

function onTemplateReady(evt) {
	// When the video player first intialises, set player ready
	playerReady = 1;
}

function onContentLoad(evt) {
	// When the video player content loads get the loaded video or last fetched if not first time

	var vID;
	if (fetchedID == 0) {
		var currentVideo = modVP.getCurrentVideo();
		vID = currentVideo.id;
	} else {
		vID = fetchedID;
	}

	modCon.getVideoAsynch(vID);
}
		
function onVideoLoad(evt) {
    // When the video is loaded, play the video
    modVP.loadVideo(evt.video.id);
}

function onVideoBegin(evt) {
   // When Video starts playback load video detail
   
   	if (evt.media.id == autoUpdateStory) {
		// The latest report needs to use todays date rather the publsh date
   		var myDate = new Date();
	} else {
		var myDate = evt.media.publishedDate;
	}
	
	// Format the dates into the needed format
	var displayDate = formatDate(myDate);
	var displayTime  = msToDisplayTime(evt.media.length);
	
	// Send the info collected to fucntion to write video info into space below player
	updateVideoDetail(evt.media.displayName, evt.media.shortDescription, displayDate, displayTime);
}

function updateVideoDetail(title, abs, vidDate, vidTime) {
	
	
	var outputHTML = '';
	outputHTML += "<h4>" + title.escapeHTML() + " <em>("+vidTime +")</em> </h4>";
	outputHTML += "<p class='ss-text-caption'>" + vidDate.escapeHTML() + "</p>";
	outputHTML += "<p>" + abs.escapeHTML() + "</p>"

	$("#player-detail").html(outputHTML);
}
	
function onAdvertBegin(evt) {
	// When an advert begins playback write holding message into area below player
	updateAdvertDetail();
}

function updateAdvertDetail() {
	// triggered when advert begins playback, write holding message
	$("#player-detail").html('<p class="v-player-ad">Advertisement</p>');
}	

function playBCVideo(titleId) {
	// Display the information box below player
	$("#player-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();
			}
			
			modCon.getVideoAsynch(titleId);
			$("#video-detail").show();
		}
	}
	
}

//// SKY PLAYER FUNCTIONS/////
function initSP(videoPath) {
	//stop currently playing BC video
	if (modVP) {
		modVP.stop();
	}
	
	//hide BC player
	$("#bc-container").hide();
	$("#player-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();
	
	//Set current player to SP to we can check whether to destroy it
	currentPlayer = "SP";
}

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

function playSPVideo(videoPath) {
	
	//remove current skyplayer code
	destroySkyPlayer();
	
	if (currentPlayer == "SP") {
		//if SkyPlayer has already been created just play selected video
		//__spHost.play(videoPath);
	} else {
		//Re-initialise skyplayer code
		//initSP(videoPath);
	}
	
	//Re-initialise skyplayer code
	initSP(videoPath);
	
	currentPlayer == "SP";
	return false;
}