// These variables are for setting up the IDs and classes for player elements
var playerId = 'thePlayerId';		// This variable contains the ID to assign to the player object
var volSliderId = 'volSlider';
var posSliderId = 'posSlider';
var bufferingId = 'buffering';
var pauseButtonId = 'pause_button';
var initBarId = 'init_bar';
var playbackBarId = 'playback_bar';
var loadingBarId = 'loading_bar';
var playbackTimeId = 'playback_time';
var volumeBarId = 'volume_bar';
var muteId = 'mute';
var currentPlayPosition = 0;
var fileFinishedLoading = false;
var prevSliderPos = 0;
var totalPlaySliderSize = 10000;
var playerPath = 'http://service.ichristianlife.com/player5/mediaplayer-4-2/player.swf';		// This variable contains the path to the player SWF
var totalMovieLength = 0;
var currentVolume = 0;
var mute = false;
var blockSlide = false;
var playerCreated = false;
var currentPlayerState = 0;
var previousPlaybackTime = 0;
var muteOpacity = 1;

var playerExists = false;
var player;

var iclPlayer = {
	'file_playing': '',
	'previous_file': '',
	'current_time': 0,
	'maximum_time': 0,
	'current_volume': 0,
	'is_muted': false,
	'is_playing': false,
	'has_started_playing': false
};

var iclPlayerMeasure = {
	'last_seconds_sent': 0,
	'last_file_start_filename': '',
	'last_file_start_time': 0,
	'measure_url': 'http://service.ichristianlife.com/measure/'
};

//////////////////////////////////////////////////////////////////////////////////////////
// The following are functions that maintain a javascript interface to the player object //
///////////////////////////////////////////////////////////////////////////////////////////

function volumeListener(obj) {
	volumeChangedCallback(obj.percentage);
}

function stateListener(obj) {
	switch(obj.newstate) {
//		case "COMPLETED": playerStateChangedCallback(0); break;
		case "PAUSED": playerStateChangedCallback(0); break;
		case "BUFFERING": playerStateChangedCallback(1); break;
		case "PLAYING": playerStateChangedCallback(2); break;
		case "COMPLETED": playerStateChangedCallback(3); break;
	}
}

function loadedListener(obj) {
	loadedChangedCallback( (100 * ((1.0 * obj.loaded) / obj.total)));
}

function timeListener(obj) {
	playbackTimeChangedCallback(obj.position, (obj.duration - obj.position));
}

function bufferingListener(obj) {
	// Can extend this function to provide a "Buffering" display
	var percentage = obj.percentage;
}

function initPlayer(obj) {
	// Initialize listeners
	player = document.getElementById(obj['id']);
	playerExists = true;
	playerCreated = false;
	player.addControllerListener("VOLUME", "volumeListener");
	player.addModelListener("STATE", "stateListener");
	player.addModelListener("LOADED", "loadedListener");
	player.addModelListener("TIME", "timeListener");
	player.addModelListener("BUFFER", "bufferingListener");
	player.add
}

// these functions are caught by the JavascriptView object of the player.
// Don't mess with these functions as they are the interface between the player
//   and my custom API callback functions
function sendEvent(typ,prm) {
	if(playerExists) {
		var movie = thisMovie(playerId);
		switch(typ) {
			case 'playpause': movie.sendEvent("PLAY"); break;
			case 'volume': movie.sendEvent("VOLUME", prm); break;
			case 'scrub': movie.sendEvent("SEEK", prm); break;
			case 'redraw': movie.sendEvent("REDRAW"); break;
			
		}
	}
//	movie.sendEvent(typ,prm);
}

function getUpdate(typ,pr1,pr2,pid) {   
	if(typ == "state") { playerStateChangedCallback(pr1);  }	
	else if(typ == "volume") { volumeChangedCallback(pr1); }
	else if(typ == "load") { loadedChangedCallback(pr1); }
	else if(typ == "time") { playbackTimeChangedCallback(pr1, pr2); }
}

// This is a javascript handler for the player and is always needed.
// Don't mess with this since it's an interface element.
function thisMovie(movieName) {
	return document.getElementById(movieName);
}

