// *************************************************************
function ______SUPPLEMENTAL_WINDOWS______ () {}

/* type values and old function mappings for OpenSupp calls

New values can be added to this list at any point.  To do so, we need to 
configure suppAPI.js to handle the type.  If there is any special processing
that has to be done before handing control to suppAPI, it should be done in
the OpenSupp function below.


	aimm - function OpenAIMM(chap, number)
	animation - function OpenAnimation(chap, number)
	dse (Instructions for using/obtaining Deep Space Explorer) - function OpenDSE()
	figure - function OpenFigure(chap, number)
	flashcard - function OpenFlashcards(chap, number)
	fm (Front matter and back matter, e.g. preface, note to students, etc.) - function OpenFrontMatter(which)
	glossary - function OpenGlossary(termId)
	guideddiscovery (essay type) - function OpenGuidedDiscovery(chap, number)
	index (print book index) - function OpenIndex()
	intex (interactive exercise) - function OpenIntEx(chap, number)
	moretoknow (essay type) - function OpenMTK(chap, number)
	notes (ALL notes for a chapter) - function OpenAllNotes(chap)
	onlinequiz - function OpenOnlineQuiz(chap)
	prefs - function OpenPrefs()
	qaonline (Q&A Online) - function OpenQA(chap) OR OpenQAOnline
	quickstart (Quickstart guide) - function OpenQuickStart()
	search (full text search) - function OpenSearch()
	subscriberlist (note set subscriber list) - function OpenSubscriberList(setId)
	syscheck (system check) - function OpenSystemCheck()
	table - function OpenTable(chap, number)	
	toc (TOC for supplemental resources -- all figures, tables, animations, etc.) - function OpenResourceContents(chap)
	video - function OpenVideo(chap, number) 
	weblinks (a page with all weblinks for a chapter) - function OpenWebLinkWindow(chap)
*/


var glossaryHistoryArr = new Array();	// variable to keep track of the glossary history
var lastDefinedTermId = null;			// see below

var indexHistoryArr = new Array();	// variable to keep track of the index history

var searchHistoryArr = new Array();	// variable to keep track of the search history
var searchType = 0;					// the search window uses this to keep track of what was last searched (text, glossary, or index)

