var playerTimecodeOffset =0;
var endOffset = null;
var lastSetOutPoint =0;
var lastSetInPoint =0;
var timeDifference = 10; /*frequency of calls */
var videoIsLoaded =false;
var currentVideoPath ="";
var currentPlayerTimecode = '00:00:00';
var onStatus ="";
var playingBin = false;
var loadingNewClip = false;
var isPaused = false;
var currentClipId = null;
var currentTapeId = null;
var currentTapeJSON = null;
var offsetIn = null;
var offsetOut = null;
var logEntryOffsetIn = null;
var logEntryOffsetOut = null;
var logScrollOffset = 60;
var clipChanged = false;
var openPlayerInDialog = true;
var clipTitle ='';
var newClipTitle = '';
var highlightingClip = false;
var currentClipType= '';
var videoPopup = false;
var defaultClipTitleText = "<span class=\"empty\">(Click here to attach a name or note to this clip)<\/span>";
var clipIsEditable = true;

/**************************Video Player controls ******************************/


function videoHandler(command, options) {
	var currentTime = new Date();
	
	optionsObj = $.parseJSON(options);
	switch (command) {
			//case 'playEnd': alert('end!'); break;
		case 'playStart':
			isPaused = false;
			break;
		case 'playStop':
			isPaused = true;
			break;
		case 'playEnd':
		
			if (playingBin) {
				playNextClip();
			}
			break;
		case 'setIn':
			if (loadingNewClip || highlightingClip) break;
			if (highlightingClip) {
				highlightingClip = false;
				if (typeof(updateSearchHash) == 'function') {
					updateSearchHash();
				}
				break;
			}
			
			
			if (optionsObj.time != offsetIn && currentTime.getTime() > lastSetInPoint + timeDifference) {
				
				if (optionsObj.time != offsetIn) {
					offsetIn = optionsObj.time;
					
					if (currentClipId && !shareBin) {
						clipChanged =true;
						$(".videoPlayer .titleBar .save").show();
					}
					highlightClip(optionsObj.time, offsetOut);
					lastSetInPoint = currentTime.getTime();
				}
			}
			break;
		case 'setOut':
			
			if (loadingNewClip) break;
		
			if (highlightingClip) {
				highlightingClip = false;
				if (typeof(updateSearchHash) == 'function') {
					updateSearchHash();
				}
				break;
			}
			
			if (optionsObj.time != offsetOut && currentTime.getTime() > lastSetOutPoint + timeDifference) {
				
				if (optionsObj.time != offsetOut) {
					offsetOut = optionsObj.time;
					if (currentClipId  && !shareBin) {
						clipChanged =true;
						$(".videoPlayer .titleBar .save").show();
					}
					highlightClip(offsetIn,optionsObj.time);
				}
				lastSetOutPoint = currentTime.getTime();
			}
			break;
		case 'setFullscreenMode':
			break;
		case 'setVolume':
			$.cookie('playerVolume', optionsObj.volume, {expires: volumeCookieLifetime});
			if ( optionsObj.volume == 0) {
				$.cookie('maualMute', 'true');
			} else {
				$.cookie('maualMute', null);
			}
			break;
		case 'setLockedToLog':
			if (!optionsObj.lockedToLog) {
				clearLogHighlighting();
			}
			break;
		case 'setFullscreenMode':
			
			break;
		case 'location':
			
			currentPlayerTimecode = formatTimecode(Math.round(playerTimecodeOffset + optionsObj.time));
			if ($("#lockLog").is(":checked")) {
				highlightNearestLogEntry(Math.round(playerTimecodeOffset + optionsObj.time));
			}
			break;
		case 'status':
			
			currentPlayerTimecode = formatTimecode(Math.round(playerTimecodeOffset + optionsObj.time));
			switch (onStatus) {
				case 'createLogEntry':
					createLogEntry(currentPlayerTimecode);
					break;
				case 'markIn':
					document['videoPlayer'].setIn(optionsObj.time);
					break;
				case 'markOut':
					document['videoPlayer'].setOut(optionsObj.time);
					break;
			}
				
			onStatus=='';
			break;
		case 'error':
			break;
	}
	
}

function load(options) {
	if (document['videoPlayer'].load != undefined) {
		document['videoPlayer'].load(options);
		videoIsLoaded = true;
		loadingNewClip= false;	
		var volume  = $.cookie('playerVolume') ? $.cookie('playerVolume') : DEFAULT_PLAYER_VOLUME;
		document['videoPlayer'].setVolume(volume);
	} else {
		setTimeout(function() {  load(options); }, 200);
	}
}

function unloadVideo() {
	if (videoIsLoaded && document['videoPlayer'].unload != undefined) {
		document['videoPlayer'].unload();
	}
	videoIsLoaded = false;
	currentVideoPath = '';
	offsetIn= 0;
	offsetOut =null;
	currentClipId =null;
	currentTapeId = null;
	highlightLogId = null;
}

function setVideoTime(seconds) {
	if (videoIsLoaded) {
		document['videoPlayer'].playVideo(Math.ceil(seconds));
		
	}
}

