/*
    This file is part of LibSCORM 2004.

    LibSCORM 2004 is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    LibSCORM 2004 is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with LibSCORM 2004; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

*/

//////////////////// These variables are available to content pages ///////////////////
var dc, lms, iss, nav, pm, ssp;
///////////////////////////////////////////////////////////////////////////////////////

function boilerplate_handleException(e) {
	dc.Error(e.toString());
	try {
		if(typeof(e.description) != "undefined") { // extra IE info
			dc.Error(e.description);
		}
	} catch(f) {}
	if(DC_popupErrors) {
		dc.Show();
	}
}

function boilerplate_load() {
	dc = new DebugConsole(DC_showConsoleIcon ? document.getElementById('debug') : null,
	                      DC_showDebugLines, DC_noErrorImg, DC_errorImg, DC_hideDbgImg);
	try {
		lms = new LMS(this);
		if(LMS_trackSessionTime) {
			lms.StartSessionTimer();
		}
		if(SSP_enabled) {
			ssp = new SSP(lms);
		}
	} catch(e) {
		boilerplate_handleException(e);
	}

	// The show can go on even if the LMS fails to connect, and we can show the
	// content offline. Hence a separate try...catch to construct the navigation.
	try {
		iss = new InterScoSeq(lms, boilerplate_beforeTerminate);
		nav = new Nav(lms, iss,
		              NAV_show ? document.getElementById('nav')
		                       : null,
		              document.getElementById('content'),
		              NAV_pages, boilerplate_handleException,
		              NAV_prevEnabledImg, NAV_prevDisabledImg,
		              NAV_nextEnabledImg, NAV_nextDisabledImg,
		              NAV_pastTickImg, NAV_presentTickImg, NAV_futureTickImg);
		if(PM_trackProgress) {
			pm = PM_create(nav);
		}
	} catch(e) {
		boilerplate_handleException(e);
	}
}

function boilerplate_beforeTerminate() {
	nav.UnloadContent();
	if(lms) {
		if(NAV_bookmarkingEnabled) {
			nav.SaveLocation();
		}
		if(LMS_trackSessionTime) {
			lms.RecordSessionTime();
		}
		if(PM_trackProgress) {
			lms.SetValue("cmi.progress_measure", pm.GetProgress());
		}
	}
}

function boilerplate_unload() {
	if(lms && lms.IsTerminated()) {
		return;
	}
	try {
		boilerplate_beforeTerminate();
		if(lms) {
			lms.Terminate();
		}
		if(DC_popupErrorsOnUnload && dc.HasError()) {
			dc.Show();
		}
	} catch(e) {
		boilerplate_handleException(e);
	}
}