// Open a supplemental window
function OpenSupp(type) {
	// We will need the type of window plus a search string, which we'll 
	// feed into the supplemental window, whose code will handle it 
	// from there.
	
	// type should be case-insensitive
	type = type.toLowerCase();
	
	// Special processing for pageId type
	// This should be the new standard.  It makes eBook processing simpler
	// and allows for the eBook in Angel to open Angel resources.
	if (type == 'pageid') {
		var pageId = arguments[1];
		// In angel...
		if (angelStyle == 1) {
			// just pass the pageId along to processPageRequest
			OpenSuppWindow(angelServer + '/processPageRequest.asp?page_id=' + pageId, true);
			return;
		// else standalone...
		} else {
			// we have to find the suppTitle and url to use
			var suppTitle, url;

			// First try to get info out of suppInfo[] associative array
			// If it's there we want to override anything that's inline
			if (window.suppInfo != null && suppInfo[pageId] != null) {
				var si = suppInfo[pageId];
				suppTitle = si['suppTitle'];
				url = si['url'];
			// If we didn't get suppInfo out of the database, it should be here.
			} else {
				suppTitle = arguments[2];
				url = arguments[3];
				// alert(url);
				
			}
			
			// If we didn't find a url, alert
			if (url == null || url == '') {
				alert('This resource is not yet available.');
				return;

			// Otherwise put them into arguments[] to be processed below
			} else {
				arguments[0] = type = 'bcs';	// not really bcs, but this is what we call these.
				arguments[1] = suppTitle;
				arguments[2] = url;
				// delete any more arguments so they don't get passed on
				arguments[3] = null;
				arguments.length = 3;
			}
		}
	}

	var searchString = type;

	// The search string holds different info for different windows; we
	// construct it here, then call OpenSuppWindow to actually 
	// open the window
	
	// First handle windows that aren't functional yet
	if (type == "quickstart" && bookId != "life" && bookId != "life8e") {
		alert("The QuickStart guide is not online yet...");
		return;
	
//	} else if (type == "onlinequiz") {
//		alert("Online quizzes are not online yet for this eBook...");
//		return;
			
	} else if (type == "index" && bookId == 'exploring') {
		alert("The index is not yet available...");
		return;
	
	} else if (type == "search" && (bookId == "blah")) {
		alert("Full text search is not yet available for this eBook");
		return;
			
	// Certain windows need some extra processing
	} else if (type == "search") {
		// If the user clicked the search button in the leftLinks frame, note this
		// so that the search window will get the search terms from there.
		if (arguments[1] == true) {
			searchCalledFromMain = true;
		}
	
	} else if (type == "weblinks" || type == "notes") {
		// Add the current chapter to searchString if arguments[1] not sent in
		if (arguments[1] != null) {
			searchString += "&" + arguments[1];
		} else {
			searchString += "&" + CurrentChapter();
		}

	} else if (type == "glossary") {
		termId = arguments[1];
		// If no termId (arguments[1]) sent in, try lastDefinedTermId,
		// which is set every time Define() is called (see ebookPopInAPI.js)
		if (termId == null) {
			termId = lastDefinedTermId;
		}
		
		// If termId is still null, set to "" (used to be the current chapter)
		if (termId == null && CurrentChapter() > 0) {
			// For life, use CurrentChapter, as life includes chapter glossaries.
			if (bookId == "life") {
				termId = CurrentChapter();
			} else {
				termId = "";
			}
		}
		
		// If termID is *STILL* null, set to "" (won't happen unless we go back to chapters)
		if (termId == null) {
			termId = "";
		}
		
		// MZ: 09232010 Fix suggested by Paul R. so that search box
		// is populated by term when opened by 'Open Full Glossary' link
		if ( termId ) {
			searchString += "&" + termId;
		}
		
	// For now, "Looking Deeper"s from Universe are just PDFs
	} else if (type == "lookingdeeper") {
		window.open(urlStartBookID + 'lookingdeepers/Look_Deep' + arguments[1] + '-' + arguments[2] + '.pdf'
			, "", "width=600,height=450", true);
		return;
	
	// If no special processing, just tack all arguments on to searchString
	} else {
		var i = 1;
		while (arguments[i] != null) {
			searchString += "&" + arguments[i];
			++i;
		}
	}
    // alert("searchString: " + searchString);
	// bcs&CrunchIt&URL
	// For CrunchIts, we want to just open a window pointing directly to the resource with no banner
	// Otherwise we get cross-domain errors 
	
	// MZ 01202012: suppAPI.js sends to ANGEL crunchit bridge page if  OpenSupp('crunchit','bookid','dataset'). No change for OpenSupp('bcs','crunchit'... unchanged
	if ( (searchString.indexOf("crunchit/") >= 0) 
			&& (angelStyle == 1) 
			&& (searchString.indexOf("bcs&") >= 0) ) {

		searchString = searchString.replace(/^.*?http:/, "");
		OpenSuppWindow(searchString, true);

	}
	// KC: EBPM-47 Hide ebook banner for any links containing bcs.bedfordstmartins.com 
	if (searchString.indexOf("bcs.bedfordstmartins.com") >= 0) {

		searchString = searchString.replace(/^.*?http:/, "");
		OpenSuppWindow(searchString, true);

	}
	
	// MZ: 04042011 In glossary window the word bookId was being entered into term field
	if ( type != 'glossary' ) {
		searchString += "&bookId=" + bookId;
	}
	// Now call OpenSuppWindow
	OpenSuppWindow(searchString);
}

// Open the supplemental window.  The code in supp windows should 
// call this function to change, so that the main window 
// can keep track of what's there.
var sw = null;
var lastSupp = null;
var searchCalledFromMain = false;
var suppWinPos = 10;
function OpenSuppWindow(searchString, noEbookBanner) {
	var url;

	// KC EBPM-47 Try adding some URL/URI encoding
	/*
	searchString = searchString.replace(/#/, "%23");
	searchString = searchString.replace(/\//g, "%2F");
	searchString = searchString.replace(/:/g, "%3A");
	*/
//	alert(searchString);


	// try to bring the window to focus; if the supp window isn't open, open it
	if (!FocusWindow(sw)) {
		if (noEbookBanner == true) {
			url = searchString;
		} else {
			url = GetFilename(urlStart + 'supp3.php?' + searchString);
//			alert(url);
		}
		sw = window.open(url, "", "top=" + suppWinPos + ",left=" + suppWinPos + ",width=785,height=600,menubar,resizable,scrollbars,status", true);	

	// else the supp window is open, so if the requested url isn't 
	// the same as the last one opened, change to the new url
	} else if (lastSupp != searchString || searchCalledFromMain == true) {
		if (noEbookBanner == true) {
			sw.location = searchString;
		} else {
//			alert(searchString);
			sw.ChangeSupp(searchString);
		}
	}

	// Save the requested url for the next visit to this function
	lastSupp = searchString;
}

// Reload the last-loaded supp window; only works if the window is still open
function ReloadSuppWindow() {
	if (FocusWindow(sw)) {
		sw.ReloadSupp();
	}
}

function CloseSuppWindow() {
	if (sw != null && !sw.closed) {
		sw.close();
	}
}

