var offset = 0; // The offset from which the thumbnails are loaded
var limit = 18; // The number of thumbnais per page
var requestedinterval = 5; // The default offset upon loading the thumbnail view
var previousPage = 0;
var nextPage = 0;

/*!
* \brief loads in the requested thumbnails and pagination values
*
* \param[in]  offset       The number of seconds between each frame
*/
function scroll_thumbnails(offset) 
{
	// Get thumbnails from XML script using a number of required parameters for things like offsets, etc
	$.ajax({
		type: "GET",
		url: "/xml/record_thumbnails.php",
		dataType: "xml",
		data: "start="+offset+"&limit="+limit+"&numstills="+total+"&suffix="+thumbnail_suffix+"&requestedinterval="+requestedinterval+"&stillsinterval="+stillsinterval+"&thumbstillsumid="+thumbsUMID+"",
		success: function(xml) {
			// Loop through each thumbnail item
			$(xml).find('item').each(function(){
											  
				// Set variables picked-up from thumbnail item xml
				var img_no = $(this).find('img_no').text();
				var url = $(this).find('url').text();
				var timecode = $(this).find('timecode').text();	
				var frameSeconds = $(this).find('frameSeconds').text();	
				
				// Populate #record_thumbnails_container div with thumbnails
				$('<div class="record_thumbnail_item"></div>').html('<p><img src="'+url+'" height="90" width="120" alt="'+img_no+'" onclick="seekPrompt('+frameSeconds+')" /></p><p onclick="seekPrompt('+frameSeconds+')">'+timecode+'</p>').appendTo('#record_thumbnails_container');
			});
			
			// Clear floated thumbnails within #record_thumbnails_container div
			$('#record_thumbnails_container').append('<div class="clear"></div>');
			
			// Get offsets for back/next links
			previousPage = $(xml).find('previousPage').text(); // Get back and next values from XML request
			nextPage = $(xml).find('nextPage').text();
			
			// Only display previous link if the previous offset is greater than -1
			if(previousPage > -1)
			{
				$('<p id="record_thumbnail_pagination_back"><a href="#" onclick="thumb_nav('+previousPage+'); return false;">Back</a></p>').appendTo('#record_thumbnails_container');
			}
			
			// Display page numbers
			$('<ul id="list_of_pages" class="black-link-with-underline"></ul>').appendTo('#record_thumbnails_container');
			$(xml).find('page').each(function(){
				
				var pageNo = $(this).text();	
				
				$('<li>'+pageNo+'</li>').appendTo('ul#list_of_pages');
				
			});
			
			// Only display next link if the next offset is greater than 0 (0 is returned if next offset goes beyond the total number of stills)
			if(nextPage > 0)
			{
				$('<p id="record_thumbnail_pagination_next"><a href="#" onclick="thumb_nav('+nextPage+'); return false;">Next</a></p>').appendTo('#record_thumbnails_container');
			}
			
			$('<div class="clear"></div>').appendTo('#record_thumbnails_container');
		}
	});	
}

/*!
* \brief toggle between showing the frames view and the metadata under a record
*
* \param[in]  showDiv       The div to display
* \param[in]  hideDiv       The div to hide
*/

function toggle_two_divs(showDiv, hideDiv)
{
	//Get the divs to show/hide
	var show_div = document.getElementById(showDiv);
	var hide_div = document.getElementById(hideDiv);
	
	//First hide the div
	if(hide_div.style.display == "block") 
	{
		hide_div.style.display = "none";
	}
	
	//Show the other div
	if(show_div.style.display == "none") 
	{
		show_div.style.display = "block";
	}
}

/*!
* \brief toggle between two styles
*
* \param[in]  elementOne    First element to change the style of
* \param[in]  elementTwo    Second element to change the style of
* \param[in]  classOne     	class for the first element
* \param[in]  classTwo     	class for the second element
*/

function toggle_two_styles(elementOne, elementTwo, classOne, classTwo)
{
	//Get the elements
	var ele_one = document.getElementById(elementOne);
	var ele_two = document.getElementById(elementTwo);
	
	//Change the classes
	ele_one.setAttribute("class", classOne);
	ele_two.setAttribute("class", classTwo);
	
}

/*!
* \brief show an element
*
* \param[in]  showDiv    The element to display
*/

function show_div(showDiv)
{
	var show_div = document.getElementById(showDiv);
	
	//Show the div
	if(show_div.style.display == "none") 
	{
		show_div.style.display = "block";
	}
}

