<!--

//
// "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";
  }
}


// -->


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

Array.prototype.refresh=function() {

	//re-paint the playlist on the page
	if (document.getElementById('playlist')) {
		
		//re-add the clips in the current order
		var thePlaylistHTML = '';
		if (this.length>0) {
		
			$('#cliptabs2 a span').text('My Playlist (' + myPlaylist.length + ')');
		
			for (var p = 0;p< this.length;p++) {
				thePlaylistHTML += '<div class="playlist-clip">';
				if (this[p].getImg()) {
				thePlaylistHTML += '<a href="#" title="' + this[p].getAbstr().escapeHTML() + '"><img width="60" height="45" alt="" src="'+ this[p].getImg() +'" /></a>';
				}
				thePlaylistHTML += '<p class="next_up_clip_title"><a href="javascript:myPlaylist.playClip(' + p + ')" title="' + this[p].getAbstr().escapeHTML() + '">' + this[p].getTitle().escapeHTML() + '</a></p>';
				thePlaylistHTML += '<p class="streamer"><a href="javascript:myPlaylist.playClip(' + p + ')" title="' + this[p].getAbstr().escapeHTML() + '">Watch Now</a>';
				thePlaylistHTML += '<a href="javascript:myPlaylist.removeClip(' + p + ')" title="Remove from playlist" class="vp-rempl">Remove</a></p>';
				thePlaylistHTML += '<input type="hidden" id="clipAbstract' + this[p].getSid() + '" value="' + this[p].getAbstr().escapeHTML() + '" />';
				thePlaylistHTML += '<input type="hidden" id="clipDate' + this[p].getSid() + '" value="' + this[p].getPubdate() + '" />';
				thePlaylistHTML += '<input type="hidden" id="clipTitle' + this[p].getSid() + '" value="' + this[p].getTitle() + '" />';
				thePlaylistHTML += '</div>';
				
			}
			thePlaylistHTML = '<p><a class="cl-pl" href="javascript:myPlaylist.clear()" title="Clear all items from your playlist" >Clear playlist</a></p>' + thePlaylistHTML;
		} else {
			$('#cliptabs2 a span').text('My Playlist');
			//thePlaylistHTML= '<p>Your Clips</p>';
			thePlaylistHTML= '<div class="playlist-blank"><p>Click the plus sign to add videos to your playlist</p></div>';
		}
		
		//blank the list
		$("#playlist").empty();
		$('#playlist').append(thePlaylistHTML);
		$("#playlist .playlist-clip a").ToolTip("#CEE6F0", "#000");
	}
}
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('my_skysports_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) {
	//adds a clip to the playlist array
	
	if (!src) src = 'VideoList';
	
	//var cTitle = document.getElementById('clipTitle' + sid).value;
	var cTitle = $('#' + src + ' #clipTitle' + sid).val();

	if (cTitle.match(/%20/)) cTitle = unescape(cTitle);
	
	//var cAbstract = document.getElementById('clipAbstract' + sid).value;
	var cAbstract = $('#' + src + ' input#clipAbstract' + sid).val();
	if (cAbstract.match(/%20/)) cAbstract = unescape(cAbstract);

	//var cDate = document.getElementById('clipDate' + sid).value;
	var cDate = $('#' + src + ' input#clipDate' + sid).val();
	var cImg;
	//if (document.getElementById('clipImage' + sid)) cImg = document.getElementById('clipImage' + sid).src;
	if ($('#' + src + ' #clipImage' + sid).length > 0) cImg = $('#' + src + ' #clipImage' + sid).attr('src')
	
	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);
		//callFlash("addEventListener", "mediaComplete", "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) {
		//callFlash("removeEventListener", "mediaComplete", "onMediaComplete");
		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 ($("#cliptabs1")) {
			//if the playlist tab doesn't have the focus, show it
			$("#cliptabs1").removeClass("tabs-selected");
			$("#cliptabs2").addClass("tabs-selected");		
	
			$("#nextup").addClass("tabs-hide");
			$("#playlist").removeClass("tabs-hide");
		}

		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();
		
		modCon.getVideoAsynch(clipId);
		//callFlash("fetchTitleById", clipId); //fetches the id from the account - when finished, the onTitleLoad function will run
		
		fetchedId = clipId; //stores the titleId in a global variable so that i can use it in the onTitleLoad function
		
		/* because we have reinstigated removal of clips on completion, this code is now replaced
		if (this.length > i+1) {
			var nextClip = i+1;
		} else if (this.length > 1) {
			var nextClip = 0;
		} else {
			var nextClip = -1
		}
		*/
		
		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) {
			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); 
			//callFlash("removeEventListener", "mediaComplete", "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('');
}

