var startTime = 8;
var userPlayer = 'jwflv42';
var userController = '1';
var userButtons = '1';
var userDvs = '1';
var userClosedDvs = '1';
var userCaptions = '0';
var userSearchDvs = '0';
var userCaptionSize = '12';

var playerID = 'gaoPlayer';
var player = null;
var currentVolume;
var previousvolume;
var currentPosition = 0;
var previousPosition = 0;
var currentState;
var previousState;
var loaded = true;
var seeking = false;
var seekPosition = 0;
var admin = 0; 
var portion = 0;

var randomID = 0;
//jw video player

function createPlayer(video, cc, image, useDvs, audio, autoStart, width, height, passed_portion) {
	if (passed_portion != null)
		portion = passed_portion;
	randomID = Math.floor(Math.random()*100000000);
	// if this player causes another player to unload, we need to log that.
	if (player) {
		
		if (currentState == 'PLAYING') {
//			clickLog('Hard Exit',currentPosition);
			player.sendEvent("STOP");
			player.sendEvent("START");
		// 	console.log('This should be current Position 0, but is still: '+currentPosition);
			currentPosition 	= 0;
		}
	}
	
	var vw = 425; /*default width*/
	var vh = 239; /*default height*/
	if (width > 0)
		vw = width;
	if (height > 0)
		vh = height;
	
	if (userController == 1) {
		var vhfull = vh + 20; /* video height + height of scrub bar */
	} else
		var vhfull = vh;
	var flashVersion = '9.0.0'; /*
								 * 9 is required for full screen; otherwise 8
								 * should work
								 */
	// var playerSwf = 'players/mediaplayer-4-2/player.swf';
	var playerSwf = '/videos/player-licensed.swf';

	// define streamerScript path relative to player.swf
	if (useDvs == 1)
		var streamerScript = '../../../FLV_DVS/xmoov.php';
	else
		var streamerScript = '../../../FLV/xmoov.php';

	var s1 = new SWFObject(playerSwf, playerID, vw, vhfull, flashVersion);

	var flashVars = 'file=' + video;
	flashVars = flashVars + '&type=video';
	flashVars = flashVars + '&volume=70'; /* program volume */

	// flashVars = flashVars + '&streamer=' + streamerScript;
	flashVars = flashVars + '&image=' + image;
	flashVars = flashVars + '&plugins=captions-1';
	flashVars = flashVars + '&captions.state=false';
	flashVars = flashVars + '&captions.fontsize=' + userCaptionSize;
	flashVars = flashVars + '&captions.back=1';

	s1.addVariable('usecaptions', 'false');
	
	if (cc)
		flashVars = flashVars + '&captions=' + cc;
//	if (audio)
//		flashVars = flashVars + '&audio=' + audio;
	flashVars = flashVars + '&id=' + playerID;

	flashVars = flashVars + '&controlbar=bottom'; // pixels
	flashVars = flashVars + '&controlbarsize=50'; // pixels
	flashVars = flashVars + '&bufferlength=1'; // seconds

	if (autoStart == 1) {
		flashVars = flashVars + '&autostart=true';
	} else {
		flashVars = flashVars + '&autostart=false';
	}

// flashVars = flashVars + '&plugins=accessibility';
//	flashVars = flashVars + '&accessibility.volume=100'; 
//	flashVars = flashVars + '&accessibility.fontsize=' + userCaptionSize;


	s1.addParam('allowfullscreen', 'true');
	s1.addParam('allowscriptaccess', 'always');
	s1.addParam("seamlesstabbing","true");
	
	s1.addParam('flashvars', flashVars);

	// write player to div - if div doesn't exist, write it NOW!!!
	s1.write('player');
}

