//
// library.js -- Copyright 2011 One More Story, Inc.
//
// setFocusOnFlash -- sets the focus to the Flash player.  This allows it to sense keystrokes
// updateLibraryLock -- calls the dbCall updateLibraryLock function.
// unlockLibrary -- removes the library lock for this session.  Should be run on the unload event
// getITSLibrarySettings -- Gets the library settings for an ITS user.
// getLibrarySettings -- Gets the library settings and embeds the OMS Library Player if the user is properly logged in
// callBook -- opens a Legacy Book
// showNew -- Shows the main player's flash div
// showOld -- Shows the legacy player's flash div
// printf -- Shows an alert sent in from the Flash player
// launchParentsPlace -- Opens the Parent's Place in a new window
// launchTeachersPlace
// getSwf -- returns the handle to the swf object
//

var debug	= false;
if ( debug ) {
	alert( "In library.js" );
}

	// Globals

var UPDATE_INTERVAL	= 900000;				// 900000 == 15 minutes
var PP_LOGIN		= "pplog";
var TP_LOGIN		= "tplog";

	// SWF Object parameters

var attributes = {};
attributes.allowscriptaccess = "always";

var params = {};

params.bgcolor				= "#006699";
params.allowscriptaccess	= "always";
params.scale				= "showall";
params.wmode				= "opaque";
params.xmlFile				= "xml/data.xml";
params.allowFullScreen		= "true"

params.BASE_URL				= "";
params.API_URL				= "";
params.userType				= "";
params.userList				= "";
params.userid				= "";
params.studentid			= "";
params.instid				= "";
params.jserror				= "";
params.tracing				= "";
params.mustlogin			= "";
params.showechoreading		= "";
params.showlogout			= "";
params.showMWList			= "";

var flashvars = {};

flashvars.xmlFile			= "xml/data.xml";
flashvars.allowFullScreen	= "true";

flashvars.BASE_URL			= "";
flashvars.API_URL			= "";
flashvars.userType			= "";
flashvars.userList			= "";
flashvars.userid			= "";
flashvars.studentid			= "";
flashvars.instid			= "";
flashvars.jserror			= "";
flashvars.tracing			= "";
flashvars.mustlogin			= "";
flashvars.showechoreading	= "";
flashvars.showlogout		= "";
flashvars.showMWList		= "";


//
// setFocusOnFlash -- sets the focus to the Flash player.  This allows it to sense keystrokes
//
function setFocusOnFlash() {
	var debug	= false;

	if ( debug ) {
		writeMainMessage( "In setFocusOnFlash" );
		writeMainMessage( "div.length = [" + $( "#omsFlash" ).length + "]" );
	}

	var fl = document.getElementById( "omsFlash" );
	if ( fl ) {
		if ( debug ) {
			writeMainMessage( "Got omsFlash handle" );
		}

		fl.focus();
	}
}

//
// updateLibraryLock -- calls the dbCall updateLibraryLock function.
//
function updateLibraryLock() {
	var debug	= false;
	if ( debug ) {
		writeMainMessage( "In updateLibraryLock" );
	}

	var argStr	= "";
	if ( $.cookie( "itsUserId" )) {
		if ( debug ) {
			writeMainMessage( "Found ITS cookie in updateLibraryLock" );
		}
		var itsUserId	= $.cookie( "itsUserId" );
		argStr	= addToJSONStr( argStr, "ITSUserId", itsUserId );

	}

	callDB( "updateLibraryLock", argStr, function( data ) {

		var returnObj   = new Object;
		returnObj       = createArray( returnObj, data );

		if ( debug ) {
			writeMainMessage( "In updateLibraryLock anon function, data = [" + data + "]" );
		}
		window.setTimeout( "updateLibraryLock()", UPDATE_INTERVAL );

	});
}


//
// unlockLibrary -- removes the library lock for this session.  Should be run on the unload event
//
function unlockLibrary() {
	var debug	= true;
	if ( debug ) {
		writeMainMessage( "In unlockLibrary" );
	}

	var argStr	= "";
	if ( $.cookie( "itsUserId" )) {
		if ( debug ) {
			writeMainMessage( "Found ITS cookie in updateLibraryLock" );
		}
		var itsUserId	= $.cookie( "itsUserId" );
		argStr	= addToJSONStr( argStr, "ITSUserId", itsUserId );

	}

	if ( debug ) {
		writeMainMessage( "Calling dbCall unlockLibrary" );
	}
	$.ajax( "async=false" );
	callDB( "unlockLibrary", argStr );

}


