var AJAX_Pulling = false;
var playerReady = 0;
var newPlayer = "";
var outputHTML = "";
var paginationHTML = "";
var myPlaylist = new Array();

function initialLoad(basketID, tabBasketID) {
    loadBasket(basketID, 1);

    if (GetCookie('PlanetF1_video_playlist')) {
        //load the playlist into memory
        myPlaylist.load(GetCookie('PlanetF1_video_playlist'));
    } else {
        //paint the default text into the playlist
        myPlaylist.refresh();
    }

    if(tabBasketID) loadTabBasket(tabBasketID, 1, ""+tabBasketID+"");

}

function loadBasket(vidBasketID, thisPageNum) {

	var myPageNum = thisPageNum;
	var numVids = 9;

	$("#clip-pagination").empty();
	$("#clip-container").empty();

	$("#clip-container").html('<div align="center" style="width:300px;color:#ffffff"><img src="/images/loadingAnimation.gif" border="0" /><br/><br/>Finding Video Clips</div>');

	paginationHTML ="";
	outputHTML ="";

	var loadBasketURL = "/media/video/cliplistxml.php?basketId="+vidBasketID+"&page="+thisPageNum+"";

	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("videoId");
					var cVidPath = $(this).attr("vidPath");
					var cThumb = $(this).attr("thumbPath");
					if (cThumb == "") {cThumb = "/shared/images/default/210x110.gif"}
					var cOrigin = $(this).attr("origin");

					/*if ((i%4) == 0) {
						 var clipClass = "no-mrgn"
					} else {
						var clipClass = ""
					}*/

					var cLinktag = " href=\"javascript:;\" onclick=\"javascript:fetchAndLoad('"+ cID +"_"+ cStoryID +"'); return false;\" "
					var cPlaylistTag = " href=\"javascript:;\" onclick=\"javascript:myPlaylist.addClip('"+ cID +"', '"+ cStoryID +"'); return false;\" "

					if (i == 2 || i == 5 || i == 8) {
					    outputHTML += "<div class=\"base-video-box first\">";
					} else{
					    outputHTML += "<div class=\"base-video-box\">";
					}
                                        outputHTML += "<a class=\"base-video-box-link\" "+ cLinktag +" title=\""+ cTitle +"\"><span class=\"base-video-box-image\"><span>Watch Now</span><img src=\""+ cThumb +"\" alt=\""+ cTitle +"\" /></span>";
                                        outputHTML += "<h5 class=\"base-text-caption\">"+ cDate +"</h5>";
                                        outputHTML += "<h4>"+ cTitle.escapeHTML() +"</h4>";
					outputHTML += "<p>"+ cAbstract.escapeHTML() +"</p>";
					outputHTML += "</a>";

					outputHTML += "<ul>";
	        			outputHTML += "<li class=\"base-video-button-play\"><a "+ cLinktag +" title=\"Play Video\">Play Video</a></li>";
	    				outputHTML += "<li class=\"base-video-button-add\"><span></span><a "+ cPlaylistTag +" title=\"Add to playlist\">Add to Play list</a></li>";
	        			outputHTML += "</ul>";
					outputHTML += "</li></div>";

					//Hidden values used as temp store for loadAbstract func
					outputHTML += "<input type=\"hidden\" id=\"clipStory" + cID+ "\" value=\"" + cStoryID+ "\" />";
					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:#ffffff;font-size:16px;'>There are currently no video clips</div>"
			}

			//////// PAGINATION ////////////////
			var pLength = $(xmlData).find('page').length;
			var pCurrent = $(xmlData).find('pagination').attr("currentPage");
			var pTotal = $(xmlData).find('pagination').attr("totalPages");

			paginationHTML += "<li class=\"pag-key\">Page <span>"+ pCurrent +"</span> of "+ pTotal +"</li>";
			if (pLength > 0) {

				$('page',xmlData).each(function(i) {
					var pNumber = $(this).attr("pageNumber");
					var pIsCurrent = $(this).attr("isCurrent");
					var pLink = " href=\"javascript:;\" onclick=\"javascript:loadBasket('"+ vidBasketID +"', '"+ pNumber +"'); return false;\" title=\"Page "+ pNumber +"\"";

					if(pIsCurrent == 1) {
						paginationHTML += "<li>"+ pNumber +"</li>";
					} else {
						paginationHTML += "<li><a "+ pLink +">"+ pNumber +"</a></li>";
					}
				});
			}

				$("#clip-container").html(outputHTML);
				$(".base-pagination").html(paginationHTML);
			 }, "xml");

		AJAX_Pulling = false;
	}
}

