var pg;
var videoclips;
var saved_filter;
var linkNumber = 5;

//This code gets the playlist value from the URL 
//e.g video.html#playlist=p12345
var hash=window.location.hash;
var playlist;
if (hash.indexOf('#playlist=')==0)
{   
    var start=hash.indexOf('=')+1;
    playlist=hash.slice(start);
}
//end code

$(document).ready(function () {
	$("#videopage").addClass("videoScriptEnabled");
	//Generate playlist dropdown box
	var playlistform = "<form name='playlist_form'>";
	playlistform += "<p><label for='playlist'>Select a Playlist</label> <select id='playlist'><option value=''>All Videos</option>";
	
	$("#playlist_form ul li a").each(function(){

		//Code to set the selected playlist, for when the playlist parameter is set in the URL
		var selectedValue="";
		if (playlist==$(this).attr("name"))
		{
			selectedValue='selected="selected"';
		}
		//playlistform += "<option value='" + $(this).attr("name") + "'>" + $(this).text() + "</option>"
		playlistform += "<option "+selectedValue+" value='" + $(this).attr("name") + "'>" + $(this).text() + "</option>"
	});
	
	playlistform += "</select> ";
	playlistform += "<input name='go' title='Go' type='button' onclick=\"javascript:filter(document.playlist_form.playlist.options[document.playlist_form.playlist.selectedIndex].value,true)\" value='Go' />"
	playlistform +=	"<span id='vpage_link_label'></span> <span id='vpage_links'>&nbsp;</span></p></form>"
	
	$("#playlist_form").html(playlistform);
	//end playlist generation code
		
	var isTranscript = getCookie("transcript");
	
	// show/hide transcript
	$("#transcriptNav").html("<a href='#trans' id='vpg_translink'>Hide Transcript</a>");
	if(isTranscript == "false"){
		$("#vtranscript").addClass("invisible");
		$("#vpg_translink").text("Show Transcript");	
	}
	else{
		$("#vtranscript").removeClass("invisible");
		$("#vpg_translink").text("Hide Transcript");
	}
	
	$("#vpg_translink").click(function(){		
		var $tmp = $("#vtranscript");		
		if($tmp.hasClass("invisible")){			
			$tmp.removeClass("invisible");
			$("#vpg_translink").text("Hide Transcript");
			setCookie("transcript", "true","","/","");
		}
		else{			
			setCookie("transcript", "false","","/","");
			$("#vpg_translink").text("Show Transcript");
			$tmp.addClass("invisible");
		}
		return false;
	});
	
	
	
	videoclips = $("div#video_clips").html();
	
	//Get saved filter infromation	
	saved_filter = getCookie('video_filter_cookie');	
	
	video_page = getCookie("video_page");
	if(saved_filter != ""){				
		if($("#playlist").val() == ""){							
			$("#playlist option").each(function(i){
				if($(this).val() == saved_filter){					
					$("#playlist")[0].selectedIndex = i;					
				}				
			});
			
			filter(saved_filter);			
			fetchDuration();
		}
	}
	else{		
		group(true);
		
		
	}	
	if(video_page && video_page != 1){
		page(video_page);
	}
	
	
	$("#transLink a").click(function() {		
		if($(".ytTranscript").hasClass("hide_transcript")){
			$(this).text("Hide Transcript");
			$(".ytTranscript").removeClass("hide_transcript");
		}
		else{
			$(this).text("Show Transcript");
			$(".ytTranscript").addClass("hide_transcript");
		}
		
		
		return false;
	});
	
	
	$(".video-gallery-box span.duration").each(function(){		
			videoDuration($(this).attr("id"));		
	});
	
});

//Search all the video duration span tag in a video page and retrive the duration from youtube
function fetchDuration(){
	$("#video_clips .vpage:visible span.duration").each(function(){
		videoDuration($(this).attr("id"));
	});
	
}


