//
// public.js -- Copyright 2012 One More Story, Inc.
//

// ! Table of Contents
//
// $( document ).ready
//
// acctInfoAccord -- Account Info Accordion -- parents/teachers place; shows/hides account information (plug in)
// aHrefFixer -- fixes the source link of an image, making it correctly relative to the root
// checkExpDate -- checks institution expiration date from cookie
// checkIPAddress -- calls the DB with the checkIPAddress command
// checkForCookies -- runs on index.html and looks for previously saved cookies
// checkForClosePlayer -- checks for a 'closePlayerNow' cookie on the home page and closes the player -- MDE
// checkForSSL -- checks protocal and page ID to put the site into https mode when necessary
// checkPageID --  Check the Page ID and raise the opacity of the 'selected' tab, giving the impression of a 'front' tab
// checkReferrer -- check the referrer and reset the cookies if they are coming back from another site
// clearCookies -- clears cookies for log out, also calls db with wipeSession
// closeCur -- closes any open accordian folds
// disablePopup -- disables currently open pop up
// emailAddressFixer -- protect our email address from being picked up by spammers.
// filterableBooks -- Filterable Books- 'Browse Our Books' page; enables user to view books parsed by keywords
// formConfirm - Password retrieval confirmation - hides form and shows confirmation message or error
// getBookID - gets the bookID of the book of the current SAB user
// getBrowserInfo -- gets the users current browser info and write the info into the User Info page
// getInstitution -- calls the DB with the getInstitution command
// getLocation -- Count the /s in the URL to determine location from root
// getSABUser -- calls db wiht getSABUser and populates the page with the 'read a book' flayer player code
// getUser -- calls the DB with the getUser command
// goToLibrary -- closes PP or TP (depending on param) and redirects to library
// goToSabdone -- redirects to sabdone.html, with userid added onto the URL
// ifOther -- if other is chosen in a dropdown, an input is added
// jQuery.cookie -- jquery cookie plugin, includes instructions
// logErrorMessage -- calls the DB with the logMessage command to track errors on the site
// logInAreaTextSwap -- swaps the text 'Not a member? Subscribe' for 'Remember my login' checkbox when text is input
// loginFieldSwap -- swaps the 'sample password field' for the 'real password field' onfocus and swaps back onblur
// loginInstitution -- calls the DB with the loginInstitution command
// loginPPTPUser -- calls the DB with the loginPPTPUser command
// loginUser -- calls db with loginUser, set cookies and redirects accordingly
// logOut -- 'log out' from One More Story completely
// logOutPP -- Log out ( 'Close' ) from the Parents place
// logOutTP -- Log out ( 'Close' ) from the Teachers place
// logOutSAB -- Log out from ReadABook
// navBarDispatcher --  checks the current constant page and sets the visual cues in the navigation bar
// navBarReady -- runs to set up navigation bar on all pages
// Navigation Bar Accordian - jquery accordian plugin set up
// pageMovedDispatch -- looks for referring page and redirects to the closest page match
// populate - populates fields using returnObj from previously run functions, like getUser, etc.
// redirect -- takes url as the param, add global prefix and redirects user, used after a setTimeout
// sendABook -- calls the DB with the sendABook command
// sendEmail -- calls the DB with the sendEmail command
// sendtrackingrequest -- uses the XMLHttpRequest object to send a tracking request to
// sendInstInfoRequest -- calls the DB with the sendInstInfoRequest command
// sendPassword -- calls the DB with the sendPassword command
// setHLG -- runs on bookshelf, checks IP and shows "Home Listening Game" only for schools, teachers and SAs.
// setInfoBanner - sets the details of the info banner
// setInfoCookies -- runs getUser and getInstitution and sets cookies with full (first/last) name and institution name
// setLogInArea -- checks cookies and sets the upper-right-hand corner log in area
// setStatus -- runs on bookshelf, checks IP and shows "Home Listening Game" only for schools, teachers and SAs.
// showAlert -- shows an alert with a message passed through as a param
// showAlertHoliday -- shows a holiday alert with a message passed through as a param
// showBook -- Send A Book, book selector
// showICRI -- hides and shows the ICRI div on the aboutourbooks.html page
// slideSwitch -- Slideshow on the home page- simple carousal of three images on homepage
// srcFixer -- fixes the source link of an image, making it correctly relative to the root
// startPopup -- is called in the onclick to trigger the pop up
// styleInputs - styles inputs and controls style-related changes to inputs on focus, blur, etc.
// unsubscribeMe -- gets email from URL and unsubscribes a user from our mailing list
// Validation Code -- jquery validation plugin
// validateNow -- validates the forms when the submit buttom is click, runs the next routine (via param) and holds the custom error messages.

var debug	= false;

if ( debug ) {
	alert( 'In public.js' );
}

	// for startPopup and disablePopup; 0 means disabled

var popupStatus = 0;		// MDE -- This must be defined before disable popup or it will break in IE 8
var lastFocus	= false;	// MDE -- holds the last field that had the focus when an alert is shown

	// turns the proper pages into https and all others back into http

checkForSSL();


//
//* $( document ).ready
//
$( document ).ready( function() {
	var debug = false;

		//this code checks to see if a user is returning to this page after navigating away from onemorestory.com
		// if yes, the cookies are wiped

	checkReferrer();

	styleInputs();

	getLocation();

		// bind logInAreaTextSwap() to the onblur of this input field

	$( '#username,#passHome' ).blur( function(){
		var thisID = $( this ).attr( 'id' );
		var thisVal = $( this ).val();
		var thisDefVal = this.defaultValue;
		logInAreaTextSwap( thisID, thisVal, thisDefVal );
	});

		// check which page, certain code is index-specific or non-index specific

	switch ( page ) {

		case "index":

			if ( debug ) {
				alert( "page is index" );
			}

				// setLogInArea and checkForCookies run at the end of checkIPAddress, so it shouldn't go here also

			checkIPAddress();

				// check for a cookie which tells us to close the player window

			checkForClosePlayer();

			break;

		default:

			if ( debug ) {
				alert( "page is not index" )
			}

			setLogInArea();

			navBarReady();

			break;

	}

	srcFixer();
	aHrefFixer();
	emailAddressFixer();
	setInfoBanner();

});


//
// acctInfoAccord -- Account Info Accordion -- parents/teachers place; shows/hides account information (plug in)
//  	Important: Due to the existance of OTHER unordered lists (<li>s) inside the accordians, there are several 'checks' below to make sure this routine only affects the correct <li>s.
//
function acctInfoAccord() {

	$( function() {

		// Hide all the content except the first

		$( '.accordian li:odd' ).each( function() {

				// this is to make sure this function is not triggered accidentally by other <li>s inside the accordian

			if ( $( this ).hasClass( 'state1' ) ) {

				return false;

			} else if ( $( this ).hasClass( 'stateOption' ) ) {

				return false;

			}

			$( this ).hide();

		});

		// Add the dimension class to all the content

		$( '.accordian li:odd' ).each( function() {

				// this is to make sure this function is not triggered accidentally by other <li>s inside the accordian

			if ( $( this ).hasClass( 'state1' )) {

				return false;

			} else if ( $( this ).hasClass( 'stateOption' )) {

				return false;

			}

			$( this ).addClass( 'dimension' );

		});

		// Set the even links with an 'even' class

		$( '.accordian li:even:even' ).each( function() {

				// this is to make sure this function is not triggered accidentally by other <li>s inside the accordian

			if ( $( this ).hasClass( 'state1' )) {

				return false;

			} else if ( $( this ).hasClass( 'stateOption' )) {

				return false;

			}

			$( this ).addClass( 'even' );

		});

		// Set the odd links with a 'odd' class

		$( '.accordian li:even:odd' ).each( function() {

				// this is to make sure this function is not triggered accidentally by other <li>s inside the accordian

			if ( $( this ).hasClass( 'state1' )) {

				return false;

			} else if ( $( this ).hasClass( 'stateOption' )) {

				return false;

			}

			$( this ).addClass( 'odd' );

		});

			// Show the correct cursor for the links

		$( '.accordian li:even' ).css( 'cursor', 'pointer' );

			// Handle the click event

		$( '.accordian li:even' ).click( function() {

				// this is to make sure this function is not triggered accidentally by other <li>s inside the accordian

			if ( $( this ).hasClass( 'state1' )) {

				return false;

			} else if ( $( this ).hasClass( 'stateOption' )) {

				return false;

			}


			if ( $( this ).hasClass( 'curTitle' )) {

				//alert( "does have curTitle" );

				var curLi = ( '.accordian li.dimension:visible' );

				$( curLi ).slideUp(300);
				$( this ).animate({
					paddingLeft:"5px"
				});
				$( this ).removeClass( 'curTitle' );

			} else {



				var cur = $(this).next();		// Get the content that needs to be shown
				var old = $( '.accordian li:odd:visible' );		// Get the content that needs to be hidden

					// Make sure the content that needs to be shown
					// isn't already visible

				if ( cur.is( ':visible' ))
					return false;

				old.slideToggle(300);		// Hide the old content
				cur.stop().slideToggle(300);		// Show the new content

					// Animate (add) the padding in the new link

				$(this).stop().animate({
					paddingLeft:"30px"
				});

				$(this).addClass( 'curTitle' );

					// Animate (remove) the padding in the old link

				old.prev().stop().animate({
					paddingLeft:"5px"
				});

				old.prev().removeClass( 'curTitle' );

			}

		} );

			// now, just in case any of that accidentally affected a combo box dropdown item, lets run clear it off:

		$( '.accordian #comboUL li', '.accordian #comboUL li:even', '.accordian #comboUL li:odd' ).show().removeClass('dimension').removeClass('even').removeClass('odd');

	});

}


//
// aHrefFixer -- fixes the source link of an image, making it correctly relative to the root
// 				Must run after getLocation in a document.ready, because it uses Global Variable prefix (see above)
//
function aHrefFixer() {
	$( ".aHrefFix" ).each(function () {

		var hrefLink = $(this).attr( "href" );

		if ( debug ) {
			alert( "hrefLink = [" + hrefLink + "]" );
			}

		$(this).attr( "href", prefix + hrefLink );

	});
}


//
// checkExpDate -- checks institution expiration date from cookie
//
// this routine should only ??? if the user is not home, parent, homeExpired, sab,
// studentAtHome, teacherAtHome
//
function checkExpDate() {
	var debug = false;

	if ( debug ) {
		alert( "In checkExpDate" );
	}

		// Check user type and exit if not inst user

	var thisUserType = $.cookie( 'userType' );
	if (( thisUserType = "home" )
		|| ( thisUserType = "parent" )
		|| ( thisUserType = "sab" )) {

		if ( debug ) {
			alert( "this user is not an institution user and should not be checked for expiration here" );
		}

		return false;
	}

		// Check the expiration date

	var thisExpDateStr	= $.cookie( 'expDate' );

	if ( thisExpDateStr ) {

		var todaysDate	= new Date();
		todaysDate		= Date.parse( todaysDate );
		var thisExpDate = Date.parse( thisExpDateStr );

		if ( debug ) {
			alert( "todaysDate = [" + todaysDate + "]\n" +
					"thisExpDate = [" + thisExpDate + "]" );
		}

		if ( thisExpDate < todaysDate ) {
			if ( debug ) {
				alert( "Institution is expired" );
			}

			alert( "Sorry, your school's subscription has expired - please renew today!" );
			$.cookie( "userType", "schoolExpired", { path: '/', domain: DOMAIN_NAME });
			setInfoCookies( "other/schoolrenewal.html" );

			return false;

		} else {
			if ( debug ) {
				alert( "Institution okay" );
			}

		}

	}

	if ( debug ) {
		alert( "done checkExpDate" );
	}

	return true;

}


//
// checkIPAddress -- calls the DB with the checkIPAddress command
//
function checkIPAddress() {
	var debug	= false;

	if ( debug ) {
		alert( "In checkIPAddress" );
	}

	var logoutCookie 	= $.cookie( 'loggedOut' );
	var docref 			= document.referrer;
	var cameFromOMS		= "";

	if ( docref.indexOf( "onemorestory.com") != -1 ){

		cameFromOMS = true;

	} else {

		cameFromOMS = false;

	}

	if ( debug ) {
		alert( "logoutCookie is [" + logoutCookie + "]" );
	}

		// Call the database

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

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

		if ( debug ) {
			alert( "now in anon function from checkIPAddress" );
			alert( "data is [" + data + "]" );
			alert( "page is [" + page + "]" );
			alert( "About to set cookies" );
		}

		var inst = returnObj [ "Institution Type" ] ;

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

			//there is a problem, checkIP was not successful

			if ( debug ) {
				alert( "results is not success" );
			}

			if ( returnObj[ "error" ] == 'Not an Institution IP' ) {

					// if the IP is not recognized, we check for previously set cookies
					// if IPrecog was previously set to anything at all, show alert and clearCookies

				if ( debug ) {
					alert( "IP is not an institution, not recognized" );
				}

				var ipCookie = $.cookie( 'IPrecog' );

				if (( ipCookie != '' ) && ( ipCookie != undefined ))  {

					clearCookies( 'redirectNowhere' );

				}

			}

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

			var curUT = $.cookie( 'userType' );

				// IP-recognized schools who do not require log in should be redirected to the library

			if ( page == 'index' ) {

				if (( returnObj [ "loginRequired" ] == "false" )
					&& ( logoutCookie != 'true' )
					&& ( cameFromOMS != true )) {

					if ( debug ) {
				    	alert( "page is index, results is success, loginreqd is false and the user did not just log out - redirecting to library" );
				    }

				    	// setting the userType and IPrecog cookies

				    switch ( inst ) {

				    	case "SCH":

				    		if (( curUT == undefined )
				    			|| ( curUT == "" )
				    			|| ( curUT == "schoolIP" )) {

				    			$.cookie( "userType", "school", { path: '/', domain: DOMAIN_NAME });

				    		}

				    		$.cookie( "IPrecog", "school", { path: '/', domain: DOMAIN_NAME });

				    		break;

				    	case "LIB":

				    		if (( curUT == undefined )
				    			|| ( curUT == "" )
				    			|| ( curUT == "libraryIP" )) {

				    			$.cookie( "userType", "library", { path: '/', domain: DOMAIN_NAME });

				    		}

				    		$.cookie( "IPrecog", "library", { path: '/', domain: DOMAIN_NAME });

				    		break;

				    	case "HOP":

				    		if (( curUT == undefined )
				    			|| ( curUT == "" )
				    			|| ( curUT == "hospitalIP" )) {

				    			$.cookie( "userType", "hospital", { path: '/', domain: DOMAIN_NAME });

				    		}

				    		$.cookie( "IPrecog", "hospital", { path: '/', domain: DOMAIN_NAME });

				    		break;

				    	default:

				    		if ( debug ) {
				    			alert( "userType and IPrecog cookies not set" );
				    		}

				    	break;

				    }

				   	setInfoCookies( "Library/library.html" );

				} else {

						// setting the userType and IPrecog cookies

				    switch ( inst ) {

				    	case "SCH":

				    			// only set the userType to _IP if it isn't already set

				    		if (( curUT == undefined )
				    			|| ( curUT == "" )
				    			|| ( logoutCookie == 'true' )) {

				    			$.cookie( "userType", "schoolIP", { path: '/', domain: DOMAIN_NAME });

				    		} else {

				    			$.cookie( "IPrecog", "school", { path: '/', domain: DOMAIN_NAME });

							}


				    		break;

				    	case "LIB":

				    		if (( curUT == undefined )
				    			|| ( curUT == "" )
				    			|| ( logoutCookie == 'true' )) {


				    			$.cookie( "userType", "libraryIP", { path: '/', domain: DOMAIN_NAME });

				    		} else {

				    			$.cookie( "IPrecog", "library", { path: '/', domain: DOMAIN_NAME });

				    		}

				    		break;

				    	case "HOP":

				    		if (( curUT == undefined )
				    			|| ( curUT == "" )
				    			|| ( logoutCookie == 'true' )) {


				    			$.cookie( "userType", "hospitalIP", { path: '/', domain: DOMAIN_NAME });

				    		} else {

				    			$.cookie( "IPrecog", "hospital", { path: '/', domain: DOMAIN_NAME });

				    		}

				    		break;

				    	default:

				    		if ( debug ) {
				    			alert( "userType and IPrecog cookies not set" );
				    		}

				    	break;

					}

				}

			}

		}

	setLogInArea();

	checkForCookies( inst );

	});

	if ( debug ) {
		alert( "Done checkIPAddress" );
	}
}


//
// checkForCookies -- runs on index.html and looks for 'remember my login' cookie
//
function checkForCookies( inst ) {

	var debug = false;

	if ( debug ) {
		alert( "In checkForCookies" );
	}

		// this should not run if userType cookie is set

	var docref = document.referrer;

	var logoutCookie = $.cookie( 'loggedOut' );

	if ( debug ) {
		alert( "docref is [" + docref + "]" );
		alert( "logoutCookie is [" + logoutCookie + "]" );
	}

	var doNotRedirectOrLogIn ;

	if (( docref.indexOf( "onemorestory.com") != -1 )
		|| ( logoutCookie == 'true' )) {

		if ( debug ) {
			alert( "this user is coming from an oms page OR just clicked log out" );
		}

			// if user has just clicked log out, don't auto log them back in
			// to avoid a loop, don't redirect to the library even the user has cookies or autologin turned on

		doNotRedirectOrLogIn = true;
	}

	if (($.cookie( "homeuserInfo=homeusername" ) == undefined)) {

		 // do nothing

		 if ( debug ) {
			alert( "homeuserInfo=homeusername cookie is undefined" );
		}

	} else {

			// if this cookie was set that means the user chose 'remember my password'
			// So parse out the username and password from the cookie and use it to log them in

		var curCookie = $.cookie( "homeuserInfo=homeusername" );

		if ( debug ) {
			alert( "current cookie is [" + curCookie + "]" );
		}

		var curCookie2 	= curCookie.replace( "&pwd=",":" );
		var curCookie3 	= curCookie2.split( ":" );
		var curUsername = curCookie3[0];
		var curPassword = curCookie3[1];

		if ( debug ) {
			alert( "curUsername is [" + curUsername + "]\n\n" +
					"and curPassword is [" + curPassword + "]" );
		}
			// Autopopulate the fields on screen

		$( "#username" ).val( curUsername );
		$( "#passHome" ).val( curPassword );

		$( '#textPassFieldHome' ).hide();
		$( '#passPassFieldHome' ).show();

		$( '#notAMemberDiv' ).hide();
		$( '#rememberLoginDiv' ).show();

		$( '.remember' ).attr( 'checked', 'checked' );		//Check 'remember my password' again

			//Begin log in sequence

		if ( doNotRedirectOrLogIn != true ){

			loginUser();

			checkPageID();

		}

		return false;

	}

		// now do the same exact thing for schools

	if (($.cookie( "schooluserInfo=schoolusername" ) == undefined)) {

		 // do nothing

		 if ( debug ) {
			alert( "schooluserInfo=schoolusername cookie is undefined" );
		}

	} else {

			// if this cookie was set that means the school chose 'remember my password'
			// So parse out the username and password from the cookie and use it to log them in

		var curCookie = $.cookie( "schooluserInfo=schoolusername" );

		if ( debug ) {
			alert( "current cookie is [" + curCookie + "]" );
		}

		var curCookie2 	= curCookie.replace( "&schoolpwd=",":" );
		var curCookie3 	= curCookie2.split( ":" );
		var curUsername = curCookie3[0];
		var curPassword = curCookie3[1];

		if ( debug ) {
			alert( "curUsername is [" + curUsername + "]\n\n" +
					"and curPassword is [" + curPassword + "]" );
		}

		$( '.remember' ).attr( 'checked' );		//Check 'remember my password' again

			// Begin log in sequence

		if ( doNotRedirectOrLogIn != true ){

			loginInstitution( null, 'useThese', curUsername, curPassword );

			checkPageID();

		} else {

			if ( debug ) {
				alert( "now here!!" );
			}

			if ( inst != undefined ){

					// the user just logged out so don't log them back in, just fill in the input fields
				inst = inst.toLowerCase();

				var thisInstType ;

				if ( inst == 'sch' ){

					thisInstType = "School";

				} else if ( inst == 'lib' ){

					thisInstType = "Library";

				} else if ( inst == 'hop' ){

					thisInstType = "Hospital";

				}

				$( "#user" + thisInstType ).val( curUsername );
				$( "#pass" + thisInstType ).val( curPassword );

			}

		}

	}

	if ( debug ) {
		alert( "Done checkForCookies" );
	}

}


//
// checkForClosePlayer -- checks for a 'closePlayerNow' cookie on the home page and closes the player -- MDE
//		Explanation: a user may press 'Log Out' on any page while browsing the site
// 			and this should close the player window
// 			But the code to close the player is located in player.js which isn't on every page
// 			Therefore, if a user clicks 'Log Out' and the player window is open,
// 			Then a 'closePlayer' cookie is set, all other cookies are deleted, and the user is sent to the home page
// 			On the home page, this routine runs, checks for the cookie,
// 			if its there, the routine closes the player and deletes the cookie
//

function checkForClosePlayer() {
	var debug = false;

	if ( debug ) {
		alert( "now in checkForClosePlayer" );
	}

	var closePlayerNow = $.cookie( 'closePlayerNow' );

	if ( closePlayerNow ) {

		if ( debug ) {
			alert( "closePlayerNow is true" );
		}

		closeAllPlayers();		// Close the players

		if ( debug ) {
			alert( "Done closing players" );
		}

			// Remove the trigger cookie

		$.cookie( PLAYER_COOKIE, null, { path: '/', domain: DOMAIN_NAME } );
		$.cookie( SAB_PLAYER_COOKIE, null, { path: '/', domain: DOMAIN_NAME } );
		$.cookie( TAB_PLAYER_COOKIE, null, { path: '/', domain: DOMAIN_NAME } );
		$.cookie( 'closePlayerNow', null, { path: '/', domain: DOMAIN_NAME } );

	}

	if ( debug ) {
		alert( "done in checkForClosePlayer" );
	}

}


//
// checkForSSL -- checks protocal and page ID to put the site into https mode when necessary
//
function checkForSSL() {
	var debug = false;
	if ( debug ) {
		alert( "now in checkForSSL" );
	}

		// get protocal

	var curProt 	= location.protocol;
	var curURL 		= document.URL;

	if ( debug ) {
		alert( "Checking curURL" );
	}
	if ( curURL == "undefined" ) {
		if ( debug ) {
			alert( "curURL is undefined" );
		}
		return false;
	}
	var nextURL 	= "";

	var forceSSL 	= 'no';

		// Force SSL mode for pages in this list

	if (( curURL.indexOf( 'homeuseform.html' ) != -1 )
			|| ( curURL.indexOf( 'givegiftform.html' ) != -1 )
			|| ( curURL.indexOf( 'parentsplace/accountsettings.html' ) != -1 )
			|| ( curURL.indexOf( 'other/accountrenewal.html' ) != -1 )
			|| ( curURL.indexOf( 'teachersplace/classlist.html' ) != -1 )
			|| ( curURL.indexOf( 'teachersplace/masterstudentlist.html' ) != -1 )
			|| ( curURL.indexOf( 'teachersplace/studentinfo.html' ) != -1 )
			|| ( curURL.indexOf( 'teachersplace/teacherinfo.html' ) != -1 )
			|| ( curURL.indexOf( 'itslearning/add.php' ) != -1 )
			|| ( curURL.indexOf( 'itslearning/view.php' ) != -1 )) {

		forceSSL	= 'yes';

		// Ignore SSL state for these pages

	} else if ( curURL.indexOf( 'player.html' ) != -1 ) {
		if ( debug ) {
			alert( "page is player.html, exiting" );
		}
		return false;
	}

		// if it has http://

	if ( curProt == "http:" ) {

		if ( debug ) {
			alert( "protocol is http:" );
		}

			// check for page ID, if it is home use form or gift use form

		if ( forceSSL == 'yes' ) {

			if ( debug ) {
				alert( "and the page is either home use or give use form, now changing to https" );
			}

				// then change to https

			nextURL = curURL.replace( "http:", "https:" );

			window.location.assign( nextURL );

			return false;

		}

	}

		// if it has https://

	if ( curProt == "https:" ) {

		if ( debug ) {
			alert( "protocol is https:" );
		}

			// check for page ID, if it is NOT home use form or gift use form

		if ( forceSSL != 'yes' ) {

			if ( debug ) {
				alert( "and the page is NOT home use form or give gift form, changing to http" );
			}

				// then change to http

			nextURL = curURL.replace( "https:", "http:" );

			window.location.assign( nextURL );

			return false;

		}

	}

	if ( debug ) {
		alert( "done in checkForSSL" );
	}

}


//
// checkPageID --  Check the Page ID and raise the opacity of the 'selected' tab, giving the impression of a 'front' tab
//
function checkPageID() {

	var debug = false;

	if ( debug) {
		alert( "about to run Page switch, page = [" + page + "]" );
	}

	switch ( page ) {

		case "private_parent":

			$( "#PP" ).css({ opacity: 1.0 });

			break;

		case "private_parent_acct":

			$( "#PP_acct" ).css({ opacity: 1.0 });

			break;

		case "private_parent_childInfo":

			$( "#PP_childInfo" ).css({ opacity: 1.0 });

			break;

		case "private_parent_log":

			break;

		case "private_parent_renew":

			$( "#PP_acct_renew" ).css({ opacity: 1.0 });

			break;

		case "private_teacher":

			$( ".TP" ).css({ opacity: 1.0 });

			break;

		case "private_teacher_acct":

			$( "#TP_acct" ).css({ opacity: 1.0 });

			break;

		case "private_teacher_classlist":

			$( "#TP_classlist" ).css({ opacity: 1.0 });

			break;

		case "private_teacher_log":

			break;

		case "private_admin":

			$( "#AP" ).css({ opacity: 1.0 });

			break;

		case "private_admin_acct":

			$( "#AP_acct" ).css({ opacity: 1.0 });

			break;

		case "private_admin_classroom":

			$( "#AP_classroom" ).css({ opacity: 1.0 });

			break;

		case "private_admin_log":

			break;

		case "library":

			break;

		case "index":

				//because of the layout of the homepage, only the main tabs are shown

			$( '.noIndex' ).each( function() {
				$( this ).hide();
			});

			$( '.index' ).each( function() {
				$( this ).show();
				$( this ).css( { 'opacity' : '.85' } );
			});


			break;

		default:

			//do nothing

		break;
	}
}


