
/* *::: VIDZAPPER PLAYER :::**************************************** */
/* Used for creating loading changing and listening to player events
/* ***************************************************************** */

var videoHolder = "";
var videoPlaceHolderID = "";
var videoPlayerID ="";
var videoWidth = 0;
var videoHeight = 0;

function loadVzPlayer(videoHold, placeHolderID, playerID, width, height){
	$(document).ready(function(){ 
		videoHolder = videoHold;
		videoPlaceHolderID = placeHolderID;
		videoPlayerID = playerID;
		videoWidth = width;
		videoHeight = height;

		var flashvars;
			 flashvars = {
				controlbar:'over'
			}
		var params = {
			allowfullscreen:'true', 
			allowscriptaccess:'always',
			wmode: 'opaque'
		}
		var attributes = {
			id:playerID,  
			name:playerID
		}
		swfobject.removeSWF(playerID);
		$("#" + videoHold).html('<div id="'+placeHolderID+'" style="z-index:1000;">&nbsp;</div>');
		$("#" + videoPlaceHolderID).hide();
		swfobject.embedSWF('vidzapper/player/vzPlayer4.swf', placeHolderID, width, height,'9', false, flashvars, params, attributes);

		

		//first time inside the player... lets get the playlist...
		changePlaylist(0, playlistArray[0]);

	});

}

function startFirstVideo(){
	//play the first track...
	var playlistArrayLength = playlistArray.length;
	var contentArrayLength = contentArray.length;
	if(playlistArrayLength > 0 && contentArrayLength > 0){
		changeVideo(0);
	}
}

function changeVideo(index){
	$(document).ready(function(){ 

		CurrentVideoIndex = index;
		var playingItem = contentArray[CurrentVideoIndex];
		rtmpFileName = playingItem.VideoPath;
		videoImage = playingItem.ThumbnailPath;
	 
		try{
			highlightPlaylistItem(CurrentVideoIndex);
			displayPlaylistItemDetails(CurrentVideoIndex);
		}catch(e){
			//swallow the error.
		}



		startVideoFromCDN(videoImage, rtmpFileName,playingItem.ContentID,playingItem.MetaDataID,playingItem.NoClickAway);
	});
}


function initFlashPlayer(videoImage, rtmpServer, rtmpFileName,contentID,metaDataID,noClickAway){
$(document).ready(function(){ 
		if(currentPlayer != null){
			displayPlayingItem(); // displays in title/description of the currently playing video.
			highlightPlaylistItem(); //highlights the playlist item currently playing.
			
			//okay wait we need to split filename if server is nothing....
			if(rtmpServer == ""){
				var fileName = getFileName(rtmpFileName);
				var server = rtmpFileName.replace(fileName, "");
				rtmpServer = server;
				rtmpFileName = fileName;
			}
			currentPlayer.sendEvent("start", contentID, metaDataID, false, rtmpServer, rtmpFileName);

		}else{
			create = setTimeout(function() { initFlashPlayer(videoImage, rtmpServer, rtmpFileName,contentID,metaDataID, noClickAway) }, 500);
		}

	});

}


function playerReady(obj)
{
	currentPlayer = gid(obj.id);
	//alert("currentPlayer" + currentPlayer);
	$("#" + videoPlaceHolderID).show();
}

function callStateEvent(obj) {
	//alert("obj.newstate" + obj.newstate);
	//alert("obj.oldstate" + obj.oldstate);
	currentState = obj.newstate; 
	previousState = obj.oldstate;
	if ((currentState == "COMPLETED")) {
		//Do something when the video is complete
		changeVideo(CurrentVideoIndex +1);
	}
}



/* *::: VIDZAPPER PLAYLIST ITEMS :::******************************** */
/* These functions deal with creating displaying and interacting with
// the playlist
/* ***************************************************************** */
function changePlaylist(tabID, pID){
	if(pID == ""){
		pID = playlistArray[tabID];
	}
	
	try{
		highlightTab(tabID);
	}catch(e){
		//swallow the error.
	}	
	
	$("#playlist_scroller").html("<div id='item1' class='playlist_item'><div class='playlist_item_image'><img ID='imgThumbnail' Width='101' Height='76' src='images/playeritem_no_image.png' runat='server' class='border_on' /></div><div class='playlist_item_text'><h1>Loading Playlist...</h1></div><div class='clear_noheight'><!--  --></div></div> ");
	playlistID = pID;
	loadPlaylistContent(tabID, pID);
	startFirstVideo();


}