// This function creates the player instance
// Values here can be altered to change the behavior of the player object itself
function createplayer(theFile, playerDiv, autoStart, playerOptions) {
	var swfOptions = {
		'width': '320',
		'height': '160'
	};
	if(typeof(playerOptions) != "undefined") {
		if(typeof(playerOptions.width) != "undefined") {
			swfOptions.width = playerOptions.width;
		}
		if(typeof(playerOptions.width) != "undefined") {
			swfOptions.height = playerOptions.height;
		}
	}
	if(autoStart) {
		autoStart = '&autostart=true';
	} else {
		autoStart = '';	
	}

	var s = new SWFObject(playerPath,playerId,swfOptions.width,swfOptions.height,'9');
	var flashParams = {
		'allowscriptaccess': 'always',
		'allowfullscreen': 'true',
		'flashvars': '&file=' + theFile + '&controlbar=none&icons=false' + autoStart + '&width=' + swfOptions.width + '&height=' + swfOptions.height + '&plugins=gapro-1&gapro.accountid=UA-3614417-4&gapro.trackstarts=true&gapro.trackpercentage=true&gapro.tracktime=true&gapro.trackcompletes=true'
	};
	if(typeof(playerOptions) != "undefined" && typeof(playerOptions.flashParams) != "undefined") {
		for(var i in playerOptions.flashParams) {
			flashParams[i] = playerOptions.flashParams[i];
		}
	}
	for(var i in flashParams) {
		s.addParam(i, flashParams[i]);
	}
	s.write(playerDiv);
	iclPlayer.previous_file = iclPlayer.file_playing;
	iclPlayer.file_playing = theFile;

/*	var s = new SWFObject(playerPath,playerId,"100%","100%","7");
	s.addParam("allowfullscreen","false");

	s.addParam('allowscriptaccess','always');

	s.addVariable("file", theFile);
	s.addVariable("displayheight","9999");
	s.addVariable("showicons","false");
	s.addVariable("enablejs","true");
	s.addVariable("javascriptid",playerId);
	s.addVariable("shownavigation", "false");
	s.addVariable("showdigits", "false");
	if (autoStart) { s.addVariable("autostart","false"); }
	s.write(playerDiv);*/
}

/////////////////////////////////////////////////////////////////////////
// The following are functions you can call to change the player state //
/////////////////////////////////////////////////////////////////////////

// This function toggles the played / paused status of the player
function playToggle() {
	if(thisMovie(playerId)) {
		sendEvent('playpause');
	}
}

// This function sets the volume to a new percentage
function setVolume(setToPercent) {
	if(thisMovie(playerId)) {
		currentVolume = setToPercent;
		if(!mute) {
			sendEvent('volume', currentVolume);
		}
		helperSetVolumeBarWidth(setToPercent);
	}
}

// This function sets the playback position to a new time in seconds
function setPlayPosition(setToSeconds) {
	if(thisMovie(playerId)) {
		sendEvent('scrub', setToSeconds);
	}
}

function loadFile(swf,filename,fileType) { 
  if(playerExists) {
	  if(fileType == null) {
		  var extension = filename.substr((filename.length-3), 3)
		  switch (fileType) {
			  case 'flv': fileType = 'video'; break;
			  case 'mp3': fileType = 'audio'; break;
			  case 'm4a': fileType = 'audio'; break;	  
		  }
	  }
	  thisMovie(swf).sendEvent("LOAD", {type:fileType,file:filename});
	  iclPlayer.file_playing = filename;
	//  thisMovie(swf).loadFile({file:filename});
	  playerCreated = false;
	  fileFinishedLoading = false;
	  helperSetLoadBarWidth(0);
	  helperSetPlaybackBarWidth(0.0);
	  // alert(filename); // detect audio/video here and update display accordingl
  }
}

function loadFileAndPlay(swf,filename,fileType) { 
  loadFile(swf, filename,fileType);
//  setTimeout("playToggle();", 500);
}

//function playWhenLoaded() {
//	setTimeout("playWhenLoaded()",1000);	
//}

function redrawPlayer() {
	sendEvent('redraw', null);
}

///////////////////////////////////////////////////////////
// The following are callback functions from the player. //
///////////////////////////////////////////////////////////