//
// checkReferrer -- check the referrer and reset the cookies if they are coming back from another site
//					This is a work-around for clearing cookies when they navigate away from One More Story
// 					checkReferrer should only run if the user has logged in previously
// 					so look for the IPrecog cookie and userType cookie
// 					if the IPrecog is anything and the userType is anything - proceed to clearCookies
// 					Why? Because:
// 						if the userType is anything, then this is a returning user and they should have to sign in again
// 						unless the IPrecog is set, in which case their userType is set automatically upon IP recognition
// 							and this would send them into a neverending loop of clearing cookies and setting cookies and...
//
function checkReferrer() {

	var debug = false;

	if ( debug ) {
		alert( "now in checkReferrer" );
	}

	var playerCookieStat = $.cookie( PLAYER_COOKIE );

	if ( debug ) {
		alert( "playerCookieStat is [" + playerCookieStat + "]" );
	}

	var thisRef = document.referrer;		// find the referring URL

	if ( debug ) {
		alert( "thisRef = [" + thisRef + "]" );
	}

		// if its null or not onemorestory.com, we will clear the cookies
		// check if its NOT null

	if (( thisRef != null )
			&& ( thisRef != 'undefined' )
			&& ( thisRef != "" )) {

			// now check if its onemorestory.com or localhost
			// parse for the domain
			// if onemorestory.com IS located in the referrer

		if ( thisRef.indexOf( DOMAIN_NAME ) != -1 ) {

			if ( debug ) {
				alert( "referrer is onemorestory.com" );		// do nothing
			}

		} else {

			if ( debug ) {
				alert( "you navigated away from our site!" );
			}

			var thisURL = document.URL;

			$.cookie( PLAYER_COOKIE, null, { path: '/', domain: DOMAIN_NAME });
			$.cookie( SAB_PLAYER_COOKIE, null, { path: '/', domain: DOMAIN_NAME });
			$.cookie( TAB_PLAYER_COOKIE, null, { path: '/', domain: DOMAIN_NAME });

		}

	} else {

		if ( debug ) {
			alert( "referrer is null" );		// do nothing
		}

	}

	if ( debug ) {
		alert( "done in checkReferrer" );
	}

}


//
// clearCookies -- clears cookies for log out, also calls db with wipeSession
// 		the param is a block of code to run after the cookies are cleared - its usually a redirect
//
function clearCookies( thisInstr, thisURL ) {

	var debug = false;

	if ( debug ) {
		alert( "now in clearCookies and thisInstr is [" + thisInstr + "]" );
	}

	if ( debug ) {
		alert( "1. unlock library" );
	}

		// unlock the library -- MDE
		// Note that we must wait for the return so that the lock id gets cleared

	callDB( "unlockLibrary", "", function() {

			// Clear cookies

		if ( debug ) {
			alert( "2. in callback function - now clearing all cookies manually \n\n DOMAIN_NAME is [" + DOMAIN_NAME + "]" );
		}

		$.cookie( "userType", null, { path: '/', domain: DOMAIN_NAME });
		$.cookie( "thisTeacher", null, { path: '/', domain: DOMAIN_NAME });
		$.cookie( "thisStudent", null, { path: '/', domain: DOMAIN_NAME });
		$.cookie( "thisInst", null, { path: '/', domain: DOMAIN_NAME });
		$.cookie( "cameFrom", null, { path: '/', domain: DOMAIN_NAME });
		$.cookie( "homeUserName", null, { path: '/', domain: DOMAIN_NAME });
		$.cookie( "userid", null, { path: '/', domain: DOMAIN_NAME });
		$.cookie( "instid", null, { path: '/', domain: DOMAIN_NAME });
		$.cookie( "IPrecog", null, { path: '/', domain: DOMAIN_NAME });
		$.cookie( "instname", null, { path: '/', domain: DOMAIN_NAME });
		$.cookie( "fullname", null, { path: '/', domain: DOMAIN_NAME });
		$.cookie( "classLogType", null, { path: '/', domain: DOMAIN_NAME });
		$.cookie( "expDate", null, { path: '/', domain: DOMAIN_NAME });
		$.cookie( "schooluserInfo", null, { path: '/', domain: DOMAIN_NAME });
		$.cookie( "homeuserInfo", null, { path: '/', domain: DOMAIN_NAME });
		$.cookie( "refPage", null, { path: '/', domain: DOMAIN_NAME });

		if ( debug ) {
			alert( "done clearing cookies line by line \n\n3. now calling wipeSession" );
		}

			// Wipe session objects

		callDB( "wipeSession", "", function() {

			if ( debug ) {
				alert( "now in callback function \n\n4. now redirecting according to parameter: [" + thisInstr + "]" );
			}

			if ( thisInstr == 'redirectHome' ) {

				if ( debug ) {
					alert( "redirecting home" );
				}

				document.location = ( prefix + "index.html" );

			} else if ( thisInstr == 'redirectSABLogOut' ) {

				if ( debug ) {
					alert( "redirection to sab logout page" );
				}

				document.location = prefix + "sab/logout.html"

			} else if ( thisInstr == 'URL' ) {

				if ( debug ) {
					alert( "redirection to param URL" );
				}

				document.location = prefix + thisURL;

			} else if ( thisInstr == 'redirectNowhere' ) {

				if ( debug ) {
					alert( "redirecting no where" );
				}

				setLogInArea();		// don't redirect but since the cookies have been cleared, we do need to run setLogInArea
			}
		});

	});

	if ( debug ) {
		alert( "done clearCookies" );
	}

}


//
// closeCur -- closes any open accordian folds
//		Once a form is validated and submited inside this accordian, closeCur runs to close the currently open div and reset the css.
//


function closeCur() {
	var debug = false;

	if ( debug ) {
		alert( "now in closeCur" );
	}

	var curTitleLi 	= ( '.accordian li.curTitle' );
	var curLi 		= ( '.accordian li.dimension:visible' );

	$( curLi ).slideUp(300);
	$( 'li.even, li.odd' ).css( 'padding-left', '5px' );
	$( 'li.curTitle' ).css( 'padding-left', '5px' ).removeClass( 'curTitle' );

	if ( debug ) {
		alert( "now in closeCur" );
	}

}


//
// disablePopup -- disables currently open pop up
//
// MDE -- missing thisNum parameter.  Better name would be popUpNum
//
function disablePopup( thisNum ) {
	var debug = false;

	if ( debug ) {
		alert( "thisNum is [" + thisNum + "]" );		// MDE this will break IE 8
	}

		// disables popup only if it is enabled

	if ( popupStatus==1 ) {

		$( "#backgroundPopup" ).fadeOut( "slow" );
		$( "#popup" + thisNum ).fadeOut( "slow" );
		popupStatus = 0;

		if ( lastFocus != false ) {
			$( lastFocus ).focus();
			lastFocus	= false;
		}
	}
}


//
// emailAddressFixer -- protect our email address from being picked up by spammers.
//
//
function emailAddressFixer() {

		// for each span with the class hideEMail

	$( ".hideEmail" ).each( function() {

			// the content of the span

		var emailID = ( $(this).text());
		var part1 = "@";
		var part2 = "onemorestory";
		var part3 = ".com";

			// make it into an email address

		var fullEmail = emailID + part1 + part2 + part3;

			// write it into a mailto link

		var final = ( '<a href="mailto:' + fullEmail + '" target="_blank">' + fullEmail + '</a>' );

			// put it back in the span

		$( this ).html( final );

	});

}


//
// enterLibrary -- allows a new subscriber to automatically log in to the site
//
function enterLibrary( type ) {

	var debug = false;

	if ( debug ) {
		alert( "now in enterLibrary" );
	}

	if( type == 'expired' ) {

		$.cookie( "userType", "home", { path: '/', domain: DOMAIN_NAME });

		setInfoCookies( "Library/library.html" );

	} else {

		loginUser( 'auto' );

	}

	if ( debug ) {
		alert( "done in enterLibrary" );
	}

}


//
// filterableBooks -- Filterable Books- 'Browse Our Books' page; enables user to view books parsed by keywords
//
function filterableBooks() {
	$( 'ul#filter a' ).click( function() {

		$(this).css( 'outline','none' );
		$( 'ul#filter .current' ).removeClass( 'current' );
		$(this).parent().addClass( 'current' );

		var filterVal = $(this).text().toLowerCase().replace( ' ','-' );

		if (filterVal == 'all' ) {

			$( 'ul#books li.hidden' ).fadeIn( 'slow' ).removeClass( 'hidden' );

		} else {

			$( 'ul#books li' ).each( function() {
				if (!$(this).hasClass(filterVal)) {
					$(this).fadeOut( 'normal' ).addClass( 'hidden' );
				} else {
					$(this).fadeIn( 'slow' ).removeClass( 'hidden' );
				}
			});
		}

		return false;
	});
}


//
// formConfirm - Password retrieval confirmation - hides form and shows confirmation message or error
//					(depending on if param is success or failure
//
function formConfirm( requestType, confirmMessage, errorMessage ) {
	var debug = false;

	if ( debug ) {
		alert( "now in formConfirm" );

			//checks curResults, which is a global variable set by the function that calls formConfirm

		alert ( "curResults is [" + curResults + "]" );
	}

		//reset spans to default (hidden) in case this form is being submitted for the second time

	$( '#formError' ).hide();
	$( '#formError2' ).hide();
	$( '#formErrorMain' ).hide();
	$( '#formConfirmation' ).hide();
	$( '#formConfirmationMain' ).hide();
	$( '#successMessageSpan' ).text( '' );
	$( '#additionalSuccessSpan' ).text( '' );
	$( '#errorMessSpan' ).text( '' );

	var curStatus = curResults;

		// certion forms don't need a pop up

	var showPop = true;

	if (( requestType == 'sendPassword' )
			|| ( requestType == 'sendInstInfoRequest' )) {

		showPop = false;

	}

	if ( curStatus == "success" ) {

		if ( debug ) {
			alert( "curStatus is success" );
		}
			//hide input fields

		$( '#formInput' ).hide();

			//on these pages, the accordion should be closed and reset to defaults

		if (( page == "private_parent_acct" )
			|| ( page == "private_admin_acct" )) {

			if ( debug ) {
				alert( "page is [" + page + "] and now closing accordian" );
			}

			closeCur();


		} else {

			//

		}

		if ( showPop ) {

				//show confirmation message

			startPopup( 'formConfirmation' );

			$( '#formConfirmationMain' ).show();

		}

		$( '#formConfirmation' ).show();

		$( '#successMessageSpan' ).text(confirmMessage);

		$( '#additionalSuccessSpan' ).html(confirmMessage);


			// special instructions on the schoolRenewal page

		if ( requestType == 'schoolRenewal' ) {

			$('#standardSuccess').hide();
			$('#renewalSuccess').show();

		}

	} else if ( curStatus == "error" ) {

		if ( debug ) {
			alert( "curStatus is error" );
		}
			//hide input fields

		$( '#formInput' ).hide();

			//on these pages, accordian should be closed and reset to default

		if (( page == "private_parent_acct" )
			|| ( page == "private_admin_acct" )) {

			if ( debug ) {
				alert( "now in if statement; page is [" + page + "]" );
			}

			closeCur();

		} else {

			//

		}

		if ( showPop ) {

				//Populate field with error message, to tell user what went wrong

			startPopup( 'formConfirmation' );

			$( '#errorMessSpan' ).text( errorMessage );

		}

		$( '#formErrorMain' ).show();

		$( '#formError' ).show();

		$( '#formError2' ).show();

		logErrorMessage( returnObj[ 'error' ], '' );

		if ( debug ) {
			alert( "done logging error message" );
		}

	}

	if ( debug ) {
		alert( "done in formConfirm" );
	}
}


//
// getBookID - gets the bookID of the book of the current SAB user
//
function getBookID() {
	var debug	= false;
	if ( debug ) {
		alert( "In getBookID" );
	}

	var jsonStr = "";
	if ( debug ) {
		alert( "jsonStr = [" + jsonStr + "]" );
	}

	callDB( "getSABUser", jsonStr, function( data ) {

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

		if ( debug ) {
			alert( "In getSABUser anon function, data = [" + data + "]" );
		}

		if ( returnObj[ "results" ] == 'error' ) {

			if ( debug ) {
				alert( "result is error" );
			}

			logErrorMessage( returnObj[ 'error' ], '' );

			showAlert( "Sorry, there was an error accessing your 'free week' guest account.\nIf this problem persists, please contact us." );

		}

	});

	if ( debug ) {
		alert( "Done getBookID" );
	}

}


//
// getBrowserInfo -- gets the users current browser info and write the info into the User Info page
//
function getBrowserInfo() {

		var BrowserDetect = {
		init: function() {
			this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
			this.version = this.searchVersion(navigator.userAgent)
				|| this.searchVersion(navigator.appVersion)
				|| "an unknown version";
			this.OS = this.searchString(this.dataOS) || "an unknown OS";
		},
		searchString: function (data) {
			for (var i=0;i<data.length;i++)	{
				var dataString = data[i].string;
				var dataProp = data[i].prop;
				this.versionSearchString = data[i].versionSearch || data[i].identity;
				if (dataString) {
					if (dataString.indexOf(data[i].subString) != -1){
						return data[i].identity;
					}
				}
				else if (dataProp){
					return data[i].identity;
				}
			}
		},
		searchVersion: function (dataString) {
			var index = dataString.indexOf(this.versionSearchString);
			if (index == -1) return;
			return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
		},
		dataBrowser: [
			{
				string: navigator.userAgent,
				subString: "Chrome",
				identity: "Chrome"
			},
			{ 	string: navigator.userAgent,
				subString: "OmniWeb",
				versionSearch: "OmniWeb/",
				identity: "OmniWeb"
			},
			{
				string: navigator.vendor,
				subString: "Apple",
				identity: "Safari",
				versionSearch: "Version"
			},
			{
				prop: window.opera,
				identity: "Opera"
			},
			{
				string: navigator.vendor,
				subString: "iCab",
				identity: "iCab"
			},
			{
				string: navigator.vendor,
				subString: "KDE",
				identity: "Konqueror"
			},
			{
				string: navigator.userAgent,
				subString: "Firefox",
				identity: "Firefox"
			},
			{
				string: navigator.vendor,
				subString: "Camino",
				identity: "Camino"
			},
			{		// for newer Netscapes (6+)
				string: navigator.userAgent,
				subString: "Netscape",
				identity: "Netscape"
			},
			{
				string: navigator.userAgent,
				subString: "MSIE",
				identity: "Internet Explorer",
				versionSearch: "MSIE"
			},
			{
				string: navigator.userAgent,
				subString: "Gecko",
				identity: "Mozilla",
				versionSearch: "rv"
			},
			{ 		// for older Netscapes (4-)
				string: navigator.userAgent,
				subString: "Mozilla",
				identity: "Netscape",
				versionSearch: "Mozilla"
			}
		],
		dataOS : [
			{
				string: navigator.platform,
				subString: "Win",
				identity: "Windows"
			},
			{
				string: navigator.platform,
				subString: "Mac",
				identity: "Mac"
			},
			{
				   string: navigator.userAgent,
				   subString: "iPhone",
				   identity: "iPhone/iPod"
		    },
			{
				string: navigator.platform,
				subString: "Linux",
				identity: "Linux"
			}
		]

	};
	BrowserDetect.init();

	$( '#userInfo' ).append( "Browser: " + BrowserDetect.browser + "<br /> Version: " + BrowserDetect.version + "<br /> OS: " + BrowserDetect.OS + "" );

}


//
// getInstitution -- calls the DB with the getInstitution command
//
function getInstitution( populate1, populate2, populate3 ) {
	var debug	= false;
	if ( debug ) {
		alert( "In getInstitution" );
	}

	var jsonStr = "";

	if ( debug ) {
		alert( "jsonStr = [" + jsonStr + "]" );
	}

	callDB( "getInstitution", jsonStr, function( data ) {

		returnObj   = new Object;							// Uses global returnObj so the populate routine can make use of the values
		returnObj   = createArray( returnObj, data );

		if ( debug ) {
			alert( "In getInstitution anon function, data = [" + data + "]" );
		}

		if ( populate1 ) {

			populate( populate1 );

		}

		if ( populate2 ) {

			populate( populate2 );

		}

		if ( populate3 ) {

			populate( populate3 );

		}

	});

	if ( debug ) {
		alert( "Done getInstitution" );
	}
}


//
// getLocation -- Count the /s in the URL to determine location from root
// 				!! - This defines the global variable 'prefix' which is used many times throughout this javascript file
//
function getLocation( nextFunc ) {
	var debug = false;

	var useParent = "../";
	var curpage = "index.html";
	var str = document.location.href;
			if ( debug ) {
				alert( "str = [" + str + "]" );
			}

	var count = 0;
	var pos = str.indexOf( "/" );

				if ( debug ) {
					alert( "pos = [" + pos + "]" );
					alert( "count = [" + count + "]" );
				}

	while (( pos != -1 ) && ( count < 10 )) {
					if ( debug) {
						alert( "pos = [" + pos + "]" );
					}
		pos = str.indexOf( "/", pos + 1 );
		count++;
	}

	for ( var numPrefixes = 0; ( numPrefixes < ( count - NESTING_LEVEL )); numPrefixes++ ) {
		prefix = prefix + useParent;
		}

	if ( debug ) {
		alert( "prefix is [" + prefix + "]" );
	}

	if ( nextFunc ) {

		nextFunc();

	}
}


//
// getSABUser -- calls db wiht getSABUser and populates the page with the 'read a book' flayer player code
//
function getSABUser() {

	var debug	= false;

	if ( debug ) {
		alert( "In getSABUser" );
	}

	var jsonStr = "";

	callDB( "getSABUser", jsonStr, function( data ) {

		returnObj   = new Object;				// Uses global returnObj so the populate routine can make use of the values
		returnObj   = createArray( returnObj, data );

		if ( debug ) {
			alert( "In getSABUser anon function, data = [" + data + "]" );
		}

		populate( 'sab' );

	});

}


//
// getUser -- calls the DB with the getUser command
//
function getUser( populate1, populate2, populate3 ) {
	var debug = false;
	if ( debug ) {
		alert( "In getUser" );
	}

	var jsonStr = "";
	if ( debug ) {
		alert( "jsonStr = [" + jsonStr + "]" );
	}

	callDB( "getUser", jsonStr, function( data ) {

		returnObj   = new Object;				// Uses global returnObj so the populate routine can make use of the values
		returnObj  	= createArray( returnObj, data );

		if ( debug ) {
			alert( "In getUser anon function, data = [" + data + "]" );
		}

			// run populate to use this information to fill in spans and inputs on various pages

		if ( returnObj[ "results" ] == 'success' ) {

			if ( debug ) {
				alert( "getUser is success" );
			}

			if ( populate1 ) {

				if ( debug ) {
					alert( "populate1 running now, it is [" + populate1 + "]" );
				}
				populate( populate1 );

			}

			if ( populate2 ) {

				if ( debug ) {
					alert( "populate2 running now, it is [" + populate2 + "]" );
				}
				populate( populate2 );

			}

			if ( populate3 ) {

				if ( debug ) {
					alert( "populate3 running now, it is [" + populate3 + "]" );
				}
				populate( populate3 );

			}

		} else {

			if ( debug ) {
				alert( "getUser is error" );
			}

		}

	});

	if ( debug ) {
		alert( "Done getUser" );
	}
}


//
// getUserAndInstitution
//

function getUserAndInstitution() {
	var debug = false;

	if ( debug ) {
		alert( "now in getUserAndInstitution" );
	}

	var jsonStr = "";

	callDB( "getUser", jsonStr, function( data ) {

		returnObj   	= new Object;					// Uses global returnObj so the populate routine can make use of the values
		returnObj       = createArray( returnObj, data );

		if ( debug ) {
			alert( "In getUser anon function, data = [" + data + "]" );
		}

			// set the first and last name as escaped cookies, to populate the log in area

		if ( returnObj[ "results" ] == 'success' ) {

			if ( debug ) {
				alert( "getUser is success" );
			}

			populate( 'userInfo' );

		} else {

			if ( debug ) {
				alert( "getUser is error" );
			}

		}

		jsonStr = "";

		callDB( "getInstitution", jsonStr, function( data ) {

			returnObj   = new Object;						// Uses global returnObj so the populate routine can make use of the values
			returnObj       = createArray( returnObj, data );

			if ( debug ) {
			    alert( "In getInstitution anon function, data = [" + data + "]" );
			}

			    // set the first and last name as escaped cookies, to populate the log in area

			if ( returnObj[ "results" ] == 'success' ) {

			    if ( debug ) {
			    	alert( "getInstitution is success" );
			    }

			    populate( 'instInfo' );

			} else {

			    if ( debug ) {
			    	alert( "getInstitution is error" );
			    }

			}

			if ( debug ) {
				alert( "done with getUser and getInstitution" );
			}

		});

	});

	if ( debug ) {
		alert( "done in getUserAndInstitution" );
	}

}

//
// goToLibrary -- closes PP or TP (depending on param) and redirects to library
//
function goToLibrary( type ) {

	var debug = false;

	if ( debug ) {
		alert( "now in goToLibrary and type is [" + type + "]" );
	}

	var thisType = type;

	var IPrecog = $.cookie( "IPrecog" );

		// if the user is a teacher or school admin

	if ( thisType == 'TP' ) {

			// and if the user is logged in at school

		if ( IPrecog == "school" ) {

				// change the cookie to school (i.e. log the school in as an institution)

			$.cookie( "userType", "school", { path: '/', domain: DOMAIN_NAME });

		} else {

				// change the cookie to teacherAtHome (i.e. close the TP but keep the teacher logged in at home)

			$.cookie( "userType", "teacherAtHome", { path: '/', domain: DOMAIN_NAME });

		}

	} else if ( thisType == 'PP' ) {

		$.cookie( "userType", "home", { path: '/', domain: DOMAIN_NAME });

	}

	if ( debug ) {
		alert( "done changing userType (closing " + thisType + " ), now redirecting to library" );
	}

	document.location = prefix + 'Library/library.html';

	if ( debug ) {
		alert( "done in goToLibrary" );
	}

}


//
// goToSabdone -- redirects to sabdone.html, with userid added onto the URL
//

function goToSabdone() {

	var debug = false;

	if ( debug ) {
		alert( "now in goToSabdone" );
	}

	var thisUserID = $.cookie( 'userid' );

	document.location = prefix + 'sab/sabdone.html?userid=' + thisUserID;

	if ( debug ) {
		alert( "done in goToSabdone" );
	}
}


//
// ifOther -- Adds a text field if "Other" is chosen for "HowHeard"
//
// (the correct spans must be there to recieve the input html)
//
function ifOther( question ) {
	var debug = false;

	if ( debug ) {
		alert( "In ifOther()" );
	}

	if ( question == 'howhear' ) {

		if ( debug ) {
			alert( "Dropdown is howhear" );
		}

		if ( $( '#howHear' ).val() == 'Other' ) {

			if ( debug ) {
				alert( "Showing text input field" );
			}

			$( '#otherSpan' ).html( '<label for="howHearOther"><p class="smallText indent">Other: </p></label>' +
									'<input id="howHearOther" name="howHearOther" class="postFocus" type="text" />' +
									'<br />' );
			$( '#howHearOther' ).focus();

		} else {

			if ( debug ) {
				alert( "Removing text input field" );
			}

			$( '#otherSpan' ).html( '' );
		}

	} else if ( question == 'iam' ) {

		if ( debug ) {
			alert( "Dropdown is iam" );
		}

		if ( $('#iam').val() == 'Other' ) {

			if ( debug ) {
				alert( "Showing text input field" );
			}

			$( '#otherSpan' ).html( '<label for="iamother"><p class="smallText indent">Other: </p></label>' +
									'<input id="iamother" name="iamother" class="postFocus" type="text" /><br />' );
			$( '#iamother' ).focus();

		} else {

			if ( debug ) {
				alert( "Removing text input field" );
			}

			$( '#otherSpan' ).html( '' );

		}

	}

}