/*!
* \brief hide an element
*
* \param[in]  hideDiv    The element to hide
*/
function hide_div(hideDiv)
{
	var hide_div = document.getElementById(hideDiv);
	
	//Hide the div
	if(hide_div.style.display == "block") 
	{
		hide_div.style.display = "none";
	}
}


/*!
* \brief  used to navigate between pages of thumbnails
*
* \param[in]  offset   Number of seconds between each frame
*
*/

function thumb_nav (offset) 
{
	$('#record_thumbnails_container').slideUp("fast", function () {
		$('#record_thumbnails_container').empty();
		scroll_thumbnails(offset);
	});	
	$('#record_thumbnails_container').fadeIn("slow");
}


/*!
* \brief  used to switch between different user-requested time intervals
*
* \param[in]  interval   Number of seconds between each frame
*
*/

function thumb_offset (interval) 
{
	
	// Don't allow double clicks to interval tabs
	$('#thumb_link_'+interval+'').dblclick(function () {
		return false;
	});	
	
	// Set the requestedinterval variable to the user requested interval, this is used within the scroll_thumbnails function
	requestedinterval = interval;
	
	// Change the CSS classes of the interval tabs depending on which offset the user requests
	if(interval == 15) // 15 second interval
	{
		
		// 5 second tab: unselect
		if($('#thumb_5').hasClass('thumb_offset_selected')) 
		{
			$("#thumb_5").removeClass("thumb_offset_selected black_link");
			$("#thumb_5").addClass("thumb_offset_unselected white_link");
		}
		
		// 10 second tab: unselect
		if($('#thumb_10').hasClass('thumb_offset_selected')) 
		{
			$("#thumb_10").removeClass("thumb_offset_selected black_link");
			$("#thumb_10").addClass("thumb_offset_unselected white_link");
		}
		
		// 15 second tab: select
		if($('#thumb_15').hasClass('thumb_offset_unselected')) 
		{
			$("#thumb_15").removeClass("thumb_offset_unselected white_link");
			$("#thumb_15").addClass("thumb_offset_selected black_link");
		}
	}
	else if(interval == 10) // 10 second interval
	{
		
		// 5 second tab: unselect
		if($('#thumb_5').hasClass('thumb_offset_selected')) 
		{
			$("#thumb_5").removeClass("thumb_offset_selected black_link");
			$("#thumb_5").addClass("thumb_offset_unselected white_link");
		}
		
		// 15 second tab: unselect
		if($('#thumb_15').hasClass('thumb_offset_selected')) 
		{
			$("#thumb_15").removeClass("thumb_offset_selected black_link");
			$("#thumb_15").addClass("thumb_offset_unselected white_link");
		}
		
		// 10 second tab: select
		if($('#thumb_10').hasClass('thumb_offset_unselected')) 
		{
			$("#thumb_10").removeClass("thumb_offset_unselected white_link");
			$("#thumb_10").addClass("thumb_offset_selected black_link");
		}		
	}
	else // 5 second interval
	{
		
		// 10 second tab: unselect
		if($('#thumb_10').hasClass('thumb_offset_selected')) 
		{
			$("#thumb_10").removeClass("thumb_offset_selected black_link");
			$("#thumb_10").addClass("thumb_offset_unselected white_link");
		}
		
		// 15 second tab: unselect
		if($('#thumb_15').hasClass('thumb_offset_selected')) 
		{
			$("#thumb_15").removeClass("thumb_offset_selected black_link");
			$("#thumb_15").addClass("thumb_offset_unselected white_link");
		}
		
		// 5 second tab: select
		if($('#thumb_5').hasClass('thumb_offset_unselected')) 
		{
			$("#thumb_5").removeClass("thumb_offset_unselected white_link");
			$("#thumb_5").addClass("thumb_offset_selected black_link");
		}		
	}
	
	// Reload thumbnails (from thumbnail 0) using the new interval
	$('#record_thumbnails_container').slideUp("fast", function () {
		$('#record_thumbnails_container').empty(); // Empty thumbnails container before requesting new interval
		scroll_thumbnails(0);
	});
	$('#record_thumbnails_container').fadeIn("slow");
}


// Function will check if a div exists. Usage: if($('#annotation_container_'+i+'').exists()){ }
jQuery.fn.exists = function(){return jQuery(this).length>0;}

$(document).ready(function()
{
	if(typeof(total) !== 'undefined' && stills > 0){
		scroll_thumbnails(0);
	}
});