function filter(){		
	var newfilter = false;
	var str = "";
	if(arguments.length >= 2){
		str = arguments[0];
		newfilter = arguments[1];
	}
	else if(arguments.length == 1){
		str = arguments[0];
		
	}
	
	
	$("div#video_clips").html(videoclips);	
	if(str != ""){
		$("div#video_clips > div").not("." + str).remove();
	}
	
	group(true);	
	if(newfilter){				
		setCookie('video_filter_cookie', str,"","/","");
		setCookie("video_page","","","/","");		
	}
    	//Set #playlist=<playlist id> in the current URL
	if (str != ""){
		window.location.hash="playlist="+str;
	}else
	{
		window.location.hash="#";
	}
}
function group(){
	var isnewpage = false;
	if(arguments.length == 1){
		isnewpage = arguments[0];
	}
		
	totalsize=$("div#video_clips div.video_clip").size();
	
	pg = 0;
	$("div#video_clips div.video_clip").each(function(i, item){
		
		if( !( i % 6) ){
			var nextobj = $(item).next();
			var obj = $(this).wrap("<div class='vpage' id='pg" + pg + "' />");
			for(c=i; c < i+6; c++,c<totalsize)
				$("div#pg" + pg).append( $("div#video_clips div.video_clip:eq(" + c +")") );			
			pg++;
		}
	});
	
	//alert(totalsize + "\n" + pg);
	//alert(getCookie("video_page"));
	if(isnewpage){
		pageLink(1);		
	}
	else if (getCookie("video_page") != "" && ! isnewpage){		
		pageLink(getCookie("video_page"),false);
	}
	
	$("div.vpage").hide();
	$("div.vpage:first").show();
	fetchDuration();
}

function pageLink(pgnumber){			
	$("span#vpage_links").html("");	
	var linkstr = "";
	
	if(pg > 1){		
		if(pgnumber > 1){			
			linkstr = "<a href='javascript:page(" + (pgnumber - 1) + ", true)'>" + "<img src='" + rxs_navbase + "/images/sys_images/video/left_arrow.jpg' alt='Previous page'/>" + "</a>";
		}
		else{
			linkstr = "<span><img src='" + rxs_navbase + "/images/sys_images/video/left_arrow.jpg' alt='Previous page'></span>";
		}
		var startpg = endpg = ajustedpg = 0;
		
		if(pg > linkNumber){
			ajustedpg = pgnumber + 1;
			startpg = ajustedpg - Math.ceil(linkNumber / 2);
			endpg = startpg + linkNumber;
			if(startpg <= 0){				
				endpg += Math.abs(startpg) + 1;
				startpg = 1;
			}			
			else if(endpg > pg){
				startpg = pg - linkNumber;
				endpg = pg;
			}
		}
		else{
			
			startpg = 1;
			endpg = pg;
		}
		
		
		
		for(i=startpg; i <= endpg; i++){
			if(i == pgnumber){				
				linkstr += "<span>" + i + "</span>";				
			}
			else{				
				linkstr += "<a href='javascript:page(" + i + ", true)'>" + i + "</a>"
			}
		}
		
		if(pgnumber < pg){
			//linkstr += "<img src='/images/sys_images/video/right_arrow.jpg' alt='previous page'/>";
			linkstr += "<a href='javascript:page(" + (pgnumber + 1) + ",true)'>" + "<img src='" + rxs_navbase + "/images/sys_images/video/right_arrow.jpg' alt='Next page'/>" + "</a>";
		}else{
			linkstr += "<span><img src='" + rxs_navbase + "/images/sys_images/video/right_arrow.jpg' alt='Next page'></span>";
		}
	}
	if(linkstr != ""){			
			$("#vpage_link_label").html(" Or go to page");
			$("span#vpage_links").html(linkstr);
		}
		else{
			$("#vpage_link_label").html("");
		}

}

function videoClip(i){
	$("div.live_video").hide();
	$("div.viewPort div.videoblock").hide();
	$("div.viewPort div.videoblock").eq(i).show();
}

function page(){
	
	var setbit = false;
	
	i = arguments[0];
	setbit = arguments[1];	
	if(setbit){		
		setCookie("video_page",i,"","/","");		
	}
	
	$("div.vpage").hide();
	$("div.vpage").eq(i-1).show();	
	fetchDuration();
	pageLink(i);
}

function livevideo(){
	$("div.viewPort div.videoblock").hide();
	$("div.live_video").show();
	
}


function pad2(number) {
     return (number < 10 ? '0' : '') + number
}

//Fetch the video duration by id
function videoDuration(vid){	
  $.ajax({
	    url: "http://gdata.youtube.com/feeds/api/videos/" + vid + "?v=2&alt=jsonc&prettyprint=true",
	    type: 'GET',
	    dataType: 'jsonp',
	    success: function(data) {
           var seconds=(data["data"]["duration"] % 60)
           var minutes=Math.floor(data["data"]["duration"] / 60)
	         //$("#" + vid).text(minutes + ":" + pad2(seconds));
	         $("#" + vid).html("|&nbsp; " + minutes + ":" + pad2(seconds)).attr("class","duratin_filled").removeAttr("id");
	         //process duplicated id inside the third party plugin slider
	         $("#" + vid).html("|&nbsp; " + minutes + ":" + pad2(seconds)).attr("class","duratin_filled").removeAttr("id");
	    }
	});	
}

 