//
// jQuery.cookie -- jquery cookie plugin, includes instructions
//

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie( 'the_cookie', 'the_value' );
 * @desc Set the value of a cookie.
 * @example $.cookie( 'the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie( 'the_cookie', 'the_value' );
 * @desc Create a session cookie.
 * @example $.cookie( 'the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

 // MDE   Note this is extremely tricky code!

jQuery.cookie = function(name, value, options) {

	var debug = false;

	if ( debug ) {
		alert( "now in jquery.cookie; name is [" + name + "] and value is [" + value + "] and options is [" + options + "]" );
	}

    if (typeof value != 'undefined' ) { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (((options.expires) && (typeof options.expires == 'number' || options.expires.toUTCString))) {
            var date;
            if (typeof options.expires == 'number' ) {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }

        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...

        var path = options.path ? '; path=' + (options.path) : '';


        	// MDE -- this doesn't take into account explicit references to localhost.  Note that setting explicit
        	// domains when using localhost is buggy, because localhost appears to be a TLD

        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';

        	// MDE -- if localhost, drop the domain and secure portions.

		var newCookie	= "";
        if ( options.domain == 'localhost' ) {
        	if ( debug ) {
        		alert( "domain is local host" );
        	}
	        newCookie	= [name, '=', encodeURIComponent(value), expires, path].join( '' );
        } else {
	        newCookie	= [name, '=', encodeURIComponent(value), expires, path, domain, secure].join( '' );
	    }

	    if ( debug ) {
	    	alert( "now setting this cookie: [" + newCookie + "]" );
	    }

	    document.cookie	= newCookie;

    } else { // only name given, get cookie
        var cookieValue = null;

        	// this line was replaced by the one below - supposedly an IE7 fix (found on a jquery plugin bug forum)
        //if (document.cookie && document.cookie != '' ) {

        if (((typeof(document.cookie) != 'undefined' ) && (document.cookie != ''))) {
            var cookies = document.cookie.split( ';' );
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=' )) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;

        if ( debug ) {
        	alert( "now getting this cookie: [" + cookieValue + "]" );
        }
    }

	var newOptions = { domain: DOMAIN_NAME, path: '/', hoursToLive: "", secure: true }

};


//
// logErrorMessage -- calls the DB with the logMessage command to track errors on the site
//
function logErrorMessage( returnObjError, nextInstr ) {

	var debug	= false;

	if ( debug ) {
		alert( "In logMessage and returnObjError is [" + returnObjError + "]" );
	}

		// An error has occured - sending an error message to the log, so this can referenced
    	// This way, if a user calls OMS about receiving an error, we can check the log to find out more info

    var errorMessage = ( "Web Error -- returnObj[ 'error' ] = [" + returnObjError + "], " +
						"page = [" + page + "], " +
						"userid cookie = [" + $.cookie( "userid" )  + "]. " );

    if ( debug ) {
    	alert( "errorMessage is [" + errorMessage + "]" );
	}

	var jsonStr	= addToJSONStr( jsonStr, "eventMsg", errorMessage );

	callDB( "logMessage", jsonStr, function( data ) {

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

		if ((nextInstr != undefined)&&(nextInstr != null)) {

			nextInstr;

		}

	});

	if ( debug ) {
		alert( "Done logMessage" );
	}
}


//
// logInAreaTextSwap -- swaps the text 'Not a member? Subscribe' for 'Remember my login' checkbox when text is input
//
function logInAreaTextSwap( id, val, defVal ){
	var debug = false;

	if ( debug ) {
		alert( "now in logInAreaTextSwap" );
		alert( "now blurred from this input field, id is [" + id + "] and value is [" + val + "] and default value is [" + defVal + "]" );
	}

		// if the value is the default value or empty

	var showRememberDiv = false ;

	var curUsernameInput = $( '#username' ).val();

	if ( ( curUsernameInput != '' )
		&& ( curUsernameInput != 'Username' ) ){

		showRememberDiv = true ;

	}

	if ( showRememberDiv == true ){

		$( '#notAMemberDiv' ).hide();

		$( '#rememberLoginDiv' ).show();

	} else {

		$( '#rememberLoginDiv' ).hide();

		$( '#notAMemberDiv' ).show();

	}

	if ( debug ) {
		alert( "done in logInAreaTextSwap" );
	}

}


//
// loginFieldSwap -- swaps the 'sample password field' for the 'real password field' onfocus and swaps back onblur
// 					param showOrHide refers to the 'real' password field
// 					param type is what kind of log in (Home, School, Library, Hospital)
//
function loginFieldSwap( action, thisType ) {
	var debug = false;

	if ( debug ) {
		alert( "now in loginFieldSwap" );
	}

	if ( action == 'show' ) {

		$( '#textPassField' + thisType ).hide();
		$( '#passPassField' + thisType ).show();

		$( '.getFocus' ).blur();

			// the classes referenced below are mostly controled in styleInputs() - check there before making changes

		$( '#fakePass' + thisType ).removeClass( "focusField" ).addClass( "idleField" );
		$( '#pass' + thisType ).focus();

	} else if ( action == 'hide' ) {

		var thisPass = "";

		thisPass = $( '#pass' + thisType ).val();


		if ( thisPass == '' ) {

				// the classes referenced below are mostly controled in styleInputs() - check there before making changes


			$( '#fakePass' + thisType ).removeClass( "focusField" ).addClass( "idleField" );
			$( '#passPassField' + thisType ).hide();
			$( '#textPassField' + thisType ).show();

		}

	}

	if ( debug ) {
		alert( "done in loginFieldSwap" );
	}

}


//
// loginInstitution -- calls the DB with the loginInstitution command
//			This login process is complicated because both institutions and home users must be able to log in here
//			First we check for success with command: loginInstitution
//			Then check for InstitutionType
//			However, 'SCH' might mean both a school institution, a teacher/SA AND a home user
//				(this is because InstitutionType refers to the IP that has been recognized)
//			So, we set the school cookies but then run getUser
//			If getUser fails, this mean it is a school institution log in
//			Otherwise, set the cookies again according to what kind of user it is
//			Another note: once userType cookies have been set, you'll see that setInfoCookies( "Library/library.html" ) is run below
//				This sets important cookies that are used to populate the Log In Area throughout the site and then redirects
//
function loginInstitution( instType, instr, un, pw ) {
	var debug = false;
	if ( debug ) {
		alert( "In loginInstitution" );
	}

	var thisInstType = "";
	var thisUserName = "";
	var thisPassword = "";

	if ( !instr ) {

		thisInstType = instType;
		thisUserName = $( "#user" + thisInstType ).val();
		thisPassword = $( "#pass" + thisInstType ).val();


	} else {

		thisUserName = un;
		thisPassword = pw;

	}

		// Get username and password from form

	var jsonStr	= addToJSONStr( jsonStr, "username", thisUserName );
		jsonStr	= addToJSONStr( jsonStr, "password", thisPassword );

	if ( debug ) {
		alert( "jsonStr = [" + jsonStr + "]" );
	}

	if ( debug ) {
		if ( $( '#remember' + thisInstType ).attr( 'checked' )) {
			alert( "remember is checked" );
		} else {
			alert( "remember me is not checked" );
		}
	}

		// If 'remember me' is clicked, turn instuser into instcookieuser and set cookie

	if ( $( '#remember' + thisInstType ).attr( 'checked' )) {

		var instcookieuser	= thisUserName;
		var instcookiepass	= thisPassword;

		// Set the cookie username and password, if any.  Note that this simulates the Remember
		// My Password feature

		if ( debug ) {
			alert( "instcookieuser = [" + instcookieuser + "]\n" +
					"instcookiepass = [" + instcookiepass + "]" );
		}

		var expireDate	= new Date();

		var newCookie = "";

		if (( instcookieuser.length > 0 ) || ( instcookiepass.length > 0 )) {
			if ( debug ) {
				alert( "Setting schooluserInfo cookie" );
			}

				// Set the homeuserInfo cookie

			expireDate.setDate( expireDate.getDate() + 365 );
			if ( debug ) {
				alert( "expireDate = [" + expireDate + "]" );
			}

			newCookie	= "schooluserInfo=schoolusername=" + escape( instcookieuser ) +
								"&schoolpwd=" + escape( instcookiepass ) +
								";expires=" + expireDate.toUTCString();

			if ( debug ) {
				alert( "newCookie = [" + newCookie + "]" );
			}

			document.cookie = newCookie;
			if ( debug ) {
				alert( "Done setting cookie" );
			}

		} else {

				// Check for and remove the homeuserInfo cookie by setting it one year
				// in the past

			var startPos = document.cookie.indexOf( "schooluserInfo=" );
			if ( startPos != -1 ) {

				if ( debug ) {
					alert( "removing existing cookie, startPos = [" + startPos + "]" );
				}

				expireDate		= new Date();
				var expireYear	= expireDate.getFullYear();
				expireDate.setFullYear( expireYear - 1 );
				if ( debug ) {
					alert( "expireDate = [" + expireDate + "]" );
				}

				var endPos	= document.cookie.indexOf( ";", startPos );
				if ( endPos == -1 ) {
					endPos	= document.cookie.length;
				}
				if ( debug ) {
					alert( "endPos = [" + endPos + "]" );
				}

				newCookie	= document.cookie.substring( startPos, endPos ) +
									";expires=" + expireDate.toUTCString();

				if ( debug ) {
					alert( "newCookie = [" + newCookie + "]" );
				}

				document.cookie = newCookie;
			}
		}
	}

	callDB( "loginInstitution", jsonStr, function( data ) {

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

		if ( debug ) {
			alert( "In loginInstitution anon function, data = [" + data + "]" );
		}

		// clear the loggedOut cookie, which is set to true when a user clicks 'log out'

			$.cookie( 'loggedOut', null, { path: '/', domain: DOMAIN_NAME } );

		if ( returnObj[ "error" ] == 'Invalid username or password' ) {

				showAlert( "Invalid username or password" );

				$( "#user" + thisInstType ).val( '' ).focus();

				$( "#pass" + thisInstType ).val( '' );

				return false;

		} else if ( returnObj[ "error" ] == 'empty user object' ) {

				showAlert( "Invalid username or password.<br />Please note: passwords <b>are</b> case sensitive." );

				$( "#user" + thisInstType ).val( '' ).focus();

				$( "#pass" + thisInstType ).val( '' );

				return false;

		} else if ( ( returnObj[ "note" ] == 'Invalid Institution login, checking for user login' )
					|| ( returnObj[ "valid" ] == 'Valid user' ) ) {

			// the user is non-inst logging at a school
			// could be a teacher, SA, pre-K, home or sab

			if ( returnObj[ "error" ] == 'Subscription expired' ) {

				if ( returnObj[ "expired" ] == 'User subscription expired' ) {

					if ( debug ) {
						alert( "User sub has expired" );
					}

				    alert( "Sorry, your account has expired - please renew your subscription!" );

				    $.cookie( "userType", "homeExpired", { path: '/', domain: DOMAIN_NAME });

				    	//set username as a cookie, to be used in renewal form

				    var newHomeUserName = escape( thisUserName );

				    $.cookie ( "homeUserName", newHomeUserName, { path: '/', domain: DOMAIN_NAME } );

    			    setInfoCookies( "other/accountrenewal.html" );

				    return false;

				}

			}

			if ( returnObj[ "Elem_Prek" ] == 'P' ) {

				if ( debug ) {
					alert( "This is a preK user" );
				}

			    $.cookie( "userType", "prek", { path: '/', domain: DOMAIN_NAME });

    		    setInfoCookies( "Library/library.html" );

			    return false;

			}

			if ( returnObj[ "SABUser" ] == 'This is a Send A Book User' ) {

				if ( debug ) {
					alert( "This is a SAB user" );
				}

    		    loginUser( 'sab', thisUserName, thisPassword );

			    return false;

			}

			var jsonStr2 = "";

			callDB( "getUser", jsonStr2, function( data ) {

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

				if ( debug) {
					alert( "In getUser anon function, data = [" + data + "]" );
				}

				var newData = data;

				// Look at returnObj to determine if user type and direct to the correct page

				if ( debug ) {
						alert( "returnObj is [" + returnObj + "]" );
					}

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

					if ( debug ) {
						alert ( "result equals something" );
					}

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

						if ( debug ) {
							alert( "getUser results is error" );
						}

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

						if ( debug ) {
							alert ( "result equals success" );
						}

							//check authorization type

						if ( returnObj[ "IsHomeTeacher" ] == 'True' ) {

							if ( debug ) {
								alert( "this user is a teacher at home" );
							}

								// they are a teacher from home

							$.cookie( "userType", "teacherAtHome", { path: '/', domain: DOMAIN_NAME });

							setInfoCookies( "Library/library.html" );

						} else if ( returnObj[ "IsHomeStudent" ] == 'True' ) {

							if ( debug ) {
								alert( "this user is a student from home" );
							}

								// they are a student from home

							$.cookie( "userType", "studentAtHome", { path: '/', domain: DOMAIN_NAME });

							setInfoCookies( "Library/library.html" );

						} else {

							switch ( returnObj[ "Authorized" ] ) {

								case "H":

									if ( debug ) {
										alert ( "this user is a home user" );
									}

									if ( returnObj[ "Expired" ] == 'True' ) {

										if ( debug ) {
											alert( "this home user account is expired" );
										}

										var expiredMsg = confirm( "Sorry, your account has expired!\nPress 'Ok' to fill out an Account Renewal form" );

										if ( expiredMsg == true) {

	    								    //user pressed ok

	    								    $.cookie( "userType", "homeExpired", { path: '/', domain: DOMAIN_NAME });

	    								    setInfoCookies( "parentsplace/accountrenewal.html" );

	    								} else {

	    								    //user pressed cancel

	    								    clearCookies( 'redirectHome' );

	    								    return false;

	    								}

									}

								    	// they must be a standard home user

								    $.cookie( "userType", "home", { path: '/', domain: DOMAIN_NAME });

								    	//set username as a cookie, to be used when parent logs into PP with password only

								    var homeUserName = ( returnObj [ "UserName" ] );

								    var newHomeUserName = escape( homeUserName );

								    $.cookie ( "homeUserName", newHomeUserName, { path: '/', domain: DOMAIN_NAME } );

									setInfoCookies( "Library/library.html" );

									break;

								case "T":

									if ( debug ) {
										alert ( "this user is a teacher" );
									}

									$.cookie( "userType", "teacher", { path: '/', domain: DOMAIN_NAME });

										// redirect

									setInfoCookies( "Library/library.html" );

									break;

								case "SA":

									if ( debug ) {
										alert ( "this user is a school admin" );
									}

									$.cookie( "userType", "schooladmin", { path: '/', domain: DOMAIN_NAME });

										// redirect

									setInfoCookies( "Library/library.html" );

									break;

								case "A":

									if ( debug ) {
										alert ( "this user is a site admin" );
									}

									$.cookie( "userType", "home", { path: '/', domain: DOMAIN_NAME });

									setInfoCookies( "Library/library.html" );

									break;

								case "SAB":

									if ( debug ) {
										alert ( "this user is a send a book user" );
									}

									$.cookie( "userType", "sab", { path: '/', domain: DOMAIN_NAME });

									setInfoCookies( "library/sablibrary.html" );

									break;

								default:

									if ( debug ) {
										alert( "Error - there is a user object but the authorized was not H, T, SA, A or SAB" );
									}

									break;

							}

						}

					}

				}

			});

			return false;

		} else if ( returnObj[ "expired" ] == 'Institution expired' ) {

			if ( debug ) {
			    alert( "Institution has expired" );
			}

			if ( returnObj[ "InstUser" ] == "This is a home student" ) {

				alert( "Sorry, your school's subscription has expired." );

				clearCookies( 'redirectHome' );

				return false;

			}

			if ( returnObj[ "Institution Type" ] == 'SCH' ) {

				alert( "Sorry, your institution's subscription has expired - please renew today!" );

			    $.cookie( "IPrecog", "schoolIP", { path: '/', domain: DOMAIN_NAME });

			    $.cookie( "userType", "schoolExpired", { path: '/', domain: DOMAIN_NAME });

			    setInfoCookies( "other/schoolrenewal.html" );

			    return false;

			} else if ( returnObj[ "Institution Type" ] == 'LIB' ) {

				alert( "Sorry, your institution subscription has expired - please renew today!" );

			    $.cookie( "IPrecog", "libraryIP", { path: '/', domain: DOMAIN_NAME });

			    $.cookie( "userType", "libraryExpired", { path: '/', domain: DOMAIN_NAME });

			    setInfoCookies( "other/libraryrenewal.html" );

			    return false;

			} else if ( returnObj[ "Institution Type" ] == 'HOP' ) {

			    // nothing happens if a hospital is expired!

			}

		} else if ( returnObj[ "notactive" ] == 'Institution not active yet' ) {

			if ( debug ) {
			    alert( "Institution is not yet active" );
			}

			alert( "Sorry, your institution's account has not yet been activated - please contact us if you have any questions." );

			document.location = "/help/contactus.html";

			return false;

		} else if ( returnObj[ "notactive" ] == 'Institution deactivated' ) {

			if ( debug ) {
			    alert( "Institution is deactivated" );
			}

			alert( "Sorry, your institution's account has been deactivated - please contact us today!" );

			document.location = "/help/contactus.html";

			return false;

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

			if ( debug ) {
				alert( "result is error" );
			}

			logErrorMessage( returnObj[ 'error' ], '' );

			alert( "Sorry, there was an error logging in.\nIf this problem persists, please contact us." );

			clearCookies( 'redirectHome' );

			return false;

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

			if ( debug ) {
				alert( "loginInstitution was a success" );
			}

			switch ( returnObj [ "Institution Type" ] ) {

				case "SCH":

					if ( debug ) {
						alert( "inst is a school - now checking if its a pre-k school or not" );
					}

					if ( returnObj[ "Elem_Prek" ] == 'P' ) {

						$.cookie( "userType", "prek", { path: '/', domain: DOMAIN_NAME });

					} else {

						$.cookie( "userType", "school", { path: '/', domain: DOMAIN_NAME });

					}

					if ( debug ) {
						alert( "done setting school cookies" );
					}

					setInfoCookies( "Library/library.html" );

					break;

				case "LIB":

					$.cookie( "userType", "library", { path: '/', domain: DOMAIN_NAME });

					setInfoCookies( "Library/library.html" );

					break;

				case "HOP":

					$.cookie( "userType", "hospital", { path: '/', domain: DOMAIN_NAME });

					setInfoCookies( "Library/library.html" );

					break;

				default:

					//

					break;

			}

		}

		//

	});

	if ( debug ) {
		alert( "Done loginInstitution" );
	}
}


//
// loginPPTPUser -- calls the DB with the loginPPTPUser command
//
function loginPPTPUser( pptp_type ) {
	var debug	= false;
	if ( debug ) {
		alert( "In loginPPTPUser" );
	}

	var pptpType = pptp_type;
	var pptpUser = "";
	var pptpPass = "";

	if ( pptpType == "pp" ) {

		if ( debug ) {
			alert( "logging in PP user" );
		}

		var parentsUserName = $.cookie( "homeUserName" );

		var newParentsUserName = unescape( parentsUserName );

		if ( debug ) {
			alert( "unescaped parentsUserName is [" + newParentsUserName + "]" );
		}

		pptpUser = newParentsUserName;
		pptpPass = $( "#pppassword" ).val();

	} else if ( pptpType == "tp" )  {

		if ( debug ) {
			alert( "logging in TP user" );
		}

		pptpUser = $( "#tpusername" ).val();
		pptpPass = $( "#tppassword" ).val();

	} else {

		if ( debug ) {
			alert( "not a TP or PP log in, something is wrong" );
		}
	}

		// Get the username and password from form

	var jsonStr	= addToJSONStr( jsonStr, "username", pptpUser );
		jsonStr	= addToJSONStr( jsonStr, "password", pptpPass );

	if ( debug ) {
		alert( "jsonStr = [" + jsonStr + "]" );
	}

	callDB( "loginPPTPUser", jsonStr, function( data ) {

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

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

			if ( debug ) {
				alert( "results is a success" );
			}

			switch ( returnObj [ "UserTypeCode" ] ) {

				case "SA":

					if ( debug ) {
						alert( "User is a school admin, redirecting now" );
					}

					$.cookie( "userType", "schooladmin", { path: '/', domain: DOMAIN_NAME });

					setInfoCookies( "teachersplace/adminsplace.html" );

					break;

				case "T":

					if ( debug ) {
						alert( "User is a teacher, redirecting now" );
					}

					$.cookie( "userType", "teacher", { path: '/', domain: DOMAIN_NAME });

					setInfoCookies( "teachersplace/teachersplace.html" );

					break;

				case "A":

					if ( debug ) {
						alert( "User is an OMS admin, redirecting now" );
					}

					$.cookie( "userType", "parent", { path: '/', domain: DOMAIN_NAME });

					setInfoCookies( "parentsplace/parentsplace.html" );

					break;

				case "H":

					if ( debug ) {
						alert( "the UserTypeCode is H, now doing further testing" );
					}

						// the following code will parse out who is a home comp, institution comp or reg home user
						// but right now, this code does nothing - just alerts on debug and they all go to the same place

					jsonStr = "";

					callDB( "getUser", jsonStr, function( data) {

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

						var instIDVar = ( returnObj[ "InstID" ] );

						if ( returnObj[ "FreeBookID" ] == "999" ) {

							if ( debug ) {
								alert( "FreeBookID equals 999, user is comp, now testing for InstID" );
							}

							if ( instIDVar == "-1" ) {

								if ( debug ) {
									alert( "instIDVar equals -1, this user is a home comp" );
								}

							} else if ( instIDVar == "" ) {

								if ( debug ) {
									alert( "instIDVar equals nothing, this user is a home comp" );
								}

							} else if ( instIDVar > 0 ) {

								if ( debug ) {
									alert( "instIDVar is greater than zero, this user is an inst comp" );
								}

							} else {

								if ( debug ) {
									alert( "none of the above is true, thats weird" );
								}

							}


						} else {

							if ( debug ) {
								alert( "FreeBookID does not equal 999, so this user is a home user" );
							}

						}

						$.cookie( "userType", "parent", { path: '/', domain: DOMAIN_NAME });

						setInfoCookies( "parentsplace/parentsplace.html" );

					});


					break;

				case "P":

					if ( debug ) {
						alert( "the UserTypeCode is H, now doing further testing" );
					}

						// the following code will parse out who is a home comp, institution comp or reg home user
						// but right now, this code does nothing - just alerts on debug and they all go to the same place

					jsonStr = "";

					callDB( "getUser", jsonStr, function( data) {

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

						var instIDVar = ( returnObj[ "InstID" ] );

						if ( returnObj[ "FreeBookID" ] == "999" ) {

							if ( debug ) {
								alert( "FreeBookID equals 999, user is comp, now testing for InstID" );
							}

							if ( instIDVar == "-1" ) {

								if ( debug ) {
									alert( "instIDVar equals -1, this user is a home comp" );
								}

							} else if ( instIDVar == "" ) {

								if ( debug ) {
									alert( "instIDVar equals nothing, this user is a home comp" );
								}

							} else if ( instIDVar > 0 ) {

								if ( debug ) {
									alert( "instIDVar is greater than zero, this user is an inst comp" );
								}

							} else {

								if ( debug ) {
									alert( "none of the above is true, thats weird" );
								}

							}


						} else {

							if ( debug ) {
								alert( "FreeBookID does not equal 999, so this user is a home user" );
							}

						}

						$.cookie( "userType", "parent", { path: '/', domain: DOMAIN_NAME });

						setInfoCookies( "parentsplace/parentsplace.html" );

					});

					// case H action

					break;



				default:
			}

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

			alert( "Your username or password is incorrect, please try again." );

		}

	});

	if ( debug ) {
		alert( "Done loginPPTPUser" );
	}
}


//
// loginUser -- calls db with loginUser, set cookies and redirects accordingly
// param type will be 'auto' if the login is an automatical 'Enter library' from the subscription confirmation
// page, or 'sab' if the sab user was logging in at an IP-recognized location (in which case the username and
// password will be passed as parameters
//
function loginUser( type, username, password ) {
	var debug	= false;
	if ( debug ) {
		alert( "In loginUser:\n" +
				"type = [" + type + "]\n" +
				"username = [" + username + "]\n" +
				"password = [" + password + "]\n" +
				"\n\n\nNote: this routine is wrapped in a try catch, beginning after this alert" );
	}

	try {

		if ( debug ) {
			alert( "now entering the try" );
		}

			// Get the username and password from form

		var jsonStr = "";
		var thisUsername = "";
		var thisPassword = "";

		if ( type == 'auto' ) {

			if ( page == 'homeuse' ) {

				thisUsername = $( "#ps_UserName" ).val();
				thisPassword = $( "#sp_password" ).val();

			}

		} else if ( type == 'sab' ) {

			thisUsername = username;
			thisPassword = password;

		} else {

			thisUsername = $( "#username" ).val();
			thisPassword = $( "#passHome" ).val();

		}

		if ( ( thisUsername == "Username" ) && ( thisPassword == "" ) ) {

			showAlert( "Please enter your username and password." );

			return false;

		}

		var jsonStr	= addToJSONStr( jsonStr, "username", thisUsername );
			jsonStr	= addToJSONStr( jsonStr, "password", thisPassword );

		if ( debug ) {
			alert( "jsonStr = [" + jsonStr + "]" );
		}

			// If Remember my password is checked, save the username and password as a cookie.
			// Turn instuser into instcookieuser, etc. ??

		if ( $( '.remember' ).attr( 'checked' )) {

			if ( debug ) {
				alert( "remember me is checked" );
			}

			var cookieuser	= $( "#username" ).val();
			var cookiepass	= $( "#passHome" ).val();

			if ( debug ) {
				alert( "cookieuser = [" + cookieuser + "]\n" +
						"cookiepass = [" + cookiepass + "]" );
			}

			var expireDate	= new Date();
			var newCookie = "";

			if (( cookieuser.length > 0 ) || ( cookiepass.length > 0 )) {
				if ( debug ) {
					alert( "Setting homeuserInfo cookie" );
				}

					// Set the homeuserInfo cookie

					// Set expire date one year from today (i.e. 'from last login' )

				expireDate.setDate( expireDate.getDate() + 365 );

				if ( debug ) {
					alert( "expireDate = [" + expireDate + "]" );
				}

				newCookie	= "homeuserInfo=homeusername=" + escape( cookieuser ) +
									"&pwd=" + escape( cookiepass ) +
									";expires=" + expireDate.toUTCString();

				if ( debug ) {
					alert( "newCookie = [" + newCookie + "]" );
				}

				document.cookie = newCookie;

				if ( debug ) {
					alert( "Done setting cookie" );
				}

			} else {

					// Check for and remove the homeuserInfo cookie by setting it one year
					// in the past

				var startPos = document.cookie.indexOf( "homeuserInfo=" );
				if ( startPos != -1 ) {

					if ( debug ) {
						alert( "removing existing cookie, startPos = [" + startPos + "]" );
					}

					expireDate		= new Date();
					var expireYear	= expireDate.getFullYear();
					expireDate.setFullYear( expireYear - 1 );
					if ( debug ) {
						alert( "expireDate = [" + expireDate + "]" );
					}

					var endPos	= document.cookie.indexOf( ";", startPos );
					if ( endPos == -1 ) {
						endPos	= document.cookie.length;
					}
					if ( debug ) {
						alert( "endPos = [" + endPos + "]" );
					}

					newCookie	= document.cookie.substring( startPos, endPos ) +
										";expires=" + expireDate.toUTCString();

					if ( debug ) {
						alert( "newCookie = [" + newCookie + "]" );
					}

					document.cookie = newCookie;
				}

			}
		}

			// begin actual database log in sequence

		callDB( "loginUser", jsonStr, function( data ) {

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

			if ( debug ) {
				alert( "In loginUser anon function, data = [" + data + "]" );
			}

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

				if ( debug ) {
					alert( "results is success" );
				}

					// clear the loggedOut cookie, which is set to true when a user clicks 'log out'

				$.cookie( 'loggedOut', null, { path: '/', domain: DOMAIN_NAME } );

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

				if ( debug ) {
					alert( "result is error" );
				}

				if ( returnObj[ "error" ] == "Subscription expired" ) {

					if ( debug ) {
						alert( "this user is expired" );
					}

					alert( "Sorry, your account has expired - please renew your subscription!" );

					$.cookie( "userType", "homeExpired", { path: '/', domain: DOMAIN_NAME });

						//set username as a cookie, to be used in renewal form

					var newHomeUserName = escape( thisUsername );

					$.cookie ( "homeUserName", newHomeUserName, { path: '/', domain: DOMAIN_NAME } );

    				setInfoCookies( "other/accountrenewal.html" );

    				return false;

				} else if ( returnObj[ "expired" ] == "Institution expired" ) {

					if ( debug ) {
						alert( "this user's institution is expired" );
					}

					if ( returnObj[ "InstUser" ] == "This is a home student" ) {

						showAlert( "Sorry, your school's subscription has expired." );

						return false;

					}

					alert( "Sorry, your institution's account has expired - please renew your subscription!" );

					$.cookie( "userType", "schoolExpired", { path: '/', domain: DOMAIN_NAME });

    				setInfoCookies( "other/schoolrenewal.html" );

    				return false;

				} else {

					var thisErrorMessage = returnObj[ 'error' ];

					if ( thisErrorMessage == 'empty user object' ){

						thisErrorMessage = 'Invalid username or password.<br />Please note: passwords are case-sensitive.';

					}

						// this logs the error, has been turned off due to too many logs (slowing down site)

					//logErrorMessage( thisErrorMessage, '' );

					showAlert( "Sorry, there was an error logging in:<br /><br />" + thisErrorMessage +
					"<br /><br />If this problem persists, please contact us." );

					return false;

				}

			} else {

				if ( debug ) {
					alert( "results is not success or error, returnObj is undefined" );
				}

			}

			if ( returnObj[ "SABUser" ] == "This is a Send A Book User" ) {

				var jsonStr2 = "";

				callDB( "getSABUser", jsonStr2, function( data ) {

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

					if ( debug ) {
						alert( "data is [" + data + "]" );
					}

					if ( returnObj[ "results" ] == 'success' ) {

						if ( debug ) {
						    alert ( "this user is a send a book user" );
						}

						$.cookie( "userType", "sab", { path: '/', domain: DOMAIN_NAME });

						setInfoCookies( "sab/sabdone.html?userid=" + $.cookie( "userid" ));

						return false;

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

						showAlert( "Sorry, there was an error with your login. <br />" +
								"Please try again and contact us if this problem persists." );

						return false;

					}

				});

				// if SABUSER == This is..., no need to continue to getUser.

				return false;

			}

			if ( returnObj[ "Elem_Prek" ] == "P" ) {

				if ( debug ) {
					alert( "this is a Prek teacher" );
				}

				$.cookie( "userType", "prek", { path: '/', domain: DOMAIN_NAME });

				setInfoCookies( "Library/library.html" );

				return false;

			}

				// now call getUser to get user info, set cookies and redirect

			var jsonStr2 = "";

			if ( debug ) {
				alert( "jsonStr2 = [" + jsonStr2 + "]" );
				}

			callDB( "getUser", jsonStr2, function( data ) {

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

				if ( debug) {
					alert( "In getUser anon function, data = [" + data + "]" );
				}

				var newData = data;

				// Look at returnObj to determine if user type and direct to the correct page

				if ( debug ) {
						alert( "returnObj is [" + returnObj + "]" );
					}

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

					if ( debug ) {
						alert ( "result equals something" );
					}

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

						if ( debug ) {
							alert( "results is error" );
						}

						showAlert( "Sorry, there was an error with your login. <br />" +
								"Please try again, if this problem persists - please contact us." );

						return false;

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

						if ( debug ) {
							alert ( "result equals success" );
						}

							//check authorization type

						if ( returnObj[ "IsHomeTeacher" ] == 'True' ) {

							if ( debug ) {
								alert( "this user is a teacher at home" );
							}

								// they are a teacher from home

							$.cookie( "userType", "teacherAtHome", { path: '/', domain: DOMAIN_NAME });

							setInfoCookies( "Library/library.html" );

						} else if ( returnObj[ "IsHomeStudent" ] == 'True' ) {

							if ( debug ) {
								alert( "this user is a student from home" );
							}

								// they are a student from home

							$.cookie( "userType", "studentAtHome", { path: '/', domain: DOMAIN_NAME });

							setInfoCookies( "Library/library.html" );

						} else {

							switch ( returnObj[ "Authorized" ] ) {

								case "H":

									if ( debug ) {
										alert ( "this user is a home user" );
									}

										// they must be a standard home user

								    $.cookie( "userType", "home", { path: '/', domain: DOMAIN_NAME });

								    	//set username as a cookie, to be used when parent logs into PP with password only

								    var homeUserName = ( returnObj [ "UserName" ] );

								    var newHomeUserName = escape( homeUserName );

								    $.cookie ( "homeUserName", newHomeUserName, { path: '/', domain: DOMAIN_NAME } );

									setInfoCookies( "Library/library.html" );

									break;

								case "T":

									if ( debug ) {
										alert ( "this user is a teacher" );
									}

									$.cookie( "userType", "teacher", { path: '/', domain: DOMAIN_NAME });

									setInfoCookies( "Library/library.html" );

									break;

								case "SA":

									if ( debug ) {
										alert ( "this user is a school admin" );
										}

									$.cookie( "userType", "schooladmin", { path: '/', domain: DOMAIN_NAME });

									setInfoCookies( "Library/library.html" );

									break;

								case "A":

									if ( debug ) {
										alert ( "this user is a site admin" );
									}

									$.cookie( "userType", "home", { path: '/', domain: DOMAIN_NAME });

									setInfoCookies( "Library/library.html" );

									break;

								case "SAB":

									if ( debug ) {
										alert ( "this user is a send a book user" );
									}

									$.cookie( "userType", "sab", { path: '/', domain: DOMAIN_NAME });

									setInfoCookies( "library/sablibrary.html" );

									break;

								default:

									showAlert( "Sorry, your username or password cannot be found." );

									break;

							}

						}

					}

				}

			});

		});

		if ( debug ) {
			alert( "now at the end of the try" );
		}

	} catch (err) {

		if ( debug ) {
			alert( "now in the catch, uh oh! logging message" );
		}

		alert( "Oops, there seems to be a problem with our site - this is quite embarrassing, we are sorry for the inconvenience. Please contact us and we will address this issue immediately. \n\n\n[CODE_001]" );

		logErrorMessage( 'Error Caught in loginUser : CODE_001 : err.description = [' + err.description + ']', '' );

	}

	if ( debug ) {
		alert( "Done loginUser" );
	}
}


