/* These function depend on string variables that should be declared in
   a <script> tag inside the main html.xsl stylesheet. The stylesheet
   should assign appropriate values to the variables depending on the
   interface language.

   Version: 1.080820

 */
 

// Correct some potential userid/password entry problems.
function checkLogin() {
	// Remove whitespace and convert uppercase characters to lowercase.
	var normalizedId   = document.LoginForm.collectionuserid.value.toLowerCase().replace(/[ 	]/g, '');
	var normalizedPass = document.LoginForm.passwd.value.toLowerCase().replace(/[ 	]/g, '');;

	document.LoginForm.collectionuserid.value = normalizedId;
	document.LoginForm.passwd.value = normalizedPass;

	// Set to false for testing/debugging so we don't submit the form each time.
	return (true);
}


function checkSearch() {

	// A to date with a missing start date is invalid and works the same as nothing.
	// If this happens, copy the pubto value to pubfrom to create a valid 1-year search.
	if (document.SearchForm.pubfrom.value.length == 0 &&
		document.SearchForm.pubto.value.length > 0) {
		document.SearchForm.pubfrom.value = document.SearchForm.pubto.value;
	}

	// If the search text contains numbers with dashes, replace the
	// dashes with underscores. This facilitates easy CIHM number
	// searching. E.g. 9-12345 becomes 9_12345.
	document.SearchForm.query.value =
		document.SearchForm.query.value.replace (/([0-9])-([0-9])/g, "$1_$2");

	// Check for potentially excessive OR searches.
	// FIXME: leading spaces will result in an extra term being counted.
	nSearchTerms = document.SearchForm.query.value.split(/\s+\w/).length;
	if (nSearchTerms >= 3 && document.SearchForm.bool.value == 'any') {
		return confirm (txtBigOrSearch);
	}
	else {
		return true;
	}
}

// Make sure that the user has entered something that looks like a real
// email address, to prevent emails without '@somehwere.com' in them
// from being quietly discarded.
function checkPrintSubmit(email) {
	if (email.indexOf("@") == -1) {
		alert(txtIncompleteEmail);
		return false;
	}
	return true;
}


// Set all search options back to defaults.
function resetSearchOptions() {
	document.SearchForm.pubfrom.value = '';
	document.SearchForm.pubto.value = '';
	document.SearchForm.range.selectedIndex = 0;
	document.SearchForm.bool.selectedIndex = 0;
	document.SearchForm.subset.selectedIndex = 0;
}

function toggleAdvanced() {
	var element = document.getElementById('AdvancedOptions');
	var label   = document.getElementById('AdvancedLabel');
	if (element.style.display == 'none') {
		var newText = document.createTextNode (txtHideAdvanced);
		label.replaceChild (newText, label.firstChild);
		element.style.display = 'block';
		document.cookie="showAdvanced=1; path=/";
	}
	else {
		var newText = document.createTextNode (txtShowAdvanced);
		// When advanced options are turned off, search options
		// should be reset to default values.
		resetSearchOptions();
		label.replaceChild (newText, label.firstChild);
		element.style.display = 'none';
		document.cookie="showAdvanced=0; path=/";
	}
	return (false);
}

// Start a new session, but warn password users that they will have to
// log in again, and give them a chance to cancel.
function newSession(url, usertype) {
	var msg = txtNewSession1;
	if (usertype == "user") { msg += txtNewSession2; }
	msg += txtNewSession3;
	if (! confirm (msg)) return;
	window.location = url;
}

