// Functions to support a sequential recording application.
//
// This application simulates a recording session where the user records several phrases
// and uploads them to the server.
//
// This code may be used freely with the ListenUp Applet.
// Author Phil Burk (C) 2007 Mobileer Inc

// This Web Application is implemented as a state machine.
// That is handy way to construct an application that runs in lots of asynchronous callbacks.
// It is driven by calls LUPJS_StateChanged() function and from button presses.

// Define possible states
var LUPJS_STATE_UNINITIALIZED = 0;
var LUPJS_STATE_READY = 1;
var LUPJS_STATE_RECORDING = 2;
var LUPJS_STATE_STOPPING = 3; // Set by Stop button press.
var LUPJS_STATE_SENDABLE = 4;
var LUPJS_STATE_UPLOADING = 5; // Set when recording stops and upload starts.

var LUPJS_State = LUPJS_STATE_UNINITIALIZED;

// ********************************************************************************
// These are the phrases we will ask the user to speak.
var LUPJS_PhraseArray = new Array(
	"Time flies like an arrow.",
	"Fruit flies like a banana.",
	"The sun rises over the lake." );

var LUPJS_PhraseIndex = -1;

// ********************************************************************************
// Display a series of phrases to be recorded by the user.
function LUPJS_DisplayNextPhrase()
{
	LUPJS_PhraseIndex += 1;
	if( LUPJS_PhraseIndex < LUPJS_PhraseArray.length )
	{
		message = "<h3>Please Record the following phrase and then Upload it.</h3>\n" +
			"<blockquote><p>Phrase #" + LUPJS_PhraseIndex + ":\"" + LUPJS_PhraseArray[ LUPJS_PhraseIndex ] + "\"</blockquote></p>\n";
	}
	else
	{
		// All done.
		message = "<h3>Thank you for recording all of the messages.</h3>\n";
	}
	LUPJS_SetInnerHTML('phrasebox',message);
}

// ********************************************************************************
// Change HTML in a DIV or other element
function LUPJS_SetInnerHTML(id,message)
{
	// Voodoo for browser compatibility.
	d=document;
	re=d.all?d.all[id]:d.getElementById(id);
	re.innerHTML=message;
}

// ********************************************************************************
// Called by Applet when it is finished loading.
function LUPJS_AppletReady()
{
	LUPJS_SetState( LUPJS_STATE_READY );
	LUPJS_DisplayNextPhrase();
}

// ********************************************************************************
// Set state machine and update buttons.
function LUPJS_SetState( state )
{
	LUPJS_State = state;
	LUPJS_SetInnerHTML( 'js_statebox', "JavaScript State changed to " +  state ); // debug
	
	// Set properties of record/stop button based on state.
	if( state == LUPJS_STATE_READY )
	{
		document.recordingControlForm.recordStopButton.disabled = false;
		document.recordingControlForm.recordStopButton.value = "Record";
	}
	else if( state == LUPJS_STATE_SENDABLE )
	{
		document.recordingControlForm.recordStopButton.disabled = false;
		document.recordingControlForm.recordStopButton.value = "Re-Record";
	}
	else if( state == LUPJS_STATE_RECORDING )
	{
		document.recordingControlForm.recordStopButton.disabled = false;
		document.recordingControlForm.recordStopButton.value = "Stop";
	}
	else
	{
		document.recordingControlForm.recordStopButton.disabled = true;
		document.recordingControlForm.recordStopButton.value = "=======";
	}
	
	// Set properties of upload button based on state.
	if( state == LUPJS_STATE_SENDABLE )
	{
		document.recordingControlForm.uploadButton.disabled = false;
	}
	else
	{
		document.recordingControlForm.uploadButton.disabled = true;
	}
		
}

// ********************************************************************************
// Check to make sure we are not leaving the page before uploading the recording.
window.onbeforeunload=ConfirmPageExit;
function ConfirmPageExit()
{
	if( !document.ListenUpRecorder.isActive() )
	{
		return (void 0); // prevent compiler warning
	}
	else
	{
	    var playable = document.ListenUpRecorder.isPlayable();
		if( playable )
    	{
			return "WARNING - If you leave this page without Uploading your "
				+ "ListenUp recording then you will LOSE your recording.";
		}
		else
		{
			return (void 0);
		}
	}
}