//
// logOut -- 'log out' from One More Story completely
//
function logOut( options, problem ) {

	var debug = false;

	if ( debug ) {
		alert( "now in logOut" );
	}

		// set loggedOut to true so the auto-log-in process does not create a loop on the home page

    $.cookie( 'loggedOut', 'true', { path: '/', domain: DOMAIN_NAME } );

		// set this cookie telling a routine on the home page to close the player when the user gets there

    $.cookie( 'closePlayerNow', true, { path: '/', domain: DOMAIN_NAME } );

		// if param problem == yes, this means the log out is triggered by a problem somewhere

	if ( problem == 'true' ){

		alert( "Oops, it appears your session has expired. Please log in again.\n\n" +
				"If this issue occurs repeatedly, please contact us." );

		if ( mainHandle ) {

			mainHandle.clearCookies( 'redirectHome' );

		} else {

			window.opener.clearCookies( 'redirectHome' );

		}

	} else {

		if ( options == 'hospital' ) {

			document.location = prefix + "index.html";

			return false;

		}

			//confirm they want to log out completely

		var areYouSure = confirm( "This will log you out of One More Story completely.\n\nDo you want to continue?" );

		if ( areYouSure == true) {

	    	// user pressed ok, lets continue
	    	// do nothing

	    	if ( debug ) {
	    		alert( "user pressed OK, continue with logout routine" );
	    	}

	    } else {

	    	// user pressed cancel

	    	if ( debug ) {
	    		alert( "user pressed cancel, now returning false." );
	    	}

	    	return false;

	    }

	    clearCookies( 'redirectHome' );

	}

	if ( debug ) {
		alert( "done in logOut" );
	}
}


//
// logOutPP -- Log out ( 'Close' ) from the Parents place
//
function logOutPP() {

		//switch userType to home, because the user is closing PP and still should be in logged into OMS

	$.cookie( "userType", "home", { path: '/', domain: DOMAIN_NAME });

	document.location = prefix + "Library/library.html"

}


//
// logOutTP -- Log out ( 'Close' ) from the Teachers place
// 		this is slightly more complicated than other log outs because a teacher may be logged from home or school
// 		check the IPrecog cookie to make sure
// 		if logged in from school, then log out redirects to library
// 		if logged in from home, then log out redirects to home page
//
function logOutTP() {

	var debug = false;

	var IPrecogStatus = $.cookie( "IPrecog" );

		//check to see if the IPrecog is set to school

	if ( IPrecogStatus == "school" ) {

		if ( debug ) {
			alert( "this teacher is at school, logging out teacher/admin but not school, redirecting to library" );
		}
			//set userType to school,

		$.cookie( "userType", "school", { path: '/', domain: DOMAIN_NAME });

		$.cookie( "fullname", null, { path: '/', domain: DOMAIN_NAME });

			//if it is, redirect to library

		document.location = prefix + "Library/library.html"

		//if the IPrecog != school, then the teacher must be logged in at home

	} else {

		if ( debug ) {
			alert( "IPrecog is not set, teacher is at home: setting cookie and redirecting to library" );
		}

			//set userType to 'teacherAtHome'

		$.cookie( "userType", "teacherAtHome", { path: '/', domain: DOMAIN_NAME });

			//redirect to home page

		document.location = prefix + "Library/library.html"

	}

}


//
// logOutSAB -- Log out from ReadABook
//
function logOutSAB() {

	 	// set loggedOut to true so the auto-log-in process does not create a loop on the home page

    $.cookie( 'loggedOut', 'true', { path: '/', domain: DOMAIN_NAME } );

		// confirm they want to log out completely

	var areYouSure = confirm( "This will log you out of One More Story completely.\n\nDo you want to continue?" );

	if ( areYouSure == true) {

    	// user pressed ok, lets continue
    	// do nothing

    } else {

    	// user pressed cancel

    	return false;

    }

	clearCookies( 'redirectSABLogOut' );

}


//
// navBarDispatcher --  checks the current constant page and sets the visual cues in the navigation bar
//
function navBarDispatcher() {
	var debug = false;

	if ( debug) {
		alert( "navBarDispatcher is running" );
		alert( "page is [" + page + "]" );
		alert( "category is [" + category + "]" );
	}

	$( '#' + category + 'UL' ).css( 'display','block' );

	$( '#' + category + 'UL' ).addClass( 'expand' );

	$( '#' + category + 'A' ).addClass( 'active' );

	$( '#' + page ).addClass( 'selected' );

	if ( debug ) {
		alert( "done navbarDispatch" );
	}
}


//
// navBarReady -- runs to set up navigation bar on all pages
//
function navBarReady() {

	$( '.menu' ).initMenu();
	navBarDispatcher();

}


//
// Navigation Bar Accordian
//
jQuery.fn.initMenu = function() {
    return this.each( function() {
        var theMenu = $(this).get(0);
        $( '.acitem', this).hide();
        $( 'li.expand > .acitem', this).show();
        $( 'li.expand > .acitem', this).prev().addClass( 'active' );
		$( 'li a', this).click(
            function(e) {
                e.stopImmediatePropagation();
                var theElement = $(this).next();
                var parent = this.parentNode.parentNode;
                if ($(parent).hasClass( 'noaccordion' )) {
                    if (theElement[0] === undefined) {
                        window.location.href = this.href;
                    }
                    $(theElement).slideToggle( 'normal', function() {
                        if ($(this).is( ':visible' )) {
                            $(this).prev().addClass( 'active' );
                        }
                        else {
                            $(this).prev().removeClass( 'active' );
                        }
                    });
                    return false;
                }
                else {
                    if ((theElement.hasClass( 'acitem' )) && (theElement.is( ':visible' ))) {
                        if ($(parent).hasClass( 'collapsible' )) {
                            $( '.acitem:visible', parent).first().slideUp( 'normal',
                            function() {
                                $(this).prev().removeClass( 'active' );
                            }
                        );
                        return false;
                    }
                    return false;
                }
                if ((theElement.hasClass( 'acitem' )) && (!theElement.is( ':visible' ))) {
                    $( '.acitem:visible', parent).first().slideUp( 'normal', function() {
                        $(this).prev().removeClass( 'active' );
                    });
                    theElement.slideDown( 'normal', function() {
                        $(this).prev().addClass( 'active' );
                    });
                    return false;
                }
            }
        }
    );
});
};


//
// pageMovedDispatch -- looks for referring page and redirects to the closest page match
//
function pageMovedDispatch() {

	var debug = false;

	if ( debug ) {
		alert( "now in pageMovedDispatch" );
	}

	var ref = document.referrer;
	var doc = document.URL;
	var pageTitle = "";
	var redirectURL = "";

	if (( ref.indexOf( "/tour/samplebook.html" ) != -1 )
		|| ( ref.indexOf( "tour/ontour_books.html" ) != -1 )
		|| ( ref.indexOf( "promo/TheSnowyDatLite.html" ) != -1 )
		|| ( ref.indexOf( "tour/ontour.html" ) != -1 )) {

		// about our books

		pageTitle = "Site Tour";
		redirectURL = "ourlibrary/aboutourbooks.html";

	} else if (( doc.indexOf( "index_login.aspx" ) != -1 )
		|| ( doc.indexOf( "index.aspx" ) != -1 )
		|| ( doc.indexOf( "sch_login.aspx" ) != -1 )
		|| ( doc.indexOf( "index_login.aspx" ) != -1 )) {

		// home page

		pageTitle = "Log In Page";
		redirectURL = "index.html";

	} else if ( ref.indexOf( "com/faq" ) != -1 ) {

		// faq

		pageTitle = "FAQ";
		redirectURL = "help/faq.html";

	} else if ( ref.indexOf( "terms.html" ) != -1 ) {

		// faq

		pageTitle = "Terms of Agreement";
		redirectURL = "other/terms.html";

	} else if ( ref.indexOf( "privacy.html" ) != -1 ) {

		// faq

		pageTitle = "Privacy Policy";
		redirectURL = "other/privacy.html";

	} else if ( ref.indexOf( "Library/bookplayer.html" ) != -1 ) {

		// about our books

		pageTitle = "Library";
		redirectURL = "ourlibrary/aboutourbooks.html";

	} else if (( ref.indexOf( "kore_signup_home" ) != -1 )
				|| ( doc.indexOf( "signup_home.aspx" ) != -1 )) {

		// home subscribe

		pageTitle = "Home Sign Up Information";
		redirectURL = "subscribe/homesubscription.html";

	} else if (( doc.indexOf( "signup.aspx" ) != -1 )) {

		// home subscribe

		pageTitle = "Sign Up Information";
		redirectURL = "subscribe/howtosubscribe.html";

	} else if (( doc.indexOf( "signup_gift.aspx" ) != -1 )) {

		// gift subscribe

		pageTitle = "Gift Sign Up Information";
		redirectURL = "subscribe/giftsubscription.html";

	} else if (( doc.indexOf( "SendABook.aspx" ) != -1 )) {

		// gift subscribe

		pageTitle = "Send A Free Book Page";
		redirectURL = "share/sendafreebook.html";

	} else if ( doc.indexOf( "ontour_school.aspx" ) != -1 ) {

		// tour school page

		pageTitle = "School Subscription Information Page";
		redirectURL = "subscribe/schoolsubscription.html";

	} else if ( doc.indexOf( "ontour_hospital.aspx" ) != -1 ) {

		// tour hospital page

		pageTitle = "Hospital Subscription Information Page";
		redirectURL = "subscribe/hospitalsreadfree.html";

	} else if ( ref.indexOf( "/tour/" ) != -1 ) {

		// any other 'tour' page

		pageTitle = "Site Tour";
		redirectURL = "ourlibrary/aboutourbooks.html";

	} else if ( ref.indexOf( "kindergartenreadiness" ) != -1 ) {

		// a learning resources page for kintergarden readiness

		pageTitle = "Kindergarten Readiness";
		redirectURL = "learningresources/kindergarten_readiness.html";

	} else {

		// referring site not recognized, oh well

		return false;

	}

	var clickHereLink = "<a href=\"" + prefix + redirectURL + "\"> click here </a>";

	$('#redirectNone').hide();
	$('#redirectOK').show();
	$('#clickHereSpan').html( clickHereLink );
	$('#pageTitle').text( pageTitle );

	setTimeout( function() { redirect( redirectURL ) }, 5000 );

	if ( debug ) {
		alert( "done in pageMovedDispatch" );
	}

}