function setPlayerIn(timecodeStr) {
	if (videoIsLoaded) {
		timecode = new Timecode(timecodeStr);	
		document['videoPlayer'].setIn(timecode.toPosition() - playerTimecodeOffset);
	}
}

function setPlayerOut(timecodeStr) {
	if (videoIsLoaded) {
		timecode = new Timecode(timecodeStr);	
		document['videoPlayer'].setOut(timecode.toPosition() - playerTimecodeOffset);
	}
}

function setPlayerOffsetIn(offset) {
	if (videoIsLoaded) {
		document['videoPlayer'].setIn(offset);
	}
}

function setPlayerOffsetOut(offset) {
	if (videoIsLoaded) {
		document['videoPlayer'].setOut(offset);
	}
}

function setPlayerOffsets(offsetIn, offsetOut) {
	setPlayerOffsetIn(offsetIn);
	setPlayerOffsetOut(offsetOut);
	
}

function goToInPoint() {
	setVideoTime(inPos - playerTimecodeOffset);
}

function goToOutPoint() {
	setVideoTime(outPos - playerTimecodeOffset);
}

function getPlayerTime(statusEvent) {
	onStatus = statusEvent;
	document['videoPlayer'].getStatus();

}

function setVideoPosition(timecodeStr) {
	
	if (videoIsLoaded) {
		
		var timecode = new Timecode(timecodeStr );
		document['videoPlayer'].playVideo(timecode.toPosition() - playerTimecodeOffset);
	}
}

function pauseVideo() {
	if (videoIsLoaded) {
		try {
			document['videoPlayer'].stopVideo();
		} catch (e) {
			//do nothing
		}
	}
}

function togglePlayPause() {
	if (videoIsLoaded) {
		if (isPaused) {
			document['videoPlayer'].playVideo();
		} else {
			document['videoPlayer'].stopVideo();
		}
	}
}

function setReceiveAudio(value) {
	if (videoIsLoaded) {
		document['videoPlayer'].receiveAudio(value);
	}
}

function disableClipTrimming() {
	if (videoIsLoaded) {
		document['videoPlayer'].disableClipTrimming();
	}
}

function enableClipTrimming() {
	if (videoIsLoaded) {
		document['videoPlayer'].enableClipTrimming();
	}
}

function showVideo(path, timecodeOffsetString, endTime, fps, play, newInOffset, newOutOffset, receiveAudio, clipTrimming) {
	
	if (newInOffset == undefined) {
		newInOffset = '';
	}
	if (newOutOffset == undefined) {
		newOutOffset = '';
	}
	if (receiveAudio == undefined) {
		receiveAudio = true;
	}
	if (clipTrimming == undefined) {
		clipTrimming = true;
	}
	$(".videoPlayer .tabs").show();
	
	//if the video is already loaded, just set the in and out points.
	if (videoIsLoaded && currentVideoPath == path) {
		
		if (newInOffset != "") {
			offsetIn = newInOffset;
			document['videoPlayer'].setIn(offsetIn);
		} else {
			offsetIn = 0; 
			document['videoPlayer'].setIn(0);
		}
		if (newOutOffset != "") {
			if (newOutOffset == null) {
				endTc = new Timecode(endTime, fps);
				newOutOffset =  Math.round(endTc.toPosition() - playerTimecodeOffset);
			} 
			offsetOut = newOutOffset;
			document['videoPlayer'].setOut(offsetOut);
		} else {
			endTc = new Timecode(endTime, fps);
			offsetOut = endTc.toPosition() -playerTimecodeOffset;
			document['videoPlayer'].setOut(offsetOut);
		}
		if(play) {
			document['videoPlayer'].playVideo();
		}
		if (clipTrimming) {
			enableClipTrimming();
		} else {
			disableCliTrimming();
		}
		loadingNewClip = false;
		return;
	}

	var options = {url:path};
	currentPlayerTimecode = timecodeOffsetString;
	currentVideoPath = path;

	endTc = new Timecode(endTime, fps);
	offsetOut = Math.round(endTc.toPosition() - playerTimecodeOffset);
	offsetIn = 0;
	if (newInOffset != "") {
		offsetIn = Math.round(newInOffset);
		
	}
	if (newOutOffset != "" && newOutOffset != -1) {
		offsetOut = Math.round(newOutOffset);
	}
	
	options.inTime = offsetIn;
	options.outTime = offsetOut;
	options.timecodeOffset = playerTimecodeOffset;
	options.play = play;
	options.nonDropFrame = (fps== 30);
	options.receiveAudio = receiveAudio;	
	options.clipTrimming = clipTrimming;
	
	try {	
		
		//If the flash player is not yet initialized, wait a little while and try again.
		load(options);
	} catch (err) {
		//showAlert(err);
		currentVideoPath = '';
		videoIsLoaded = false;
	}
}

/*********************** Clip handling ****************************************/