//
// getITSLibrarySettings -- Gets the library settings for an ITS user.
//
function getITSLibrarySettings( omsInstId, itsUserId ) {
	var debug	= false;

	if ( debug ) {
		writeMainMessage( "In getITSLibrarySettings:" );
		writeMainMessage( "omstInstId = [" + omsInstId + "]" );
		writeMainMessage( "itsUserId = [" + itsUserId + "]" );
	}

	if ( debug ) {
		writeMainMessage( "Calling callDB" );
	}

	var argStr	= "";
	argStr		= addToJSONStr( argStr, "OMSInstId", omsInstId );
	argStr		= addToJSONStr( argStr, "ITSUserId", itsUserId );
	callDB( "getITSLibrarySettings", argStr, function( data ) {

		if ( debug ) {
			writeMainMessage( "In getITSLibrarySettings anon return" );
			writeMainMessage( "data = [" + data + "]" );
		}

		var returnObj   = new Object;
		returnObj       = createArray( returnObj, data );
		if ( debug ) {
			writeMainMessage( "returnObj[ \"results\" ] = [" + returnObj[ "results" ] + "]" );
		}

		if ( returnObj[ "results" ] == undefined ) {
			if ( debug ) {
				writeMainMessage( "results is undefined" );
			}

			var errMsg	= "returnObj[ results ] = undefined in getLibrarySettings.\n";
			errMsg		+= "data = [" + data + "]";
			var argStr	= addToJSONStr( argStr, "eventMsg", errMsg );
			callDB( "logMessage", argStr );

				// trigger the log out process to force the user to log back in

			logOut( '', 'true' );
			self.close(); // close the player window


		} else if ( returnObj[ "results" ] == "error" ) {
			if ( debug ) {
				writeMainMessage( "returnObj[ \"error\" ] = [" + returnObj[ "error" ] + "]" );
			}

			if ( returnObj[ "reason" ] == "Library locked" ) {
				writeMainMessage( "Library lock found" );
				self.close();
			} else {

				var errMsg	= "returnObj[ results ] = error in getLibrarySettings.\n";
				errMsg		+= "data = [" + data + "]";
				var argStr	= addToJSONStr( argStr, "eventMsg", errMsg );
				callDB( "logMessage", argStr );

				logOut( '', 'true' );	// trigger the log out process to force the user to log back in
				self.close();
				// ARGH why isn't this change showing up on flash?
			}


		} else {

			if ( debug ) {
				writeMainMessage( "Showing Library Player:\n" +
						"data = [" + data + "]\n" +
						"" );
			}

				// Check for php cookie

			var phpSessionId	= "";
			if ( $.cookie( "PHPSESSID" )) {
				phpSessionId	= $.cookie( "PHPSESSID" );
			}



				// Set the flash parameters

			params.BASE_URL				= returnObj[ "BASE_URL" ];
			params.API_URL				= returnObj[ "API_URL" ];
			params.userType				= returnObj[ "userType" ];
			params.userList				= returnObj[ "userList" ];
			params.userid				= returnObj[ "userid" ];
			params.studentid			= returnObj[ "studentid" ];
			params.instid				= returnObj[ "instid" ];
			params.jserror				= returnObj[ "jserror" ];
			params.tracing				= returnObj[ "tracing" ];
			params.mustlogin			= returnObj[ "mustLogin" ];
			params.showechoreading		= returnObj[ "showEchoReading" ];
			params.showlogout			= returnObj[ "showLogin" ];
			params.showMWList			= returnObj[ "showMWList" ];
			params.instType				= "ITS";
			params.phpSessionId			= phpSessionId;

			flashvars.BASE_URL			= returnObj[ "BASE_URL" ];
			flashvars.API_URL			= returnObj[ "API_URL" ];
			flashvars.userType			= returnObj[ "userType" ];
			flashvars.userList			= returnObj[ "userList" ];
			flashvars.userid			= returnObj[ "userid" ];
			flashvars.studentid			= returnObj[ "studentid" ];
			flashvars.instid			= returnObj[ "instid" ];
			flashvars.jserror			= returnObj[ "jserror" ];
			flashvars.tracing			= returnObj[ "tracing" ];
			flashvars.mustlogin			= returnObj[ "mustLogin" ];
			flashvars.showechoreading	= returnObj[ "showEchoReading" ];
			flashvars.showlogout		= returnObj[ "showLogin" ];
			flashvars.instType			= "ITS";
			flashvars.phpSessionId		= phpSessionId;

				// Embed the player.  Note the use of the random number to force
				// the browser to download a new copy

			if ( debug ) {
				writeMainMessage( "Calling embedSWF" );
			}

			var randomnumber = Math.floor( Math.random() * 10000 );

			swfobject.embedSWF( "/Library/oms.swf?" + randomnumber,
								"omsFlashDiv",
								"100%",
								"100%",
								"9.0.0",
								true,
								flashvars,
								params );

				// Set a timeout to update the library lock

			if ( debug ) {
				writeMainMessage( "Setting timeout for updateLibraryLock" );
			}
			window.setTimeout( "updateLibraryLock()", UPDATE_INTERVAL );

				// Hook unlockLibrary to the unload event

			if ( debug ) {
				writeMainMessage( "Hooking unlockLibrary to unload event" );
			}
			$( window ).unload( function() {
				unlockLibrary();
			});

				// Give Flash the focus

			if ( debug ) {
				writeMainMessage( "Setting focus to flash object" );
			}
			if ( swfobject.hasFlashPlayerVersion("9.0.0")) {
				if ( debug ) {
					writeMainMessage( "adding dom event" );
				}
				swfobject.addDomLoadEvent( setFocusOnFlash );
			}

			if ( debug ) {
				writeMainMessage( "Done embedSWF" );
			}

		}

		if ( debug ) {
			writeMainMessage( "Done getITSLibrarySettings anon return" );
		}
	});

	if ( debug ) {
		writeMainMessage( "Done getITSLibrarySettings" );
	}

}