// The following are callback functions to respond to the player doing things
function volumeChangedCallback(updateVolPercent) {
	// You can do things here to respond to the player having updated the playback volume
	// New playback volume is in updateVolPercent
	if(typeof(updateVolPercent) == "string") updateVolPercent = parseInt(updateVolPercent);
	// Only update the slider if it needs updating	
	// This "if" prevents an infinite loop between callbacks of the player & slider objects
	if($("#" + volSliderId).slider("option", "value") != updateVolPercent && !mute) {
		$("#" + volSliderId).slider("option", "value", updateVolPercent);
	}
	// Change the volume bar width if the player is not muted
	// This is to make the interface look right when you adjust the volume while
	//   the player is muted.
	if(!mute) {
		helperSetVolumeBarWidth(updateVolPercent);
	}
	iclPlayer.current_volume = updateVolPercent;
}

function loadedChangedCallback(updateLoadedPercent) {
	// You can do things here to respond to the player having updated the % of the file loaded
	// New percent loaded is in updateLoadedPercent

	if(updateLoadedPercent == 100) fileFinishedLoading = true;
	// Change the progress width on the "load bar"
	helperSetLoadBarWidth(updateLoadedPercent);
}

var userSliding = false;
var userDragging = false;
var userSlidingVal = 0;

function playbackTimeChangedCallback(updateElapsedTime, updateRemainingTime) {
	// You can do things here to respond to the player having updated remaining playback time
	// New elapsed time is in updateElapsedTime
	// New remaining time is in updateRemainingTime

	// Set variable "totalMovieLength" on first invocation
	// This is done to allow us to have the total movie length handy
	if((fileFinishedLoading == false && currentPlayPosition != updateElapsedTime) || (fileFinishedLoading == true && totalMovieLength == 0) || playerCreated == false) {
		totalMovieLength = updateRemainingTime + updateElapsedTime;
		iclPlayer.maximum_time = totalMovieLength;
	}
	currentPlayPosition = updateElapsedTime;
	iclPlayer.current_time = updateElapsedTime;

	// On the first invocation (and after the player is correctly created and whatnot), create
	//   the slider bar to adjust the play position.
	// This is done because the slider UI element needs to have max length set at creation time
	//   and we don't have the max length available until after the player has been created and
	//   is loaded
	if(playerCreated == false && totalMovieLength > 1) {
		// Destroy the old slider
		if($("#" + posSliderId).slider("option", "value") != undefined) {
			$("#" + posSliderId).slider( "destroy" );
		}
		// Create a position slider
		$("#" + posSliderId).slider({
			min: 1,
			max: totalPlaySliderSize,
			slide: function(event, ui) {
				userDragging = true;			
			},
			stop: function(event,ui) {
				if(blockSlide == false) {
					var newPos = (parseFloat(ui.value) / parseFloat(totalPlaySliderSize)) * totalMovieLength;
					userSliding = true;
					userSlidingVal = newPos;
					setPlayPosition(newPos);
				}
				blockSlide = false;
				userDragging = false;
			}/*,
			change: function(event,ui) { 
				if(blockSlide == false) {
					var newPos = (parseFloat(ui.value) / parseFloat(totalPlaySliderSize)) * totalMovieLength;
					setPlayPosition(newPos);
				}
				blockSlide = false;
			}*/
		});
		playerCreated = true;
		if(typeof(iclPlayerFileLoaded) == 'function') {
			iclPlayerFileLoaded();
		}
		playerMeasureLoaded(iclPlayer.file_playing);
	}

	var percentPlayback = (parseFloat(updateElapsedTime) / parseFloat(totalMovieLength)) * 100.00;
	// Adjust the "playback bar" progress indicator and the text indicators.
	helperSetPlaybackBarWidth(percentPlayback);
	helperSetPlaybackTimer(updateElapsedTime, totalMovieLength);
	
	if(updateElapsedTime != previousPlaybackTime) {
		previousPlaybackTime = updateElapsedTime;
	}
}