function loadVideoText(video_id, title,runtime,description) {
	// replace the video title area with the new title, if it's all tested to be present
	if (video_id != '' && document.getElementById('video_id')) {
		document.getElementById('video_id').value = video_id;
	}
	if (title != '' && document.getElementById('video_title')) {
		document.getElementById('video_title').innerHTML = title;
	}
	if (runtime != '' && document.getElementById('video_runtime')) {
		document.getElementById('video_runtime').innerHTML = runtime;
	}
	if (description != '' && document.getElementById('video_description')) {
		document.getElementById('video_description').innerHTML = description;
	}
}

function playerReady(obj) {
	var id = obj['id'];
	player = document.getElementById(id);
	addListeners();
};

function addListeners() {
	if (player) {
		var config = player.getConfig();
		currentVolume = config['volume'];
		player.addControllerListener("SEEK", "seekListener");
		player.addControllerListener("VOLUME", "volumeListener");
		player.addModelListener("TIME", "positionListener");
		player.addModelListener("LOADED", "loadedListener");
		player.addModelListener("STATE", "stateListener");
	} else {
		setTimeout("addListeners()", 100);
	}
}

function accessibilityCaptions(txt) {
	// console.log('access listener ran');
	document.getElementById('captions').innerHTML = txt;
};

function seekListener(obj) {
	clickLog('Seek Start',currentPosition);
	seekPosition = obj.position;
	
	if (seekPosition >= currentPosition) {
		time_watched = (seekPosition-currentPosition);
//		console.log('this is time skipped: '+time_watched)
	} else {
		time_watched = currentPosition-seekPosition;
		// console.log('time watched again: '+time_watched)
	}
	clickLog('Seeking',time_watched);
	
	var tmp = document.getElementById("debugSeekPosition");
	if (tmp) {
		tmp.innerHTML = seekPosition;
	}
	var tmp = document.getElementById("debugSeeking");
	if (tmp) {
		tmp.innerHTML = seeking;
	}
	if (seeking == true) {
		if (seekPosition == startTime) {
			player.sendEvent('PLAY', true);
			player.sendevent('MUTE', false);
			seeking = false;
		}
	}
}

function volumeListener(obj) {
	currentVolume = obj.percentage;
	var tmp = document.getElementById("debugVolume");
	if (tmp) {
		tmp.innerHTML = currentVolume;
	}
}

function stateListener(obj) {
	// IDLE, BUFFERING, PLAYING, PAUSED, COMPLETED
	currentState = obj.newstate;
	previousState = obj.oldstate;

	// alert('was :'+previousState+' Now:'+currentState);
	// console.debug('OLD state: '+obj.oldstate+' new state: '+obj.newstate);
	
	var tmp = document.getElementById("debugState");
	if (tmp) {
		tmp.innerHTML = currentState;
	}
	
	// not sure this is doing anything for us... 
	if (currentState == 'PAUSED' && seeking == true) {
		// user wants to play a caption. Seek to caption point
		player.sendEvent('SEEK', startTime);
	}
	
	if (obj['newstate'] == "PLAYING" && obj['oldstate'] == "PLAYING") {
		// console.log('Playing with seek, to '+currentPosition+ ' start time :'+startTime);
		// clickLog('Seeking',currentPosition);
	}


	if (obj['newstate'] == "PLAYING" && obj['oldstate'] != "PAUSED" && obj['oldstate'] != "PLAYING") {
		clickLog('Playing',currentPosition);
		
		// if it's admin tool, start the bar highlighter
		if (admin == 1) {
			this_sec = currentPosition;
			startAdminHighlighting();
		}
	}
	
	if (obj['newstate'] == "IDLE") {
		// console.log('Idle, user stopped it deliberately: '+currentPosition);
		clickLog('Stopped',previousPosition);
		randomID = Math.floor(Math.random()*100000000);
		
		// if it's admin tool, start the bar highlighter
		if (admin == 1) {
			this_sec = -1;
			document.getElementById('cell_'+this_sec+1).style.backgroundColor='white';
			clearTimeout(timer);
		}
	}

	// no longer interested in logging pauses... 
	if (obj['newstate'] == "PAUSED") {
//		// console.log('Paused : '+currentPosition);
//		clickLog('Paused',currentPosition);
	}

	if (obj['newstate'] == "COMPLETED") {
		// console.log('Completed : '+currentPosition);
		clickLog('Completed',currentPosition);
		randomID = Math.floor(Math.random()*100000000);
		// if it's admin tool, start the bar highlighter
		if (admin ==1) {
			this_sec = -1;
			clearTimeout(timer);
		}
	}
}