//
// getLibrarySettings -- Gets the library settings and embeds the OMS Library Player if the user is properly logged in
// and doesn't have a library lock.
//
function getLibrarySettings() {
	var debug	= false;

	if ( debug ) {
		writeMainMessage( "In getLibrarySettings" );
	}

	if ( debug ) {
		writeMainMessage( "Calling callDB" );
	}

	callDB( "getLibrarySettings", "", function( data ) {

		var returnObj   = new Object;
		returnObj       = createArray( returnObj, data );

			//
			// MDE callback actually starts the player after setting the params
			//

		var debug	= true;
		if ( debug ) {
			writeMainMessage( "In getLibrarySettings return function" );
		}

		if ( debug ) {
			writeMainMessage( "returnObj = [" + returnObj + "]" );
			writeMainMessage( "returnObj[ \"results\" ] = [" + returnObj[ "results" ] + "]" );
		}

		if ( returnObj[ "results" ] == undefined ) {

			if ( debug ) {
				writeMainMessage( "results is undefined" );
			}

			var errMsg	= "returnObj[ results ] = undefined in getLibrarySettings.\n";
			errMsg		+= "data = [" + data + "]";
			var argStr	= addToJSONStr( argStr, "eventMsg", errMsg );
			callDB( "logMessage", argStr );

			self.close(); // close the player window

				// trigger the log out process to force the user to log back in

			logOut();

		} else if ( returnObj[ "results" ] == "error" ) {

			if ( debug ) {
				writeMainMessage( "results is returning in error" );
			}

			if ( returnObj[ "reason" ] == "Library locked" ) {
				writeMainMessage( "Library lock found" );
				self.close();
			} else {

				var errMsg	= "returnObj[ results ] = error in getLibrarySettings.\n";
				errMsg		+= "data = [" + data + "]";
				var argStr	= addToJSONStr( argStr, "eventMsg", errMsg );
				callDB( "logMessage", argStr );

				logOut( '', 'true' );	// trigger the log out process to force the user to log back in

			}
		} else {

				// Show the player

			if ( debug ) {
				writeMainMessage( "Showing Library Player:\n" +
						"data = [" + data + "]\n" +
						"" );
			}

				// Set the flash parameters

			params.BASE_URL				= returnObj[ "BASE_URL" ];
			params.API_URL				= returnObj[ "API_URL" ];
			params.userType				= returnObj[ "userType" ];
			params.userList				= returnObj[ "userList" ];
			params.userid				= returnObj[ "userid" ];
			params.studentid			= returnObj[ "studentid" ];
			params.instid				= returnObj[ "instid" ];
			params.jserror				= returnObj[ "jserror" ];
			params.tracing				= returnObj[ "tracing" ];
			params.mustlogin			= returnObj[ "mustLogin" ];
			params.showechoreading		= returnObj[ "showEchoReading" ];
			params.showlogout			= returnObj[ "showLogin" ];
			params.showMWList			= returnObj[ "showMWList" ];

			flashvars.BASE_URL			= returnObj[ "BASE_URL" ];
			flashvars.API_URL			= returnObj[ "API_URL" ];
			flashvars.userType			= returnObj[ "userType" ];
			flashvars.userList			= returnObj[ "userList" ];
			flashvars.userid			= returnObj[ "userid" ];
			flashvars.studentid			= returnObj[ "studentid" ];
			flashvars.instid			= returnObj[ "instid" ];
			flashvars.jserror			= returnObj[ "jserror" ];
			flashvars.tracing			= returnObj[ "tracing" ];
			flashvars.mustlogin			= returnObj[ "mustLogin" ];
			flashvars.showechoreading	= returnObj[ "showEchoReading" ];
			flashvars.showlogout		= returnObj[ "showLogin" ];
			flashvars.showMWList		= returnObj[ "showMWList" ];

				// Embed the player.  Note the use of the random number to force
				// the browser to download a new copy

			if ( debug ) {
				writeMainMessage( "Calling embedSWF" );
			}

			var randomnumber = Math.floor( Math.random() * 10000 );

			swfobject.embedSWF( "/Library/oms.swf?" + randomnumber,
								"omsFlashDiv",
								"100%",
								"100%",
								"9.0.0",
								true,
								flashvars,
								params );

				// Set a timeout to update the library lock

			if ( debug ) {
				writeMainMessage( "Setting timeout for updateLibraryLock" );
			}
			window.setTimeout( "updateLibraryLock()", UPDATE_INTERVAL );

				// Hook unlockLibrary to the unload event

			if ( debug ) {
				writeMainMessage( "Hooking unlockLibrary to unload event" );
			}
			$( window ).unload( function() {
				unlockLibrary();
			});

				// Give Flash the focus

/*			alert( 'settingFocus' );
			window.document.omsFlashDiv.focus();
			alert( 'done settingFocus' );
*/

			if ( debug ) {
				writeMainMessage( "Setting focus to flash object" );
			}
			if ( swfobject.hasFlashPlayerVersion("9.0.0")) {
				if ( debug ) {
					writeMainMessage( "adding dom event" );
				}
				swfobject.addDomLoadEvent( setFocusOnFlash );
			}

			if ( debug ) {
				writeMainMessage( "Done embedSWF" );
			}
		}

		if ( debug ) {
			writeMainMessage( "Done getLibrarySettings anon function" );
		}
	});


}