// ********************************************************************************
// Called by Applet upon upload.
function LUPJS_UploadCompleted()
{
	LUPJS_ShowStatus( "<p>Upload succeded.</p>\n" );
	LUPJS_SetState( LUPJS_STATE_READY );
	LUPJS_DisplayNextPhrase();
}

// ********************************************************************************
// Keep checking to see if Applet is loaded.
// This call to isActive() will be the first LiveConnect call and will hide the delay from the user.
function touchLoadLiveConnect()
{
	if( !document.ListenUpRecorder.isActive() )
	{
		// Wait 100 milliseconds and try again.
		setTimeout('touchLoadLiveConnect()', 100 );
	}
}

// ********************************************************************************
// Tell ListenUp to start recording.
function LUPJS_RecordMessage()
{
	if( !document.ListenUpRecorder.isActive() )
	{
		alert("Applet is not yet ready!");
	}
	else
	{
	    var stopped = document.ListenUpRecorder.isStopped();
		
		if( !stopped )
		{
			alert("You are already recording!");
			return;
		}
		// Send info and recording to server.
		document.ListenUpRecorder.record();
	}
}

// ********************************************************************************
// Tell ListenUp to stop.
function LUPJS_StopRecording()
{
	if( !document.ListenUpRecorder.isActive() )
	{
		alert("Applet is not yet ready!");
	}
	else
	{
		LUPJS_SetState( LUPJS_STATE_STOPPING );
		document.ListenUpRecorder.stopAudio();
	}
}


// ********************************************************************************
function LUPJS_RecordOrStop()
{
	if( LUPJS_State == LUPJS_STATE_RECORDING )
	{
		LUPJS_StopRecording();
	}
	else
	{
		LUPJS_RecordMessage();
	}
	
}
// ********************************************************************************
// Tell ListenUp to upload the recording.
function LUPJS_UploadMessage()
{
	if( !document.ListenUpRecorder.isActive() )
	{
		alert("Applet is not yet ready!");
	}
	else
	{
		var stopped = document.ListenUpRecorder.isStopped();
		var playable = document.ListenUpRecorder.isPlayable();
		var sendable = stopped && playable;
		
		if( !sendable )
		{
			alert("You must record a voice message before sending!");
			return;
		}
		
		// Define what happens if the upload succeeds.
		document.ListenUpRecorder.setUploadCompletionScript( "LUPJS_UploadCompleted();" );
		
		// Send info and recording to server.
		LUPJS_SetState( LUPJS_STATE_UPLOADING );
		
		// You can upload multiple name/value pairs associated with the recording.
		document.ListenUpRecorder.addNameValuePair( "phrase_index", LUPJS_PhraseIndex );
		
		document.ListenUpRecorder.sendRecordedMessage();
		// The uploading will happen asynchronously so do not follow this
		// code with a redirection to another page. Otherwise the ListenUp
		// Applet will be unloaded before the upload has completed.
		// If you want to go to another page as soon as the upload has finished
		// then please use the refreshURL parameter, or use setUploadCompletionScript()
		// above to cause the redirection. Then the redirection will occur after the upload has finished.
	}
}


// ********************************************************************************
function LUPJS_RanOutOfTime( message )
{
	alert("Sorry. You ran out of time.");
}

// ********************************************************************************
function LUPJS_ShowStatus( message )
{
	LUPJS_SetInnerHTML( 'statebox', message );
}

// ********************************************************************************
// This is called from the ListenUp Applet when its internal state changes.
function LUPJS_StateChanged( previousState, newState )
{
	msg = "<p>State changed from " + previousState + " to " + newState + "</p>\n";
	LUPJS_ShowStatus( msg );
	
	if( (previousState == "recording") && (newState == "stopped") )
	{
		if( LUPJS_State != LUPJS_STATE_STOPPING )
		{
			LUPJS_RanOutOfTime();
		}
		LUPJS_SetState( LUPJS_STATE_SENDABLE );
	}
	else if( newState == "recording" )
	{
		LUPJS_SetState( LUPJS_STATE_RECORDING );
	}
	
}

// ********************************************************************************
// This is called periodicall from the ListenUp Applet over time.
function LUPJS_TimeChanged( currentTime, maxTime )
{
	msg = "<p><span class=\"style1\">Time = " + currentTime + " / " + maxTime + "</span></p>\n";
	// infobox is the ID of the DIV in the page below.
	LUPJS_SetInnerHTML( 'timebox', msg );
}