//
// populate - populates fields using returnObj from previously run functions, like getUser, etc.
//		Parameter is the type of information to be populated (i.e. studentInfo, userInfo, instInfo, instSub, etc)
//      Important: 	No field or <span> should appear twice below: this is because populate may run more than once in a row,
//	  			  	which will cause some values to populate as 'undefined', if both functions are populating the same fields with different info
//					(or the second populate may clear info filled in the first time)
//
function populate( infoType ) {
	var debug = false;

	if ( debug ) {
		alert( "In populate" );
	}

	var curType = infoType;

	switch( curType ) {

			// Populate a user's information into the fields
			// 		i.e. Prepolate a renew subscribe form in the parents place
		case "userInfo" :

			if ( debug ) {
				alert( "populating userInfo data" );
				alert( "test, first name is [" + returnObj[ 'FirstName' ] + "]" );
			}

			$( "#FirstName" ).html( returnObj[ "FirstName" ]);
			$( "#FirstName" ).val( returnObj[ "FirstName" ] );

			$( "#LastName" ).html( returnObj[ "LastName" ]);
			$( "#LastName" ).val( returnObj[ "LastName" ]);

			$( "#UserName" ).html( returnObj[ "UserName" ]);
			$( "#UserName" ).val( returnObj[ "UserName" ]);

			if (( returnObj[ "ExpirationDate" ] != null ) && ( returnObj[ "ExpirationDate" ] != undefined )) {

				var thisExpDate = returnObj[ "ExpirationDate" ];

				var spaceLoc = thisExpDate.indexOf( ' ' );

				thisExpDate = thisExpDate.slice( 0, spaceLoc );

				$( "#ExpirationDate" ).html( thisExpDate );
				$( "#ExpirationDate" ).val( thisExpDate );

			}

			$( "#UserID" ).html( returnObj[ "UserID" ] );
			$( "#UserID" ).val( returnObj[ "UserID" ] );

			$( "#NameID" ).html( returnObj[ "NameID" ] );
			$( "#NameID" ).val( returnObj[ "NameID" ] );

			$( "#Address1" ).html( returnObj[ "Address1" ] );
			$( "#Address1" ).val( returnObj[ "Address1" ] );

			$( "#Address2" ).html( returnObj[ "Address2" ] );
			$( "#Address2" ).val( returnObj[ "Address2" ] );

			$( "#City" ).html( returnObj[ "City" ] );
			$( "#City" ).val( returnObj[ "City" ] );

			$( "#NYCounty" ).html( returnObj[ "NYCounty" ] );

			$( "#county1" ).val( returnObj[ "NYCounty" ] );
			$( "#county2" ).val( returnObj[ "NYCounty" ] );

				//setting the value of a dropdown select input is different

			var selNYCounty =  ( returnObj[ "NYCounty" ] );
			$( "select[name='NYCounty'] option[value='selNYCounty']" ).attr( "selected", true);
			$( "select[name='NYCounty_ppupdate'] option[value='selNYCounty']" ).attr( "selected", true);

			$( "#State" ).html( returnObj[ "State" ] );
			$( "#state1" ).val( returnObj[ "State" ] );
			$( "#state2" ).val( returnObj[ "State" ] );

			showCounty( '1' );

			var zip = "";

			if (( returnObj[ 'Zip2' ] != null ) && ( returnObj[ 'Zip2' ] != undefined )) {

				zip = (( returnObj[ 'Zip' ] ) + ( returnObj[ 'Zip2' ] ));

			} else {

				zip = ( returnObj[ 'Zip' ] );

			}

			$( "#zipcode" ).html( zip );
			$( "#zipcode" ).val( zip );

			$( "#EMail" ).html( returnObj[ "EMail" ] );
			$( "#EMail" ).val( returnObj[ "EMail" ] );

			$( "#Phone" ).html( returnObj[ "Phone" ] );
			$( "#Phone" ).val( returnObj[ "Phone" ] );

			if ( debug ) {
				alert( "done populating userInfo data" );
			}

			break;

		case "teacherInfo" :

			if ( debug ) {
				alert( "populating teacherInfo data" );
			}

			$( "#FirstName" ).html( returnObj[ "FirstName" ]);
			$( "#FirstName" ).val( returnObj[ "FirstName" ] );

			$( "#LastName" ).html( returnObj[ "LastName" ]);
			$( "#LastName" ).val( returnObj[ "LastName" ]);

			$( "#UserName" ).html( returnObj[ "UserName" ]);
			$( "#UserName" ).val( returnObj[ "UserName" ]);

			$( "#UserID" ).html( returnObj[ "UserID" ] );
			$( "#UserID" ).val( returnObj[ "UserID" ] );

			$( "#EMail" ).html( returnObj[ "EMail" ] );
			$( "#EMail" ).val( returnObj[ "EMail" ] );

			$( "#Phone" ).html( returnObj[ "Phone" ] );
			$( "#Phone" ).val( returnObj[ "Phone" ] );

			var optOut = returnObj[ "OptOut" ] ;

			if ( optOut == 'False' ){

				$('#optOut').attr('checked','checked');

			}

			if ( debug ) {
				alert( "done populating teacherInfo data" );
			}

			break;

		case "ppUpdateAcct" :

			if ( debug ) {
				alert( "populating ppUpdateAcct data" );
				alert( "test, first name is [" + returnObj[ 'FirstName' ] + "]" );
			}

			$( "#FirstName_ppupdate" ).val( returnObj[ "FirstName" ] );

			$( "#LastName_ppupdate" ).val( returnObj[ "LastName" ]);

			$( "#UserName_ppupdate" ).val( returnObj[ "UserName" ]);

			if (( returnObj[ "ExpirationDate" ] != null ) && ( returnObj[ "ExpirationDate" ] != undefined )) {

				var thisExpDate = returnObj[ "ExpirationDate" ];

				var spaceLoc = thisExpDate.indexOf( ' ' );

				thisExpDate = thisExpDate.slice( 0, spaceLoc );

				$( "#ExpirationDate_ppupdate" ).val( thisExpDate );

			}

			$( "#UserID_ppupdate" ).val( returnObj[ "UserID" ] );

			$( "#NameID_ppupdate" ).val( returnObj[ "NameID" ] );

			$( "#Address1_ppupdate" ).val( returnObj[ "Address1" ] );

			$( "#Address2_ppupdate" ).val( returnObj[ "Address2" ] );

			$( "#City_ppupdate" ).val( returnObj[ "City" ] );

			$( "#County1_ppupdate" ).val( returnObj[ "NYCounty" ] );

				//setting the value of a dropdown select input is different

			var selNYCounty =  ( returnObj[ "NYCounty" ] );
			$( "select[name='NYCounty_ppupdate'] option[value='selNYCounty']" ).attr( "selected", true);

			$( "#State_ppupdate" ).val( returnObj[ "State" ] );

			var zip = "";

			if (( returnObj[ 'Zip2' ] != null ) && ( returnObj[ 'Zip2' ] != undefined )) {

				zip = (( returnObj[ 'Zip' ] ) + ( returnObj[ 'Zip2' ] ));

			} else {

				zip = ( returnObj[ 'Zip' ] );

			}

			$( "#Zipcode_ppupdate" ).val( zip );

			$( "#EMail_ppupdate" ).val( returnObj[ "EMail" ] );

			$( "#Phone_ppupdate" ).val( returnObj[ "Phone" ] );

			if ( debug ) {
				alert( "done populating ppUpdateAcct data" );
			}

			break;

		case "ppRenewAcct" :

			if ( debug ) {
				alert( "populating ppRenewAcct data" );
				alert( "test, first name is [" + returnObj[ 'FirstName' ] + "]" );
			}

			$( "#FirstName_pprenew" ).val( returnObj[ "FirstName" ] );
			$( "#LastName_pprenew" ).val( returnObj[ "LastName" ]);
			$( "#UserName_pprenew" ).val( returnObj[ "UserName" ]);
			if (( returnObj[ "ExpirationDate" ] != null ) && ( returnObj[ "ExpirationDate" ] != undefined )) {
				var thisExpDate = returnObj[ "ExpirationDate" ];
				var spaceLoc = thisExpDate.indexOf( ' ' );
				thisExpDate = thisExpDate.slice( 0, spaceLoc );
				$( "#ExpirationDate_pprenew" ).val( thisExpDate );
			}
			$( "#Address1_pprenew" ).val( returnObj[ "Address1" ] );
			$( "#Address2_pprenew" ).val( returnObj[ "Address2" ] );
			$( "#City_pprenew" ).val( returnObj[ "City" ] );
			$( ".NYCounty" ).html( returnObj[ "NYCounty" ] );
			$( "#County1_pprenew" ).val( returnObj[ "NYCounty" ] );

				//setting the value of a dropdown select input is different

			var selNYCounty =  ( returnObj[ "NYCounty" ] );
			$( "select[name='NYCounty_pprenew'] option[value='selNYCounty']" ).attr( "selected", true);
			$( "#State_pprenew" ).val( returnObj[ "State" ] );
			showCounty( '1' );
			var zip = "";
			if (( returnObj[ 'Zip2' ] != null ) && ( returnObj[ 'Zip2' ] != undefined )) {
				zip = (( returnObj[ 'Zip' ] ) + ( returnObj[ 'Zip2' ] ));
			} else {
				zip = ( returnObj[ 'Zip' ] );
			}
			$( "#Zipcode_pprenew" ).val( zip );
			$( "#EMail_pprenew" ).val( returnObj[ "EMail" ] );
			$( "#Phone_pprenew" ).val( returnObj[ "Phone" ] );

			if ( debug ) {
				alert( "done populating ppRenewAcct data" );
			}
			break;

			// Populate an institution's information into the fields
			// 		i.e. Populate the institution's ID number in the Log In Area

		case "basicInstInfo" :

			if ( debug ){
				alert( "populating basicInstInfo data" );
			}

			var curSubType = $.cookie( 'instSubType' );

			$( '#instInfo_SubType' ).text( curSubType );

			var curInstId = $.cookie( 'thisInst' );

			$( '#instInfo_InstId' ).text( curInstId );

			break;

		case "instInfo_SAonly" :

			$( "#ContactFirstName" ).val( returnObj[ "ContactFirstName" ] );

			$( "#ContactLastName" ).val( returnObj[ "ContactLastName" ] );

			$( "#ContactPhoneNo" ).val( returnObj[ "ContactPhoneNo" ] );

			$( "#ContactEmail" ).val( returnObj[ "ContactEmail" ] );

			$( "#ContactTitle" ).val( returnObj[ "ContactTitle" ] );

		case "instInfo" :

			if ( debug ) {
				alert( "populating instInfo data" );
			}

			$( "#ContactFirstName" ).val( returnObj[ "ContactFirstName" ] );

			$( "#ContactLastName" ).val( returnObj[ "ContactLastName" ] );

			$( "#ContactPhoneNo" ).val( returnObj[ "ContactPhoneNo" ] );

			$( "#ContactEmail" ).val( returnObj[ "ContactEmail" ] );

			$( "#ContactTitle" ).val( returnObj[ "ContactTitle" ] );

			if (( returnObj[ "AccessExpirationDate" ] != null ) && ( returnObj[ "AccessExpirationDate" ] != undefined )) {

				var thisExpDate = returnObj[ "AccessExpirationDate" ];

				var spaceLoc = thisExpDate.indexOf( ' ' );

				thisExpDate = thisExpDate.slice( 0, spaceLoc );

				$( "#AccessExpirationDate" ).text( thisExpDate );

			}

			$( "#InstIDSpan" ).text( returnObj[ "InstID" ] );
			$( "#InstIDSpan2" ).text( returnObj[ "InstID" ] );
			$( "#InstID" ).val( returnObj[ "InstID" ] );

			var thisInstName = returnObj[ "InstName" ]

			$( "#InstName" ).text( returnObj[ "InstName" ]);
			$( "#InstName2" ).text( returnObj[ "InstName" ]);
			$( "#InstName" ).val( returnObj[ "InstName" ] );

			$( "#Address1Inst" ).text( returnObj[ "Address1" ]);
			$( "#Address2Inst" ).text( returnObj[ "Address2" ]);
			$( "#CityInst" ).text( returnObj[ "City" ]);

			$( "#NYCountyInst" ).text( returnObj[ "NYCounty" ]);

				//setting the value of a dropdown select input is different

			var selNYCounty =  ( returnObj[ "NYCounty" ] );
			$( "select[name='NYCountyInst'] option[value='selNYCounty']" ).attr( "selected", true);

			$( "#StateInst" ).text( returnObj[ "State" ]);

				//setting the value of a dropdown select input is different

			var selState =  ( returnObj[ "State" ] );
			$( "select[name='StateInst'] option[value='selState']" ).attr( "selected", true);

			$( "#ZipInst" ).text( returnObj[ "Zip" ]);
			$( "#EMailInst" ).text( returnObj[ "EMail" ]);
			$( "#PhoneInst" ).text( returnObj[ "Phone" ]);

			var curSubType = $.cookie( 'instSubType' );

			$( '#instInfo_SubType' ).text( curSubType );

			var curInstId = $.cookie( 'thisInst' );

			$( '#instInfo_InstId' ).text( curInstId );

			if ( debug ) {
				alert( "done populating instInfo data" );
			}

			break;

		case "schoolRenewFormInfo" :

			if ( debug ) {
				alert( "populating schoolRenewFormInfo data" );
			}

			$( "#InstName" ).text( returnObj[ "InstName" ]);

			$( "#InstID" ).val( returnObj[ "InstID" ]);

			$( "#schoolName" ).val( returnObj[ "InstName" ]);

			$( "#ageRange" ).val( returnObj[ "StudentsAgeRange" ]);

			$( "#numberUsing" ).val( returnObj[ "NoOfStudents" ]);

			if ( returnObj[ "IsPublic" ] == 'False' ) {

				var schoolType = 'Private';

			} else {

				var schoolType = 'Public';

			}

			$( "#schoolTypeNR" ).val( schoolType );

			$( "#contact_firstname" ).val( returnObj[ "ContactFirstName" ] );

			$( "#contact_lastname" ).val( returnObj[ "ContactLastName" ] );

			$( "#contact_phone" ).val( returnObj[ "ContactPhoneNo" ] );

			$( "#contact_email" ).val( returnObj[ "ContactEmail" ] );

			$( "#contact_title" ).val( returnObj[ "ContactTitle" ] );

			if (( returnObj[ "AccessExpirationDate" ] != null ) && ( returnObj[ "AccessExpirationDate" ] != undefined )) {

				var thisExpDate = returnObj[ "AccessExpirationDate" ];

				var spaceLoc = thisExpDate.indexOf( ' ' );

				thisExpDate = thisExpDate.slice( 0, spaceLoc );

				$( "#AccessExpirationDate" ).text( thisExpDate );

			}

			$( "#sch_address1" ).val( returnObj[ "Address1" ]);
			$( "#sch_address2" ).val( returnObj[ "Address2" ]);
			$( "#sch_city" ).val( returnObj[ "City" ]);

			$( "#sch_state" ).val( returnObj[ "State" ]);

				//setting the value of a dropdown select input is different

			var selState =  ( returnObj[ "State" ] );
			$( "select[name='sch_state'] option[value='selState']" ).attr( "selected", true);

			$( "#sch_zipcode" ).val( returnObj[ "Zip" ]);

			if ( debug ) {
				alert( "done populating schoolRenewFormInfo data" );
			}

			break;

		case "libraryRenewFormInfo" :

			if ( debug ) {
				alert( "populating libraryRenewFormInfo data" );
			}

			$( "#libraryName" ).text( returnObj[ "InstName" ]);

			$( "#InstID" ).val( returnObj[ "InstID" ]);

			$( "#InstName" ).val( returnObj[ "InstName" ]);

			$( "#contact_firstname" ).val( returnObj[ "ContactFirstName" ] );

			$( "#contact_lastname" ).val( returnObj[ "ContactLastName" ] );

			$( "#contact_phone" ).val( returnObj[ "ContactPhoneNo" ] );

			$( "#contact_email" ).val( returnObj[ "ContactEmail" ] );

			$( "#contact_title" ).val( returnObj[ "ContactTitle" ] );

			if (( returnObj[ "AccessExpirationDate" ] != null ) && ( returnObj[ "AccessExpirationDate" ] != undefined )) {

				var thisExpDate = returnObj[ "AccessExpirationDate" ];

				var spaceLoc = thisExpDate.indexOf( ' ' );

				thisExpDate = thisExpDate.slice( 0, spaceLoc );

				$( "#AccessExpirationDate" ).text( thisExpDate );

			}

			$( "#lib_address1" ).val( returnObj[ "Address1" ]);
			$( "#lib_address2" ).val( returnObj[ "Address2" ]);
			$( "#lib_city" ).val( returnObj[ "City" ]);

			$( "#lib_state" ).val( returnObj[ "State" ]);

				//setting the value of a dropdown select input is different

			var selState =  ( returnObj[ "State" ] );
			$( "select[name='lib_state'] option[value='selState']" ).attr( "selected", true);

			$( "#lib_zipcode" ).val( returnObj[ "Zip" ]);

			if ( debug ) {
				alert( "done populating libraryRenewFormInfo data" );
			}

			break;

		case "instSub":

			if ( debug ) {
				alert( "populating instSub data" );
			}

			var endMonthDig = "";
			var endMonth = "";

				//Subscription Info - retrieved by getInstSubscription not getInstitution

			$( "#SubscriptionType" ).text( returnObj[ "SubscriptionType" ] );


			var startGrad = ( returnObj[ "StartingGrade" ] );

				// the dropdown select should be set with the value exactly as it comes from the database

			$( 'select#StartingGrade' ).val( startGrad );

				// but if the StartingGrade is 'P', we want to populate 'Pre-K' but all other values we can pass directly to an html span

			var thisstartGrad = "";

			if ( startGrad == 'P' ) {

				thisstartGrad = 'Pre-K';

			} else {

				thisstartGrad = startGrad;

			}

			$( "#StartingGradeSpan" ).html( thisstartGrad );

				// if the EndingGrade is 'P', we want to populate 'Pre-K' but all other values we can pass directly

			var endGrad = ( returnObj[ "EndingGrade" ] );
			var thisEndGrad = "";

			if ( endGrad == 'P' ) {

				thisEndGrad = 'Pre-K';

			} else {

				thisEndGrad = endGrad;

			}

			$( "#EndingGradeSpan" ).html( thisEndGrad );
			$( 'select#EndingGrade' ).val( thisEndGrad );

			endMonthDig = ( returnObj[ "EndingMonth" ] );
			endMonth = "";

			switch ( endMonthDig ) {

				case "1":

					endMonth = "January";

					break;

				case "2":

					endMonth = "February";

					break;

				case "3":

					endMonth = "March";

					break;

				case "4":

					endMonth = "April";

					break;

				case "5":

					endMonth = "May";

					break;

				case "6":

					endMonth = "June";

					break;

				case "7":

					endMonth = "July";

					break;

				case "8":

					endMonth = "August";

					break;

				case "9":

					endMonth = "September";

					break;

				case "10":

					endMonth = "October";

					break;

				case "11":

					endMonth = "November";

					break;

				case "12":

					endMonth = "December";

					break;

				default:

					//

			}

			$( "#EndingMonthSpan" ).html( endMonth );

				// populate the dropdown with the digit because that is what the value is (not the word)

			$( 'select#EndingMonth' ).val( endMonthDig );

			$( ".SchoolLicenses" ).each( function() {
				$( ".SchoolLicenses" ).html( returnObj[ "SchoolLicenses" ]);
			});

				// this is in the renew subscription form on adminsettings.html

			$( "#numNewStudents" ).val( returnObj[ "SchoolLicenses" ]);

			$( "#HomeLicenses" ).html( returnObj[ "HomeLicenses" ]);
			$( "#HomeLicenses2" ).html( returnObj[ "HomeLicenses" ]);



			$( "#UsedSchoolLicenses" ).html( returnObj[ "UsedSchoolLicenses" ]);

			$( "#UsedHomeLicenses" ).html( returnObj[ "UsedHomeLicenses" ]);

				// in the renew sub form on the admina acct page, a div with di 'upgradeUADiv' is hidden
				// here we check if the inst has UA; if it does not, we show the div asking to upgrade

			var numHomeLic = returnObj[ "HomeLicenses" ];

			if ( numHomeLic < 1 ) {

				$( '#upgradeUADiv' ).show();

			}

			if ( debug ) {
				alert( "done populating instSub data" );
			}

			break;

		case "studentInfo" :

			if ( debug ) {
				alert( "populating studentInfo data" );
			}

			$( ".StudentID" ).html( returnObj[ "StudentID" ]);
			$( "#StudentID" ).val( returnObj[ "StudentID" ] );

			$( ".InstID" ).html( returnObj[ "InstID" ]);
			$( "#InstID" ).val( returnObj[ "InstID" ] );

			$( ".InstStudentID" ).html( returnObj[ "InstStudentID" ]);
			$( "#InstStudentID" ).val( returnObj[ "InstStudentID" ] );

			$( ".Firstname" ).html( returnObj[ "Firstname" ]);
			$( "#Firstname" ).val( returnObj[ "Firstname" ] );

			$( ".Lastname" ).html( returnObj[ "Lastname" ]);
			$( "#Lastname" ).val( returnObj[ "Lastname" ] );

			$( ".Username" ).html( returnObj[ "Username" ]);
			$( "#Username" ).val( returnObj[ "Username" ] );

			$( ".Level" ).html( returnObj[ "Level" ]);
			$( "#Level" ).val( returnObj[ "Level" ] );

			$( ".Password" ).html( returnObj[ "Password" ]);
			$( "#Password" ).val( returnObj[ "Password" ] );

			$( ".PEmailOne" ).html( returnObj[ "PEmailOne" ]);
			$( "#PEmailOne" ).val( returnObj[ "PEmailOne" ] );

			$( ".PEmailTwo" ).html( returnObj[ "PEmailTwo" ]);
			$( "#PEmailTwo" ).val( returnObj[ "PEmailTwo" ] );

				//set checkbox value of Homeuse

			if (( returnObj[ "Homeuse" ] ) == "True" ) {

				$( 'input[name=Homeuse]' ).attr( 'checked', true);
				$( '#Homeuse' ).val( 'on'  );
				$( '#uaCaution' ).hide();

			} else {

				$( 'input[name=Homeuse]' ).attr( 'checked', false);
				$( '#Homeuse' ).val( 'off'  );
				$( '#uaCaution' ).show();

			}

				//set checkbox value of Homeuse

			if (( returnObj[ "Homegame" ] ) == "True" ) {

				$( 'input[name=Homegame]' ).attr( 'checked', true);
				$( '#Homegame' ).val( 'on'  );

			} else {

				$( 'input[name=Homegame]' ).attr( 'checked', false);
				$( '#Homegame' ).val( 'off'  );

			}

			$( ".PPassword" ).html( returnObj[ "PPassword" ]);
			$( "#PPassword" ).val( returnObj[ "PPassword" ] );

			$( ".Notes" ).html( returnObj[ "Notes" ]);
			$( "#Notes" ).val( returnObj[ "Notes" ] );

				// these fields are on the addstudent form

			$( "#studentFirstnameSpan" ).text( returnObj[ "Firstname" ] );
			$( "#studentLastnameSpan" ).text( returnObj[ "Lastname" ]);
			$( "#studentUsernameSpan" ).text( returnObj[ "Username" ]);
			$( "#studentPasswordSpan" ).text( returnObj[ "Password" ]);
			$( "#studentLevelSpan" ).text( returnObj[ "Level" ] );
			$( "#student_id" ).val( returnObj[ "StudentID" ] );

				// populate the username and password in the sendMail form

			$( "#studUAUN" ).text( returnObj[ "Username" ]);
			$( "#studUAPW" ).text( returnObj[ "PPassword" ]);

			if ( debug ) {
				alert( "done populating studentInfo data" );
			}

			break;

		case "subFormHomeGiftReview":

			if ( debug ) {
				alert( "now populating subFormHomeGiftReview" );
			}

			$( "#firstnamePr" ).text( $( "#firstname" ).val());
			$( "#lastnamePr" ).text( $( "#lastname" ).val());
			$( "#address1Pr" ).text( $( "#address1" ).val());
			if ( $( "#address2" ).val() != "" ) {
				$( "#address2Pr" ).text(  ", " + $( "#address2" ).val());
			}
			$( "#cityPr" ).text( $( "#city" ).val());

			$( "#zipcodePr" ).text( $( "#zipcode" ).val());
			$( "#statePr" ).text( $( "#state" ).val());
			$( "#countryPr" ).text( $( "#country" ).val());
			$( "#emailPr" ).text( $( "#email" ).val());
			$( "#phonePr" ).text( $( "#phone" ).val());

			if ( page == 'giveagift' ){

				$( "#rec_firstname" ).text( $( "#rcpt_firstname" ).val());
				$( "#rec_lastname" ).text( $( "#rcpt_lastname" ).val());
				$( "#rec_address1" ).text( $( "#rcpt_address1" ).val());

				if ( $( "#rcpt_address2" ).val() != "" ) {
					$( "#rec_address2" ).text( ", " + $( "#rcpt_address2" ).val());
				}

				$( "#rec_city" ).text( $( "#rcpt_city" ).val());

				if ( $( "#rcpt_nycounty" ).val() != "" ) {
					$( ".rec_nycounty" ).text( $( "#rcpt_nycounty" ).val());
				}

				$( "#rec_zipcode" ).text( $( "#rcpt_zipcode" ).val());
				$( "#rec_state" ).text( $( "#rcpt_state" ).val());
				$( "#rec_country" ).text( $( "#rcpt_country" ).val());
				$( "#rec_email" ).text( $( "#rcpt_email" ).val());
				$( "#rec_phone" ).text( $( "#rcpt_phone" ).val());

			}

			if ( $( "#promoCode1" ).val() != "" ) {
				$( "#promoTitle" ).text( "Promo Code: " );
				$( "#promo" ).text( $( "#promoCode1" ).val());
			}

			if ( debug ) {
				alert( "done populating user info, now calculating prices" );
			}

			var sublength = "";
			var length = "";
			var price = "";
			var lengthInt = "";

			var checkedValue = $( "input[name=subType]:checked" ).val();

			switch( checkedValue ) {

				case "length1" :

					if ( debug ) {
						alert( "length1" );
					}

					sublength = "length1";
					length = textPrice1;
					price = price1;
					lengthInt = "1";

					break;

				case "length2" :

					if ( debug ) {
						alert( "length2" );
					}

					sublength = "length2";
					length = textPrice2;
					price = price2;
					lengthInt = "2";

					break;

				case "length3" :

					if ( debug ) {
						alert( "length3" );
					}

					sublength = "length3";
					length = textPrice3;
					price = price3;
					lengthInt = "3";

					break;

				default:

					if ( debug ) {
						alert( "no sub" );
					}

					alert( "Sorry, we can't find your subscription type - please go back and reselect a subscription type." );

					return false;

			}

			var thePrice = price;
			var theLength = length;

			$( '#subLengthInt' ).val( lengthInt );

			if ( debug ) {
			   alert( "new alert: thePrice is [" + thePrice + "] and theLength is [" + theLength + "] and lengthInt is [" + lengthInt + "]" );
			}

			thePrice = ( parseFloat(thePrice));

			thePrice = thePrice.toFixed(2);

			if ( debug ) {
				alert( "thePrice is now [" + thePrice + "]" );
			}

			$( '#sub_price' ).text( thePrice );
			$( '#sub_length' ).text( theLength );
			$( '#sub_length2' ).text( theLength );
			$( '#subLengthInt' ).val( lengthInt );

				// get the tax rate from the stored global variable

			thisTaxRate = NYSCountyTaxRate;

			if ( debug ) {
				alert( "now declared thisTaxRate variable from global = [" + thisTaxRate + "]" );
			}

			var nyCounty = $( '#nycounty' ).val();

			if ( $( "#state" ).val() != 'NY' ) {

				if ( debug ) {
		   			alert( "state is not ny" );
		   		}

		   		$( '#sub_tax' ).text( '$0.00' );

		   		theTotal = thePrice;

		   		theTotal = ( parseFloat(theTotal));

		   		theTotal = theTotal.toFixed(2);

		   		$( '#sub_total' ).text( theTotal );

		   } else if ( $( "#state" ).val() == 'NY' ) {

		   		if ( debug ) {
		   			alert( "state is ny, now calculating tax" );
		   		}

		   		thisTaxRate = parseFloat( thisTaxRate );

		   		if ( debug ) {
					alert( "thisTaxRate is [" + thisTaxRate + "]" );
				}

				thisTaxRate = ( thisTaxRate * .01 );

				if ( debug ) {
					alert( "thisTaxRate is now [" + thisTaxRate + "]" );
				}

				theTax = ( thisTaxRate * thePrice )

				if ( debug ) {
					alert( "theTax is [" + theTax + "]" );
				}

				theTax = theTax.toFixed(2);

				if ( debug ) {
					alert( "theTax is now [" + theTax + "]" );
				}

				$( '#sub_tax' ).text( "$" + theTax );

				theTotal = (( parseFloat(thePrice)) + ( parseFloat(theTax)));

				theTotal = theTotal.toFixed(2);

				if ( debug ) {
					alert( "theTotal is [" + theTotal + "]" );
				}

				$( '#sub_total' ).text( theTotal );

		   	}

			$( "#cc_type" ).text( $( "#creditcard" ).val());

			var ccNumber = $( "#ccnumber" ).val();

			var displayNum = "";

			for ( var i = 0; i < ccNumber.length - 4; i++ ) {

				displayNum += "*";

			}

			displayNum += ccNumber.substr( ccNumber.length - 4 );

			$( "#cc_number" ).text( displayNum );

			$( "#cc_expMonth" ).text( $( "#expMonth" ).val());
			$( "#cc_expYear" ).text( $( "#expYear" ).val());
			$( "#cc_cvv" ).text( $( "#cvv" ).val());

			if ( debug ) {
				alert( "done populating subFormHomeGiftReview" );
			}

			break;


		case "subFormRenewReview":

			if ( debug ) {
				alert( "now populating subFormRenewReview" );
			}

			$( "#firstnamePr" ).text( $( "#FirstName_pprenew" ).val());
			$( "#lastnamePr" ).text( $( "#LastName_pprenew" ).val());
			$( "#address1Pr" ).text( $( "#Address1_pprenew" ).val());
			if ( $( "#Address1_pprenew" ).val() != "" ) {
				$( "#address2Pr" ).text( ", " + $( "#Address2_pprenew" ).val());
			}
			$( "#cityPr" ).text( $( "#City_pprenew" ).val());
			$( "#zipcodePr" ).text( $( "#Zipcode_pprenew" ).val());
			$( "#statePr" ).text( $( "#State_pprenew" ).val());
			$( "#countryPr" ).text( $( "#Country_pprenew" ).val());
			$( "#emailPr" ).text( $( "#EMail_pprenew" ).val());
			$( "#phonePr" ).text( $( "#Phone_pprenew" ).val());
			if ( $( "#promoCode1" ).val() != "" ) {
				$( "#promoTitle" ).text( "Promo Code: " );
				$( "#promo" ).text( $( "#promoCode1" ).val());
			}

			if ( debug ) {
				alert( "done populating user info, now calculating prices" );
			}

			var sublength = "";
			var length = "";
			var price = "";
			var lengthInt = "";

			var checkedValue = $( "input[name=subType]:checked" ).val();

			switch( checkedValue ) {

				case "length1" :

					if ( debug ) {
						alert( "length1" );
					}

					sublength = "length1";
					length = textPrice1;
					price = price1;
					lengthInt = "1";

					break;

				case "length2" :

					if ( debug ) {
						alert( "length2" );
					}

					sublength = "length2";
					length = textPrice2;
					price = price2;
					lengthInt = "2";

					break;

				case "length3" :

					if ( debug ) {
						alert( "length3" );
					}

					sublength = "length3";
					length = textPrice3;
					price = price3;
					lengthInt = "3";

					break;

				default:

					if ( debug ) {
						alert( "no sub" );
					}

					alert( "Sorry, we can't find your subscription type - please go back and reselect a subscription type." );

					return false;

			}

			var thePrice = price;
			var theLength = length;

			$( '#subLengthInt' ).val( lengthInt );

			if ( debug ) {
			   alert( "new alert: thePrice is [" + thePrice + "] and theLength is [" + theLength + "] and lengthInt is [" + lengthInt + "]" );
			}

			thePrice = ( parseFloat(thePrice));

			thePrice = thePrice.toFixed(2);

			if ( debug ) {
				alert( "thePrice is now [" + thePrice + "]" );
			}

			$( '#sub_price' ).text( thePrice );
			$( '#sub_length' ).text( theLength );
			$( '#sub_length2' ).text( theLength );
			$( '#subLengthInt' ).val( lengthInt );

				// get the tax rate from the stored global variable

			thisTaxRate = NYSCountyTaxRate;

			if ( debug ) {
				alert( "now declared thisTaxRate variable from global = [" + thisTaxRate + "]" );
			}

			var nyCounty = $( '#NYCounty_pprenew' ).val();

			if ( $( "#State_pprenew" ).val() != 'NY' ) {

				if ( debug ) {
		   			alert( "state is not ny" );
		   		}

		   		$( '#sub_tax' ).text( '$0.00' );

		   		theTotal = thePrice;

		   		theTotal = ( parseFloat(theTotal));

		   		theTotal = theTotal.toFixed(2);

		   		$( '#sub_total' ).text( theTotal );

		   } else if ( $( "#State_pprenew" ).val() == 'NY' ) {

		   		if ( debug ) {
		   			alert( "state is ny, now calculating tax" );
		   		}

		   		thisTaxRate = parseFloat( thisTaxRate );

		   		if ( debug ) {
					alert( "thisTaxRate is [" + thisTaxRate + "]" );
				}

				thisTaxRate = ( thisTaxRate * .01 );

				if ( debug ) {
					alert( "thisTaxRate is now [" + thisTaxRate + "]" );
				}

				theTax = ( thisTaxRate * thePrice );

				if ( debug ) {
					alert( "theTax is [" + theTax + "]" );
				}

				theTax = theTax.toFixed(2);

				if ( debug ) {
					alert( "theTax is now [" + theTax + "]" );
				}

				$( '#sub_tax' ).text( "$" + theTax );

				theTotal = (( parseFloat(thePrice)) + ( parseFloat(theTax)));

				theTotal = theTotal.toFixed(2);

				if ( debug ) {
					alert( "theTotal is [" + theTotal + "]" );
				}

				$( '#sub_total' ).text( theTotal );

		   	}

			$( "#cc_type" ).text( $( "#creditcard" ).val());

			var ccNumber = $( "#ccnumber" ).val();

			var displayNum = "";

			for ( var i = 0; i < ccNumber.length - 4; i++ ) {

				displayNum += "*";

			}

			displayNum += ccNumber.substr( ccNumber.length - 4 );

			$( "#cc_number" ).text( displayNum );

			$( "#cc_expMonth" ).text( $( "#expMonth" ).val());
			$( "#cc_expYear" ).text( $( "#expYear" ).val());
			$( "#cc_cvv" ).text( $( "#cvv" ).val());

			if ( debug ) {
				alert( "done populating subFormRenewReview" );
			}

			break;


		case "pricing":

			if ( debug ) {
				alert( "now populating pricing" );
			}

			$( "#oneYear" ).html( returnObj[ "one  year" ]);
			$( "#sixMonths" ).html( returnObj[ "six months" ]);
			$( "#threeMonths" ).html( returnObj[ "three months" ]);

			if ( debug ) {
				alert( "done populating pricing" );
			}

			break;

			// this is called on the class activity log page, becuase the name could be either the user or the thisTeacher

		case "curTeacherInfo":

			if ( debug ) {
				alert( "now populating curTeacherInfo" );
			}

			var typeCode = $.cookie( 'classLogType' );

			if ( debug ) {
				alert( "typeCode is [" + typeCode + "]" );
			}

				// if the typeCode is 'tt', the page is for meant to show the class act list of a specific teacher

			if ( typeCode == "tt" ) {

				if ( debug ) {
					alert( "populating name of this teacher" );
				}

				    // so get the id form the userid cookie

			    var thisTeacherID = ( $.cookie( 'thisTeacher' ));

			    var jsonStr	= addToJSONStr( jsonStr, "UserID", thisTeacherID );

			    if ( debug ) {
			    	alert( "jsonStr = [" + jsonStr + "]" );
			    }

			    callDB( "getUser", jsonStr, function( data ) {

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

			    		//populate fields

			    	$( "#curTeacherFN" ).text( returnObj[ "FirstName" ]);
			    	$( "#curTeacherLN" ).text( returnObj[ "LastName" ]);

			    });

				// if the typeCode is 'tu', the page is for meant to show the class act list of the user

			} else if ( typeCode == "tu" ) {

				if ( debug ) {
					alert( "populating name of user" );
				}

				var jsonStr	= "";

					// so call getTeacher and populate the First and last name spans

				callDB( "getUser", jsonStr, function( data ) {

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

						//populate fields

			    	$( "#curTeacherFN" ).text( returnObj[ "FirstName" ]);
			    	$( "#curTeacherLN" ).text( returnObj[ "LastName" ]);

				});

			}

			if ( debug ) {
				alert( "done populating curTeacherInfo" );
			}

			break;

		case "sab":

			if ( debug ) {
				alert( "now populating sab info" );
			}

			$( ".Email" ).text( returnObj[ "Email" ]);

			if ( debug ) {
				alert( "done populating sab info" );
			}

			break;

		case "logInArea":

			if ( debug ) {
				alert( "now populating logInArea" );
			}

				// populate the log in area with user's first and last name, institution name and/or SAB email - from cookies

				// // the first and last name of the current user

			var thisFullName = $.cookie( "fullname" );

			if (( thisFullName != null ) && ( thisFullName != undefined )) {

					// get location of semicolon plus one (to get the location after the semicolon)

				var semicolLoc = ( thisFullName.indexOf( ';' ));
				var semicolLocPlusOne = semicolLoc + 1;

					// slice out the section after the equal sign

				var thisFN = thisFullName.slice( 0, semicolLoc );
				var thisLN = thisFullName.slice( semicolLocPlusOne );

				thisFN = thisFN.replace( 'FN=', '' );
				thisLN = thisLN.replace( 'LN=', '' );

					// unescape

				thisFN = unescape( thisFN );
				thisLN = unescape( thisLN );

					// populate field

				$( ".FirstNameSpan" ).each( function() {
					$( this ).text( thisFN );
				});

				$( ".LastNameSpan" ).each( function() {
					$( this ).text( thisLN );
				});

			}

				// // the institution name

			var thisInstName = $.cookie( "instname" );

			if (( thisInstName != null ) && ( thisInstName != undefined )) {

					// unescape

				thisInstName = unescape( thisInstName );

					// populate field

				$( ".InstNameSpan" ).each( function() {
					$( this ).text( thisInstName );
				});

			}

			if ( debug ) {
				alert( "done populating logInArea" );
			}

			break;

		default:

			if ( debug ) {
				alert( "no param was passed" );
			}

	}

	if ( debug ) {
		alert( "Done populate" );
	}

}


//
// redirect -- takes url as the param, add global prefix and redirects user, used after a setTimeout
//
function redirect( url ) {

	document.location = prefix + url;

}