function findNearestTimecode(seconds) {
	var rows = $(".tabPanel .textLog tr");
	seconds = Math.round(seconds);
	var first= 0;
	var last = rows.length;
	
	for (;;) {
		if (last <= first) {
			return $(rows[first]);
		}
		var mid = first + Math.ceil((last - first) / 2);
		var midPos = new Timecode($(rows[mid]).find(".timecode").text()).toPosition();
		if (midPos ==  seconds) {
			return $(rows[mid]);
		} else if (midPos <  seconds) {
			first = mid;
		} else {
			last = mid - 1;
		}
	}
}

var currentEntryTime =0;
var nextTime =0;
function highlightNearestLogEntry(seconds) {
	
	if (seconds >= currentEntryTime && seconds < nextTime) {
		return;
	}
	
	$("table.textLog tr.current").removeClass('current');
	entry = findNearestTimecode(seconds);
	
	if (entry.length) {
		currentEntryTime = seconds;
		if(!entry.is(':last-child')) {
			nextTime = new Timecode($(".timecode", entry.next()).text()).toPosition();
		}
		
		entry.addClass('current');
		$(".tabPanel div.textLog").animate({
			scrollTop: $(".tabPanel div.textLog").scrollTop() +  entry.position().top - logScrollOffset
		});
	}
	
}

function clearLogHighlighting() {
	$(".tabPanel .log tr.current").removeClass('current');
}

function highlightClip(newInOffset, newOutOffset) {
	highlightingClip = true;
	if (newInOffset != offsetIn || $(".tabPanel .log tr.inPoint").length == 0) {
		$(".tabPanel .log tr.inPoint").removeClass("inPoint");
		var inPoint = findNearestTimecode(playerTimecodeOffset + Number(newInOffset));
		inPoint.addClass('inPoint');
		offsetIn = newInOffset;
		if (!loadingNewClip && currentClipId  && !shareBin) {
			clipChanged =true;
			$(".videoPlayer .titleBar .save").show();
		}
		
	} else {
		var inPoint = $(".tabPanel .log tr.inPoint");
	}
	
	if (newOutOffset != offsetOut || $(".tabPanel .log tr.outPoint").length == 0) {
		$(".tabPanel .log tr.outPoint").removeClass("outPoint");
		
		if (newOutOffset != null && newOutOffset != -1) {
			var outPoint = findNearestTimecode(playerTimecodeOffset + Number(newOutOffset));
			outPoint.addClass('outPoint');
		} else {
			newOutOffset = endOffset;
		}
		offsetOut = newOutOffset;
		if (!loadingNewClip  && currentClipId && !shareBin) {
			clipChanged =true;
			$(".videoPlayer .titleBar .save").show();
		}
	} else {
		var outPoint = $(".tabPanel .log tr.outPoint");
	}
	
	var cloneTable = $(".log table.textLog").clone();
	
	$(".subSelect", cloneTable).removeClass("subSelect");

	var tmp = $("tr.inPoint", cloneTable).nextAll().andSelf();
	tmp.each(function() {
		
		if ($(this).hasClass('outPoint')) {
			return false;
		}
		$(this).addClass('subSelect');
		
	});
	
	//if everything is highlighted, highlight nothing.
	//if ($("tr:not(.subSelect)", cloneTable).length == 0) {
	//	$("tr.subSelect", cloneTable).removeClass('subSelect');
	//}
	$(".log table.textLog").replaceWith(cloneTable);
	
	if (offsetOut == null) {
		var out = "END";
	} else {
		var out = formatTimecode(playerTimecodeOffset + Number(offsetOut));
	}
		
	var timecodes = displayTCRange(formatTimecode(playerTimecodeOffset + Number(offsetIn)), out);
	
	if (timecodes) {
		$(".titleBar .timecodes").html('(' + timecodes+ ')');
	}
	if (offsetOut != null) {
		$(".titleBar .length").html((timecodes ? ' - ' :'')+
			getLengthDisplayString(Number(offsetOut) - Number(offsetIn))
		);
	} else {
		$(".videoPlayer .titleBar .length").html('');
	}
	if (videoIsLoaded) {
		setPlayerOffsetOut(offsetOut); 
		setPlayerOffsetIn(offsetIn); 
	} else {
		highlightingClip = false;
		if (typeof(updateSearchHash) == 'function') {
			updateSearchHash();
		}
	}
}