function playerStateChangedCallback(updateState) {
	// You can do things here to respond to the player having updated its state
	// updateState contains the number of the new state
	// State values:
	//	0: Stopped
	//	1: Buffering
	//	2: Playing
	//  3: Completed
	currentPlayerState = updateState;
	if (updateState == 0) {
		// When stopped, the buffering indicator is hidden
		$('#' + bufferingId).css("display", 'none');
		// When stopped, the pause/play button displays the "press here to play" side
		$('#' + pauseButtonId).css("filter", 'alpha(opacity=0)');
		$('#' + pauseButtonId).css("-moz-opacity", "0.0");
		$('#' + pauseButtonId).css("opacity", '0.0');
		iclPlayer.is_playing = false;
	} else if (updateState == 1) {
		// When buffering, the buffering indicator is displayed
		$('#' + bufferingId).css("display", 'inline');
		// When buffering, the pause/play button displays the "press here to play" side
		$('#' + pauseButtonId).css("filter", 'alpha(opacity=0)');
		$('#' + pauseButtonId).css("-moz-opacity", "0.0");
		$('#' + pauseButtonId).css("opacity", '0.0');
		iclPlayer.is_playing = false;
	} else if (updateState == 2) {
		// When playing, the buffering indicator is hidden
		$('#' + bufferingId).css("display", 'none');
		// When playing, the pause/play button displays the "press here to pause" side
		$('#' + pauseButtonId).css("filter", 'alpha(opacity=100)');
		$('#' + pauseButtonId).css("-moz-opacity", "1.0");
		$('#' + pauseButtonId).css("opacity", '1.0');
		iclPlayer.is_playing = true;
		iclPlayer.has_started_playing = true;
	} else if (updateState == 3) {
		// When finished, the buffering indicator is hidden
		$('#' + bufferingId).css("display", 'none');
		// When finished, the pause/play button displays the "press here to play" side
		$('#' + pauseButtonId).css("filter", 'alpha(opacity=0)');
		$('#' + pauseButtonId).css("-moz-opacity", "0.0");
		$('#' + pauseButtonId).css("opacity", '0.0');
		iclPlayer.is_playing = false;
		fileDonePlayingCallback();
	}
}

function fileDonePlayingCallback() {
	if(typeof(iclPlayerFileCompleted) == 'function') {
		iclPlayerFileCompleted();
	}
	playerMeasureCompleted(iclPlayer.file_playing);
	if(playlist && playlist.length > 0 && typeof(currentPlaylistItem) == 'number') {
		if((currentPlaylistItem + 1) < playlist.length) {
			selectPlayListItem(currentPlaylistItem + 1);
		}
	}
}

function helperSetPlaybackBarWidth(percentage) {
	// Calculate the new width in pixels of the playback progress bar
	//  based on the percentage done and the maximum width
	var playbackBarMaxWidth = $('#' + initBarId).css('width');
	playbackBarMaxWidth=parseInt(playbackBarMaxWidth.substring(0, playbackBarMaxWidth.length-2)); // drop PX
	var playbackBarWidth = percentage;
	playbackBarWidth = (percentage / 100.0) * parseFloat(playbackBarMaxWidth);
	// This adjustment prevents display errors when starting
	if (playbackBarWidth == 0) playbackBarWidth = 1;
	// Change the playback progress bar
	$('#' + playbackBarId).css( "width", playbackBarWidth + 'px');
}

function helperSetLoadBarWidth(percentage) {
	// Calculate the new width in pixels of the loading progress bar
	//  based on the percentage done and the maximum width
	var loadingBarWidth = percentage;
	var loadingBarMaxWidth = $('#' + initBarId).css('width');
	loadingBarMaxWidth=parseInt(loadingBarMaxWidth.substring(0, loadingBarMaxWidth.length-2)); // drop PX
	loadingBarWidth = (percentage / 100) * loadingBarMaxWidth;
	// This adjustment prevents display errors when initializing
	if (loadingBarWidth == 0) loadingBarWidth = 1;
	// Change the loading progress bar
	$('#' + loadingBarId).css("width", loadingBarWidth + 'px');
}