//
// sendABook -- calls the DB with the sendABook command
//
function sendABook( type ) {
	//If type is auto, this means to get the 'From' fields from the userObject
	//		because the form is filled out by a person already logged in.

	var debug	= false;

	if ( debug ) {
		alert( "In sendABook" );
	}

	var thisType = type;

	var curBook = "";
	var curBook2 = "";
	var bookid = "";
	var filename = "";

	if ( debug ) {
		alert( "now here" );
	}

	curBook = $( "#bookSelect" ).val();

	if ( debug ) {
		alert( "curBook variable is now [" + curBook + "]" );
	}

	curBook2 = ( curBook.replace( "../img/bookcovers/", "" ));

	if ( debug ) {
		alert( "curBook2 variable is now [" + curBook2 + "]" );
	}

	switch ( curBook2 ) {

		case "snowy_day.jpg":

			bookid = "21";

			filename = "theSnowyDay.jpg";

			break;

		case "gulliver_snip.jpg":

			bookid = "52";

			filename = "gulliverSnip.jpg";

			break;

		case "jamaica_james.jpg":

			bookid = "9";

			filename = "jamaicaLouiseJames.jpg";

			break;

		case "kiss_cow.jpg":

			bookid = "7";

			filename = "kissTheCow.jpg";

			break;

		case "owl_babies.jpg":

			bookid = "8";

			filename = "owlBabies.jpg";

			break;

		case "petes_a_pizza.jpg":

			bookid = "49";

			filename = "petesAPizza.jpg";

			break;

		case "song_dance.jpg":

			bookid = "36";

			filename = "songAndDanceMan.jpg";

			break;

		case "this_is_the_tree.jpg":

			bookid = "20";

			filename = "thisIsTheTree.jpg";

			break;

		case "happened_dinosaurs.jpg":

			bookid = "17";

			filename = "whateverHappenedToTheDinosaurs.jpg";

			break;

		case "yesterday_blues.jpg":

			bookid = "27";

			filename = "YesterdayIHadTheBlues.jpg";

			break;

	}

	filename = curBook2;

	if ( debug ) {
		alert( "bookid is [" + bookid + "] and filename is [" + filename + "]" );
	}

	var from = "";

		// if the param is auto
		// get the 'From' info from the current userObject

	if ( thisType == 'auto' ) {

		if ( debug ) {
			alert( "thisType is auto, now running calldb with getUser" );
		}

		var jsonStr = "";

			//call getUser and get the user's email address

		callDB( "getUser", jsonStr, function( data ) {

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

			if ( debug ) {
				alert( "now in getUser anon function" );
			}

			from = returnObj[ "EMail" ];

			if ( debug ) {
				alert( "Email from getUser is [" + from + "]" );
			}

			var recipient		= $( "#sab_recipient" ).val();
			var recipientName 	= $( "#sab_recipientName" ).val();
			var message			= $( "#sab_message" ).val();

			if ( debug ) {
				alert( "recipient = [" + recipient + "]\n" +
						"from = [" + from + "]\n" +
						"bookid = [" + bookid + "]\n" +
						"filename = [" + filename + "]\n" +
						"message = [" + message + "]\n" +
						"" );
			}

			var jsonStr	= addToJSONStr( jsonStr, "recipient", recipient );
				jsonStr	= addToJSONStr( jsonStr, "from", from );
				jsonStr	= addToJSONStr( jsonStr, "bookid", bookid );
				jsonStr	= addToJSONStr( jsonStr, "filename", filename );
				jsonStr	= addToJSONStr( jsonStr, "message", message );

			if ( debug ) {
				alert( "jsonStr = [" + jsonStr + "]" );
			}

			callDB( "sendABook", jsonStr, function( data ) {

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

					// set curResults global var so formConfirm can know whether the function was a success or error

				curResults = ( returnObj[ "results" ] );
				var curError = ( returnObj[ "error" ] );

					//show confirmation or error message

				formConfirm( 'sendABook', 'Thanks for sending a book! The recipient of this gift will get an email with their temporary password and login instructions. Have another friend or coworker in mind? Send another book!', curError );

				if ( curResults == 'success' ) {

					$( "#sab_recipient" ).val( '' );
					$( "#sab_recipientName" ).val( '' );
					$( "#sab_message" ).val( '' );

				}

			});

		});

		// else if thisType is autoSAB, get the from info from getSABUser

	} else if ( thisType == 'autoSAB' ) {

		if ( debug ) {
			alert( "thisType is autoSAB, now running calldb with getSABUser" );
		}

		var jsonStr = "";

			//call getUser and get the user's email address

		callDB( "getSABUser", jsonStr, function( data ) {

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

			if ( debug ) {
				alert( "now in getSABUser anon function" );
			}

			from = returnObj[ "Email" ];

			if ( debug ) {
				alert( "Email from getUser is [" + from + "]" );
			}

			var recipient		= $( "#sab_recipient" ).val();
			var recipientName 	= $( "#sab_recipientName" ).val();
			var message			= $( "#sab_message" ).val();

			if ( debug ) {
				alert( "recipient = [" + recipient + "]\n" +
						"from = [" + from + "]\n" +
						"bookid = [" + bookid + "]\n" +
						"filename = [" + filename + "]\n" +
						"message = [" + message + "]\n" +
						"" );
			}

			var jsonStr	= addToJSONStr( jsonStr, "recipient", recipient );
				jsonStr	= addToJSONStr( jsonStr, "from", from );
				jsonStr	= addToJSONStr( jsonStr, "bookid", bookid );
				jsonStr	= addToJSONStr( jsonStr, "filename", filename );
				jsonStr	= addToJSONStr( jsonStr, "message", message );

			if ( debug ) {
				alert( "jsonStr = [" + jsonStr + "]" );
			}

			callDB( "sendABook", jsonStr, function( data ) {

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

					// set curResults global var so formConfirm can know whether the function was a success or error

				curResults = ( returnObj[ "results" ] );
				var curError = ( returnObj[ "error" ] );

					//show confirmation or error message

				formConfirm( 'sendABook', 'Thanks for sending a book! The recipient of this gift will get an email with their temporary password and login instructions. Have another friend or coworker in mind? Send another book!', curError );

				if ( curResults == 'success' ) {

					$( "#sab_recipient" ).val( '' );
					$( "#sab_recipientName" ).val( '' );
					$( "#sab_message" ).val( '' );

				}

			});

		});

		//else, get the info from the field

	} else {

		from = $( "#sab_from" ).val();

		var recipient		= $( "#sab_recipient" ).val();
		var recipientName 	= $( "#sab_recipientName" ).val();
		var message			= $( "#sab_message" ).val();

		if ( debug ) {
			alert( "recipient = [" + recipient + "]\n" +
					"from = [" + from + "]\n" +
					"bookid = [" + bookid + "]\n" +
					"filename = [" + filename + "]\n" +
					"message = [" + message + "]\n" +
					"" );
		}

		var jsonStr	= addToJSONStr( jsonStr, "recipient", recipient );
			jsonStr	= addToJSONStr( jsonStr, "from", from );
			jsonStr	= addToJSONStr( jsonStr, "bookid", bookid );
			jsonStr	= addToJSONStr( jsonStr, "filename", filename );
			jsonStr	= addToJSONStr( jsonStr, "message", message );

		if ( debug ) {
			alert( "jsonStr = [" + jsonStr + "]" );
		}

		callDB( "sendABook", jsonStr, function( data ) {

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

				// set curResults global var so formConfirm can know whether the function was a success or error

			curResults = ( returnObj[ "results" ] );
			var curError = ( returnObj[ "error" ] );

				//show confirmation or error message

			formConfirm( 'sendABook', 'Thanks for sending a book! The recipient of this gift will get an email with their temporary password and login instructions. Have another friend or coworker in mind? Send another book!', curError );

			if ( curResults == 'success' ) {

				$( "#sab_recipient" ).val( '' );
				$( "#sab_recipientName" ).val( '' );
				$( "#sab_message" ).val( '' );

			}

		});

	}

	if ( debug ) {
		alert( "Done sendABook" );
	}
}


//
// sendEmail -- calls the DB with the sendEmail command
//
function sendEmail( messageParam ) {
	var debug	= false;
	if ( debug ) {
		alert( "In sendEmail" );
	}

	if ( debug ) {
		alert( "messageParam is [" + messageParam + "]\n\n" +
				"page is [" + page + "]\n\n" +
				"category is [" + category + "]" );
	}

	var fullMessage 	= "";
	var recipient		=  CONTACT_EMAIL;
	var from			= $( "#from" ).val() + "";
	var subject			= $( "#subject" ).val();
	var name			= $( "#name" ).val();
	var message			= $( "#message" ).val();
	var phone			= $( "#phoneNR" ).val();
	var email			= $( "#email" ).val();
	var note			= $( "#note" ).val();
	var school			= $( "#schoolNameNR" ).val();
	var iam				= $( "#iam" ).val();
	var iamother		= $( "#iamother" ).val();
	var howhear			= $( "#howhear" ).val();
	var userIP			= $( "#ipAddress" ).val();
	var serverIP		= $( "#serverIpAddress" ).val();
	var browserInfo		= $( "#userInfo" ).text();
	var browserInfo2	= $( "#browserInfo" ).val();
	var javascript		= $( "#javascriptResponse" ).text();
	var flashVer		= $( "#flashVer" ).val();

	if ( debug ) {
	    alert( "recipient = [" + recipient + "]\n" +
	    		"from = [" + from + "]\n" +
	    		"subject = [" + subject + "]\n" +
	    		"message = [" + message + "]\n" +
	    		"email = [" + email + "]\n" +
	    		"note = [" + note + "]\n" +
	    		"phone = [" + phone + "]\n" +
	    		"name = [" + name + "]\n" +
	    		"school = [" + school + "]\n" +
	    		"iam = [" + iam + "]\n" +
	    		"other = [" + iamother + "]\n" +
	    		"howhear = [" + howhear + "]\n" +
	    		"userIP = [" + userIP + "]\n" +
	    		"serverIP = [" + serverIP + "]\n" +
	    		"browserInfo = [" + browserInfo + "]\n" +
	    		"javascript = [" + javascript + "]\n" +
	    		"flashVer = [" + flashVer + "]\n" +
	    		"" );
	}

		// if the param is not empty, use it as the message

	if ( messageParam != undefined ){

		if ( debug ) {
			alert( "messageParam is not undefined - i.e. a message was included in the parameter" );
		}

		fullMessage = messageParam ;

	} else {

		if ( debug ) {
			alert( "messageParam is undefined, i.e. a message wasn't included in the parameter, we now build the message from the form on the page" );
		}

		// check for page ID and put together different

		var thisConfirmMessage = "";

		if ( page == 'techreq' ) {

			if ( debug ) {
				alert( "page is techreq" );
			}

			// This is the user info form on the technical requirements page

			fullMessage = (   " Name - " + name +
							"\\n School Name - " + school +
							"\\n Email - " + email +
							"\\n Note - " + note +
							"\\n User Browser Information - " + browserInfo +
							"\\n Full Browser Agent String - [" + navigator.userAgent + "]" +
							"\\n User IP Address - " + userIP +
							"\\n Server IP Address - " + serverIP +
							"\\n Javascript - " + javascript +
							"\\n User Flash Verification - " + flashVer + "" );

			thisConfirmMessage = "Your information has been sent.";

			if ( debug ) {
				alert( "" );
			}

		} else if ( category == 'help' ) {

			if ( debug ) {
				alert( "page is help" );
			}

			// this is either Contact Us or Report An Issue

			fullMessage = (     "School/Org Name: " + name +
							"\n Email: " + email +
							"\n Phone Number: " + phone +
							"\n School: " + $( "#schoolName" ).val() +
							"\n Message: " + message +
							"\n I am a: " + iam +
							"\n Or, other: " + iamother +
							"\n How I heard about OMS: " + howhear +
							"\n User IP address: " + userIP +
							"\n Browser Agent: " + browserInfo2 );

			thisConfirmMessage = "Your message has been sent.";

		} else if (( category == 'its' )&&( page == 'subscription' )){

			// this is the Itslearning Subscription Form

			if ( debug ) {
				alert( "page is its subscription" );
			}

			fullMessage = (	"Name: " + $( "#schoolName" ).val() +
							"\n Site Name: " + $( "#schoolSystemNR" ).val() +
							"\n Age Range of Students: " + $( "#ageRange" ).val() +
							"\n Number of Students Using OMS: " + $( "#numberUsing" ).val() +
							"\n Address 1: " + $( "#sch_address1" ).val() +
							"\n Address 2: " + $( "#sch_address2" ).val() +
							"\n City: " + $( "#sch_city" ).val() +
							"\n State: " + $( "#sch_state" ).val() +
							"\n Zip code: " + $( "#sch_zipcode" ).val() +
							"\n\n Contact Information" +
							"\n Title: " + $( "#contact_title" ).val() +
							"\n Email Address: " + $( "#contact_email" ).val() +
							"\n Phone Number: " + $( "#contact_phone" ).val() +
							"\n\n Information Requested By:" +
							"\n First Name: " + $( "#req_firstname" ).val() +
							"\n Last Name: " + $( "#req_lastname" ).val() +
							"\n Email Address: " + $( "#req_email" ).val() +
							"\n Accept Terms: " + $( "#acceptTerms" ).val() );

			thisConfirmMessage = "Your subscription form was submitted, thank you!";

		} else {

			if ( debug ) {
				alert( "else" );
			}

		}

	}

	var jsonStr	= addToJSONStr( jsonStr, "recipient", CONTACT_EMAIL );
		jsonStr	= addToJSONStr( jsonStr, "from", $( "#from" ).val() );
		jsonStr	= addToJSONStr( jsonStr, "subject", $( "#subject" ).val() );
		jsonStr	= addToJSONStr( jsonStr, "message", fullMessage );

	if ( debug ) {
		alert( "jsonStr = [" + jsonStr + "]" );
	}

	callDB( "sendEmail", jsonStr, function( data ) {

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

			// set curResults global var so formConfirm can know whether the function was a success or error

		curResults = ( returnObj[ "results" ] );
		var curError = ( returnObj[ "error" ] );

			//show confirmation or error message

		if ( page == 'techreq' ) {

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

				alert( "Your information has been submitted to the staff at One More Story." );

				$( "#name" ).val( '' );
				$( "#email" ).val( '' );
				$( "#note" ).val( '' );
				$( "#schoolNameNR" ).val( '' );

			} else {

				alert( "Sorry, there was a problem submitting your information." );

			}

		} else if ( category == 'help' ) {

		    // this is either Contact Us or Report An Issue

		    formConfirm( 'sendEmail', thisConfirmMessage, curError );

		    if ( $( "#detector" ).val() == "yes" ) {

		    	$( "#name" ).val( '' );
		    	$( "#schoolNameNR" ).val( '' );
		    	$( "#email" ).val( '' );
		    	$( "#note" ).val( '' );

		    } else {

		    	$( "#name" ).val( '' );
		    	$( "#email" ).val( '' );
		    	$( "#phoneNR" ).val( '' );
		    	$( "#message" ).val( '' );
		    	$( "#iam" ).val( '' );
		    	$( "#iamother" ).val( '' );
		    	$( "#howhear" ).val( '' );

		    }

		} else if (( category == 'its' )
		    		&&( page == 'freeweek' )){

			// do nothing right now

		} else if (( category == 'its' )
		    		&&( page == 'subscription' )){

		    // this is the Itslearning Subscription Form

		    formConfirm( 'sendInstInfoRequest', thisConfirmMessage, curError );

		    if ( debug ) {
		    	alert( "now submitting event tracking for Itslearning Sub" );
		    }

		    try {
  		    	_gaq.push(['_trackEvent', 'Itslearning', 'Subscription Requested']);		// track event in google analytics
  		    } catch(err) {
  		    	if ( debug ) {
  		    		alert( "ERROR caught trying to submit event tracking for Itslearning sub request, now logging message" );
  		    	}
  		    	logErrorMessage( 'Error Caught : Submitting Event Tracking : Itslearning Subscription Request' );
  		    }

		}

	});

	if ( debug ) {
		alert( "Done sendEmail" );
	}
}


//
// sendInstInfoRequest -- calls the DB with the sendInstInfoRequest command
//
function sendInstInfoRequest() {
	var debug	= false;
	if ( debug ) {
		alert( "In sendInstInfoRequest" );
	}

	var instType = $( '#instType' ).val();

	if ( debug ) {
		alert( "instType is [" + instType + "]" );
	}

	var siir_name = "";
	var siir_address1 = "";
	var siir_address2 = "";
	var siir_city = "";
	var siir_state = "";
	var siir_zip1 = "";
	var siir_zip2 = "";
	var siir_contactFirstName = "";
	var siir_contactLastName = "";
	var siir_contactTitle = "";
	var siir_email = "";
	var siir_phone = "";
	var siir_reqFirstName = "";
	var siir_reqLastName = "";
	var siir_reqEmail = "";
	var thisInst = "";
	var siir_schoolSystem = "";
	var siir_schoolType = "";
	var siir_ageRange = "";
	var siir_numStudents = "";
	var siir_librarySystem = "";
	var siir_howHeard = "";
	var siir_other = "";
	var siir_renewalID = "";
	var siir_saChanging = "";
	var siir_contactDirectly = "";

	switch( instType ) {

		case "School" :

			if ( category == 'its' ){

				siir_schoolSystem = '[ITS] ' + $( '#schoolSystemNR' ).val();

			} else {

				siir_schoolSystem = $( '#schoolSystemNR' ).val();

			}

			siir_name = $( '#schoolName' ).val();
			siir_address1 =$( '#sch_address1' ).val();
			siir_address2 = $( '#sch_address2' ).val();
			siir_city = $( '#sch_city' ).val();
			siir_state = $( '#sch_state' ).val();

				//break the value of zipcode into zip1 and zip2, first five digits go into zip1, the rest spill into zip2

			var zipFull = "";
			var zip1 = "";
			var zip2 = "";

			zipFull = $( "#sch_zipcode" ).val();

			zipFull = zipFull.replace(/[\(\)\.\-\s,]/g, "");

			zip1 = zipFull.substr(0,5);

			zip2 = zipFull.substr(5);

			siir_zip1 = zip1;
			siir_zip2 = zip2;
			siir_contactFirstName = $( '#contact_firstname' ).val();
			siir_contactLastName = $( '#contact_lastname' ).val();
			siir_contactTitle = $( '#contact_title' ).val();
			siir_email = $( '#contact_email' ).val();
			siir_phone = $( '#contact_phone' ).val();
			siir_reqFirstName = $( '#req_firstname' ).val();
			siir_reqLastName = $( '#req_lastname' ).val();
			siir_reqEmail = $( '#req_email' ).val();

			thisInst = "School";

			siir_schoolType = $( '#schoolTypeNR' ).val();
			siir_ageRange = $( '#ageRange' ).val();
			siir_numStudents = $( '#numberUsing' ).val();
			siir_howHeard = $( '#howHear' ).val();
			siir_other = $( '#howHearOther' ).val();
			siir_renewalID = $( '#InstID' ).val();
			siir_saChanging = $( '#SA_changing' ).val();

			break;

		case "Library" :

			siir_name = $( '#libraryName' ).val();
			siir_address1 =$( '#lib_address1' ).val();
			siir_address2 = $( '#lib_address2' ).val();
			siir_city = $( '#lib_city' ).val();
			siir_state = $( '#lib_state' ).val();

				//break the value of zipcode into zip1 and zip2, first five digits go into zip1, the rest spill into zip2

			var zipFull = "";
			var zip1 = "";
			var zip2 = "";

			zipFull = $( "#lib_zipcode" ).val();

			zipFull = zipFull.replace(/[\(\)\.\-\s,]/g, "");

			zip1 = zipFull.substr(0,5);

			zip2 = zipFull.substr(5);

			siir_zip1 = zip1;
			siir_zip2 = zip2;

			siir_contactFirstName = $( '#contact_firstname' ).val();
			siir_contactLastName = $( '#contact_lastname' ).val();
			siir_contactTitle = $( '#contact_title' ).val();
			siir_email = $( '#contact_email' ).val();
			siir_phone = $( '#contact_phone' ).val();
			siir_reqFirstName = $( '#req_firstname' ).val();
			siir_reqLastName = $( '#req_lastname' ).val();
			siir_reqEmail = $( '#req_email' ).val();

			thisInst = "Library";

			siir_librarySystem = $( '#librarySystemNR' ).val();
			siir_howHeard = $( '#howHear' ).val();
			siir_other = $( '#howHearOther' ).val();
			siir_renewalID = $( '#InstID' ).val();
			siir_saChanging = $( '#SA_changing' ).val();

			break;

		case "Hospital" :

			siir_name = $( '#hospitalName' ).val();
			siir_address1 =$( '#hosp_address1' ).val();
			siir_address2 = $( '#hosp_address2' ).val();
			siir_city = $( '#hosp_city' ).val();
			siir_state = $( '#hosp_state' ).val();

				//break the value of zipcode into zip1 and zip2, first five digits go into zip1, the rest spill into zip2

			var zipFull = "";
			var zip1 = "";
			var zip2 = "";

			zipFull = $( '#hosp_zipcode' ).val();

			zipFull = zipFull.replace(/[\(\)\.\-\s,]/g, "");

			zip1 = zipFull.substr(0,5);

			zip2 = zipFull.substr(5);

			siir_zip1 = zip1;
			siir_zip2 = zip2;

			siir_contactFirstName = $( '#contact_firstname' ).val();
			siir_contactLastName = $( '#contact_lastname' ).val();
			siir_contactTitle = $( '#this' ).val();
			siir_email = $( '#contact_email' ).val();
			siir_phone = $( '#contact_phone' ).val();
			siir_reqFirstName = $( '#req_firstname' ).val();
			siir_reqLastName = $( '#req_lastname' ).val();
			siir_reqEmail = $( '#req_email' ).val();
			thisInst = "Hospital";
			siir_howHeard = $( '#howHear' ).val();
			siir_other = $( '#howHearOther' ).val();
			siir_renewalID = $( '#InstID' ).val();
			siir_saChanging = $( '#SA_changing' ).val();

			break;

		default:

			//nothing

			break;
	}

		// Get the user information from the form.

	var jsonStr	= addToJSONStr( jsonStr, "Name", siir_name );
		jsonStr	= addToJSONStr( jsonStr, "Address1", siir_address1 );
		jsonStr	= addToJSONStr( jsonStr, "Address2", siir_address2 );
		jsonStr	= addToJSONStr( jsonStr, "City", siir_city );
		jsonStr	= addToJSONStr( jsonStr, "State", siir_state );
		jsonStr	= addToJSONStr( jsonStr, "Zip1", siir_zip1 );
		jsonStr	= addToJSONStr( jsonStr, "Zip2", siir_zip2 );
		jsonStr	= addToJSONStr( jsonStr, "ContactFirstName", siir_contactFirstName );
		jsonStr	= addToJSONStr( jsonStr, "ContactLastName", siir_contactLastName );
		jsonStr	= addToJSONStr( jsonStr, "ContactTitle", siir_contactTitle );
		jsonStr	= addToJSONStr( jsonStr, "Email", siir_email );
		jsonStr	= addToJSONStr( jsonStr, "Phone", siir_phone );
		jsonStr	= addToJSONStr( jsonStr, "ReqFirstName", siir_reqFirstName );
		jsonStr	= addToJSONStr( jsonStr, "ReqLastName", siir_reqLastName );
		jsonStr	= addToJSONStr( jsonStr, "ReqEmail", siir_reqEmail );
		jsonStr	= addToJSONStr( jsonStr, "InstType", thisInst );
		jsonStr	= addToJSONStr( jsonStr, "SchoolSystem", siir_schoolSystem );
		jsonStr	= addToJSONStr( jsonStr, "SchoolType", siir_schoolType );
		jsonStr	= addToJSONStr( jsonStr, "AgeRange", siir_ageRange );
		jsonStr	= addToJSONStr( jsonStr, "NumStudents", siir_numStudents );
		jsonStr	= addToJSONStr( jsonStr, "LibrarySystem", siir_librarySystem );
		jsonStr	= addToJSONStr( jsonStr, "HowHeard", siir_howHeard );
		jsonStr	= addToJSONStr( jsonStr, "Other", siir_other );
		jsonStr	= addToJSONStr( jsonStr, "RenewalID", siir_renewalID );
		jsonStr	= addToJSONStr( jsonStr, "SAChanging", siir_saChanging );
		jsonStr	= addToJSONStr( jsonStr, "ContactDirectly", siir_contactDirectly );

	if ( debug ) {
		alert( "jsonStr = [" + jsonStr + "]" );
	}

	callDB( "sendInstInfoRequest", jsonStr, function( data ) {

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

			// set curResults global var so formConfirm can know whether the function was a success or error

		curResults = ( returnObj[ "results" ] );
		var curError = ( returnObj[ "error" ] );

			//show confirmation or error message

		formConfirm( 'sendInstInfoRequest', 'Your request for information has been submitted', curError );

		if ( category == 'its' ){		// if this form is for ITS users

			var message = "";

			if ( page == 'freeweek' ){			// if this is the free week request form

				if ( debug ) {
					alert( "this is an Itslearning freeweek form, now sending email to Carl" );
				}

				message = "An Itslearning User has signed up for a free week";

				if ( debug ) {
					alert( "now submitting event tracking" );
				}

				try {
  					_gaq.push(['_trackEvent', 'Itslearning', 'Free Week Requested']);		// track event in google analytics
  				} catch(err) {
  					if ( debug ) {
  						alert( "ERROR caught trying to submit event tracking for Itslearning free week request, now logging message" );
  					}
  					logErrorMessage( 'Error Caught : Submitting Event Tracking : Itslearning Free Week Request' );
  				}

			}

			message = (	message +
						"\n School/Org Name: - " + siir_name +
						"\n Site Name: - " + siir_schoolSystem );

			sendEmail( message );			// send as email to Carl, so he knows to set it up

		}


	});

	if ( debug ) {
		alert( "Done sendInstInfoRequest" );
	}
}


//
// sendtrackingrequest -- uses the XMLHttpRequest object to send a tracking request to
// the server.  Any response is ignored.
//		** This routine is not currently in use **
/*
function sendtrackingrequest( message, insubdir ) {
       var debug       = false;

       if ( debug ) {
               alert( "In sendtrackingrequest:\n" +
                               "message = [" + message + "]\n" +
                               "insubdir = [" + insubdir + "]" );
       }

       if ( message == undefined ) {
               message = "";
       }

       if ( insubdir == undefined ) {
               insubdir = false;
       }

               // Create the request object

   if ( window.XMLHttpRequest ) {

       // Use native XMLHttpRequest object

               req = new XMLHttpRequest();
   } else if ( window.ActiveXObject ) {

       // Use IE/Windows ActiveX version

       req = new ActiveXObject( "Microsoft.XMLHTTP" );
       }

               // Build the POST fields

       if ( debug ) {

               alert( "document.referrer = [" + document.referrer + "]" );
               alert( "location.host = [" + location.host + "]" );
       }
       var url = "";
       if ( insubdir ) {
               url     += "../";
       }
       url     += "Logic/TrackHTMLpage.aspx";
       if ( debug ) {
               alert( "url = [" + url + "]" );
       }
       var fieldstr    = "url=" + location.pathname +
                                               "&message=" + message +
                                               "&referrer=" + document.referrer;

       if ( debug ) {
               alert( "fieldstr = [" + fieldstr + "]" );
       }

               // Send the request

       req.open( "POST", url, true );
       req.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded' );
       req.setRequestHeader( "Content-length", fieldstr.length );
       req.setRequestHeader( "Connection", "close" );
       req.send( fieldstr );

       if ( debug ) {
               alert( "Done sendtrackingrequest" );
       }

}
*/


//
// sendPassword -- calls the DB with the sendPassword command
//
function sendPassword() {
	var debug	= false;
	if ( debug ) {
		alert( "In sendPassword" );
	}

	var email		= $( "#sie_email" ).val();
	var username	= $( "#sie_username" ).val();
	if ( debug ) {
		alert( "email = [" + email + "]\n" +
				"username = [" + username + "]\n" +
				"" );
	}

	var jsonStr	= addToJSONStr( jsonStr, "email", $( "#sie_email" ).val() );
		jsonStr	= addToJSONStr( jsonStr, "username", $( "#sie_username" ).val() );

	if ( debug ) {
		alert( "jsonStr = [" + jsonStr + "]" );
	}

	callDB( "sendPassword", jsonStr, function( data ) {

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

		if ( debug ) {
			alert( "now in sendPassword anon function" );
		}

			// set curResults global var so formConfirm can know whether the function was a success or error

		curResults = ( returnObj[ "results" ] );
		var curError = ( returnObj[ "error" ] );

			//show confirmation or error message

		formConfirm( 'sendPassword', 'Your password has been sent to the email provided.\n\nThis email is automatically generated and may have been filtered into your Spam or Junk folders.', curError );

	});

	if ( debug ) {
		alert( "Done sendPassword" );
	}
}