/**** COMMON FORMATTING FUNCTIONS ****/

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: 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, onInitialLoad);
    modVP.addEventListener(BCVideoEvent.VIDEO_LOAD, onVideoLoad);

    modVP.addEventListener(BCMediaEvent.BEGIN, onVideoBegin);
    modAd.addEventListener(BCAdvertisingEvent.AD_START, onAdvertBegin);
}

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

function onInitialLoad(evt) {
    //alert("EVENT: BCExperienceEvent.CONTENT_LOAD");

    //var currentVideo = modVP.getCurrentVideo();

    //modCon.getVideoAsynch(currentVideo.id);
    //modVP.loadVideo(currentVideo.id);
}

function onVideoLoad(evt) {
    //alert("EVENT: BCVideoEvent.VIDEO_LOAD");
    //modVP.loadVideo(evt.video.id);
}

function onVideoBegin(evt) {
   // When Video starts playback load video detail

    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
    var recStoryID = $("#clipStory"+evt.media.id).val();
    updateVideoDetail(evt.media.displayName, evt.media.shortDescription, displayDate, displayTime,recStoryID );
}

function updateVideoDetail(title, abs, vidDate, vidTime, recStoryID) {
    var outputHTML = '';
    outputHTML += "<h4>" + title.escapeHTML() + " <em>("+vidTime +")</em> </h4>";
    outputHTML += "<h5 class=\"base-text-caption\">" + vidDate.escapeHTML() + "</h5>";
    outputHTML += "<p>" + abs.escapeHTML() + "</p>"
    outputHTML += "<ul class=\"base-article-tools\">"


    outputHTML += "<li class=\"base-icon-facebook\" id=\"face-book-share\"><a onclick=\"window.open('http://www.facebook.com/share.php?u='+location.href);return false\" href=\"http://www.facebook.com\"  >Post to Facebook</a></li>";
    outputHTML += "<li class=\"base-icon-twitter gap\"><a href=\"http://www.twitter.com\" onclick=\"window.open('http://twitter.com/home?status=Currently reading '+location.href);return false\">Post to Twitter</a></li>";
    outputHTML += "</ul>"
    $("#video-detail").html(outputHTML);
    //$("#video-detail").trigger('videoDetailLoaded');
	renderRecommendArticleLink($("#video-detail .base-article-tools"), recStoryID);
	
}

var fetchedId = null; //this allows me to store the id i'm fetching for use in the onTitleLoad function

function fetchAndLoad(titleId) {
    //alert('Player Ready ' + playerReady + 'New Player ' + newPlayer + 'Title' + titleId + '')
    if (playerReady == 1) {
        $("#video-detail").html('<p class="v-player-ad">Your video is loading</p>');
        var title_array=titleId.split("_");
        titleId = title_array[0];
        storyId = title_array[1];


        modVP.loadVideo(titleId);

        if(modMP.isMenuPageShowing() ) {
            //If internal menu is showing send video full size when clicked
            modMP.closeMenuPage();
        }

        fetchedId = titleId; 	// stores the titleId in a global variable to be used in content load
        $("#video-detail").show();

    } else {
        $("#video-detail").html("The Player is still loading please wait");
    }
}

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
    $("#video-detail").html('<p class="v-player-ad">Advertisement</p>');
}

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

Array.prototype.refresh=function() {
    var playlistClearHTML = "";
    var thePlaylistHTML = "";

    //re-paint the playlist on the page
    if ($("#v-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=\"base-video-box base-video-box-t2\">";
                                    if(pImg) {
                                    thePlaylistHTML += "<a class=\"base-video-box-link\" "+ pPlayLink +"><span class=\"base-video-box-image\"><img src=\"" + pImg + "\" alt=\"" + pTitle + "\" title=\"" + pTitle + "\" /></span>";
                                    }
                                    thePlaylistHTML += "<h4>"+ pTitle +"</h4></a>";

                                    thePlaylistHTML += "<ul>";
                                    thePlaylistHTML += "<li class=\"base-video-button-play\"><a "+ pPlayLink +">Play Video</a></li>";
                                    thePlaylistHTML += "<li class=\"base-video-button-add\"><a "+ pRemoveLink +">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/video/tt-clip-btns-clear.gif\" />Clear playlist</a></div>";

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

            $("#v-playlist").empty();
	    $("#v-playlist").append(playlistClearHTML);
            $("#v-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('PlanetF1_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;
    }
}

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


// -->