function displayClip(clipTape) {
	
	if (clipTape.clipType == 'Clip' &&  $("li#clip" + clipTape.id).length) {
		var clipNum = $("li#clip" + clipTape.id).prevAll().length +1;
		var numClips =  $("li#clip" + clipTape.id).siblings().length +1;
		$("#navigationControls .matchInfo").text('Viewing clip #' + clipNum + ' of ' + numClips + ' in "' 
			+ $("#clipBin .binSelect :selected").text() + '"');
	} else {
		var clipNum = $("li#clipDetails" + clipTape.id).prevAll().length +1;
		var numClips =  $("li#clipDetails" + clipTape.id).siblings().length +1;
		$("#navigationControls .matchInfo").text('Viewing clip #' + clipNum + ' of ' + numClips + ' in "' 
			+ $("#binTitle").text() + '"');
	}
	$(".videoPlayer").removeClass('search').addClass('clip');
	$("#navigationControls .match").hide();
	$("#navigationControls img").not('.match').removeClass('disabled');
	$(".bin li").removeClass('selected');
	$("li#clip" + clipTape.id).addClass('selected');

	
	
	if (clipNum == numClips) {
		$("#navigationControls .nextTape").addClass('disabled');
	}
	
		if (clipNum == 1) {
		$("#navigationControls .prevTape").addClass('disabled');
	}
	
	$("#navigationControls").show();
	
	trackEvent("View", 
		clipTape.specialtyCollection ? 'Specialty Collection' : 'Standard Collection',
		clipTape.tape.tapeId
	);
	showVideoPlayerClip(clipTape);
	if (typeof(updateSearchHash) !== 'undefined') {
		updateSearchHash();
	} else {
		setHash('c' + currentClipId);
	}
}

function showClip(clipId, isWritable,orderClip, shareBinClip) {
	
	if (isWritable == undefined) {
		isWritable = true;
	}
	if (orderClip == undefined) {
		orderClip = isOrder;
		
	}
	if (shareBinClip == undefined) {
		shareBinClip = shareBin;
		
	}
	if (orderClip) {
		currentClipType ="OrderClip";
	} else if (shareBinClip) {
		currentClipType ="ShareClip";
	} else {
		currentClipType ="Clip";
	}
	
	clipIsWritable = isWritable;
	$.ajax({
		data: {
			action: 'getClip',
			clipId: clipId,
			shareBin: shareBinClip,
			order: orderClip
		},
		success: function(data) {

			clipTape = $.parseJSON(data);
			displayClip(clipTape); 
			
		}
	});
}

/************************* Displaying the player window ***********************/

function hideVideoPlayer() {
	if ($('#videoWindow').hasClass('standalone')) {
		pauseVideo();
		return;
	}
	if (clipChanged) {
		clipChanged = false;
	// successHandler, cancelHandler, successBtnText, cancelBtnText, autoClose, closeHandler
		showConfirm("You have made changes to this clip. Would you like to save it?",
			function() {
				
				saveClipChanges(function() {
					hideVideoPlayer();
				});
				
			},
			function() {
				hideVideoPlayer();
			},
			"Save",
			"Continue without Saving");
		return false;
	}
	$(".playerBlackout").remove();
	$("#videoWindow").removeAttr('style');
	$("#videoWindow").hide();
	unloadVideo();
	currentClipType ='';
	clipTitle ='';
	newClipTitle ='';
	videoPopup = false;
	
	$("#binContents li, #clipBin li, #resultsList .displayed").removeClass('displayed');
	//$(".ui-dialog-title-videoWindow .titleBar").empty();
	if (typeof(updateSearchHash) == 'function') {
		updateSearchHash();
	} else {
		setHash('');
	}
	$(".videoWindow .titleBar .save").hide();
	return true;
	
}

function getThumbnails(id, clipId, clipType) {
	$.ajax ({
		data: {
			action: 'getThumbnails',
			tapeId: id,
			clipId: clipId ? clipId : '',
			clipType: clipType
		},
		success: function(data) {
			var obj = $.parseJSON(data);
			drawThumbnails(obj);
			
		}
	});
}

function drawThumbnails(thumbnails) {
	$(".videoPlayer .tabPanel .thumbnails").empty();
	$(".videoPlayer .tabs .thumbnails").show();
	if(thumbnails.hasOwnProperty('smallThumbnails')) {
		var numThumbnails = thumbnails.smallThumbnails.length;
		
		for (i=0; i< numThumbnails; i++) {
			
			$(".videoPlayer .tabPanel .thumbnails").append(
				$('<img />')
					.attr('src',thumbnails.smallThumbnails[i])
					.attr('alt', 'Thumbnail ' + i)
					.attr('id', 'thumb' + i)
					.attr('class', 'thumbBtn')
			
			);
		}
	} else {
		$(".videoPlayer .tabs .thumbnails").hide();
	}
}

function makeClipTitleEditable() {
	
	$("#clipTitle").attr('title', "Click here to edit this clip's name/note");
	$("#clipTitle").editInPlace({
		html: false,
		multiline: false,
		saveCallBack: function(obj, text, originalContents) {
			
			if ( jQuery("<div/>").append(text).html() == jQuery("<div/>").append(defaultClipTitleText).html()) {
				text ="";
			} else {
				text = jQuery("<div/>").append(text).text();
			}
			if (text == "") {
				obj.html(defaultClipTitleText);
			}
			newClipTitle = text;
			if (currentClipId && !shareBin) {
				clipChanged =true;
				$(".videoPlayer .titleBar .save").show();
			}
			
		},
		outsideClick: 'cancel',
		defaultMarkUp: defaultClipTitleText,
		
		wysiwyg :false
	});
}