//
// setHLG -- runs on bookshelf, checks IP and shows "Home Listening Game" only for schools, teachers and SAs.
//         - the function is triggered in checkIPAddress
//
function setHLG () {
	var debug = false;

    var userType = $.cookie( "userType" );

    if ( debug ) {
    	alert( "now in setHLG" );
    	alert( "cookies are userType is [" + userType + "]" );
    }

    if (
    	( userType == "teacher" ) ||
    	( userType == "schooladmin" ) ||
    	( userType == "school" )  ||
    	( userType == "schoolIP" )  ||
    	( userType == "itsTeacher" )
    	) {

    		$( '.HLG' ).show();

    } else {

    	$( '.HLG' ).hide();

    }

    if (
    	( userType == "teacher" ) ||
    	( userType == "schooladmin" ) ||
    	( userType == "itsTeacher" )
    	) {

    		$( '.HLG_QA' ).show();

    } else {

    	$( '.HLG_QA' ).hide();

    }

    if ( debug ) {
    	alert( "done in setHLG" );
    }
}


//
// setInfoBanner - sets the details of the info banner
//
function setInfoBanner() {

	if ( BANNER_STATUS != 'on' ) {

		// do nothing

	} else {

		$('#infoBanner').text( BANNER_SUBJECT );
		$('#infoBanner').slideDown( 3000 );

		$('#infoBanner').click( function() {

			showAlert( BANNER_BODY );

		});

	}

	if ( HOL_BANNER_STATUS != 'on' ) {

		// do nothing

	} else {

		$('#infoBanner').text( HOL_BANNER_SUBJECT );
		$('#infoBanner').slideDown( 3000 );

		$('#infoBanner').click( function() {

			showAlert( HOL_BANNER_BODY, 'true' );		// the second param says that this is a holiday message

		});

	}

}


//
// setLogInArea -- checks cookies and sets the upper-right-hand corner log in area
//
function setLogInArea() {

	var debug = false;

	if ( debug ) {
		alert( "now in setLogInArea" );
	}

		// just in case setLogInArea is being run after a page has been set up (i.e. as a result of changed cookies),
		//	 we need to set all log in areas back to default hidden

	$( '.logInAreaDiv' ).each( function() {

		$( '.logInAreaDiv' ).addClass( 'notShown' );
		$( '.logInAreaDiv' ).hide();

	});

	$( '#public' ).removeClass( 'notShown' ).css( 'display','inline' );

	var userType = $.cookie( "userType" );

	if (( userType != null )
			&& ( userType != undefined )
			&& ( userType != "" )) {

			if ( debug ) {
				alert( "userType is set, it is [" + userType + "]" );
			}

			// a user has logged in, the userType cookie has been set

			// pass the cookie value here and show the correct Log In Area div

		$( '#public' ).css( 'display','none' ).addClass( 'notShown' );

		$( '#' + userType ).css( 'display','inline' ).removeClass( 'notShown' );

	} else {

		if ( debug ) {
			alert( "userType is not set" );
		}

	}

	if (( userType == 'itsStudent' )
		||( userType == 'itsTeacher' )) {

		$('.hideCat').show();
		$('#footerResubBtn').hide();
		$('#footerSubBtn').hide();

	}

	if ( userType == 'sab' ) {

		if ( debug ) {
			alert( "now calling getSABUser" );
		}

		getSABUser();

	}

		// now clear the inner html of each div NOT shown

	$( '.notShown' ).each( function() {

	    $( this ).html( '' );

	});

	populate( 'logInArea' );

		// now that the log in area is there, check the page ID to adjust opacity of the tabs

	checkPageID();

	if ( debug ) {
		alert( "done in setLogInArea" );
	}
}


//
// setInfoCookies -- runs getUser and getInstitution and sets cookies basic info used in the Log In Area
//					For example, if an user is logged in, the Log In Area has that users name, so the name is stored in a cookie and retrieved on each page
//					The param is either a suffix to a redirect or 'none' for no redirect.
//
function setInfoCookies( urlSuffix ) {

	var debug = false;

	if ( debug ) {
		alert( "now in setInfoCookies" );
	}

	var jsonStr = "";

	if ( debug ) {
		alert( "now calling getUser" );
	}

	callDB( "getUser", jsonStr, function( data ) {

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

		if ( returnObj[ "results" ] == 'success' ) {

		if ( debug ) {
			alert( "getUser is success" );
		}

				// set the first and last name as escaped cookies, to populate the log in area

			var thisFN = returnObj[ "FirstName" ];

			var thisLN = returnObj[ "LastName" ];

			thisFN = escape( thisFN );

			thisLN = escape( thisLN );

			var thisFullName = "FN=" + thisFN + ";LN=" + thisLN + "";

			if ( debug ) {
				alert( "thisFN is [" + thisFN + "] and thisLN is [" + thisLN + "] and thisFullName is [" + thisFullName + "]");
			}

			$.cookie( "fullname", thisFullName, { path: '/', domain: DOMAIN_NAME });

		} else {

			if ( debug ) {
				alert( "getUser is error" );
			}

		}

		data = "";
		returnObj = {};
		jsonStr = "";

		if ( debug ) {
			alert( "now calling getInstitution" );
		}

		callDB( "getInstitution", jsonStr, function( data ) {

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

			if ( debug ) {
				alert( "In getInstitution anon function, data = [" + data + "]" );
			}

			if ( returnObj[ "results" ] == 'success' ) {

				if ( debug ) {
					alert( "getInstitution is success" );
				}

					// set the first and last name as escaped cookies, to populate the log in area

				var thisInstName = returnObj[ "InstName" ];

				if ( debug ) {
					alert( "thisInstName is [" + thisInstName + "]" );
				}

				thisInstName = escape( thisInstName );

				$.cookie( "instname", thisInstName, { path: '/', domain: DOMAIN_NAME });


				var thisInstID = returnObj[ "InstID" ];

					// set thisInst cookie

				$.cookie( 'thisInst', thisInstID, { path: '/', domain: DOMAIN_NAME } );

				var thisExpDate = returnObj[ "AccessExpirationDate" ];

				$.cookie( 'expDate', thisExpDate, { path: '/', domain: DOMAIN_NAME } );

			} else {

				if ( debug ) {
					alert( "getInstitution is error" );
				}

			}

				// now put the suffix into this redirect

			var thisURLSuffix = urlSuffix;

			if ( thisURLSuffix != 'none' ) {

			    document.location = ( prefix + thisURLSuffix );

			} else {

			    if ( debug ) {
			    	alert( "the param is none, so no redirect" );
			    }

			}

		});

	});

	if ( debug ) {
		alert( "done in setInfoCookies" );
	}
}

//
// setStatus -- runs on bookshelf, checks IP and shows "Home Listening Game" only for schools, teachers and SAs.
//         - the function is triggered in checkIPAddress
//
function setStatus () {
    var debug = false;

    var userType = $.cookie( "userType" );

    if ( debug ) {
    	alert( "now in setStatus" );
    	alert( "cookies are userType is [" + userType + "]" );
    }

    $( '#forHomes' ).hide();
    $( '#forSchools' ).hide();

    if (
    	( userType == "teacher" ) ||
    	( userType == "schooladmin" ) ||
    	( userType == "sab" ) ||
    	( userType == "schoolIP" ) ||
    	( userType == "school" )
    	) {

   		$( '#forSchools' ).show();

    } else if (
    	( userType == "home" ) ||
    	( userType == "sab" ) ||
    	( userType == "parent" )
    	) {

    	$( '#forHomes' ).show();

    }

    if ( debug ) {
    	alert( "done in setHLG" );
    }
}


//
// shareFB -- generates page-specific facebook link onclick of the facebook share btn
//				The goal of this routine is to build this url: http://www.facebook.com/sharer/sharer.php?u=" + escape( "document.URL" )
//
function shareFB() {
	var debug = false;

	if ( debug ) {
		alert( "now in shareFB" );
	}

	var curURL = escape( document.location.href );

	if ( debug ) {
		alert( "curURL is [" + curURL + "]" );
	}

	var newPage = "http://www.facebook.com/sharer/sharer.php?u=" + curURL;

	if ( debug ) {
		alert( "newPage is [" + newPage + "]" );
	}

	window.open( newPage, "_blank" );

	if ( debug ) {
		alert( "done in shareFB" );
	}

}


//
// shareTWT -- generates page-specific twitter link onclick of the twitter share btn
//				The goal of this routine is to build: http://twitter.com/share?original_referer=" + escaped URL + "&text=" + escaped page title
//
function shareTWT() {
	var debug = false;

	if ( debug ) {
		alert( "now in shareTWT" );
	}

	var curURL = escape( document.location.href );

	var curTitle = escape( document.title );

	if ( debug ) {
		alert( "curURL is [" + curURL + "] and curTitle is [" + curTitle + "]" );
	}

	var newPage = "http://twitter.com/share?original_referer=" + curURL + "&text=" + curTitle;

	if ( debug ) {
		alert( "newPage is [" + newPage + "]" );
	}

	window.open( newPage, "_blank" );

	if ( debug ) {
		alert( "done in shareTWT" );
	}

}


//
// showAlert -- shows an alert with a message passed through as a param
//
function showAlert( message, holiday ) {

	var thisMess = message;

	startPopup( 'alert' );

	$('#alertMessageSpan').html( thisMess );

	if ( holiday == 'true' ){

		$( '#popup11 a.popupClose11.close11' ).hide();

		$( '#popup11 .bottomLinkSpan' ).html( '<b style="font-size:125%"><a href="/subscribe/homesubscription.html">Subscribe now!</a></b>' );

	}

}


//
// showBook --  Send A book Book Selector
//
function showBook( bookList ) {
	var debug = false;

	if ( debug ) {
		alert( " function triggered " );
	}

	var chosenBook = bookList.options[ bookList.selectedIndex ].value;

	if ( debug ) {
		alert( " var created " );
	}

	document.getElementById( "bookCover" ).src = chosenBook;

	if ( debug ) {
		alert( " getElementById completed " );
	}
}

//
// showICRI -- hides and shows the ICRI div on the aboutourbooks.html page
//
function showPreview( type, action ) {

	var debug = false;

	if ( debug ) {
		alert( "now in showICRI() and action is [" + action + "]" );
	}

	var doThis = action;
	var thisType = type;

	if ( doThis == 'show' ) {

		$( '#' + thisType + 'Div' ).slideDown('slow');

	} else if ( doThis == 'hide' ) {

		$( '#' + thisType + 'Div' ).slideUp('slow');

	}

	if ( debug ) {
		alert( "done in showICRI" );
	}

}


//
// slideSwitch -- Slideshow on the home page- simple carousal of three images on homepage
//
function slideSwitch() {
    var $active = $( '#slideshow IMG.active' );

    if ( $active.length == 0 ) $active = $( '#slideshow IMG:last' );

    var $next =  $active.next().length ? $active.next()
        : $( '#slideshow IMG:first' );


    $active.addClass( 'last-active' );

		// Set the transition effect

    $next.css({opacity: 0.0})
        .addClass( 'active' )
        .animate({opacity: 1.0}, 1000, function() {
            $active.removeClass( 'active last-active' );
        });
}

	// Set how long it waits on each slide

$( function() {
    setInterval( "slideSwitch()", 5000 );
});

//
// srcFixer -- fixes the source link of an image, making it correctly relative to the root
// 					Must run after getLocation, because it uses Global Variable prefix (see above)
//
function srcFixer() {
	var debug = false;

		// for each img with this class

	$( ".imgSrcFix" ).each(function () {

			// get the src

		var srcFile = $(this).attr( "src" );

		if ( debug ) {
			alert( "srcFile = [" + srcFile + "]" );
			}

			// put the src page, with the correct prefix (for example '../../' )

		$(this).attr( "src", prefix + srcFile );

	});

}


//
// startPopup -- is called in the onclick to trigger the pop up
//
// param is the pop up ID so we know which pop up to effect: might be numbers or a string, the switch
// converts string to number
// param is used as a string literal to pass on to the id and class tags that we manipulate
//
// Pop ups numbers, their string params and their content
// 1 - 'whatisoms' - 'What is OMS?' on home page
// 2 - 'privacy' - Privacy Policy on every page
// 3 - 'terms' - Terms of Agreement on every page
// 4 - 'classlist'- Help: Class List on classlist.html
// 5 - 'masterlist' - Help: Master Student List on masterstudentlist.html
// 6 - 'pplog' - Parents Place Log In
// 7 - 'tplog' - Teachers Place Log In
// 8 - 'books' - 'How We Organize Our Books' on bookshelves.html
// 9 - 'tppassword' - Change your Password (TP) on teachersplace.html
// 10 - 'formConfirmation' - confirmation messages relating to various forms throughout the site
//
// Put this function in the onclick on the link text or img
//
function startPopup( popID ) {
	var debug	= false;
	if ( debug ) {
		alert( "In startPopuup:\n" +
				"popID = [" + popID + "]\n" +
				"popupStatus = [" + popupStatus + "]\n" +
				"document.activeElement = [" + document.activeElement + "]\n" +
				"" );
	}


	if ( document.activeElement ) {
		lastFocus	= document.activeElement;
	}

	var thisPop 	= popID;
	var thisHTML	= "";
	var thisNum		= 0;		// Missing var declaration added by MDE.  Better name would be popUpNum

	switch( thisPop ) {

		case "whatisoms":
			thisNum = 1;
			break;

		case "privacy":
			thisNum = 2;
			thisHTML = '<a class="popupClose2 closeTop">X</a><span class="h1">Privacy Policy</span><div class="contactArea"><p>OneMoreStory.com is committed to complying fully with the Children&#39;s Online Privacy Protection Act of 1998. Our information collection practices are described below. We encourage children to check with their parent or guardian before entering any information on any website and we urge parents and guardians to discuss with their children restrictions regarding the online release of personal information to anyone they don&#39;t know.</p><br /><span class="h2">What Information Is Collected?</span><br /><div class="smallText"> OneMoreStory.com&#39;s target audience is children aged two through nine and their parents. OneMoreStory.com offers subscriptions to our parent audience. Paid subscriptions allow the parent or the parent&#39;s child access to our entire library of online books. In order to participate in our subscription activities, we ask parents to submit personal information (e.g. full name, address, e-mail address and credit card information). All such personal information is collected for the purpose of providing our users access to OneMoreStory.com&#39;s library. Subscribers may opt to receive newsletters or information from us via email. Subscribers may always opt out from receiving newsletters or other emails from us by electing to unsubscribe to such correspondence, which option can be found in all of our emails sent to users. OneMoreStory.com may also offer its users the option to purchase certain products, such as hard copies of the books in our library, directly from our site or by linking to a publisher&#39;s site. In the event a user wishes to purchase products from our site, we require personal information, such as name, shipping address and billing information, in order to fulfill the order. It is OneMoreStory.com&#39;s policy not to collect any personally identifiable information from our child users. We generally only require non-personal information such as an online username or first name in order to personalize the reading experience.</div><br /><span class="h2">Use of Information</span><br /><div class="smallText">OneMoreStory.com may use personal information for the purpose of contacting parents about their account, or to notify them of new features at the site. We do not currently disclose personally identifiable information that users provide to any third parties. We may, however, disclose personally identifiable information to third parties pursuant to applicable law, court order, or to protect the rights, property, or safety of our site and its users.</div><br /><span class="h2">Cookies and Log Data</span><br /><div class="smallText">&quot;Cookies&quot; are information files that your web browser places on the hard drive of your computer when you visit a site. OneMoreStory.com does not currently use cookies to profile users on its site. OneMoreStory.com is not responsible for the cookie policies at other sites when a user links to another site by first visiting <a href="http://www.onemorestory.com/">www.onemorestory.com</a>. Keep in mind, the only personal information a cookie can contain is information that the user itself supplies. A user can always refuse cookies by turning them off in the user&#39;s browser. No user must have cookies turned on to use OneMoreStory.com&#39;s site. Log data collected on our web servers supplies OneMoreStory.com with information about the number of visits to different pages on our site. We use this information in connection with our licensing agreements with publishers. We do not link the log data collected to the personal information that parents of children submit online when participating in our activities.</div><br /><span class="h2">Questions/Concerns?</span><br /><div class="smallText">If you have any questions, comments or concerns regarding OneMoreStory.com&#39;s privacy policy, please contact us at:<br />One More Story, Inc.<br />374 Bond Street<br />Brooklyn, NY 11231<br />(212) 925-9416<br /><span class="hideEmail">contactus</span><br /><br />This policy is subject to change as we develop and expand our product and services. We encourage you to periodically review this policy to familiarize yourself with our policies. The OneMoreStory.com website is currently intended for domestic visitors and is, consequently, specifically directed towards residents of the United States.</div><br /><span class="h2">Your California Privacy Rights</span><br /><div class="smallText">Beginning on January 1, 2005, California Civil Code Section 1798.83 permits our visitors who are California residents to request certain information regarding its disclosure of personal information to third parties for their direct marketing purposes. To make such a request, please send an e-mail to <span class="hideEmail">contactus</span> or write us at the address above.<br /><br /><center><a class="popupClose2 closeBottom">Close This Window</a></center></div></div>';
			break;

		case "terms":
			thisNum = 3;
			thisHTML = '<a class="popupClose3 closeTop">X</a><span class="h1">Terms of Agreement</span><div class="smallText"> Welcome to OneMoreStory.com (&quot;OMS&quot;). This is a legal contract outlining the rights of our institutional users such as school districts, public and private schools, libraries and hospitals (&quot;Participating Institution&quot;). You cannot access OMS&#39;s site (the &quot;Site&quot;) as an OMS Participating Institution until you have created an account (the &quot;Account&quot;) and read and agreed to the terms and conditions outlined below. As a Participating Institution, you will also be subject to OMS&#39;s Privacy Policy, which is incorporated by reference herein (together with this agreement, the &quot;Terms of Service&quot;).<br /><br />Please note that in order to meet the changing needs of the Internet business, OMS may, for any reason and at any time, update or change any of the provisions contained in the Terms of Service. OMS agrees to promptly notify you of any material changes that it implements. You may access an updated version of the Terms of Service at any time by visiting <a href="http://www.onemorestory.com/">www.onemorestory.com</a> and clicking on &quot;Terms of Use.&quot; If you do not wish to be subject to the terms of a revised agreement, your only remedy is to cancel your OMS subscription in accordance with the procedures set forth herein.<br /><br />I. GENERAL TERMS<br /><br />This agreement represents the terms and conditions governing your institution&#39;s use of the Site. The Terms of Service represents the entire agreement between your institution and OMS. This agreement may not be amended without the prior written approval of OMS, nor may you assign any of your rights or obligations to another person, school or institution without OMS&#39;s written consent.<br /><br />You will be responsible for all use of your account; including use of your account by any authorized users. &quot;Authorized Users&quot; are defined for schools as teachers, administrative personnel employed by your school or school district, registered students of your school or school district and authorized guests; for libraries library personnel and library users within the premises of the library; and for hospitals hospital personnel, patients and authorized guests within the premises of the hospital. Only Authorized Users shall be permitted access to the Site though your account. You agree not to allow access to the Site by any unauthorized users. Authorized users may only access the Site on the grounds of your institution.<br /><br />You expressly agree that the use of OMS Site is at your sole risk. OMS&#39;s Site, software, services and content are provided to you &quot;AS IS&quot; AND &quot;AS AVAILABLE&quot;. All warranties, express or implied, are disclaimed to the extent permissible by law (including, but not limited to, the disclaimer of any implied warranties of merchantability and fitness for a particular purpose). The information in said software/services may contain bugs, errors, problems or other limitations.<br /><br />OMS assumes no liability or responsibility for any errors or omissions contained in the content of the site. YOUR SOLE REMEDY AND OMS&#39;S ENTIRE LIABILITY WITH RESPECT TO THE USE OF OMS SITE AND SERVICE OR FOR DISSATISFACTION WITH YOUR SERVICE OR ACCOUNT SHALL BE TERMINATION OF YOUR ACCOUNT. OMS SHALL NOT BE LIABLE FOR ANY CONSEQUENTIAL OR INCIDENTAL DAMAGES ARISING FROM YOUR USE OF THE SITE, THE INTERNET OR FOR ANY OTHER CLAIM RELATED IN ANY WAY TO YOUR ACCOUNT (OR, IN THE EVENT THAT ANY LAW LIMITS OMS&#39;S ABILITY TO LIMIT ITS LIABILITY IN ANY WAY, OMS&#39;S LIABILITY SHALL BE LIMITED TO THE EXTENT PERMITTED BY LAW.)<br /><br />II. ACCESS TO CONTENT<br /><br />All services that OMS provides to you may only be used for lawful purposes. Text, software, communications, images, sounds, information, data, or material (&quot;Content&quot;) may not be transferred or stored in violation of any United States Federal or state statute, regulation or law. This includes, but is not limited to, material protected by copyright, trade secret, or any other statutes, laws or regulations, as well as threatening or obscene material. You agree to indemnify and hold harmless OMS from any and all claims resulting from your, or any Authorized User&#39;s, use of OMS&#39;s Site which results in damages either to you or to any third party or parties. OMS will not be responsible for any damage you might suffer from the use of OMS&#39;s Site.<br /><br />You understand that much of the Content available on OMS&#39;s Site, such as original literary works and artwork, is not owned by OMS, but is likely owned by someone else. This Content is protected by copyrights, trademarks, etc. Under no circumstances may you upload, download, copy, transmit, modify, distribute, show in public or create any derivative work from any Content that you access from our Site. Engaging in any of the above actions will result in termination of your OMS account and possible legal action - civil or criminal - by OMS, the government or the Content owners. In the event that any legal action is brought against you due to your improper use of Content, you agree to hold harmless OMS, its subsidiaries, affiliates related companies, officers, directors, employees and agents.<br /><br />You also understand that some of the areas of OMS&rsquo;s Site service are &quot;public&quot; areas in that other Participating Institutions will have access to your posted material and might copy, modify, upload, download or distribute it. You hereby represent that any material that you submit or post on-line is either owned by you or you are authorized to distribute it. Once you post or submit material, you expressly grant OMS the complete right to use, reproduce, modify, distribute, etc. the Content anywhere in any form.<br /><br />III. TERMINATION<br /><br />Either you or OMS may terminate your account at any time. You understand that your only remedy in any dispute that you might have with OMS is the termination of your account. You can terminate your membership at any time by delivering written notice to OMS at: <span class="hideEmail">unsubscribe</span>. <br /><br />OMS reserves the right to collect any fees, charges or costs incurred prior to your cancellation of your account.<br /><br />By submitting a Subscription Form along with your annual fee, and through your continued use of the Site, you, as a Participating Institution, agree to abide by these Terms and Conditions.<br /><br /><center><a class="popupClose3 closeBottom">Close This Window</a></center></div><br />';
			break;

		case "classlist":
			thisNum = 4;
			thisHTML = '<a class="popupClose4 closeTop">X</a>' +
			'<span class="h1">Help: Class List (4)</span><br /><br />' +
			'<p class="contactArea"> The Your Class List page is for you, the teacher, to manage the accounts of students using One More Story in your classroom. <br /><br />Using the fields in the <b>&quot;Add a New Student&quot;</b> box, you can enter the first and last names, and create a user name and password for each student. Click the <img src="../img/btn_addSm.png" alt="Add Student" /> icon to add that student to your Master Student List.' +
			'<br /><br />You can <b>upload a student list</b> by clicking the <img src="../img/btn_uploadSm.png" alt="Upload List" /> icon. The document selected must be a .csv file, which you can create easily from any spreadsheet application, such as Microsoft Excel. The minimum columns in the spreadsheet must be (in order): Last name, First name. To see a sample class list with all possible columns, <a href="../teachersplace/OMS_SampleStudentList.csv">click here</a>. Note: usernames and passwords will be automatically generated if left blank.' +
			'<br /><br />In the <b>&quot;Class List&quot;</b> box you can review a individual student&rsquo;s account information and usage details, or remove students&rsquo; accounts. Clicking the <img src="../img/btn_viewSm.png" alt="View More" /> icon will take you to a Student Details page where you can review their Activity Log. The <img src="../img/btn_mailSm.png" alt="Send email" /> icon will generate an email to a students&rsquo; parents. To remove a student&rsquo;s account at any time, click the <img src="../img/btn_trashSm.png" alt="Remove Student" /> icon and that student&rsquo;s information and account access will be eliminated.' +
			'<br /><br /><b>&quot;Settings for All Students&quot;</b> will affect all One More Story student accounts at your school.  If your school has a Universal Access subscription to One More Story, click the Universal Access <img src="../img/btn_checkOnSm.png" alt="Universal Access: On" /> icon to toggle between allowing and disallowing home access for your students.  You can then choose whether or not your students will have access to the Listening Game from their home accounts by clicking the Listening Game <img src="../img/btn_checkOnSm.png" alt="Universal Access: On" /> icon.  Use the <img src="../img/btn_trashSm.png" alt="Remove ALL Students" /> icon ONLY when you want to purge your ENTIRE Class List.  <i>WARNING: a deleted Class List CANNOT be retrieved.</i>' +
			'<br /><br />The <b>&quot;View Class Reports&quot;</b> box is your portal to your students&rsquo; activity on One More Story.  Use these the <img src="../img/btn_activityLogSm.png" alt="View Activity Log" /> icon to access information about what books students have read, when they read them, and their Listening Game results.' +
			'<br /><br /> <b>&quot;Additional Options&quot;</b> allow you to send out emails to parents of students using One More Story at your school.  You can also print your Master Student List by clicking the <img src="../img/btn_printSm.png" alt="Print" /> icon. </p> ' +
			'<center><a class="popupClose4 closeBottom">Close This Window</a></center>';
			break;

		case "masterlist":
			thisNum = 5;
			thisHTML = '<a class="popupClose5 closeTop">X</a>' +
			'<span class="h1">Help: Master Student List (5)</span>' +
			'<br /><br /><p class="contactArea"> The Master Student List page is for you, the school&rsquo;s One More Story administrator, to manage the accounts of students using One More Story at your school.  <br /><br />Using the fields in the <b>&quot;Add a New Student</b> box, you can enter the first and last names, and create a user name and password for each student.  Click the <img src="../img/btn_addSm.png" alt="Add Student" /> icon to add that student to your Master Student List.' +
			'<br /><br />You can <b>upload a student list</b> by clicking the <img src="../img/btn_uploadSm.png" alt="Upload List" /> icon. The document selected must be a .csv file, which you can create easily from any spreadsheet application, such as Microsoft Excel. The minimum columns in the spreadsheet must be (in order): Last name, First name. To see a sample class list with all possible columns, <a href="../teachersplace/OMS_SampleStudentList.csv">click here</a>. Note: usernames and passwords will be automatically generated if left blank.' +
			'<br /><br />In the &quot;Master Student List&quot; box you can review a individual student&rsquo;s account information and usage details, or remove students&rsquo; accounts.  Clicking the <img src="../img/btn_viewSm.png" alt="View More" /> icon will take you to a Student Details page where you can review their Activity Log.  To remove a student&rsquo;s account at any time, click the <img src="../img/btn_trashSm.png" alt="Remove Student" /> icon and that student&rsquo;s information and account access will be eliminated.' +
			'<br /><br /><b>&quot;Settings for All Students&quot;</b> will affect all One More Story student accounts at your school.  If your school has a Universal Access subscription to One More Story, click the Universal Access <img src="../img/btn_checkOnSm.png" alt="Universal Access: On" /> icon to toggle between allowing and disallowing home access for your students.  You can then choose whether or not your students will have access to the Listening Game from their home accounts by clicking the Listening Game <img src="../img/btn_checkOnSm.png" alt="Listening Game: On" /> icon.  Use the <img src="../img/btn_trashSm.png" alt="Remove ALL Students" /> icon ONLY when you want to purge your ENTIRE Master Student List. <i>WARNING: a deleted Master Student List CANNOT be retrieved.</i>' +
			'<br /><br /><b>&quot;Additional Options&quot;</b> allow you to send out emails to parents of students using One More Story at your school.  You can also print your Master Student List by clicking the <img src="../img/btn_printSm.png" alt="Print" /> icon.</p><br />' +
			'<center><a class="popupClose5 closeBottom">Close This Window</a></center>';
			break;

		case "pplog":
			thisNum = 6;
			thisHTML = '<a class="popupClose6 closeTop">X</a>  <div class="logIn"> <center><span class="h1">Parents&rsquo; Place</span><br /><br /><br /><form class="validForm" name="validForm" method = "post" action = "javascript: callDB();"><table width="" border="0" cellspacing="10"><tr><td align="right"><span class="h1"><label for="passwordPP">Password:</label></span></td><td align="left"><input name="passwordPP" type="password" value="" id="pppassword" size="13" onkeydown="if (event.keyCode == 13) { document.getElementById(\'ppLoginBtn\').click(); return false; }" /></td></tr><tr><td colspan="2" align="left"><br /><center><input class="submit styledBtn_Wh" id="ppLoginBtn" type="submit" value="Submit" onclick="javascript: loginPPTPUser( \'pp\' );" /></center><br /><br /><div class="smallText"><a href="http://' + DOMAIN_NAME + '/other/forgot.html">Forgot Your Password?</a><br />Note: This password may not be the same as the login for One More Story.</div> </td></tr></table></form></center> </div>';
			break;

		case "tplog":
			thisNum = 7;
			thisHTML = '<a class="popupClose7 closeTop">X</a><div class="logIn"><center><span class="h1">Teachers&rsquo; Place</span><br /><br /><br /><form class="validForm" name="validForm" method = "post" action = "javascript: callDB();"><table width="" border="0" cellspacing="10"><tr><td align="right"><span class="h1"><label for="usernameTP">Username:</label></span></td><td align="left"><input name="usernameTP" type="text" id="tpusername" size="13" /></td></tr><tr><td align="right"><span class="h1"><label for="passwordTP">Password:</label></span></td><td align="left"><input name="passwordTP" type="password" id="tppassword" size="13" onkeydown="if (event.keyCode == 13) { document.getElementById(\'tpLoginBtn\').click();return false; }"/></td></tr><tr><td colspan="2" align="left"><br /><center><input class="submit styledBtn_Wh"id="tpLoginBtn" type="submit" value="Submit" onclick="javascript: loginPPTPUser( \'tp\' );" /></center><br /><br /><div class="smallText"><a href="http://' + DOMAIN_NAME + '/other/forgot.html">Forgot Your Password?</a><br />Note: Both teachers and administrators log in here. If you aren&#39;t sure of your username, try your email address.</div></td></tr></table></form></center></div>';
			break;

		case "books":
			thisNum = 8;
			thisHTML = '<a class="popupClose8 closeTop">X</a>  <span class="h1">How We Organize Our Books</span><br /><br />  <p class="contactArea">Books in the One More Story library are deliberately arranged in no particular order.  Readers find familiar titles by the color of the shelf on which the book is located and select new titles by interest rather than relying on level of difficulty.  Adults can review reading levels of books by browsing our library.</p><br />';
			break;

		case "tppassword": /* #9 NOT IN USE */
			thisNum = 9;
			thisHTML = '';
			break;

		case "formConfirmation":
			thisNum = 10;
			thisHTML = '';
			break;

		case "alert":
			thisNum = 11;
			thisHTML = "";
			break;

		case "selectFromMasterList":
			thisNum = 12;
			thisHTML = "";
			break;

		default:
			thisNum = thisPop;
			break;

	}

	/// Centering Pop Up

		// request data for centering

	if ( window.innerWidth ) {
		var windowWidth	= window.innerWidth;
	} else if ( document.documentElement && document.documentElement.clientWidth ) {
		var windowWidth	= document.documentElement.clientWidth;
	} else if ( document.body ) {
		var windowWidth	= document.body.clientWidth;
	}

	if ( window.innerHeight ) {
		var windowHeight	= window.innerHeight;
	} else if ( document.documentElement && document.documentElement.clientHeight ) {
		var windowHeight	= document.documentElement.clientHeight;
	} else if ( document.body ) {
		var windowHeight	= document.body.clientHeight;
	}

	var popupHeight2	= $( "#popup" + thisNum ).height();
	var popupWidth2		= $( "#popup" + thisNum ).width();

		//centering

	$( "#popup" + thisNum ).css({
		//"position": "absolute",
		"top": windowHeight/2-popupHeight2/2,
		"left": windowWidth/2-popupWidth2/2

	});

		// only need force for IE6

	$( "#backgroundPopup" ).css({
		"height": windowHeight
	});

		/// Load Pop Up

		//loads popup only if it is disabled

	if ( popupStatus == 0 ) {
		$( "#backgroundPopup" ).css({
			"opacity": "0.7"
		});

		$ ( "#backgroundPopup" ).fadeIn( "slow" );
		$( "#popup" + thisNum ).fadeIn( "slow" );

			//scroll to top

		$( 'html, body' ).animate({
			scrollTop: '0px'
		}, 1500 );
		popupStatus = 1;

	}

		// write the HTML content of the appropriate div

	if ( thisHTML != "" ) {
		$( '#popup' + thisNum ).html( thisHTML );
	}

		// set the focus, if the pop up has a form

	if ( thisNum == 7 ) {
		if ( debug ) {
			alert( "setting focus to TP field" );
		}
		$( '#tpusername' ).focus();

			// set focus to this window

		//window.focus();    // Did not work!

	} else if ( thisNum == 6 ) {
		if ( debug ) {
			alert( "setting focus to PP field" );
		}
		$( '#pppassword' ).focus();

			// set focus to this window

		//window.focus();   // Did not work!

	}


		// Create the events that would close the pop up.  Note calls to disablePopup were missing thisNum
		// thisNum got created globally when it was just used in the old code above.  However, after declaring
		// it it no longer existed globally in scope

		//Click the x event

	$( ".popupClose" + thisNum ).click( function() {
		disablePopup( thisNum );
	});

		//Click out event

	$( "#backgroundPopup" ).unbind( 'click' ).click( function() {
		if ( debug ) {
			alert( "now closing popup number " + thisNum );
		}
		disablePopup( thisNum );

	});

		// Press Escape event

	$( document ).keypress( function( e ) {
		if (( e.keyCode == 27 ) && popupStatus == 1 ) {
			disablePopup( thisNum );
		}

	});

	if ( debug ) {
		alert( "Done startPopup" );
	}

}