// if window w is already open, bring it to the front and return true; otherwise return false
function FocusWindow(w) {
	if (w != null && !w.closed) {
		w.focus();
		return true;
	} else {
		return false;
	}
}

// KC: print the contents of the main frame (per BSM request)
function PrintSuppWindow() {
	if (sw != null && !sw.closed) {
	sw.main.print();
   }
}


// keep whatever is currently in the supp window open; the next call to OpenSuppWindow will open a new window
function KeepSuppWindowOpen() {
	sw.banner.document.getElementById('keepopen').style.display = "none";		// first hide the link, so the user will know that the window is permanent
	ChangeHistoryLinkState('supp', 'back', 'none');							// then remove the back/forward buttons from the window
	ChangeHistoryLinkState('supp', 'forward', 'none');
	sw = null;																	// then kill maintext's connection to the window, so a new one will be open next time
	suppWinPos += 10;		// Change this so that the window will be slightly offset next time
}

// Open the help window
var hw = null;
function Help(helpURL) {
	if (helpURL == null) {
		helpURL = "overview";
	}
	
	if (!FocusWindow(hw)) {
		hw = window.open(GetFilename(urlStart + 'help3/help.php?' + helpURL + "&bookId=" + bookId), "helpWindow", "top=20,left=20,width=650,height=500,menubar,resizable,scrollbars,status", true);
	} else {
		hw.NewHelp(helpURL);
	}
}

function BringSuppWindowToFront() {
	FocusWindow(sw);
}

// *************************************************************
function ______HISTORY_SYSTEM______ () {}

var SH = new Object();

function InitializeHistory(which, fn, w) {
	h = SH[which] = new Object();
	h.entries = new Array();
	h.index = -1;		// current place in the history array; will get bumped up to 0 the first time AddToHistory is called
	h.addable = true;	// set to false when back or forward pressed so page won't get added again
	h.fn = fn;
	h.window = w;
}

InitializeHistory('help', Help, 'hw');
InitializeHistory('supp', OpenSuppWindow, 'sw');

// AddToHistory: Add a page to the entries array
function AddToHistory(which, entry) {
	if (!SH[which].addable) {				// if addable is false, AddToHistory was called
		SH[which].addable = true;			// just after the forward or back button was pressed,
		return;								// so don't do anything
	}

	if (SH[which].entries[SH[which].index] == entry) {	// if this is true, the user must have just reloaded the same entry
		return;
	}
	
	++SH[which].index;							// increment index
	SH[which].entries[SH[which].index] = entry;		// store the page in the entries array
	UpdateHistoryLinks(which);
	SH[which].entries.length = SH[which].index + 1;	// update the size of the entries array, deleting any pages further than index in the array
}

// Replace the last history item.  We would want to do this, e.g., if the glossary is open
// and we don't want to add a new history entry, but we want to come back to the last-defined term.
function ReplaceHistory(which, entry) {
	SH[which].entries[SH[which].index] = entry;
}

// GoBack: Go back to the last page stored in the entries array
function GoBack(which) {
	if (SH[which].index > 0) {
		SH[which].addable = false;						// set addable to false (see AddToHistory)
		--SH[which].index;								// decrement index
		UpdateHistoryLinks(which);
		SH[which].fn(SH[which].entries[SH[which].index]);	// load the new entry
	}
}

// GoForward: Go forward to the next page stored in the entries array
function GoForward(which) {
	if (SH[which].index < SH[which].entries.length - 1) {
		SH[which].addable = false;								// set addable to false (see AddToHistory)
		++SH[which].index;										// increment index
		UpdateHistoryLinks(which);
		SH[which].fn(SH[which].entries[SH[which].index]);	// load the new entry
	}
}

// enable or disable the link in the banner frame for the forward or back button
function ChangeHistoryLinkState(which, dir, enabled) {
	if (window[SH[which].window].banner.document.getElementById(dir + 'vis')) {
		window[SH[which].window].banner.document.getElementById(dir + 'vis').style.display = ((enabled == 'vis') ? 'block' : 'none');
	} else {
		return;
	}
	
	if (window[SH[which].window].banner.document.getElementById(dir + 'dim')) {
		window[SH[which].window].banner.document.getElementById(dir + 'dim').style.display = ((enabled == 'dim') ? 'block' : 'none');
	}
}

// enable or disable the links appropriately
function UpdateHistoryLinks(which) {
	if (SH[which].index > 0) {
		ChangeHistoryLinkState(which, "back", 'vis');
	} else {
		ChangeHistoryLinkState(which, "back", 'dim');
	}
	
	if (SH[which].index < SH[which].entries.length - 1) {
		ChangeHistoryLinkState(which, "forward", 'vis');
	} else {
		ChangeHistoryLinkState(which, "forward", 'dim');
	}
}

