/**
 * ASP Treeviper Video class
 * (c)2008 Alexander Street Press
 * All Rights Reserved
 * 
 */

//declaring the class with prototype's help
var TranscriptVideo = Class.create();

//defining the rest of the class implementation
TranscriptVideo.prototype = {

/**
 * Constructor 
 */
 initialize: function() {
    this.div=$('video_player_transcript');
    this.swf=this._getFlashPlugin('videotranscript');
    this.transcript=null;
    this.index = -1;
    this.matches = 0;
    //this.sync_position = true;
    this.intervalpos = 30;
    this.ptagindex = 0;
 	this.lastSec = -1;
    this.ok = true;
    this.repositioning = false;
    this.timeCodeStep = 5;
    this.ptags = null;
    this.entityId = $('video_entity_id').innerHTML;
	this.requestPtags();
},

/*====================================================================*
  Public methods
 *====================================================================*/
 

 /**
 * Tell video to jump to given position
 * @access public
 */

requestPtags:function() {
	var url = '/Video/ptags/' + this.entityId;
	new Ajax.Request(url, {
  		method: 'get',
  		evalJSON: 'true',
 		onSuccess:this.ptagSuccessCallback.bind(this),
 		onFailure:this.ptagFailCallback.bind(this)
	});

},

/*
 * This function loads the list of paragraph tags for  
 */
ptagSuccessCallback:function(transport) {
	this.ptags=transport.responseJSON;
},

/*
 * This function loads the 
 */
ptagFailCallback:function(transport) {
	setTimout(this.requestPtags.bind(this),500);
},


takeQuery: function(dorpid,entityid,lang,query) {

	if (! query) {
		alert("You did not enter a value into the search box.");
	} else {
		this.matches = 0;
		if (this.timecodes) {
			this.clearTimecodes(this.timecodes);
		}
		$('responsebox').update('<img src="/ui/asp/icons/ajax_indicator.gif" width="16" height="16" title="please wait..." alt="please wait animation"/><span style="font-size:8pt;"> Please wait...</span>');
		var url ='/video/transcriptquery/' + dorpid + '/' + entityid + '/' + lang + '/' + query;
		new Ajax.Request(url, {
  			method: 'get',
 			onComplete: function(transport) {
				this.contextCallback(transport, query)
			}.bind(this)
		});
	}
},

contextCallback:function(transport, query) {
	this.resetTranscriptText();
	var jsonobj = transport.responseText.evalJSON();
	this.responsecount = jsonobj.count;
	this.passages = jsonobj.passages;
	this.timecodes = jsonobj.timecodes;
	this.index = -1;
	$('playresults').innerHTML = "";
	if (this.responsecount == 0) {
		this.ok = false;
		$('responsebox').innerHTML = "No results found.";
		$('leftmovement').innerHTML = "";
		$('rightmovement').innerHTML = "";
		$('playbutton').innerHTML = "";
	} else {
		$('leftmovement').innerHTML = "";
		this.sendTimecodes(this.timecodes);
		var processText = $('reserve_transcript').innerHTML;
		var query = '([\\r|\\n|\\s|\\;|\\u2014|\\-|\\.|\\!|\\,|\\/|\\?|\'|\\"|\\<|\\>])(' + query + ')([\\r|\\n|\\s|\\;|\\u2014|\\-|\\.|\\!|\\,|\\/|\\?|\'|\\"|\\<|\\>])';
		var highlightRegEx = new RegExp(query,"ig");
		$('transcript').innerHTML = processText.replace(highlightRegEx,this.replaceMatch.bind(this));
		this.moveForward();
	}
},

moveForward:function() {
	if (this.index < (this.responsecount-1)) {
		this.repositioning = true;
		this.index += 1;
		if (typeof(this.timecodes[this.index]) == 'number') {
			if (this.index > 0) {
				$('leftmovement').innerHTML = "<input type=button class=\"btn\" value=\"<-\" onclick=\"player.moveBackward()\">";
			}
			$('responsebox').innerHTML = ' Found '+(this.index + 1)+' of '+this.responsecount+' hits';
			$('playresults').innerHTML = this.passages[this.index];
			$('rightmovement').innerHTML = "<input type=button class=\"btn\" value=\"->\" onclick=\"player.moveForward()\">";
			$('playbutton').innerHTML = "<input type=button class=\"play\" value=\"     Play\" onClick=\"player.playVideo('" + this.timecodes[this.index] + "');return false;\">";
			this.transcript.clearAllHighlights();
			this.setVideoPositionPause(this.timecodes[this.index],'matches' + this.index);
			if (this.index >= (this.responsecount-1)) {
				$('rightmovement').innerHTML = "";
			}
		}
		this.repositioning = false;
	}
},

moveBackward:function() {
	if (this.index > 0) {
		this.repositioning = true;
		this.index -= 1;
		if (typeof(this.timecodes[this.index]) == 'number') {
			$('responsebox').innerHTML = ' Found '+(this.index + 1)+' of '+this.responsecount+' hits';
			$('playresults').innerHTML = this.passages[this.index];
			$('rightmovement').innerHTML = "<input type=button class=\"btn\" value=\"->\" onclick=\"player.moveForward()\">";
			$('playbutton').innerHTML = "<input type=button class=\"play\" value=\"     Play\" onClick=\"player.playVideo('" + this.timecodes[this.index] + "');return false;\">";
			//$('playbutton').innerHTML = "<input type=image src=\"/ui/common/playicon_off.gif\" onmouseover=\"this.src='/ui/common/playicon_on.gif';\" onmouseout=\"this.src='/ui/common/playicon_off.gif';\" value=\"Play\" onClick=\"player.setVideoPosition('" + this.timecodes[this.index] + "');return false;\">";
			this.transcript.clearAllHighlights();
			this.setVideoPositionPause(this.timecodes[this.index],'matches' + this.index);
		}
		this.repositioning = false;
	} 
	if(this.index == 0){
		$('leftmovement').innerHTML = "";
	}
},
	
onSendQuery:function(dorpid,entityid) {
	var query = $('tquery').value;
	this.pauseVideo();
	this.takeQuery(dorpid,entityid,'en',query);
	TabbedPanels1.showPanel('tab1');
},

replaceMatch:function() {
	//this receives a variable number of matches based on the matches to the regular expression sub-matches (parenthesized strings)
	var termMatch = arguments[2];
	var pos = arguments[arguments.length - 1];
	var replaceString = arguments[1] + "<span class=\"snippet\" tc=\"-1\" onclick=\"";
	replaceString += "player.moveBackward();return(false);\" style=\"cursor:pointer" ;
	replaceString += "\">&laquo;</span><span tc=\"-1\" id=\"matches" + this.matches + "\" class=\"snippet\">" + termMatch + "</span><span tc=\"-1\" class=\"snippet\" onclick=\"";
	replaceString += "player.moveForward();return(false);\" style=\"cursor:pointer";
	replaceString += "\">&raquo;</span>" + arguments[3];
	this.matches++;
	return(replaceString);
},

playVideo:function(seconds) {
	this.swf.asSetPositionStart(seconds);
	this.swf.asPlay();
},

setVideoPosition: function(seconds, id) {
	this.repositioning = true;
	this.swf.asSetPositionStart(seconds);
	this.setTranscriptPosition(seconds,id);
	this.repositioning = false;
},

playSegment: function(seconds) {
	this.swf.asSetPosition(seconds);
	this.setTranscriptPosition(seconds);
},

setVideoPositionPause: function(seconds,id) {
	this.swf.asSetPositionPause(seconds);
	this.setTranscriptPosition(seconds,id);
},

bindVideo:function(event)
{
	var pos=event.memo;
},

sendTimecodes:function(timecodes)
{
	this.swf=this._getFlashPlugin('videotranscript');
	this.swf.asSendTimecodes(timecodes);
},

clearTimecodes:function(timecodes)
{
	this.swf=this._getFlashPlugin('videotranscript');
	this.swf.asClearTimecodes(timecodes);
},

resetTranscriptText:function()
{
	this.index = -1;
	this.transcript.clearCache();
	$('transcript').innerHTML = $('reserve_transcript').innerHTML; 
},

populateReset:function(transport) {

	var jsonobj = transport.responseText.evalJSON();
	transcript = jsonobj.transcript

	$('transcript').innerHTML = transcript;
	
},

clearBox:function(dorpID) {

	this.clearTimecodes(this.timecodes);
	$('tquery').value = '';
	$('responsebox').innerHTML = '';
	$('leftmovement').innerHTML = '';
	$('rightmovement').innerHTML = '';
	$('playresults').innerHTML = '';
	$('playbutton').innerHTML = '';
	this.transcript.reset();
	this.resetTranscriptText();

},

sendClip: function(id,start,finish) {

	this.swf=this._getFlashPlugin('videotranscript');
	this.swf.asSendClip(id,start,finish);

},

hoverClip: function(id) {
	this.swf=this._getFlashPlugin('videotranscript');
	this.swf.asHoverClip(id);
},

hoverOut: function(id) {
	this.swf=this._getFlashPlugin('videotranscript');
	this.swf.asHoverOut(id);
},

 /**
 * Tell video to jump to given position
 * @access public
 */
sendTranscript: function(query) {

	this.swf=this._getFlashPlugin('videotranscript');
	this.swf.asSendTranscript(query);
},

pauseVideo: function() {

	this.swf=this._getFlashPlugin('videotranscript');
	this.swf.asPauseVideo();
},

 /**
 * Tell video to observe pos value of treeviperplayer
 * @access public
 */
 
observe: function(event, handler) {
	
	$('video_player_transcript').observe(event,handler);
},

_enterKeyQuery:function(event){
		
if (event.keyCode == Event.KEY_RETURN) {
alert('pressed');
}
},

changeLabel:function(){

if ($('synccheck').value == "Disable Synchronization") {
$('synccheck').value = "Enable Synchronization";
this.sync_position=false;
//console.log(this.sync_position);
return;
}

if ($('synccheck').value == "Enable Synchronization") {
$('synccheck').value = "Disable Synchronization";
this.sync_position=true;
//console.log(this.sync_position);
}

},

/**
 * tells the controller about our transcript object
 * @access public
 */
setTranscript: function(transcript) {

	this.transcript=transcript;
	
	this.sync_position=$('sync_position');

},


onNewTranscriptSelection:function(event)
{
	
	//create new clip for selection
	var clip=new Object();
	clip.start=event.memo.start;
	clip.end=event.memo.end;
	clip.title="Selection";
		
	//show clip in transcript
	//this.transcript.highlightPeriod(clip.start, clip.end);
	
},

setTranscriptPosition:function(pos,id) {

	if(typeof(id) != 'undefined') {
		this.transcript.scrollIntoView(pos,id);
	} else {
		var paragraphsToHighlight = this.getParagraphsByTime(pos);
		this.transcript.highlightTime(pos, paragraphsToHighlight);
	}
	this.repositioning = false;
},

getParagraphsByTime:function(pos) {
	var PKey = "";
	var paragraphsToHighlight = new Array();
	var firstFound = false;
	if(parseInt(this.ptags[this.ptagindex]['min']) > pos) {
		this.ptagindex = 0;
	}
	for ( var i = this.ptagindex; i < this.ptags.length;i++ ) {
		pKey = this.ptags[i]['id'];
		var lowerBound = parseInt(this.ptags[i]['min']) - this.timeCodeStep;
		var upperBound = parseInt(this.ptags[i]['max']) + this.timeCodeStep;
		if (this.ptags[i]['min'] > pos && this.ptags[i]['min'] != this.ptags[i]['max']) {
			break;
		} else if(upperBound >= pos && lowerBound <= pos) {
			if(!firstFound) {
				this.ptagindex = i;
				firstFound = true;
			}
			paragraphsToHighlight.push(pKey);
		}
	}
	return(paragraphsToHighlight);
},

onVideoPlayheadUpdate:function(event)
{
	var pos=event.memo;
	var sec = parseInt(pos);
	 
	if(typeof(pos) != 'number' || this.lastSec == sec || this.repositioning) {
		return;
	}
	
	if (this.sync_position.checked) {
		var paragraphsToHighlight = this.getParagraphsByTime(sec);
		this.transcript.highlightTime(sec, paragraphsToHighlight);
	}
	this.lastSec = sec;
},

onClipCompleted:function(event)
{
//	alert(event);
	
},

onVideoCompleted:function(event)
{
//	alert(event);
},

syncTranscript:function(status)
{
	if (status=='on') {
		this.sync_position=true;
	} else {
		this.sync_position=false;
	}
	
},

/*====================================================================*
  Internal private methods
 *====================================================================*/
/**
 * This is the Adobe approved method of getting the element
 * containing the flash plugin, but probably no different
 * to using Prototype.
 * @access private
 */
_getFlashPlugin: function (movieName) {
    if (navigator.appName.indexOf("Microsoft") != -1) {
    	return window[movieName]
    }
    else {
    	return document[movieName]
    }
}
 
};


/**
 * Actionscript calls this when the playhead moves - we fire an event
 * which can by observed by using the observe method
 * @access public
 */
function playheadUpdate(pos) 
{
	$('video_player_transcript').fire("video_player_transcript:playheadUpdate", pos);
}

function clipCompleted(event)
{
	if($('control_div')) {
		$('control_div').fire("player:finished", event);
	}
}


function videoCompleted(event)
{
	if($('control_div')) {
		$('control_div').fire("player:finished", event);
	}
}