function helperSetPlaybackTimer(currentSec, maxSec) {
	// Update the playback progress display
	// Formatting of this area is dependant on the text size of current and max sec
	if (maxSec>599) {
		$('#' + playbackTimeId).html( mmsstime(currentSec) + '/' + mmsstime(maxSec) );
	} else {
		$('#' + playbackTimeId).html( mmsstime(currentSec) + ' / ' + mmsstime(maxSec) );
	}
	// Only move the slider if it needs updated to avoid infinite loops between the
	//    player object and slider object callbacks.
	var sliderValue = (parseFloat($("#" + posSliderId).slider("option", "value")) / parseFloat(totalPlaySliderSize)) * totalMovieLength;
	var newSliderValue = (parseFloat(currentSec) / parseFloat(totalMovieLength)) * totalPlaySliderSize;
	
	if(userSliding && Math.floor(currentSec) == Math.floor(userSlidingVal)) {
		//blockSlide = true;
		prevSliderPos = currentSec;
		$("#" + posSliderId).slider("option", "value", newSliderValue);
		userSlidingVal = 0;
		userSliding = false;
	} else if(!userDragging && prevSliderPos != currentSec && !userSliding) {
		//blockSlide = true;
		prevSliderPos = currentSec;
		$("#" + posSliderId).slider("option", "value", newSliderValue);
	}
}

function helperSetVolumeBarWidth(percentage) {
	// Calculate the new width in pixels of the volume bar
	//  based on the percentage done and the maximum width
	var volBarMaxWidth = $('#' + volSliderId).css('width');
	volBarMaxWidth=parseInt(volBarMaxWidth.substring(0, volBarMaxWidth.length-2)); // drop PX
	var volBarWidth = percentage;
	volBarWidth = (percentage / 100) * volBarMaxWidth;
	// This adjustment prevents display errors when at minimum
//	if (volBarWidth == 0) volBarWidth = 1;
	// Change the volume bar
	$('#' + volumeBarId).css("width", volBarWidth + 'px');
}

function muteToggle() {
	var notMutedOpacity = (muteOpacity+1) % 2;
	if(!mute) {
		// Toggle to muted
		mute = !mute;
		iclPlayer.is_muted = mute;
		sendEvent('volume', 0);
		// Display the "muted" icon
		$('#' + muteId).css("filter", 'alpha(opacity=' + (muteOpacity*100) + ')');
		$('#' + muteId).css("-moz-opacity", muteOpacity + ".0");
		$('#' + muteId).css("opacity", muteOpacity + '.0');
	} else {
		// Toggle to "not muted"
		mute = !mute;
		iclPlayer.is_muted = mute;
		sendEvent('volume', currentVolume);
		// Hide the "muted" icon
		$('#' + muteId).css("filter", 'alpha(opacity=' + (notMutedOpacity*100) + ')');
		$('#' + muteId).css("-moz-opacity", notMutedOpacity + ".0");
		$('#' + muteId).css("opacity", notMutedOpacity + '.0');
	}
}

// Function to convert seconds to mintues & seconds display
function mmsstime(seconds) {
	if(seconds == 0 || isNaN(seconds)) {
		return '0:00';	
	}
	seconds=Math.round(seconds);
	var minutes=Math.floor(seconds / 60);
	seconds=(seconds % 60);
	if (seconds<=9) { seconds='0' + seconds; }
	var result=minutes + ':' + seconds;
	return result;
}

/////////
// Media Measurement functionality
/////////
function playerMeasureLoaded(filename) {
//http://service.ichristianlife.com/media/play/?pagename=icl2_media_player&lang=english&typ=mp3&aut=luis_palau&alb=reaching_your_world&ttl=sacrifice&cat=share&trk=&s_category=share&s_author=luis_palau&s_album=reaching_your_world&s_title=sacrifice&s_type=mp3&s_track=&dsc=The%20call%20of%20the%20Great%20Commission%20is%20a%20call%20to%20sacrifice%20for%20Jesus.&
//	var measureFilename = 'http://measure.ichristianlife.com/?category=bible&author=bill_bright&album=written_by_the_hand_of_god&title=adultery&type=mp3&language=english&detail=show';
	var now = new Date();
	now = now.getTime();
	if(now >= (iclPlayerMeasure.last_file_start_time+10000) || (iclPlayerMeasure.last_file_start_filename != filename)) {
		iclPlayerMeasure.last_file_start_filename = filename;
		iclPlayerMeasure.last_file_start_time = now;
		var measureFilename = iclPlayerMeasure.measure_url;
		iclPlayerMeasure.last_seconds_sent = 0;
		var measureData = 'detail=start&url=' + escape(unescape(filename));
		if(typeof(iclMediaMeasure) == "function") {
			iclMediaMeasure({ url: measureFilename, data: measureData, success:playerMeasureLoadedSuccessCallback, error: playerMeasureLoadedErrorCallback});
		} else {
			 $.ajax({
				type: "GET",
				url: measureFilename,
				data: measureData,
				success: playerMeasureLoadedSuccessCallback,
				error: playerMeasureLoadedErrorCallback
			});
		}
	}
}