function seekPrompt(new_startframe)
{
	var player = document.FLVClipEditor;
	var seekTime = new_startframe;
	
	if (player)
	{
		
		if (seekTime != null)
		{
			player.pausePlayback();
			player.setCurrentTime(seekTime);
			player.startPlayback();
		}
		
		var count = document.getElementById("count").value;
		var timeInputValue = document.getElementById("timeCode").value;
		var stateValue = document.getElementById("state").value;
		var count = document.getElementById("count").value;
		for(i=1;i<=count;i++){
		var annotationContainer= "annotation_container_" + i;
		var filled = document.getElementById(annotationContainer);
		filled.style.backgroundColor = '#cccccc'; 	
		filled.style.color = '#646464'; 
		}
	
	}
}


function updateTimeCode(id)
{
	var player = document.FLVClipEditor;
	var timeInput = document.getElementById("timeCode");
	var stateInput = document.getElementById("state");
	
	if (player && timeInput && stateInput)
	{
		timeInput.value = player.getCurrentTimeCode();
		stateInput.value = player.getState();
		var count = document.getElementById("count").value;
		var timeInputValue = document.getElementById("timeCode").value;
		
		//Set up where to scroll to.
		Starts = new Array(count);
		for(i=1;i<=count;i++){
		var start = "startCode_" + i;
		Starts[i] = document.getElementById(start).value;
		}
		for(i=1;i<=count;i++){
		var start = "startCode_" + i;
		var end = "endCode_" + i;
		var dur = "duration_" + i;
		var startcode = document.getElementById(start).value;
		var endcode = document.getElementById(end).value;
		var annotationContainer= "annotation_container_" + i;
		var colorContainer= "color_" + i;
		var filled = document.getElementById(annotationContainer);
		var color = document.getElementById(colorContainer).value;
			 if(timeInputValue >= startcode && timeInputValue < endcode && stateInput.value == "playing") {
				filled.style.backgroundColor = '#ffffff'; 
				filled.style.color = '#000000'; 
				filled.style.border = '3px solid #' + color;
				for(i=1;i<=count;i++){
				if(Starts[i] == startcode)	filled.parentNode.scrollTop=filled.offsetTop; 
				}
			} else {
				filled.style.backgroundColor = '#cccccc'; 	
				filled.style.color = '#646464'; 
				filled.style.border = '';

			}
		}
	} 
}


function pollForPlayer()
{
	var player = document.FLVClipEditor;

	if (player && 
		player.setPlayCallback)
	{
		player.setPlayCallback("updateTimeCode");
		// updateVersion(player.id); Function doesn't seem to exist?
	}
	else
	{
		setTimeout("pollForPlayer()", 100);
	}
}

setTimeout("pollForPlayer()", 100); 

function setSubmitValue(value)
{
	var clips_form = document.forms["clips_form"];
	clips_form.elements["submit_value"].value = value;
}

function checkClipsForm()
{
	//Check we have submitted at least one clip
	var edl = document.forms["clips_form"]["EDL"].value;
		
	if(edl == null || edl == "")
	{
		alert("Please create at least one clip.");
		return false;	
	}
	
	//Check clip is not 0 seconds
	var player = document.FLVClipEditor;
	
	if(player && edl)
	{
		edl.value = "";		
		var edlSize = player.getEDLSize();
		
		if (edlSize > 0)
		{
			edl.rows = edlSize;
		}
		else
		{
			edl.rows = 1;
		}		
		
		for (var i = 0; i < edlSize; i++)
		{
			var entry = player.getEDLEntry(i);		
			var duration = parseFloat(entry.endTime - entry.startTime);
			
			if(entry)
			{
				if(duration <= 1) 
				{
					alert("Each clip must be at least 1 second in length.");
					return false;
				} 
			}
			else
			{
				return false;
			}
		} 
	}
	
	//Check we are not creating a replica lightbox
	var submit_value = document.forms["clips_form"]["submit_value"].value;
	
	if(submit_value == "create")
	{
		var lightbox_name = document.forms["clips_form"]["title"].value;
		
		if(lightbox_name == null || lightbox_name == "")
		{
			alert("Please enter a name for the new lightbox.");
			return false;
		}
		else
		{
			var checkLightbox = $.ajax({

			type        : "POST",
			cache       : false,
			async       : false,
			url         : "/xml/lightbox_check.php",
			data        : "title="+encodeURIComponent(lightbox_name)+"",
			dataType    : "text"
		
			}).responseText;
			
			if(checkLightbox > 0)
			{
				alert("Sorry, this lightbox already exists.");
				return false;
			}
			else
			{
				return true;
			}
			
		}
		
	}
	else
	{
		return true;	
	}
	
	
	
}