function drawTapeInfo(tape, isWritable, specialAccess, specialAccessExpiryDays) {
	if (specialAccess == undefined) {
		specialAccess = false;
	}
	
	clipIsEditable = isWritable;
	if (currentTapeId != tape.id) {
		unloadVideo();
	}
	currentTapeId = tape.id;
	currentTapeJSON = tape;
	if (tape.startTimecode) {
		var tc = new Timecode( tape.startTimecode, tape.fps);
		playerTimecodeOffset = tc.toPosition();
	} else {
		playerTimecodeOffset = 0;
	}
	
	if (tape.length) {
		endOffset = tape.length;
	} else if (tape.endTimecode) {
		var endTc =  new Timecode(tape.endTimecode, tape.fps);
		endOffset = endTc.toPosition() - playerTimecodeOffset;
	} else {
		endOffset =null;
	}
	if (endOffset <= 0) {
		endOffset = null;
	}
	
	
	$(".videoPlayer .titleBar .tapeId").html(tape.tapeId);
	var timecodes = displayTCRange(tape.startTimecode, tape.endTimecode);
	if (timecodes) {
		$(".videoPlayer .titleBar .timecodes").html( '(' +timecodes + ')');
	} else {
		$(".videoPlayer .titleBar .timecodes").html('');
	}
	if (tape.length) {
		$(".videoPlayer .titleBar .length").html( (timecodes ? ' - ' : '') + getLengthDisplayString(tape.length));
	} else {
		$(".videoPlayer .titleBar .length").html('');
	}
	$(".videoPlayer .tabPanel .details .timecode").html( '(' + displayTCRange(tape.startTimecode, tape.endTimecode) + ')');
	
	var year = displayRange(tape.yearStart, tape.yearEnd);
	if (year) {
		$(".videoPlayer .tabPanel .details .yearContainer").show();
		$(".videoPlayer .tabPanel .details .year").html(year);
	} else {
		$(".videoPlayer .tabPanel .details .yearContainer").hide();
	}
	
	var genre = displayField(tape.genre);
	if (genre) {
		$(".videoPlayer .tabPanel .details .genreContainer").show();
		$(".videoPlayer .tabPanel .details .genre").html(genre);
	} else {
		$(".videoPlayer .tabPanel .details .genreContainer").hide();
	}
	var color = formatColor(tape.color);
	if (color) {
			$(".videoPlayer .tabPanel .details .colorContainer").show();
		$(".videoPlayer .tabPanel .details .color").html(color);
	} else {
		$(".videoPlayer .tabPanel .details .colorContainer").hide();
	}
	if (!(tape.description)) {
		$(".videoPlayer .tabPanel .details p.description").hide();
	} else {
		$(".videoPlayer .tabPanel .details p.description").show();
		$(".videoPlayer .tabPanel .details span.description").html(nl2br(tape.description));
	}
	
	if (DISPLAY_KEYWORDS) {
		var keywordStr = formatKeywords(tape.keywords);
		if (!keywordStr) {
			$(".videoPlayer .tabPanel .details p.keywords").hide();
			
		} else {
			$(".videoPlayer .tabPanel .details p.keywords").show();
			$(".videoPlayer .tabPanel .details span.keywords").html(keywordStr);
		}
	}
	$(".videoPlayer .lockLog").remove();
	
	
	$(".videoPlayer .noVideo").hide();
	$(".videoPlayer .restricted").hide();
	$(".videoPlayer .restricted .mos").hide();
	$(".videoPlayer .specialty").hide();
	$(".videoPlayer .specialty .specialAccessText").hide();
	$(".videoPlayer .specialty .standardText").hide();
	if (tape.specialtyCollection && !specialAccess) {
		$(".videoPlayer div.player").removeClass('player').addClass('hiddenPlayer');
		if  (!proAccount) {
			$(".videoPlayer .tabPanel").prepend($("#hiddenPlayerContent div.thumbnails"));
			$(".videoPlayer div.thumbnails").appendTo($("#hiddenPlayerContent"));
		} else {
			$(".videoPlayer .tabs").prepend($("#hiddenPlayerContent a.thumbnails"));
			$(".videoPlayer .tabPanel").prepend($("#hiddenPlayerContent div.thumbnails"));
		}
			
		$(".videoPlayer a.thumbnails").appendTo($("#hiddenPlayerContent"));
		$(".videoPlayer .specialty").show();
		$(".videoPlayer .specialty .standardText").show();
		
		$(".videoPlayer .downloadClip").removeClass('disabled');
		$(".videoPlayer .downloadClip span").text('Download a low-res version');
		
		
	} else if (!tape.hasvideo && !specialAccess) { 
		$(".videoPlayer div.player").removeClass('player').addClass('hiddenPlayer');
		$(".videoPlayer div.thumbnails").appendTo($("#hiddenPlayerContent"));
		$(".videoPlayer a.thumbnails").appendTo($("#hiddenPlayerContent"));
		$(".videoPlayer .noVideo").show();
		$(".videoPlayer .downloadClip").addClass('disabled');
		$(".videoPlayer .downloadClip span").text('Not available for download');
	
	} else {
		if (specialAccess) {
			if (tape.specialtyCollection) {
				$(".videoPlayer .specialty .specialAccessText .remaining").text(specialAccessExpiryDays +' more day' +(specialAccessExpiryDays > 1 ? 's' :''));
				$(".videoPlayer .specialty .specialAccessText").show();
				$(".videoPlayer .specialty").show();
			} else {
				$(".videoPlayer .restricted .remaining").text(specialAccessExpiryDays +' more day' +(specialAccessExpiryDays > 1 ? 's' :'')); 
				$(".videoPlayer .restricted").show();
				if (tape.QCStateId == QC_STATES['Video MOS']) {
					$(".videoPlayer .restricted .mos").show();
				}
			} 
		}
		$(".videoPlayer div.hiddenPlayer").removeClass('hiddenPlayer').addClass('player');
		$(".videoPlayer .tabs").prepend($("#hiddenPlayerContent a.thumbnails"));
		$(".videoPlayer .tabPanel").prepend($("#hiddenPlayerContent div.thumbnails"));
		
		$(".videoPlayer .noVideo").hide();
		$(".videoPlayer .tabPane.log").prepend('<input class="lockLog" type="checkbox" id="lockLog"/><label class="lockLog"  for="lockLog">Scroll with video playback</label>');
		$(".videoPlayer .downloadClip").removeClass('disabled');
		$(".videoPlayer .downloadClip span").text('Download a low-res version');
		$(".videoPlayer .lockToLog").show();
	} 
	
	if (tape.thumbnails) {
		drawThumbnails(tape.thumbnails)
	} else if (tape.hasvideo) {
		getThumbnails(tape.id, currentClipId, currentClipType);
	} else {
		$(".videoPlayer .tabs .thumbnails").hide();
	}	
	
	$(".videoPlayer .titleBar .save").hide();

	//$(".ui-dialog-titlebar",$("#videoWindow").parents('.ui-dialog')).hide();

	if (isWritable) {
		makeClipTitleEditable();
	}

	var table = $("<table />").addClass('textLog');
	var inClip =false;
	var count =0;
	$("#lockLog").prop('checked', $.cookie('lockLog') == 'true');
	$.each(tape.log, function (name, value) {
		var tr = $("<tr>")
			.attr('id', 'desc' + value.id)
			.append(
				$("<td />")
					.addClass("timecode")
					.append(trimFrames(value.timecode))
			);
			
			if (value.music) {
				tr.append($("<td/>")
					.addClass("logContents")
					.addClass("desc")	
					.append($("<div />")
						.addClass("logMusic")
						.attr('title', "Musical Performance")
						.append($("<span />")
							.addClass("artist")
							.attr('id', 'logArtist' + value.id)
							.html(value.artist== null ? '' : value.artist)
						)
						.append(value.artist  && value.title  ?' - ' :'')
						.append($("<span />")
							.addClass("title")
							.attr('id', 'logTitle' + value.id)
							.html(value.title ? value.title : '')
						)
						.append($("<span />")
							.addClass("type")
							.attr('id', 'logType' + value.id)
							.html(value.performanceType == null ? '' : ' (' + value.performanceType + ')')
						)	
					)
					.append($("<div />")
						.addClass("logDescription")
						.attr('id', 'logDescription' + value.id)
						.html(value.description == null ? '' :value.description.replace(/\n/g, '<br />'))
					)
				);
			} else if (value.description != null) {
				tr.append(
					$("<td />")
						.addClass("logContents")
						.addClass("desc")
						.append(value.description.replace(/\n/g, '<br />'))
				);
			} else {
				tr.append(
					$("<td />")
						.addClass("desc")
				);
			}
		table.append(tr);
		
		if (count % 2 == 0) {
			tr.addClass('even');
		}
		count++;
		
	});
	
	
	
	$("subSelect:first", table).addClass("inPoint");
	
	if ($("tr:not(.subSelect)", table).length == 0) {
		$("tr.subSelect", table).removeClass('subSelect');
	}
	
	$(".videoPlayer .log table.textLog").replaceWith(table);
	
	$(".videoPlayer .tabs a.log").click();	
}