function playerMeasureLoadedSuccessCallback(data, textStatus) {
	playerMeasurePlayingTimeout(iclPlayer.file_playing);
}

function playerMeasureLoadedErrorCallback(request, textStatus, errorThrown) {
	playerMeasurePlayingTimeout(iclPlayer.file_playing);
}


function playerMeasurePlaying(filename) {
	if(iclPlayer.is_playing == true && filename == iclPlayer.file_playing && playerMeasurePlayingTimeCalc() <= 0) {
		var measureFilename = iclPlayerMeasure.measure_url;
		iclPlayerMeasure.last_seconds_sent = Math.floor(iclPlayer.current_time / 10) * 10;
		var measureData = 'detail=' + Math.round(iclPlayerMeasure.last_seconds_sent) + '&url=' + escape(unescape(filename));
		if(typeof(iclMediaMeasure) == "function") {
			iclMediaMeasure({ url: measureFilename, data: measureData, success:playerMeasurePlayingSuccessCallback, error: playerMeasurePlayingErrorCallback});
		} else {
			 $.ajax({
				type: "GET",
				url: measureFilename,
				data: measureData,
				success: playerMeasurePlayingSuccessCallback,
				error: playerMeasurePlayingErrorCallback
			});
		}
	} else if(filename == iclPlayer.file_playing) {
		playerMeasurePlayingTimeout(filename);
	}
}

function playerMeasurePlayingSuccessCallback(data, textStatus) {
	var filename = playerMeasureGetFilename(this);
	playerMeasurePlayingTimeout(filename);
}

function playerMeasurePlayingErrorCallback(request, textStatus, errorThrown) {
	var filename = playerMeasureGetFilename(this);
	playerMeasurePlayingTimeout(filename);
}

function playerMeasureCompleted(filename) {
//	var measureFilename = 'http://measure.ichristianlife.com/?category=bible&author=bill_bright&album=written_by_the_hand_of_god&title=adultery&type=mp3&language=english&detail=show';
	var measureFilename = iclPlayerMeasure.measure_url;
	iclPlayerMeasure.last_seconds_sent = 0;
	var measureData = 'detail=finish&url=' + escape(unescape(filename));
	if(typeof(iclMediaMeasure) == "function") {
		iclMediaMeasure({ url: measureFilename, data: measureData, success: null, error: null});
	} else {
		 $.ajax({
			type: "GET",
			url: measureFilename,
			data: measureData,
			success: function(data, textStatus) {
			},
			error: function(request, textStatus, errorThrown) {
			}
		});
	}
}

function playerMeasureGetFilename(obj) {
	var filename = '';
	if(obj.type == 'POST') {
		param_name = 'url';
		param_name = param_name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
		var regexS = "[\\?&]"+param_name+"=([^&#]*)";
		var regex = new RegExp( regexS );
		var results = regex.exec( obj.data );
		var filename = '';
		if( results != null )
			filename=unescape(unescape(results[1]));
	} else {
		filename = unescape(obj.url.substr(obj.url.indexOf("url=")+4));
	}
	return filename;
}

function playerMeasurePlayingTimeout(filename) {
	var measureTimeOut = playerMeasurePlayingTimeCalc();
	if(measureTimeOut > 0) {
		measureTimeOut = measureTimeOut*1000;
		setTimeout("playerMeasurePlaying('" + filename + "');", measureTimeOut);
	} else {
		playerMeasurePlaying(filename);
	}
}

function playerMeasurePlayingTimeCalc() {
	var pmptcLastSent = Math.floor(iclPlayerMeasure.last_seconds_sent / 10) * 10;
//	return Math.min(10, Math.max(0, 10 - (Math.floor(iclPlayer.current_time - pmptcLastSent))));
	return Math.min(10, Math.max(0, 10 - (iclPlayer.current_time - pmptcLastSent)));
}