//
// callBook -- opens a Legacy Book
//
function callBook( book, userName, sessionID ) {
	var randomnumber = Math.floor( Math.random() * 10000 );

	showOld();
	flashvars.userName = userName;
	flashvars.sessionID = sessionID;
	flashvars.bookToLoad = book;
	swfobject.embedSWF( "legacy.swf?" + randomnumber,
						"legacyFlash",
						"100%",
						"100%",
						"9.0.0",
						true,
						flashvars,
						params,
						attributes );
	$( "#legacyFlash" ).focus();	// MDE directly supported
}


//
// showNew -- Shows the main player's flash div
//
function showNew() {
	$( "#omsFlashDiv" ).show();			// MDE directly supported
	$( "#oms" ).css( "z-index", "3" );
	$( "#legacy" ).css( "z-index", "2" );
}


//
// showOld -- Shows the legacy player's flash div
//
function showOld() {
	$( "#oms" ).css( "z-index", "2" );
	$( "#legacy" ).css( "z-index", "3" );
}


//
// printf -- Shows an writeMainMessage sent in from the Flash player
//
function printf( message ) {
	writeMainMessage( message );
	setFocusOnFlash();
}


//
// launchParentsPlace -- Opens the Parent's Place in a new window
//
function launchParentsPlace() {
	var debuglcl	= false;

	if ( debuglcl ) {
		writeMainMessage( "In launchParentsPlace" );
	}

		// hide the player and trigger the login

	if ( mainHandle ) {
		hidePlayer();
		mainHandle.startPopup( PP_LOGIN );
	}

}


//
// launchTeachersPlace
//
function launchTeachersPlace() {
	var debuglcl = false;

	if ( debuglcl ) {
		writeMainMessage( "In launchTeachersPlace" );
	}

		// hide the player and trigger the login

	if ( mainHandle ) {
		hidePlayer();
		mainHandle.startPopup( TP_LOGIN );

	}

}


//
// getSwf -- returns the handle to the swf object
//
function getSwf( id ) {
	if ( navigator.appName.indexOf( "Microsoft" ) != -1 ) {
		return window[ id ];
	} else {
		return document[ id ];
	}
}

if ( debug ) {
	alert( "Done library.js" );
	debug	= false;
}