//
//  styleInputs - styles inputs and controls style-related changes to inputs on focus, blur, etc.
//				Important note: any changes made here, should also be made in loginFieldSwap() - as that mirrors a few actions below
//
function styleInputs() {

	var debug = false;

	if ( debug ) {
		alert( "now in styleInputs" );
	}

		// style for text inputs

    $( 'input[type="text"]' ).addClass( "idleField" );

    	// when

	$( 'input[type="text"]' ).focus( function() {

		$(this).removeClass( "idleField" ).removeClass( "postFocus" ).addClass( "focusField" );

			// if the value is username, select it

        if ( this.value == "Username" ) {

			this.select();

		} else if ( this.value == "Password" ) {

			// do nothing

			// otherwise, if the value is the default, clear it

		} else if ( this.value == this.defaultValue ) {

        	this.value = '';

    	}

        if ( this.value == this.defaultValue ) {

	    	this.select();

        }

    });

    	// if the current value is the default value, clear the value to make room for user input

    $( 'input[type="text"]' ).click( function() {

        if ( this.value == "Password" ) {

			// do nothing

		} else if ( this.value == this.defaultValue ) {

        	this.value = '';

    	}

    });

    $( 'input[type="text"]' ).blur( function() {

    	$(this).removeClass( "focusField" ).addClass( "postFocus" );

        if (( this.defaultValue == 'Username' ) && ( this.value == '' )) {

			( this.value = 'Username' );

			$( this ).removeClass( "postFocus" ).addClass( "idleField" );

		} else if (( this.defaultValue != '' ) && ( this.value == '' )) {

        	this.value = (this.defaultValue);

    	}

    });
    
    	// same as above for text areas
	    
    $( 'textarea' ).focus( function() {

		$(this).removeClass( "idleField" ).removeClass( "postFocus" ).addClass( "focusField" );

        if ( this.value == this.defaultValue ) {

	    	this.select();

        }

    });

    $( 'textarea' ).click( function() {

        if ( this.value == this.defaultValue ) {

        	this.value = '';

    	}

    });
    
	$( 'textarea' ).blur( function() {

    	$(this).removeClass( "focusField" ).addClass( "postFocus" );

        if (( this.defaultValue != '' ) && ( this.value == '' )) {

        	this.value = (this.defaultValue);

    	}

    });

		//style for textareas

	$( 'textarea' ).addClass( "idleField" );

	$( 'textarea' ).focus( function() {

		$(this).removeClass( "idleField" ).removeClass( "postFocus" ).addClass( "focusField" );

    });

    $( 'textarea' ).blur( function() {

    	$(this).removeClass( "focusField" ).addClass( "postFocus" );

    });

		//style for select inputs (drop down menus)

	$( 'select' ).addClass( "idleField" );

	$( 'select' ).focus( function() {

		$(this).removeClass( "idleField" ).removeClass( "postFocus" ).addClass( "focusField" );

    });

    $( 'select' ).blur( function() {

    	$(this).removeClass( "focusField" ).addClass( "postFocus" );

    });

		// style for password inputs

    $( 'input[type="password"]' ).addClass( "idleField" );

	$( 'input[type="password"]' ).focus( function() {

		$(this).removeClass( "idleField" ).removeClass( "postFocus" ).addClass( "focusField" );

    });

    $( 'input[type="password"]' ).blur( function() {

    	$(this).removeClass( "focusField" ).addClass( "postFocus" );

    });

    if ( debug ) {
		alert( "done in styleInputs" );
	}

}


//
// toggleArrow -- shows or hide the 'open' or 'close' arrow
//
function toggleArrow( classname ){
	var debug = false;

	if ( debug ) {
		alert( "now in toggleArrow, and classname is [" + classname + "]" );
	}

	if ( $( '.' + classname + '.open' ).is( ':visible' ) ){

			$( '.' + classname + '.open' ).hide();
			$( '.' + classname + '.close' ).show();

		} else {

			$( '.' + classname + '.close' ).hide();
			$( '.' + classname + '.open' ).show();

		}

	if ( debug ) {
		alert( "done in toggleArrow" );
	}

}


//
// unsubscribeMe -- gets email from URL and unsubscribes a user from our mailing list
//
function unsubscribeMe() {

	var debug = false;

	if ( debug ) {
		alert( "now in unsubscribeMe" );
	}

	var thisURL = document.URL;

	var hashLoc = ( thisURL.indexOf ( '#' )) + 1;

	var thisEmail = thisURL.slice ( hashLoc, ( thisURL.length ));

	var jsonStr	= addToJSONStr( jsonStr, "email", thisEmail );

	callDB( "optOutEmail", jsonStr, function( data ) {

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

		if ( returnObj[ 'results' ] == 'success' ) {

			$('#processing').hide();
			$('#success').show();

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

			logErrorMessage( returnObj[ 'error' ], '' );

			$('#processing').hide();
			$('#error').show();

			showAlert( "Sorry, there was a problem unsubscribing your email address. Please try again by refreshing the page. <br /><br /> If this problem persists, you can contact us directly during regular business hours and we will unsubscribe you immediately. <br />We apologize for this inconvenience." );

		}

	});

	if ( debug ) {
		alert( "now in unsubscribeMe" );
	}

}


//
//  Validation Code -- jquery validation plugin
//

// ** Metadata - jQuery plugin for parsing metadata from elements

(function($) {

$.extend({
	metadata : {
		defaults : {
			type: 'class',
			name: 'metadata',
			cre: /({.*})/,
			single: 'metadata'
		},
		setType: function( type, name ) {
			this.defaults.type = type;
			this.defaults.name = name;
		},
		get: function( elem, opts ) {
			var settings = $.extend({},this.defaults,opts);

				// check for empty string in single property

			if ( !settings.single.length ) settings.single = 'metadata';

			var data = $.data(elem, settings.single);

				// returned cached data if it already exists

			if ( data ) return data;

			data = "{}";

			if ( settings.type == "class" ) {
				var m = settings.cre.exec( elem.className );
				if ( m )
					data = m[1];
			} else if ( settings.type == "elem" ) {
				if ( !elem.getElementsByTagName )
					return undefined;
				var e = elem.getElementsByTagName(settings.name);
				if ( e.length )
					data = $.trim(e[0].innerHTML);
			} else if ( elem.getAttribute != undefined ) {
				var attr = elem.getAttribute( settings.name );
				if ( attr )
					data = attr;
			}

			if ( data.indexOf( '{' ) <0 )
			data = "{" + data + "}";

			data = eval( "( " + data + " )" );

			$.data( elem, settings.single, data );
			return data;
			}
		}
	});

	//
	// $.fn.metadata -- Returns the metadata object for the first member of the jQuery object.
	//

	$.fn.metadata = function( opts ) {
		return $.metadata.get( this[ 0 ], opts );
	};

})(jQuery);


//
// validateNow -- validates the forms when the submit buttom is click, runs the next routine (via param) and holds
// the custom error message
//
// First param is the class of the form being validated
//
// Second param is a function to run after validation is successful and before the form is submited (if it going to
// be submited.)  (NOTE: if a function must run based on whether the submit was successful, put it outside of
// validateNow, on the onClick).
// In the subscription forms, this function hides the current tab and shows the next one.
//
// Third param is the submit command - true is a standard submit, false is nothing, and any other value is the name
// of a function to run to submit.
//
function validateNow( formName, funct, subCom ) {

	var debug = false;

	if ( debug ) {
		alert( "In validateNow" );
	}

	var	formClass = formName;
	var newFunct = funct;
	var submitCommand = subCom;

	if ( debug ) {
		alert( "2 formName is [" + formName + "] and funct is [" + funct + "] and subCom is[" + subCom + "]" );
	}

	$( formClass ).validate({

		submitHandler: function( form ) {

				if ( debug ) {
					alert( "3 this is a valid form" );
				}

				if ( debug ) {
					alert( "4 newFunct is [" + newFunct + "] and submitCommand is [" + submitCommand + "]" );
				}

				if (( newFunct != null ) && ( newFunct != '' )) {
					newFunct();
				}

				switch( submitCommand ) {

					case "saveUser":

						if ( debug ) {
							alert( "about to run saveUser" );
						}

						saveUser();

						break;

					case "sendEmail":

						if ( debug ) {
							alert( "about to run sendEmail" );
						}

						sendEmail();

						break;

					case "sendPassword":

						if ( debug ) {
							alert( "about to run sendPassword" );
						}

						sendPassword();

						break;

					case "sendABook":

						if ( debug ) {
							alert( "about to run sendABook" );
						}

						sendABook();

						break;

						//sendABookAuto is just a trick to get parameters into the function here

					case "sendABookAuto":

						if ( debug ) {
							alert( "about to run sendABookAuto" );
						}

						sendABook( 'auto' );

						break;

					case "sendABookAutoSAB":

						if ( debug ) {
							alert( "about to run sendABookAutoSAB" );
						}

						sendABook( 'autoSAB' );

						break;

					case "savePassword":

						if ( debug ) {
							alert( "about to run savePassword" );
						}

						savePassword();

						break;

					case "savePasswordPP":

						if ( debug ) {
							alert( "about to run savePasswordPP" );
						}

						savePassword( 'pp' );

						break;

					case "savePasswordLogin":

						if ( debug ) {
							alert( "about to run savePasswordLogin" );
						}

						savePassword( 'login' );

						break;

					case "sendInstInfoRequest":

						if ( debug ) {
							alert( "about to run sendInstInfoRequest" );
						}

						sendInstInfoRequest();

						break;

					case "sendItsInfoRequest":

						if ( debug ) {
							alert( "about to run sendItsInfoRequest" );
						}

						sendItsInfoRequest();

						break;

					case "saveInstSubscription":

						if ( debug ) {
							alert( "about to run saveInstSubscription" );
						}

						saveInstSubscription();

						break;

					case "sendSchoolRenewal":

						if ( debug ) {
							alert( "about to run sendSchoolRenewal" );
						}

						sendSchoolRenewal();

						break;

					case "addStudentMaster":

						if ( debug ) {
							alert( "about to run addStudentMaster" );
						}

						addStudent( 'master' );

						break;

					case "addStudent":

						if ( debug ) {
							alert( "about to run sendSchoolRenewal" );
						}

						addStudent();

						break;

					case "addStudent":

						if ( debug ) {
							alert( "about to run sendSchoolRenewal" );
						}

						addStudent();

						break;

					case "saveITSInstEmail":

						if ( debug ) {
							alert( "about to run saveITSInstEmail" );
						}

						saveITSInstEmail();

						break;

					case "sendITSSchoolRenewal":

						if ( debug ) {
							alert( "about to run sendITSSchoolRenewal" );
						}

						sendITSSchoolRenewal();

						break;

					case "true" :

						if ( debug ) {
							alert( "5 submitCommand is true, now submitting form" );
						}

						form.submit();

						break;

					default:

						if ( debug ) {
							alert( "no function was specified" );
						}

						break;

				}

			},

		rules: {

				// General Use

			username: "required",
			password: "required",
			name: "required",
			email: {
				required: true,
				email: true
			},
			message: "required",

				// Contact Us

			iam: "required",

				// Send a Book

			sab_recipientName: "required",
			sab_recipient: {
				required: true,
				email: true
			},
			sab_fromName: "required",
			sab_from: {
				required: true,
				email: true
			},
			bookSelect: "required",

				// Password Recovery - reqmts

			sie_username: {
				required: "#sie_email:blank"
			},
			sie_email: {
				required: "#sie_username:blank",
				email: true
			},

				// For School / Library / Hospital Forms

			contact_firstname: "required",
			contact_lastname: "required",
			contact_title: "required",
			contact_phone: "required",
			contact_email: {
				required: true,
				email: true
			},
			req_firstname: "required",
			req_lastname: "required",
			req_email: {
				required: true,
				email: true
			},
			req_phone: "required",

				// School Subscription Form

			schoolName: "required",
			schoolSystem: "required",
			sch_address1: "required",
			sch_city: "required",
			sch_state: "required",
			sch_zipcode: {
				required: true,
				minlength: 4
			},
			sch_country: "required",
			schoolType: "required",
			ageRange: "required",
			numberUsing: "required",

				// Hospital Subscription Form

			hospitalName: "required",
			hosp_address1: "required",
			hosp_city: "required",
			hosp_state: "required",
			hosp_zipcode: {
				required: true,
				minlength: 5
			},
			hosp_country: "required",

				// Library Learn More Form

			libraryName: "required",
			librarySystem: "required",
			numberBranches: "required",
			lib_address1: "required",
			lib_city: "required",
			lib_state: "required",
			lib_zipcode: {
				required: true,
				minlength: 5
			},
			lib_country: "required",

				// Update Account

			FirstName: "required",
			LastName: "required",
			Address1: "required",
			City: "required",
			State: "required",
			Zipcode: {
				required: true,
				minlength: 5
			},
			EMail: {
				required: true,
				email: true
			},
			Phone: "required",

				// Change Password

			sp_password: {
				required: true,
				minlength: 5
			},
			sp_passwordConfirm: {
				required: true,
				equalTo: "#sp_password"
			},
			sp_passwordPP: {
				required: true,
				minlength: 5
			},
			sp_passwordConfirmPP: {
				required: true,
				equalTo: "#sp_passwordPP"
			},
			sp_old_password: "required",

				//
				// Teacher / Admins Place
				//

				//Add A New Student

			studentID: "required",
			student_firstname: "required",
			student_lastname: "required",
			student_username: "required",
			student_password: "required",
			student_gradeLevel: "required",

				//Add a Teacher

			teacher_firstname: "required",
			teacher_lastname: "required",
			teacher_email: {
				required: true,
				email: true
			},

				//Renew school sub

			numNewStudents: "required",
			ContactFirstName: "required",
			ContactLastName: "required",
			ContactEmail: {
				required: true,
				email: true
			},
			ContactPhoneNo: "required",
			purchaseType: "required",
			needBill: "required",
			newSA: "required",

				// ITS Forms

			itsfreeweek_email: {
				required: true,
				email: true
			},
			reqEmail:  {
				required: true,
				email: true
			},
			reqFirstName: "required",
			reqLastName: "requred"

		},

		messages: {

				//General Use

			username: "Please enter a username",
			password: "Please enter a password",
			name: "Please enter your full name",
			email: {
				required: "Please enter your email address",
				email: "Please enter a valid email address"
			},
			message: "Please enter a message",
			howhear: "Please enter a message",

				//Contact Us

			iam: "Please tell us your title or select Other",

				// Send a Book

			sab_recipientName: "Name required",
			sab_fromName: "Name required",
			sab_recipient: {
				required: "Email required",
				email: "Invalid email"
			},
			sab_from: {
				required: "Email required",
				email: "Invalid email"
			},
			bookSelect: "Please choose a book",

				// Recovery Your Password - messages

			sie_username: {
				required: "Please enter either your username or email address"
			},
			sie_email: {
				required: "Please enter either your username or email address",
				email: "Please enter a valid email address"
			},

				// For School / Library / Hospital Forms

			contact_firstname: "Please enter the contact's first name",
			contact_lastname: "Please enter the contact's last name",
			contact_title: "Please enter the contact's title",
			contact_phone: "Please enter a phone number",
			contact_email: {
				required: "Please enter the contact's email address",
				email: "Please enter a valid email address"
			},
			req_firstname: "Please enter your first name",
			req_lastname: "Please enter your last name",
			req_email: {
				required: "Please enter your email address",
				email: "Please enter a valid email address"
			},
			req_phone: "Please enter a phone number",

				// School Subscription Form

			schoolName: "Please enter the school's name",
			schoolSystem: "Please enter the school system",
			sch_address1: "Please enter the school's address",
			sch_city: "Please enter the school's city",
			sch_state: "Please enter the school's state",
			sch_zipcode: {
				required: "Please enter the school's zip code",
				minlength: "Please enter at least five digits"
			},
			sch_country: "Please enter the school's country",
			schoolType: "Please enter your school's type",
			ageRange: "Please enter the age range of students using OMS",
			numberUsing: "Please enter the number of students using OMS",

				// School Learn More Form

			schoolName: "Please enter the school's name",

				//Hospital Subscription Form

			hospitalName: "Please enter the hospital's name",
			hosp_address1: "Please enter the hospital's address",
			hosp_city: "Please enter the hospital's city",
			hosp_state: "Please enter the hospital's state",
			hosp_zipcode: {
				required: "Please enter the hospital's zip code",
				minlength: "Please enter at least five digits"
			},
			hosp_country: "Please enter the hospital's country",

				//Library Subscription Form

			libraryName: "Please enter the library's name",
			librarySystem: "Please enter what system your library is part of",
			numberBranches: "Please enter the number of library branches",
			lib_address1: "Please enter the library's address",
			lib_city: "Please enter the library's city",
			lib_state: "Please enter the library's state",
			lib_zipcode: {
				required: "Please enter the library's zip code",
				minlength: "Please enter at least five digits"
			},
			lib_country: "Please enter the library's country",

				// Update Account

			FirstName: "Please enter your first name",
			LastName: "Please enter your last name",
			Address1: "Please enter your address",
			City: "Please enter your city",
			State: "Please enter your state",
			Zipcode: {
				required: "Please enter the your zip code",
				minlength: "Please enter at least five digits"
			},
			EMail: {
				required: "Please enter your email address",
				email: "Please enter a valid email address"
			},
			Phone: "Please enter your phone number",

				//
				// Parents/Teachers Place
				//

				// Change Password

			sp_password: {
				required: "Please enter a new password",
				minlength: "Passwords must be longer than 5 characters"
			},
			sp_passwordConfirm: {
				required: "Please re-enter your new password",
				equalTo: "This password must be the same as the one above"
			},
			sp_passwordPP: {
				required: "Please enter a new password",
				minlength: "Passwords must be longer than 5 characters"
			},
			sp_passwordConfirmPP: {
				required: "Please re-enter your new password",
				equalTo: "This password must be the same as the one above"
			},
			sp_old_password: "Please enter your current password",

				//
				// Teacher / Admins Place
				//

				//Add A New Student

			studentID: "Please enter a student ID",
			student_firstname: "Please enter the student's first name",
			student_lastname: "Please enter the student's last name",
			student_username: "Please enter a username",
			student_password: "Please enter a password",
			student_gradeLevel: "Please enter a grade level",

				//Add a teacher

			teacher_firstname: "Please enter the teacher's first name",
			teacher_lastname: "Please enter the teacher's last name",
			teacher_email: {
				required: "Please enter the teacher's email address",
				email: "Please enter a valid email address"
			},

				//Renew school sub

			numNewStudents: "Please enter the number of students",
			ContactFirstName: "Please enter the contact's first name",
			ContactLastName: "Please enter the contact's last name",
			ContactEmail: {
				required: "Please enter the contact's email address",
				email: "Please enter a valid email address"
			},
			ContactPhoneNo: "Please enter the contact's phone number",
			purchaseType: "Please select an option",
			needBill: "Please select an option",
			newSA: "Please select an option",

				// ITS Forms

			itsfreeweek_email: {
				required: "Please enter your email address",
				email: "Please enter a valid email address"
			},
			reqEmail: {
				required: "Please enter your email address",
				email: "Please enter a valid email address"
			},
			reqFirstName: "Please enter your first name",
			reqLastName: "Please enter your last name"
		}

	});

		// validForm2 is used for any form that is the second form on any given page. It is the same function as above.

	$( ".validForm2" ).validate({
		rules: {

			// Change Admin Password

			newPassword: {
				required: true,
				minlength: 5
			},
			newPasswordConfirm: {
				required: true,
				equalTo: "#newPassword"
			}
		},
		messages: {

			// Change Admin Password

			newPassword: {
				required: "Please enter a new password",
				minlength: "Passwords must be longer than 5 characters"
			},
			newPasswordConfirm: {
				required: "Please re-enter your new password",
				equalTo: "This password must be the same as the one above"
			}
		}
	});

	if ( debug ) {
		alert( "done in validation routine" );
	}

}


//* This must be the last line of the document

if ( debug ) {
	alert( 'Done public.js' );
}