function offsetsMatchLogEntry(logId, offsetIn, offsetOut) {
	return offsetIn == 	logEntryOffsetIn && offsetOut == logEntryOffsetOut;
}

function showProMinutesRestriction() {
	//replace the video player with the specialty collection image

}

function showNoAccess() {
	//replace the video player with the no access image
}

function showVideoPlayer(tape, inPoint, outPoint, title, clipId, autoPlay, isWritable, specialAccess, specialAccessExpiryDays, path) {
	loadingNewClip = true;
	videoPopup = true;
	if (autoPlay == undefined) {
		autoPlay = true;
	}
	if (isWritable == undefined) {
		isWritable = true;
	}
	if (specialAccess == undefined) {
		specialAccess = false;
	}
	if (path == undefined) {
		path = videosUrlPath + tape.tapeId + '_' + tape.id + '_web.mov';
	}
	if (title !== undefined && title != tape.tapeId) {
		$(".titleBar #clipTitle").html(title);
	} else {
		$(".titleBar #clipTitle").html('');
	}
	$("#videoWindow").show(0, function() {
		
		if (!$(".playerBlackout").length) {
			$('<div/>')
				.addClass('playerBlackout')
				.click(function(event) {
					hideVideoPlayer();
				})
				.insertBefore($(this));
			$(window).bind('keydown', function(event) {
				if (event.keyCode == ESCAPE) {
					hideVideoPlayer();
				}
			});
		}
	});
	
	var difference = $(window).height() - $("#videoWindow").height();
	$("#videoWindow.popup").css('top', Math.floor(difference/2) + 'px');
	adjustDialogPosition($("#videoWindow.popup"), 0);
	drawTapeInfo(tape, isWritable, specialAccess, specialAccessExpiryDays);
	offsetIn= null;
	offsetOut = null;
	if (clipId == undefined) {
		currentClipId =null;
	} else {
		currentClipId =clipId;
	}
	
	if (inPoint || outPoint) {
		//setHash('tape'+ tape.id + 'i' + inPoint + 'o' + outPoint);	
		$(".videoPlayer .tabs .log").trigger('click');
		highlightClip(inPoint, outPoint);
		
	} 
	//if the clip is highlighted in the log, scroll to it.
	if ($('tr.inPoint').length) {
		$(".tabPanel div.textLog").scrollTop($(".tabPanel div.textLog").scrollTop() + $('tr.inPoint').position().top -logScrollOffset);
	//otherwise show the tape description.
	} else {
		$(".videoPlayer .tabs .details").trigger('click');
	}
	if (specialAccess || (tape.hasvideo && !tape.specialtyCollection)) {
		
		showVideo(
			path, 
			tape.startTimecode, 
			tape.endTimecode,
			tape.fps,
			autoPlay,
			inPoint,
			outPoint,
			specialAccess || tape.QCStateId != QC_STATES['Video MOS'],
			isWritable
		);
	}  else {
		loadingNewClip = false;
	}

}