function positionListener(obj) {
	previousPosition = currentPosition;
	currentPosition = obj.position;

	if (currentPosition > 0)
		loaded = true;
	var tmp = document.getElementById("debugPosition");
	if (tmp) {
		tmp.innerHTML = currentPosition;
	}
}

function loadedListener(obj) {
	if (obj.loaded > 0)
		loaded = true;
	var tmp = document.getElementById("debugLoaded");
	if (tmp) {
		tmp.innerHTML = obj.loaded;
	}
}

function playPause() {
	player.sendEvent("PLAY");
}

var this_sec = -3;
var timer;
function startAdminHighlighting() {
	that_sec = this_sec;
	this_sec = this_sec+1;
	
	document.getElementById('cell_'+this_sec).style.backgroundColor='pink';
	if (that_sec >= 0) {
		document.getElementById('cell_'+that_sec).style.backgroundColor='white';
	}
	
	// console.log('This sec: '+this_sec);
	timer = setTimeout('startAdminHighlighting()',1000);
}

function stop() {
	player.sendEvent("STOP");
}

function seek(startTime) {
	player.sendEvent("SEEK", startTime);
}

function changeVolume(direction) {

	// volume is expressed in percent
	// move up or down in increments of 10
	// first, get current volume
	if (direction == 'up') {
		if (currentVolume <= 90)
			var volume = currentVolume + 10;
	} else if (direction == 'down') {
		if (currentVolume >= 10)
			var volume = currentVolume - 10;
	}
	if (volume >= 0 && volume <= 100)
		player.sendEvent('VOLUME', volume);
}

function mute() {

	// if volume is already muted, restore to previous volume
	// otherwise, mute
	if (currentVolume == 0) {
		player.sendEvent('VOLUME', previousVolume);
		currentVOlume = previousVolume;
	} else {
		previousVolume = currentVolume;
		player.sendEvent('VOLUME', 0);
		currentVolume = 0;
	}
}

function captions(video, cc, image, useDvs, audio, autoStart) {
	
	// get the timestamp of the current player	
	caption_switched_at = currentPosition;

	// default is 1 = ON by default right now
	if (userCaptions == 1) {
		// are on now...so keep a record in case we turn them off
		cc 		= '';
		userCaptions = 0;
	} 
	player = null;
	
	// this might nede to get logged too
	
	// alert('switch captions at: '+currentPosition);
	// create a new player,with or without captions as per instructions... auto start it
	createPlayer(video, cc, image, useDvs, audio, 1, 0, 0);

	// seek back to where we were in the new player
	//alert('seek to: '+caption_switched_at+' current '+currentPosition);
	setTimeout('seek('+(caption_switched_at-3)+')',500);	
	clickLog('Captions',currentPosition);
}

function clickLog(action,position_seconds) {
	// only log clicks if it's not in admin mode... 
	if (admin != 1 ) {
		video_id = document.getElementById('video_id').value;

		// do not log clicks from admin screens... figure that out.
		holler('POST','/index.php','&system_action=Videos_log&vid='+video_id+'&action='+action+'&position_seconds='+position_seconds+'&tmp_uri='+window.location+'&randomID='+randomID+'&portion='+portion);
	}
};

// catch it when they just leave, close browser or click to a new page
window.onunload = function exitVideo() { 
	
	// only a hard exit if the current status is playing, otherwise, it's either not started, or already finished
	if (currentState == 'PLAYING') {
		clickLog('Hard exit',currentPosition);
	}
}