function getRelatedClips(relatedClipsId,sid) {

	if (!relatedClipsId) relatedClipsId = 12599;
	if (sid) {
		
		var vUrl = "/video/skysports_video_load_basket/0,20287,thisisnotanoid_1_7,00.xml";
		var storiesToShow = 7
		
		var theRelatedClipListHTML = '';
		var storyFound = false;
		var storyCount = 1;
		
		$.get(vUrl.replace('thisisnotanoid',relatedClipsId), function(data){
	
			$("clip",data).each(function() {
			
				if ($(this).attr('storyID') != sid) {
					//only include the 7th article if we found the story to omit
					if (storyCount < storiesToShow || storyFound == true) {
						theRelatedClipListHTML += "<div class='playlist-clip'>";
						if ($(this).attr('thumbPath')) theRelatedClipListHTML += "<a href='#' title='" + $(this).attr('abstract').escapeHTML() + "'><img id='clipImage" + $(this).attr('storyID') + "' width='60' height='45' alt='" + escape($(this).attr('title')) + "' src='" + $(this).attr('thumbPath') + "' /></a>"
						
			
						theRelatedClipListHTML += "<p class='next_up_clip_title'><a href='javascript:playRelated(\"" + $(this).attr('id') + "_" + $(this).attr('storyID') + "_1\")' title=' " + $(this).attr('abstract').escapeHTML() + " '>" + $(this).attr('title') + "</a></p>";	
						theRelatedClipListHTML += "<p class='streamer'><a href='javascript:playRelated(\"" + $(this).attr('id') + "_" + $(this).attr('storyID') + "_1\")' title=' " + $(this).attr('abstract').escapeHTML() + " '>Watch Now</a>";
						theRelatedClipListHTML += "<a href='javascript:myPlaylist.addClip(\"" + $(this).attr('id') + "\",\"" + $(this).attr('storyID') + "\",\"nextup\")' title='Add to playlist' class='vp-addpl'>Add to playlist</a>";
	
						
						theRelatedClipListHTML += "</p><input type='hidden' id='clipAbstract" + $(this).attr('storyID') + "' value='" + escape($(this).attr('abstract')) + "' />";
						theRelatedClipListHTML += "<input type='hidden' id='clipDate" + $(this).attr('storyID') + "' value='" + escape($(this).attr('clipDate')) + "' />";
						theRelatedClipListHTML += "<input type='hidden' id='clipTitle" + $(this).attr('storyID') + "' value='" + escape($(this).attr('title')) + "' /></div>";
					}
				} else {
					storyFound = true;
				}
				storyCount++;
			});
			
			$("#nextup").append(theRelatedClipListHTML);
			
			$(".playlist-clip a").ToolTip("#CEE6F0", "#000");
		});	
	}
	
}

function getBestBits(relatedClipsId,sid) {
	$("#nextup").empty();
	if (!relatedClipsId) relatedClipsId = 15304;
	if (sid) {
		
		var vUrl = "/video/skysports_video_load_basket/0,20287,thisisnotanoid_1_9,00.xml";
		var storiesToShow = 9		
		var theRelatedClipListHTML = '';
		var storyFound = false;
		var storyCount = 1;
		var j = 1;
		
		$.get(vUrl.replace('thisisnotanoid',relatedClipsId), function(data){
	
			$("clip",data).each(function() {
			
			if($(this).attr('origin') == "skyplayer") {
				if ($(this).attr('storyID') != sid) {
					//only include the 7th article if we found the story to omit
					if (storyCount < storiesToShow || storyFound == true) {

					theRelatedClipListHTML += "<div class='playlist-clip clip"+ j +"'>";
						if ($(this).attr('thumbPath')) theRelatedClipListHTML += "<a href='" + $(this).attr('vidPath') + "' onclick=\"return __spHost.play(this.href);\" title='" + $(this).attr('abstract').escapeHTML() + "'><img id='clipImage" + $(this).attr('storyID') + "' width='60' height='45' alt='" + $(this).attr('title').escapeHTML() + "' src='" + $(this).attr('thumbPath') + "' /></a>"
						
						theRelatedClipListHTML += "<p class='next_up_clip_title'><a href='" + $(this).attr('vidPath') + "' onclick=\"return __spHost.play(this.href);\" title=' " + $(this).attr('abstract').escapeHTML() + " ' class='vp-link-sp'>" + $(this).attr('title') + "</a></p>";	
						theRelatedClipListHTML += "<p class='playit'><a href='" + $(this).attr('vidPath') + "' onclick=\"return __spHost.play(this.href);\" title=' " + $(this).attr('abstract').escapeHTML() + " ' class='vp-link-sp'>Watch on Sky Player</a>";
	
						theRelatedClipListHTML += "</p><input type='hidden' id='clipAbstract" + $(this).attr('storyID') + "' value='" + escape($(this).attr('abstract')) + "' />";
						theRelatedClipListHTML += "<input type='hidden' id='clipDate" + $(this).attr('storyID') + "' value='" + escape($(this).attr('clipDate')) + "' />";
						theRelatedClipListHTML += "<input type='hidden' id='clipTitle" + $(this).attr('storyID') + "' value='" + escape($(this).attr('title')) + "' /></div>";
					}
					j++;
				} else {
					storyFound = true;
				}
				storyCount++;
			}
			
			});
			
			$("#nextup").append(theRelatedClipListHTML);
			
			$(".playlist-clip a").ToolTip("#CEE6F0", "#000");
		});	
	}
	
}


function playRelated(titleId) { 

		//document.getElementById("banner").innerHTML = bannerCode;	
		if (playerReady==1) {

			var title_array=titleId.split("_");
			titleId = title_array[0];
			storyId = title_array[1];
			isJumpMenu = title_array[2];
			
			modCon.getVideoAsynch(titleId);
			
			onMediaComplete = function() {myPlaylist.playClip(0)}
			modVP.addEventListener(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(storyId, isJumpMenu);
		} else {
			alert('Please wait; player loading');
		}
}

var myPlaylist = new Array();

$(document).ready(function() {
		if (GetCookie('my_skysports_video_playlist')) { 
			//load the playlist into memory
			myPlaylist.load(GetCookie('my_skysports_video_playlist'));
		} else {
			//paint the default text into the playlist
			myPlaylist.refresh();
		}
});