function showVideoPlayerLogEntry(tape, logId) {
	highlightLogId = logId;
	drawTapeInfo(tape);
	offsets = getLogEntryOffsets(logId);
	
	showVideoPlayer(tape, offsets['in'], offsets['out']);
}

function showVideoPlayerClip(clipTape) {
	
	var path = 'clip/' + clipTape.clipType + '/' + clipTape.hashId + '.mov';
	$(".titleBar .title").html(clipTape.comment);
	$(".titleBar .type").html('clip:');
	$(".downloadClip").attr('id', 'downloadClip' + clipTape.id);
	$(".videoPlayer").removeClass('search').addClass('clip');	
	$("label[for=playerSelectBin] span").text("Save a copy to...");
	clipIn = clipTape.offsetIn;
	clipOut = clipTape.offsetOut;
	clipTitle = clipTape.comment;
	newClipTitle = clipTitle;
	$(".clip,.clipDetails").removeClass('displayed');
	$('#clipDetails' + clipTape.id).addClass('displayed');
	$('#clip' + clipTape.id).addClass('displayed');
	var specialAccess = false;
	var diffDays = 0;
	if (clipTape.accessExpires) {
		var expiryDate = Date.parseDate(clipTape.accessExpires, "Y-m-d H:i:s");
		var now =  new Date();
		specialAccess = expiryDate > now;	
		var timeDiff = Math.abs(expiryDate.getTime() - now.getTime());
		diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); 
	}
	
	showVideoPlayer(clipTape.tape, clipTape.offsetIn, clipTape.offsetOut, clipTape.notes, clipTape.id, true, clipTape.isWritable, specialAccess, diffDays, path);
}

function showTape(tapeId, inPoint, outPoint, title) {
	
	$.ajax({
		data: {
			action: 'getTape',
			tapeId: tapeId
		},
		success: function(data) {
			tapeInfo = $.parseJSON(data);
			//$("#navigationControls").show();
			showVideoPlayer(tapeInfo, inPoint, outPoint, title);
		}
	});
}

function updateVideoPlayer(offsetIn, offsetOut) {
	setPlayerOffsets(offsetIn, offsetOut);
	highlightClip(offsetIn, offsetOut);
	$(".videoPlayer .tabs .details").trigger('click');
}

function getLogEntryOffsets(logId) {
	highlightLogId = logId;
	var tcIn =  new Timecode( 
		$('.timecode', $('#desc' + logId)).text(), 
		currentTapeJSON.fps
	);
	logEntryOffsetIn = tcIn.toPosition() - playerTimecodeOffset;
	
	
	if ($('#desc' + logId).is(":last-child")) {
		logEntryOffsetOut = endOffset;
	} else {
		var tcOut = new Timecode(
			$('.timecode', $('#desc' + logId).next()).text(),
			currentTapeJSON.fps
		);
		logEntryOffsetOut = tcOut.toPosition() - playerTimecodeOffset;
	}
	
	if (logEntryOffsetOut < logEntryOffsetIn) {
		logEntryOffsetOut = null;
	}
	
	return { 
		'in': logEntryOffsetIn, 
		'out': logEntryOffsetOut
	};
}