// Things to do when the page first loads.
function initialize() {

    document.SearchForm = document.getElementById('SearchForm');
    document.BrowseForm = document.getElementById('BrowseForm');

	// Toggling the show/hide advanced options sets a user cookie
	// indicating the last selected state.  When loading a new page,
	// initialize it to the same state as last selected.
    /*
	var cookieName = "showAdvanced=";
	var cookiePos = document.cookie.indexOf(cookieName);
	var initialDisplay = 0;
	if (cookiePos != -1) {
		initialDisplay = document.cookie.charAt (cookiePos + cookieName.length );
	}

	if (initialDisplay == 0) {
		// If advanced search options are off, reset them in
		// case we got to this page via a hardlinked search,
		// e.g. cliking on a subject heading.
		resetSearchOptions();
		toggleAdvanced();
	}
	else {
		var label   = document.getElementById('AdvancedLabel');
		var newText = document.createTextNode (txtHideAdvanced);
		label.replaceChild (newText, label.firstChild);
	}
    */

	// For the page display screen, give the first "Next Page" link
	// focus, allowing the user to advance by pressing enter. This
	// doesn't seem to work under IE, but it is just an undocumented
	// bonus feature anyway, so it doesn't have to work across all
	// platforms.
	if (document.links.NextPageLink) {
		document.links.NextPageLink.focus();
	}

        //Nifty("div.NavLink", "transparent");

}




/* *** Print Preivew/Thumbnail Window
 *
 * The following functions allow for the creation and use of a separate
 * thumbnail image. They are used by the print function to allow the
 * user to cycle back and forth through a document to find the page
 * range desired.
*/

// Keeps track of the location of the preview window so that the main page can
// update it.
var winPreview;

// Use this function to dynamically create the button that launches the
// previewImage function. We have to take this roundabout kind of way
// because we can't easily mix XSL with JavaScript in the document.
function createPreviewButton(buttonValue, docID, sessionID, basePage) {
	document.writeln(
		'<input type="button" value="' +
		buttonValue +
		'" onclick="previewImage(\'' +
		docID +
		'\', \'' +
		sessionID +
		'\', \'' +
		basePage +
		'\')"/>');
}

// Open the preivew window itself.
function previewImage(docID, sessionID, basePage) {
	// Determine which menu we are dealing with: the staring
	// page or ending page. Only one should exist at any given time.
	var dataSource = getPreviewDataSource (window);
	if (! dataSource) { return false; }

	// Open the preview window, loaded with the current page.
	winPreview = 
		window.open ("javascript:'" + txtLoading + "'", "previewWin", "width=450,height=600,resizable=yes,scrollbars=yes");


	winPreview.focus();
	winPreview.location = "/ECO/PageView/" + docID + "/" + dataSource.value + "?" + 
		"&id=" + sessionID + "&size=400&Format=thumbnail&Param=PrintBasePage:" + basePage;

}

// Update the prieview window to reflect changes in the select menu on the main page.
function changePreview(docID, sessionID, basePage) {
	if (! winPreview || winPreview.closed) { return; }
	// page or ending page. Only one should exist at any given time.
	var dataSource = getPreviewDataSource (window);
	if (! dataSource) { return false; }

	winPreview.focus();
	winPreview.location = "/ECO/PageView/" + docID + "/" + dataSource.value + "?" + 
		"&id=" + sessionID + "&size=400&Format=thumbnail&Param=PrintBasePage:" + basePage;
}

// Update the thumbnail image in response to selecting the next/previous link in the preview window.
function updateThumbnail(step, url) {
	var dataSource = getPreviewDataSource(window.opener);
	window.location = url;
	dataSource.selectedIndex += step;
}

// Close the preview window.
function closePreview() {
	if (winPreview) { winPreview.close () }
	return true;
}

// Determine whether we are selecting a starting page or an ending page, and
// return a reference to the corresponding <select> object in the main print
// page.
function getPreviewDataSource(win) {
	if (win.document.SelectPage.start) {
		return win.document.SelectPage.start;
	}
	else if (win.document.SelectPage.end) {
		return win.document.SelectPage.end
	}
	else {
		return false;
	}
}


/* *** Miscellaneous Stuff
 */

// We need to specify some extra style info for the Advanced Options toggle header that
// shouldn't be displayed when JavaScript is turned off.
//document.writeln ('<style type="text/css">#AdvancedLabel { cursor: pointer; color: #0000ff }' +
	//'#AdvancedLabel:hover { text-decoration: underline }</style>');

function iefix() {
    document.writeln("              <link rel=\"stylesheet\" type=\"text/css\" href=\"/css/iefix.css\"/>");
}