function loadPlaylistContent(tabID, pID){
	$.ajax({
		type: "POST",
		url: "vidzapper/services/content.php",
		data: "clientID="+clientID+"&channelID="+channelID+"&playlistID="+pID,
		async: false,
		success: function(msg){ 
			try{
				$("#debug").html(msg);
				eval(msg);
				
				if(contentArray[0].Title != ""){
					buildPlaylistContent(tabID);
				}else{
					alert("no content items returned.");
				}
			}catch(e){
				alert("loadPlaylistContent An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message);
			}
		}
	});
}


function buildPlaylistContent(x){
	var playingItem;
	var playlistContentBuilder = '';
	$("#playlist_scroller").html(""); //clear contents.

	contentLength = contentArray.length;
	
	for(var i=0;i < contentLength;i++){
		var thumbnailpath = '';
		var title = '';
		var doNotShowInPlaylist = 'false';
		var adTag = '';
		var shortDesc = '';
		
		playingItem = contentArray[i];

		thumbnailpath = playingItem.ThumbnailPath;
		title = truncate(playingItem.Title, 30);
		shortDesc = truncate(playingItem.ShortDesc, 90);
		doNotShowInPlaylist = playingItem.DoNotShowInPlaylist;
		adTag = playingItem.AdTag;

		 // deal with missing thumbnails
		if(thumbnailpath == ""){ thumbnailpath = THUMBNAIL_MISSING; }
		
		if(doNotShowInPlaylist != 'true'){
				playlistContentBuilder += "			<div id='item"+i+"' class='playlist_item'>";
				playlistContentBuilder += "			<div class='playlist_item_image'><a href=\"javascript:changeVideo("+i+", 'content');\"><img id='imgThumbnail' class='border_on' src='"+thumbnailpath+"' width='"+THUMBNAIL_WIDTH+"' height='"+THUMBNAIL_HEIGHT+"' ></a></div>";
				playlistContentBuilder += "			<div class='playlist_item_text'>";
				playlistContentBuilder += "				<h1><a class='playlist_item_link' href=\"javascript:changeVideo("+i+", 'content');\">"+ title +"</a></h1>";
				playlistContentBuilder += "				<p>"+ shortDesc +"</p>";
				playlistContentBuilder += "			</div>";
				playlistContentBuilder += "			<div class='clear_noheight'><!--  --></div>";
				playlistContentBuilder += "</div> \n\r";

		}
	}

	$("#playlist_scroller").html(playlistContentBuilder);
	$('#playlist_scroller').jScrollPane({});
}

function displayPlayingItem(){
			//fill in any film details...
			playingItem = contentArray[CurrentVideoIndex];
			title = truncate(playingItem.Title, 90);
			description = playingItem.TranscriptText;
			$("#current_video_title").html(''+ title +'');
			$("#current_video_description").html(''+ description +'');		
}

function highlightPlaylistItem() {
	try{
		$(".playlist_item").removeClass("playlist_item_on"); //remove all the previous playlist highlights
		$("#item" + CurrentVideoIndex).addClass("playlist_item_on"); // find which playlist item to highlight
		
		if(CurrentVideoIndex > 0){
			var heightToScroll = 0;
			//we need to scroll to the playing video but we must remember to skip ads.
			
			for(var i=0;i < CurrentVideoIndex; i++){
				if(contentArray[i].AdTag == ""){
					heightToScroll = heightToScroll + 88;
				}else{
					heightToScroll = heightToScroll - 88;
					if(heightToScroll < 0){heightToScroll = 0;}
				}
			}
			//finally do the scroll.
			$('#playlist_scroller')[0].scrollTo(heightToScroll);
		}
	}catch(ex){
		// we might not be have to highlight this, if it's an advert.
	}
}

function highlightTab(index){
	try{
		$("#tab0").removeClass("item_on");
		$("#tab1").removeClass("item_on");
		$("#tab2").removeClass("item_on"); //remove all the previous playlist highlights
		$("#tab" + index).addClass("item_on"); // find which playlist item to highlight
	}catch(ex){
		// we might not be have to highlight this, if it's an advert.
	}
}


/* *::: VIDZAPPER CDN :::******************************************* */
/* used to call velocix, and get the "current" streaming URL.
/* ***************************************************************** */
var rtmpUrl = new Array();
var streamName = "";	

function startVideoFromCDN(videoImage, rtmpFileName, contentID, metaDataID, noClickAway){

	//Below is an example of the Custom URL that can be used.
	//VZ_CUSTOMURL|VELOCIX|c653|[BUCKETNAME]/[FILENAME]
	//VZ_CUSTOMURL|VELOCIX|c653|[STREAMNAME]|live
	//rtmp://fms6.streams.velocix.com/flash/fs-20d0380000000000
	var isVelocixStream = rtmpFileName.indexOf("VZ_CUSTOMURL");

	if(isVelocixStream >= 0){
		var velocixSplit = theFile.split("|");
		if(velocixSplit[4] == "live"){ //is this live?
			var scriptFileName = velocixSplit[3].replace("-","/");
			loadVelocix('http://flash.velocix.com/'+ scriptFileName +'?format=jscript2', placeHolderDIV, playerID, videoImage, rtmpFileName);
		}else{
			loadVelocix('http://flash.velocix.com/'+ velocixSplit[2] +'/'+ velocixSplit[3] +'?format=jscript2', placeHolderDIV,  playerID, videoImage, rtmpFileName);
		}
	}else{

		//wait is this an RTMP url?
		if(rtmpFileName.indexOf("rtmp://") >= 0){
			if(rtmpFileName.indexOf("flash/fs-") >= 0){
				var s = rtmpFileName;
				var parts = s.split("/fs-");
				rtmpFileName = "fs-" + parts[parts.length-1];
				rtmpUrl.push(parts[parts.length-2]);
				rtmpUrl[0] = parts[parts.length-2] + "/";
				initFlashPlayer(videoImage, rtmpUrl[0], rtmpFileName, contentID, metaDataID, noClickAway);
			}else{
				var s = rtmpFileName;
				var parts = s.split("/bt");
				rtmpFileName = "bt" + parts[parts.length-1];
				rtmpUrl.push(parts[parts.length-2]);
				rtmpUrl[0] = parts[parts.length-2] + "/";
				initFlashPlayer(videoImage, rtmpUrl[0], rtmpFileName, contentID, metaDataID, noClickAway);
			}
			

		}else{
			//no need to call velocix.
			rtmpUrl[0] = null;
			streamName = "";
			scriptLoaded(videoImage, rtmpFileName, contentID, metaDataID, noClickAway);
		}
	}

}

function loadVelocix(ScriptURL, videoImage, rtmpFileName, contentID, metaDataID, noClickAway)    
{   
	//we need to call velocix to find out our nearest streaming server.
	jQuery.getScript(ScriptURL, function(){
		scriptLoaded(videoImage, rtmpFileName, contentID, metaDataID, noClickAway);
	});
}  

function scriptLoaded(videoImage, rtmpFileName, contentID, metaDataID, noClickAway)    
{
	var streamFile = "";
	var streamURL = "";

	if (typeof(rtmpUrl) != "undefined" && streamName != "") {
		streamFile = streamName;
		streamURL = rtmpUrl[0];
		//we need to tidy this away so we can start fresh for the next video. (otherwise rtmpUrl[0] == true)
		rtmpUrl = null;
		streamName = "";	
	}else{
		streamFile = rtmpFileName;
	}

	// Finally lets go and create the player.
	initFlashPlayer(videoImage, streamURL, streamFile, contentID, metaDataID, noClickAway);
}



/* *::: GENERIC FUNCTIONS :::*************************************** */
/* 
/* ***************************************************************** */
function gid(name)
{
	return document.getElementById(name);
};

function clearAllSelectedTabs(){
	$(".ui-tabs-selected").removeClass("ui-tabs-selected"); //remove all the previous playlist highlights
}

function selectedTab(tID){
	$("#tab-" + tID).addClass("ui-tabs-selected");
}

function truncate(p, len){
  var trunc = p;
  if (trunc.length > len) {

    /* Truncate the content of the P, then go back to the end of the
       previous word to ensure that we don't truncate in the middle of
       a word */
    trunc = trunc.substring(0, len);
    trunc = trunc.replace(/\w+$/, '');

    /* Add an ellipses to the end and make it a link that expands
       the paragraph back to its original size */
    //trunc += '...';
    return trunc;
  }
	return p;
}

function getFileName(url) {
	//this removes the anchor at the end, if there is one
	url = url.substring(0, (url.indexOf("#") == -1) ? url.length : url.indexOf("#"));
	//this removes the query after the file name, if there is one
	url = url.substring(0, (url.indexOf("?") == -1) ? url.length : url.indexOf("?"));
	//this removes everything before the last slash in the path
	url = url.substring(url.lastIndexOf("/") + 1, url.length);
	//return
	return url;
}

function gid(name)
{
	return document.getElementById(name);
};