function updateVideoPlayerLogEntry(logId) {
	loadingNewClip = true;
	offsets = getLogEntryOffsets(logId);
	setPlayerOffsets(offsets['in'], offsets['out']);
	highlightClip(offsets['in'], offsets['out']);
	
	$(".tabPanel div.textLog").scrollTop($(".tabPanel div.textLog").scrollTop() + $('tr.inPoint').position().top -logScrollOffset);
	$(".videoPlayer .tabs .log").trigger('click');
	loadingNewClip = false;
}

$(document).ready(function() {

	$(".thumbBtn").live('click', function() {
		var num = $(this).attr('id').substring("thumb".length);
		var time = num*60;
		setVideoTime(time);	
	});	

	$(".videoPlayer .tabs .details").click(function() {
		$(this).parent().parent().removeClass('log thumbnails').addClass('details');
	});
	
	$(".videoPlayer  .tabs .log").click(function() {
		$(this).parent().parent().removeClass('details thumbnails').addClass('log');
	});
	
	$(".videoPlayer .tabs .thumbnails").live('click', function() {
		$(this).parent().parent().removeClass('details log').addClass('thumbnails');
	});

	$(".tabPanel .log tr").live('click',function(event) {
		var timecode = $("td.timecode", $(this)).text();
		setVideoPosition(timecode);

	});
	
	$('.tools .emailClip').click(function() {
		
		var title = $("#videoWindow .titleBar #clipTitle").text();
		if ( title == jQuery("<div/>").append(defaultClipTitleText).text()) {
			title ="";
		} 
			
		showMailClipDialog(currentTapeId, roundToSignificantDigits(offsetIn,2), roundToSignificantDigits(offsetOut, 2), title);
	});
	
	$('.tools .contactResearcherClip').click(function() {
		
		showContactResearcherClipDialog(currentTapeId, offsetIn, offsetOut, $("#videoWindow .title").text());
	});
	
	$(".videoPlayer .tabPanel .log tr").live('click',function() {
		setVideoPosition($(".timecode", $(this)).text());
	});
	
	$(".videoPlayer .tabPanel .log tr").live('mouseover', function() {
		if (!clipIsEditable) {
			return;
		}
		var logId = $(this).attr('id');
		if (!$(this).is(":last-child")) {
			var nextLogId = $(this).next().attr('id');
		} else {
			var nextLogId = null;
		}
		var top =  $(this).position().top + $(this).height()/2 - 15;
		
		$("#clipStart")
			.css('top',top + "px")
			.unbind('click')
			.click(function() {
			var logEntry = currentTapeJSON.log[logId];
			var tmpOffsetIn = Number(logEntry.offset);
	
			if ( offsetOut == null || tmpOffsetIn < offsetOut ) {
		
				highlightClip(tmpOffsetIn, offsetOut);			
			} else {
				if (nextLogId != null) {
					var logEntry = currentTapeJSON.log[nextLogId];
					var tmpOffsetOut = Number(logEntry.offset);
				} else {
					var tmpOffsetOut = -1;
				}
				highlightClip(tmpOffsetIn, tmpOffsetOut);
			
			}
			return false;
		});
		
		$("#clipEnd")
			.css('top',top + "px")
			.unbind('click')
			.click(function() {
				if (nextLogId != null) {
					var logEntry = currentTapeJSON.log[nextLogId];
					var tmpOffsetOut = Number(logEntry.offset);
				} else {
					var tmpOffsetOut = endOffset;
				}
	
			
			if ( offsetIn < tmpOffsetOut || tmpOffsetOut == null) {
				highlightClip(offsetIn, tmpOffsetOut);			
			} else {
				var logEntry = currentTapeJSON.log[logId];
				var tmpOffsetIn = Number(logEntry.offset);
				highlightClip(tmpOffsetIn, tmpOffsetOut);
			}
			
		});
		$(".markerContainer").show();
			
	}).live('mouseout', function(e) { 
	
		if (!$(e.relatedTarget).hasClass('markerContainer') && !$(e.relatedTarget).hasClass("logMarker")
			&& !$(e.relatedTarget).hasClass("textLog")) {
			$(".markerContainer").hide();
			
		}
	});
	
	$(".markerContainer").mouseleave(function(e) {
		if (!$(e.relatedTarget).is(".tabPanel .log tr") && !$(e.relatedTarget).hasClass("logMarker") ) {
			$(".markerContainer").hide();
			
		}
	});
	
	$("#lockLog").live('click', function() {
		if (!$(this).is(':checked')) {
			clearLogHighlighting();
			$.cookie('lockLog', null);
			return;
		}
		$.cookie('lockLog', 'true');
	});
	
	$("#videoWindow .titleBar .close").click(function() {
		hideVideoPlayer();
	});
	
	$(".videoPlayer .titleBar .save").live('click', function() {
		var button = $(this);
		saveClipChanges(function() {
			clipChanged = false;
			button.hide();}
		);
		
	});
	
	if (openPlayerInDialog) {
		$("#videoWindow").draggable({
			handle: "div.titleBar",
			distance: 3
		});
	}
});



