
// Initialize Variables


var popup = null;					// Persistent pop-up window handler
var pop2  = null;
var videoPopup;

// *************************
//   Login/Logout Routines
// *************************

function showLogin(type, msg) {		// Shows the appropriate dialog

	var showLogin = 0;

	setValue('loginArea', type);
	setValue('pwd', '', 'loginID', '');					// Empty the fields

	if (msg) {
		statusAlert(msg);
	} else {
		setText('statusHead', 'Please sign in.');		// Only show this prompt if no alert is set
	}

		
	if (type == 'student') {			// Show Student loginDialog

			getObjectByID('loginDialog').style.backgroundColor = '#00bef5'; 
			hideObject('lostPwdLink');
			showLogin = 1;
	} 

	if (type == 'partner') {			// Show Partner loginDialog

			getObjectByID('loginDialog').style.backgroundColor = '#fa593f';
			showObject('lostPwdLink');

			showLogin = 1;
	}

	if (showLogin) {
		setValue('pwd', '', 'loginID', '');
			
		showObject('loginDialog');
		setTimeout("focusOn('loginID');", 250);
	}
}

function logout(isTimeout) {				// Hides the signOutBar, partnerButtons, studentButtons, and deletes session cookies

	var cookieDur      = 58 * 60 * 60 * 1000;
	var cookieCallback = "goURL";
	var passVals       = 'index-signOut.php';
		
	if (isTimeout) {
		
		top.phpCookie('svsError', 3, cookieCallback, cookieDur, passVals);			// Show auto logout message after reload		
	} else {
		top.location.href = 'index-signOut.php';	
	}

		// Default to whatIsSVS if svsCurrentPage is a partner or student page
	
//	var currentPage = readCookie('svsCurrentPage');
//
//	if ( currentPage ) {
//		if ( ( currentPage.search(/partner/) > -1 ) || ( currentPage.search(/student/) > -1 ) ) {
//
//			var cookieNames    = 'svsBtnID, svsBtnClass, svsBtnClass_h, svsCurrentPage';
//			var cookieValues   = 'mb1,mainButton,mainButton_h,whatIsSVShighSchoolSpanish.html';
//		
//			top.phpCookie(cookieNames, cookieValues, cookieCallback, cookieDur, passVals);
//		}
//	}
		
	// top.location.href = 'index-signOut.php';		 
}

function goURL(url) {

	top.location.href = url;
}

// *************************
//      Common Routines
// *************************


function openURL(page, w, h) {		// Opens a resizable pop-up window

	if(popup) {
		popup.close();
	}
		popup = window.open(page, 'popup', 'height=' +h+ ',width=' +w+ ',scrollbars=yes,resizable=yes');
}


function MM_CheckFlashVersion(reqVerStr,msg){
  with(navigator){
    var isIE  = (appVersion.indexOf("MSIE") != -1 && userAgent.indexOf("Opera") == -1);
    var isWin = (appVersion.toLowerCase().indexOf("win") != -1);
    if (!isIE || !isWin){  
      var flashVer = -1;
      if (plugins && plugins.length > 0){
        var desc = plugins["Shockwave Flash"] ? plugins["Shockwave Flash"].description : "";
        desc = plugins["Shockwave Flash 2.0"] ? plugins["Shockwave Flash 2.0"].description : desc;
        if (desc == "") flashVer = -1;
        else{
          var descArr = desc.split(" ");
          var tempArrMajor = descArr[2].split(".");
          var verMajor = tempArrMajor[0];
          var tempArrMinor = (descArr[3] != "") ? descArr[3].split("r") : descArr[4].split("r");
          var verMinor = (tempArrMinor[1] > 0) ? tempArrMinor[1] : 0;
          flashVer =  parseFloat(verMajor + "." + verMinor);
        }
      }
      // WebTV has Flash Player 4 or lower -- too low for video
      else if (userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 4.0;

      var verArr = reqVerStr.split(",");
      var reqVer = parseFloat(verArr[0] + "." + verArr[2]);
  
      if (flashVer < reqVer){
        if (confirm(msg))
          window.location = "http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash";
      }
    }
  } 
}


function getThisID(name) {				//  Get an object's ID tag for easy referencing

	if (document.getElementById) {				// Firefox and Safari
		return document.getElementById(name);
	} else if (document.all) {					// IE
		return document.all[name]; 
	} else if (document.layers) {
		return document.layers[name];
	} else {
		return document.getElementById(name);		// Default for unknown browsers
	}
}

function getObjectByID(id) {				// Get an object's ID tag for easy referencing

//	if ( getThisID(id) != null && getThisID(id) ) {
//		return getThisID(id);
//		
//	} else if ( typeof getThisID('mainFrame').contentWindow.getThisID != 'function' && typeof getThisID('sidebarFrame').contentWindow.getThisID != 'function' )  {
//alert(1);
//		return '';
//		
//	} else 	if ( top.getThisID('sidebarFrame').contentWindow.getThisID(id) != null && top.getThisID('sidebarFrame').contentWindow.getThisID(id) ) {
//alert(2);
//		return top.getThisID('sidebarFrame').contentWindow.getThisID(id);	
//
//	} else if ( top.getThisID('mainFrame').location ) {				// If a document is loaded in it, check the mainFrame
//		if ( top.getThisID('mainFrame').contentWindow.getThisID(id) ) {
//alert(3);
//			return top.getThisID('mainFrame').contentWindow.getThisID(id);
//		} else {
//alert(4);
//			return '';	
//		}
//	} else {
//if (id == 'coursegoalsDiv') { alert ('h'); }	
//	}

	var frameList = new Array('mainFrame', 'sidebarFrame');		// Frames within the page where the object might exist

	if ( getThisID(id) != null && getThisID(id) ) {
		return getThisID(id);

	} else {											// Object not found on the immediate page: try looking in other frames
	
		for ( var n in frameList ) {						// Cycle through frames in the array

			thisFrame = frameList[n];
			
			if ( top.getThisID(thisFrame).contentWindow.location ) {		// If this frame has an open document, look there
			
				if (typeof top.getThisID(thisFrame).contentWindow.getThisID == 'function') {
			
					if (top.getThisID(thisFrame).contentWindow.getThisID(id) ) {
						return top.getThisID(thisFrame).contentWindow.getThisID(id);
					}
				}
			}														// No open document: try the next frame...
		}
	} 
	
		// Tried all frames, and there's nothing: return empty result
		
	return '';

}


function setValue() {				// Sets the value property of a specified field or control

	var lastObj = (setValue.arguments.length);
	for(n=0; n<lastObj; n++) {
		thisID = setValue.arguments[n]
		thisObj = getObjectByID(thisID);
		thisVal = setValue.arguments[++n];

		thisObj.value = thisVal;
	}
}


function getValue(id) {			// Returns the value property of the specified object

	var obj = getObjectByID(id);
	return obj.value;
}

function escapeRegex(inputString) {			// Prevents invalid quantifier errors when searching for special characters in Regex
	
	return inputString.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1');
}

function updateCheckbox(type, id, field) {						// Simple Ajax call to update the database when a checkbox is checked via updateForm

	setValue('updateType', type);
	setValue('updateID', id);

	var checkedVal;
	
	if ( getObjectByID(field).checked ) {								// Get the value of this box if checked
		checkedVal = getValue(field);
	} else {
		checkedVal = '';
	}

	setValue('updateV', checkedVal);
	sendReq('updateForm', ''); 
}


function emCode(prefix, suffix, text, loc, offset, mode, stClass) {	// E-mail obfuscator

								//	offset specifies how many garbage chars precede both prefix & text

								// 	mode 'a': pairs mailto href with text
								//		Example: emCode('zdn', 'p', 'zDavid Pedergnana', '', 1, 'a');

								//	mode 'n': shows e-mail only (as text)
								//		Example: emCode('zdn', 'p', '', '', 1, 'n');

								//	mode 'm': shows e-mail address as clickable mailto text
								//		Example: emCode('zdn', 'p', '', '', 1, 'm');
	var xString = prefix + suffix;
	var h = '<a href=\"mai';
	
	if (stClass) {
		h =  '<a class=\"' + stClass + '\" href=\"mai';	
	}
	
	var nom = xString.substr(offset);
	h += 'lto:';
	text = text.substr(offset);
	var end = '\">';
	text += "<" + String.fromCharCode(47);
	var z = '@';

	if (!loc) {
		var n = 101;
		loc = 'ksu.' + String.fromCharCode(n) + 'du';
	}

	if (mode == 'n') {
		document.write(nom + z + loc);
	} else if (mode == 'm') {
		document.write(h + nom + z + loc + end);
		document.write(nom + z + loc + text + 'a>');
		
	} else {
		document.write(h + nom + z + loc + end);
		document.write(text + 'a>');
	}
}

function getHTML(url, targetDiv, cookie) {		// Fetches content at url and displays it in targetDiv
													//	url:       the file to fetch
													//	targetDiv: where HTML will appear. Can be any block or inline object (not just a div)
													//	cookie:    if set, writes url to the specified cookie after fetching

	if ( getValue('getPage') ) {					// Form can only be accessed by one caller at a time. 
													// Avoid conflicts by delaying subsequent calls.
													
		var cmd = "getHTML('" + url + "', '" + targetDiv + "', '" + cookie + "'); ";
		setTimeout(cmd, 688);
		return;
	}

	setValue('getPage', url);
	sendReq('getHTMLForm', targetDiv, 0);			// HTML fetches must be asynchronous to avoid conflicts

	getObjectByID(targetDiv).scrollTop = 0;			// Scroll back to the top (for scrolling divs)

	if(cookie) {	
		makeCookie(cookie, url);
	}
	
	setValue('getPage', '');						// Clear the action to allow more requests
}



function setButton(reqPage) {		// Deselects former menu buttons and highlights the menu button for a requested page.
									//		(The button will also highlight when the new page opens;
									//		but this provides instant user feedback while the new page loads.
									
									//		Also sets messy queryStrings back to "index.html" when opening a new page; to avoid
									//			unwanted redirects on reload
											
									//		reqPage : the page we're currently trying to open

									//		btnClass_h: full spelling of the new button's selected state class
									//		btnClass:   full spelling of the new button's deselected state class

	var buttonList = {
		'whatIsSVShighSchoolSpanish.html' : 'mb1', 
		'prerequisites.html'              : 'mb2', 
		'teachingPartners.html'           : 'mb3', 
		'instructionalSupport.html'       : 'mb4', 
		'classMaterials.html'             : 'mb5', 
		'costEnroll.html'                 : 'mb6'
	}; 

	var btnClass   = 'mainButton';
	var btnClass_h = 'mainButton_h';
	
	
			// Infer the menu button ID from the page name and selectively activate or deactivate menu buttons
			
	for (pageName in buttonList) {

		var btnID = buttonList[pageName];
		
		if( pageName == reqPage ) {
			top.getObjectByID(btnID).className = btnClass_h;		// highlight the menu button
		} else {
			top.getObjectByID(btnID).className = btnClass;			// deselect the menu button
		}
	}
}

function storePage(currentPage, cookieCallback, cookiePassVals) {		// Writes the currentPage to a cookie for later reference

		// * If cookieCallback = 'top.resetURL', the page will redirect to the parent frame after storing the cookie

	var cookieNames    = 'svsCurrentPage';
	var cookieValues   = currentPage;
	var cookieDur      = 12 * 60 * 60 * 1000;		// Remember this page for half a day
		
	if (currentPage) {
		top.phpCookie(cookieNames, cookieValues, cookieCallback, cookieDur, cookiePassVals);
	}
}

function resetButton() {						// Upon page load or refresh, highlight the current button

	var btnID = readCookie('svsBtnID');
	var hClass = readCookie('svsBtnClass_h');
	
	if (btnID ) {
		getObjectByID(btnID).className = hClass;			
	}
}

function toggleBtn(whichBtn, state) {					// State = '_h' (highlighted) or ''

	var currentPage = getValue('currentPage');

	if (currentPage !== whichBtn) {						// Ignore requests if hovering over current page button
	
		var newState = 'images/' + whichBtn + 'Bt' + state + '.gif';
		getObjectByID(whichBtn + 'Bt').src = newState;			// Change the button state
	}
}


function parseURL(param) {	// Reads a frame's URL and splits it into its components
				// 	returns the requested parameter
	var result = null;

	var parameterList = location.href.split("?");		// GET Parameters

	if (parameterList.length > 1) {			// No parameters; set defaults for home page:

				// Split list into name.value pairs

		var parameterPairs = parameterList[1].split("&");
		var nameAndValue = new Array();
		var paramValue;
		var paramKey;

		for (p=0; p < parameterPairs.length; p++) {	// Cycle through name/value pairs & store values

			nameAndValue = parameterPairs[p].split("=");
			paramKey = nameAndValue[0];
			paramValue = nameAndValue[1];

			if (paramKey == param) {		// Is this the target key?
				result = paramValue;
				break;
			}
		}
	}
	return result;
}


function getScreenSpecs(defaultW, defaultH) {		// Accepts default width and height as input and returns 
							// either actual screen width and height or the defaults
	screenH = defaultH
	screenW = defaultW;

	if (parseInt(navigator.appVersion)>3) {
		 screenH = screen.height;
		 screenW = screen.width;
	}
	else if (navigator.appName == "Netscape" 
	    && parseInt(navigator.appVersion)==3
	    && navigator.javaEnabled()
	) 
	{
	 var jToolkit = java.awt.Toolkit.getDefaultToolkit();
	 var jScreenSize = jToolkit.getScreenSize();
	 screenH = jScreenSize.height;
	 screenW = jScreenSize.width;
	}

	return [screenW, screenH];
}



function openDoc(file, w, h, resizable, hOffset) {		// Opens a document of specified dimensions in a separate pop-up window
														//		Resizable is a boolean value ("yes" or "no") or "fixedSizeScroll"
														// 	hOffset is an optional parameter for offsetting the position from center screen 
	if(popup) {
		popup.close();
	}
	
	if (!hOffset) {
		hOffset = 0;
	}

	if (!resizable) {
		var resizable = 'yes';
		var scrollbars = 'yes';
	} else if (resizable == 'fixedSizeScroll') {
		var resizable = 'no';
		var scrollbars = 'yes';
	} else {
		var resizable = 'no';
		var scrollbars = 'no';
	}
	
	var screenWH = getScreenSpecs(1024, 768);
	screenW = screenWH[0];
	screenH = screenWH[1];

	popup = window.open(file, 'popUpWindow', 'height=' +h+ ', width=' +w+ ', scrollbars=' + scrollbars +', resizable=' + resizable + ',left=' + Math.round((screenW/2)-(w/2)-hOffset)+ ',top=' + Math.round((screenH/3)-(h/2)) );
}


function openDefault(page) {		// Opens a document in a default window that includes the location bar and is resizable

	pop2 = window.open(page, 'fullWin', 'scrollbars=yes, status=yes, menubar=yes, toolbar=yes, location=yes, resizable=yes, width=999, height=680');
}


function centerH(id, offset) {

	if (!offset) {
		offset = 0;
	}

	var w = getWidth(id);

	var windowW = getClientWidth();
	var leftPos = parseInt( (windowW / 2) - (w/2) + offset );

	getObjectByID(id).style.marginLeft = leftPos + 'px';
	
}

function centerV(id, offset) {

	if (!offset) {
		offset = 0;
	}

	var h = getHeight(id);
	var windowH = getClientHeight();
	var topPos = (windowH / 2) - (h/2) + offset;

	getObjectByID(id).style.marginTop = topPos + 'px';
}

function fillHeight(id, offset) {		// Checks Window Height then adjusts the height of a specified object.
						//	Offset can be specified to reduce height, in case of headers, etc.
						//	Returns the value h to the calling function
	if (!offset) {
		offset = 0;
	}

	var windowH = getWindowHeight();
	var h = parseInt(windowH) - offset;

	if (!h) {
		h = 420;
	}

	getObjectByID(id).style.height = h + 'px';
	return h;
}


function setFrame(whichPage) {					// Change the page within the mainFrame
	var frameObj = getObjectByID('mainFrame');
	frameObj.src = whichPage;
}

							
function getWindowHeight() {			
							
	if (window.innerHeight) {				// Firefox and Safari
		return window.innerHeight;
	} else {								// IE
		return document.body.clientHeight; 
	}
}
	

function getWindowWidth() {
   if (window.innerWidth) {
	return window.innerWidth;
   } else {
	return document.body.clientWidth;
   }	   	   	
}

function getClientWidth() {
	return filterResults (
		window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0,
		document.body ? document.body.clientWidth : 0
	);
}
function getClientHeight() {
	return filterResults (
		window.innerHeight ? window.innerHeight : 0,
		document.documentElement ? document.documentElement.clientHeight : 0,
		document.body ? document.body.clientHeight : 0
	);
}
function getScrollLeft() {
	return filterResults (
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
}
function getScrollTop() {
	return filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}
function filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}


function getWidth(id) {			// Returns the width of the specified object
	var obj = getObjectByID(id);

	if (obj.style.width) {
		return obj.style.width;
	} else if (obj.style.pixelWidth) {
		return obj.style.pixelWidth;
	} else {
		return obj.offsetWidth;
	}
}


function getHeight(id) {		// Returns the height of the specified object
	var obj = getObjectByID(id);

	if (obj.style.height) {
		return obj.style.height;
	} else if (obj.style.pixelHeight) {
		return obj.style.pixelHeight;
	} else {
		return obj.offsetHeight;
	}
}


function showObject() {				// Show a dynamic form field or menu
										// Iterates through argument list if an array is input
										
	var lastObj = showObject.arguments.length;
	for(n=0; n<lastObj; n++) {
		thisObj = getObjectByID(showObject.arguments[n]);
		thisObj.style.display = "";
	}
}



function hideObject() {					// Show a dynamic form field or menu
											// Iterates through argument list if an array is input
	var lastObj = hideObject.arguments.length;
	for(n=0; n<lastObj; n++) {
		
		thisObj = getObjectByID(hideObject.arguments[n]);
		thisObj.style.display = "none";
	}
}


function isShown(id) {

	if ( getObjectByID(id).style.display == 'none') {
		return 0;
	} else {
		return 1;
	}
}

function focusOn(targetID, msDelay) {		// Gives focus to the named field or form object
											// msDelay is how long to pause before giving focus

	if (msDelay) {
		var cmd = "getObjectByID('" + targetID + "').focus();" ;
		setTimeout(cmd, msDelay);
	} else {
		getObjectByID(targetID).focus();
	}
}


function showDiv(whichDiv) {			// Changes the background color of the link to match the specified div; then
										// shows the div
	var divID = whichDiv + 'Div';
	var tabID = whichDiv + 'Link';
	var hrefID = whichDiv + 'href';

	getObjectByID(divID).className = 'infoBlockOpen';		// Show the div
	getObjectByID(tabID).className = 'tabOpen';				// Change the link background color
	getObjectByID(hrefID).className = 'tabLinkOpen';		// Change the link background color
}


function hideDiv(whichDiv) {			// Changes the background color of the link to white; then
										// shows the div
	var divID = whichDiv + 'Div';
	var tabID = whichDiv + 'Link';
	var hrefID = whichDiv + 'href';

	getObjectByID(divID).className = 'hidden';				// Hide the div
	getObjectByID(tabID).className = 'tabClosed';			// Change the link background color
	getObjectByID(hrefID).className = 'tabLinkClosed';		// Change the link background color
}


function toggleInfoBlock(whichDiv) {	// Either hides or shows a specified div, depending on its current state

	var divID = whichDiv + 'Div';

	if (getObjectByID(divID).className == 'hidden') {		// Div is hidden: show it

		showDiv(whichDiv);
	} else {															// Div is visible: hide it
		hideDiv(whichDiv);
	}
}


function toggleObject(id, focusID) {		// Either hides or shows a specified div, depending on its current state

	if (getObjectByID(id).className == 'hidden') {		// Object is hidden: show it

		getObjectByID(id).className = 'visible';
		if (focusID) {
			cmd = "focusOn('" + focusID + "'); ";	// Give focus to the specified control within the parent object
			setTimeout(cmd, 250);
		}
	} else {															// Div is visible: hide it
		getObjectByID(id).className = 'hidden';
		setValue(focusID, '');				// Empty the field when hiding
	}
}


function validateField(fieldID, legalChars, feedback) {		// Returns 1 if field contents are legal; else 0
																// feedback:   An optional alert message to send when contents are illegal
	var inputString = getValue(fieldID);
	var thisChar;
	
	for (var n=0; n<inputString.length; n++) {
	
		thisChar = inputString.charAt(n);
		var matchItem = new RegExp(thisChar);
		
		if ( legalChars.search(thisChar) == -1) {					// Invalid character
			if (feedback) {
				alert(feedback);
				getObjectByID(fieldID).className = 'invalid';		// Change its color
				focusOn(fieldID);
			}
			return 0;
		}
	}

	getObjectByID(fieldID).className = 'valid';						// OK: It's valid. Clear the field (if highlighted previously)
	return 1;
}

function padLeft(inputString, padChar, n) {		// Accepts a string and character(s) to pad with (i.e., space, 
								//     zero, etc.) and returns a revised string of length n

								//     Works with multiple padChars, too! Feed it an empty 
								//     input string to generate a pattern string of specified
								//     length. Currently doesn't truncate, though...
	while (inputString.length < n) {
		inputString = padChar + inputString;
	}
	return inputString;
}

function padRight(inputString, padChar, n) {		// Accepts a string and character(s) to pad with (i.e., space, 
								//     zero, etc.) and returns a revised string of length n

								//     Works with multiple padChars, too! Feed it an empty 
								//     input string to generate a pattern string of specified
								//     length. Currently doesn't truncate, though...
	while (inputString.length < n) {
		inputString = inputString + padChar;
	}
	return inputString;
}


function validateEmailField(id) {				// Checks to see if the field named 'email' has @ and . chars
												// Returns 1 if invalid
	var email = getObjectByID(id).value;

	var emailRegEx = /^[^@]+@[^@]+.[a-z]{2,}$/i;

	if(email.search(emailRegEx) == -1){
		return 1;
	} else {
		return 0;
	}
}

function requireFields() {				// Accepts a list of field ids that must be not be empty, followed by an error prompt and a highlight class.
							// If any fields are empty, returns the specified error mesage and highlights them.
							// If no error message is specified, the alert is surpressed.
							// Returns an array list of invalid field ids
	var idList = requireFields.arguments;
	var badFields = new Array();

	var lastItem = (idList.length)-1;

	var hClass = idList[lastItem];
	var msg = idList[lastItem-1];
	
	lastItem = lastItem - 3;

	for (var n=0; n < lastItem; n++) {		// Cycle through the fields and check their contents

		var thisV = getValue( idList[n] );

		if (!thisV) {											// This field's empty:
			getObjectByID( idList[n] ).className = hClass;		// Change its color
			badFields.push( idList[n] );
		} else {
			getObjectByID( idList[n] ).className = 'valid';
		}
	}

	var badFieldsExist = badFields.length;
	if (badFieldsExist) {
		if (msg) {
			alert(msg);
		}
		focusOn( badFields[0] );
		return badFields;
	} else {
		return 0;
	}
}


// Phone number validation scripts (origin: SmartWebby.com)

function isInteger(s)
{   var i;
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag)
{   var i;
    var returnString = "";

	if(!s) {
		return "";
	}

    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function checkInternationalPhone(strPhone) {
	s = stripCharsInBag(strPhone, "()- +.");			// Valid non-integers in a phone number
	return (isInteger(s) && s.length >= 10);			// Minimum digits in an international phone number
}

function checkLocalPhone(strPhone) {
	s = stripCharsInBag(strPhone, "()- +." );			// Valid non-integers in a phone number
	return (isInteger(s) && s.length == 7);				// Minimum digits in an international phone number
}

function validatePhone(id){		// Accepts phone field id and error prompt as input and returns 1 if invalid
					// If msg is empty, it surpresses the prompt
	var Phone = getValue(id);
	var msg = '';

	if (!checkInternationalPhone(Phone)) {
		if (checkLocalPhone(Phone)) {		// Is it only missing the prefix?

			msg = 'Please include a full phone number with area code';

		} else {				// It's just wrong

			msg = 'Please use a valid phone number';
		}
	} else {
		msg = '';
	}
	return msg;
 }



function HideContent(d) {
if(d.length < 1) { return; }
document.getElementById(d).style.display = "none";
}
function ShowContent(d) {
if(d.length < 1) { return; }
document.getElementById(d).style.display = "block";
}
function ReverseContentDisplay(d) {
if(d.length < 1) { return; }
if(document.getElementById(d).style.display == "none") { document.getElementById(d).style.display = "block"; }
else { document.getElementById(d).style.display = "none"; }
}


function statusAlert(msg) {				// Send a stylized prompt to the statusDiv

	msg = "<img src='images/icon-exclaim.gif'>" + msg;
	setText('statusHead', msg);
}


function recoverLostPwd(fieldID, formID, formField) {		// Retrieve a forgotten password (if it exists)

	var email = getValue(fieldID);						// Ensure that e-mail field is filled correctly
	var alertMsg = '';

	if (email == '') { 											// E-mail field is blank

		alertMsg = 'Type your e-mail address first.';
	}

	var invalidEmail = validateEmailField(fieldID);				// Validate e-mail field before submitting request

	if(invalidEmail) {
		alertMsg = "Please type a valid e-mail address.";
	}

	if (alertMsg) {
		statusAlert(alertMsg);
	} else {											// No warnings: e-mail address is OK
					
		setValue(formField, email);				// Update recoverPwd form with e-mail address & send request
		sendReq(formID, 'js');
	}
}


function setText() {					// Sets the innerHTML of specified objects to desired text.

	var lastObj = (setText.arguments.length);
	for(n=0; n<lastObj; n++) {
		thisID = setText.arguments[n]
		thisObj = getObjectByID(thisID);

		if(!thisObj) {
			alert("Error: " + thisID + " doesn't exist");
			++n;
		} else {
			thisText = setText.arguments[++n];
			thisObj.innerHTML = thisText;
		}
	}
}

function getText(ID) {						// Returns the innerHTML of a specified <span> field

	var textSpanObj = getObjectByID(ID);
	var text = textSpanObj.innerHTML;

	return(text);
}


function setClass(prefix, newClass, itemCount, setBtnID, altClass) {		// Sets all IDs beginning with a certain prefix (as in a button group) to a specified class
										//		prefix:      the characters with which each button ID starts, i.e. "pButton"
										//		newClass:    the new className for each button
										//		itemCount:   the number of buttons in the set. If itemCount = 5, buttons are numbered 0, 1, 2, 3, & 4 (first button is "pButton0" in this example)
										//		setBtnID:    optional button number. If specified, this button will be set to altClass

	if (setBtnID == 'get') {
		setBtnID = readCookie('svsBtnID');					// setBtn = 'get': retrieve the current button ID
	} else {
		makeCookie('svsBtnID', setBtnID);					// Store the current button ID
	}

	for (var n=1; n<=itemCount; n++) {
	
		id = prefix + n;
		
		if (n == setBtnID) {
			getObjectByID(id).className = altClass;
		} else {
			getObjectByID(id).className = newClass;
		}
	}
}

function getMenu(whichMenu) {

	alert(whichMenu);
}


function makeDialog(header, msg, buttonLabel, action) {				// Configures and shows the standard alert dialog, which includes an optional button click action

	if (!action) {																// Alert action is optional; dialogue always hides upon click
		setValue('alertAction', '');
	} else {
		setValue('alertAction', action);
	}

	setAlert('alertHead', header);
	setText('alertPrompt', msg);

	if (!buttonLabel) {															// The default button label is 'OK'
		setValue('alertButton', 'OK');
		hideObject('alertCancelButton');										// Hide [Cancel] button when defaulting to [OK]
	} else {
		setValue('alertButton', buttonLabel);
		showObject('alertCancelButton');										// Show a [Cancel] button when there is an action
	}
	
	showObject('alertDialog');
}


function setAlert(nodeID, msg) {			// Send alert text to the specified node
	
	msg = "<img src='images/icon-exclaim.gif'>" + msg;
	setText(nodeID, msg);
}


function doAlertAction() {					// Do the specified action when the alertDialog confirm button is clicked

	var action = getValue('alertAction');
	hideObject('alertDialog');
	
	if (action) {
		eval(action);
	}
}


	// AJAX Submit Routines


function joinValues(fields) {		// Accepts a string of comma-separated field names as input (with spaces) and returns a string of values
									// Delimiter = |
	var fieldList = fields.split(", ");
	var lastItem = fieldList.length;
	var v = '';
	var valList = new Array();
	
	for (n=0; n<lastItem; n++) {
		v = getValue( fieldList[n] );
		valList.push(v);
	}
	
	return valList.join("|");
}

function validateAndUpdateAccount() {

	var emptyFields = requireFields('asLogin', 'asPwd1', 'asPwd2', 'Please complete the form first.', 'invalid');
	var incompleteForm = emptyFields.length;

	if (!incompleteForm) {										// Form is complete: are login and password valid?
	
		var validLogin = validateField('asLogin', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz@._- ', 'Invalid Login: Legal characters include A-Z, a-z, 0-9, @, period (.) and underscore (_)');
		
		if (validLogin) {
			var validPwd = validateField('asPwd1', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz@._- ', 'Invalid Password: Legal characters include A-Z, a-z, 0-9, @, period (.) and underscore (_)');	
		}
	
		if (!validLogin || !validPwd) {
			return;							// Invalid Login or Password characters: stop after sending alert	
		}
		
	
		if ( (getValue('asPwd1') == getValue('asPwd2')) && getValue('asPwd1')!=='' ) {			// Ensure that passwords match before updating
			
			id = getValue('asUserID');				// One-time password identifying this account

			var encLogin = dpEncode(getValue('asLogin'));
			var encPwd =   dpEncode(getValue('asPwd1'));

			setValue('asLogin', encLogin);	
			setValue('asPwd1', encPwd);
			setValue('asPwd2', encPwd);

			update('accountSetup', id, 'asLogin, asPwd1, asFirstName, asLastName, asRole, asEmail, asPhone', 'accountSetupDialog', 'js');
			update('schoolInfo', id, 'asSchool, asDistrict, asAddr1, asAddr2, asCity, asState, asZip, schoolPhone', '', 'js');
			setValue('asLogin', '', 'asPwd1', '', 'asPwd2', '');
			
		} else {											// Passwords don't match
			alert("Passwords don't match.");
			focusOn('asPwd1');
		}		
	}
}

function askInput(askInputHead, askPrompt, id, inputWidth, inputHeight, buttonLabel, jsAction, dialogWidth, cancelButtonLabel) {
								// Configures and shows a standard text input dialog with an optional custom action button
								
								//	askPrompt:      question to display along with the text entry field
								//	id:             optional ID or other value to store that can be referenced by the JS action
								//	inputWidth:     width of the text field in pixels
								//	inputHeight:    optional height of the text field in pixels. If set, use <textarea> not <input> field
								//	buttonLabel:    text description for the optional action button (i.e., [OK] )
								//	jsAction:       custom script to run if the action button is clicked
								//	dialogWidth:	the dialog box's width
								//	cancelButtonLabel:	if set to 'none', no [Cancel] button is included; if blank, defaults to "Cancel"

			// Construct the dialog
	
	if (!dialogWidth) {
		var dialogWidth = 400;
	}
	var topPos     = 178;
	var textColor  = '#000000';
	var bgColor    = '#ffc526';
	var bgImg      = '';
	
	var htmlText  = "<input id='askInputType' type='hidden' />";
	htmlText     += "<input id='askInputID' type='hidden' />";
	htmlText     += "<input id='askInputAction' type='hidden' />";
	
	htmlText     += "<h2 id='askInputHead' class='noMarginTop'>askInput Header</h2>";
	htmlText     += "<label for='askInputText' id='askInputPrompt' class='labelType'>A Prompt or Question Here</label> ";
	
	if (!inputHeight || inputHeight == 1) {
		htmlText     += "<input style='width:180px;' id='askInputText' type='text' ";
	} else {
		htmlText     += "<textarea id='askInputText' ";
	}
	
				   // Prototype: submitOnReturn(e, formID, sendFormTarget, hideDialog);

	htmlText     += "onkeypress=\"submitOnReturn(event, 'doAskInputAction();', 'e', 'askInputDialog');\"></textarea>";

	htmlText     += "<br /><br />";
	
	htmlText     += "<div style='float:right;'>";
	htmlText     += "<input id='askInputButton' type='button' value='OK' onClick='doAskInputAction();' />";
	htmlText     += "<input id='askInputCancelButton' type='button' value='Cancel' style='margin-left: 18px;' onClick=\"hideObject('askInputDialog'); \" />";
	htmlText     += "</div>";
	
	createDialog('askInputDialog', dialogWidth, topPos, textColor, bgColor, bgImg, htmlText);


			// Populate the dialog

	setValue('askInputText', '');					// Clear askInputText of possible former entry

	if (jsAction) {									// askInput action is optional... dialogue always hides upon click
		setValue('askInputAction', jsAction);
	} else {
		setValue('askInputAction', '');
	}
	
	if (id) {
		setValue('askInputID', id);
	} else {
		setValue('askInputID', '');
	}

	setText('askInputHead', askInputHead);
	setText('askInputPrompt', askPrompt);
	
	if (!buttonLabel) {															// The default button label is 'OK'
		setValue('askInputButton', 'OK');
		hideObject('askInputCancelButton');										// Hide [Cancel] button when defaulting to [OK]
	} else {
		setValue('askInputButton', buttonLabel);
		showObject('askInputCancelButton');										// Show a [Cancel] button when there is an action
	}
	
		
	if (inputWidth) {
		getObjectByID('askInputText').style.width = '' + inputWidth + 'px';				// Set the dimensions of the input field
	}

	if (cancelButtonLabel == 'none') {
		hideObject('askInputCancelButton');	
		
	} else if (cancelButtonLabel) {
		getObjectByID('askInputCancelButton').value = cancelButtonLabel;
		showObject('askInputCancelButton');	
		
	} else {
		getObjectByID('askInputCancelButton').value = 'Cancel';
		showObject('askInputCancelButton');	
	}
	
	showObject('askInputDialog');
	focusOn('askInputText', 500);
}

function doAskInputAction() {				// Do the specified action when the askInputDialog confirm button is clicked

	var action = getValue('askInputAction');
	hideObject('askInputDialog');
	
	if (action) {
		eval(action);
	}
}

function handleAskInput(askInputType,targetID) {	// Submit askInput to the server for processing

														//	askInputType : describes the interaction for use in subs-handleAskInput case switching
														//	targetID     : optional ID of an element whose HTML will update when processing completes
	if (!targetID) {
		targetID = '';
	}
	var url          = 'subs-handleAskInput.php';
	var callbackFunc = '';
	var syncReqFlag  = '';
			
	var oData = {
		askInputType   : askInputType,
		askInputID     : getValue('askInputID'),
		askInputText   : getValue('askInputText')
	};

	sendData(url, targetID, callbackFunc, oData, syncReqFlag);
	hideObject('askInputDialog');
}

function createDialog(dialogID, w, topPos, textColor, bgColor, bgImg, htmlText) {		// Constructs a new dialog of the specified type if it doesn't already exist

																// dialogID  : name or ID for the dialog
																// w         : specified width of the dialog (required)
																// topPos    : absolute top position of the dialog (required)
																// textColor : optional text color
																// bgColor   : color of the dialog's background
																// bgImg     : optional background image
																// htmlText  : optional dialog contents
	if ( !getObjectByID(dialogID) ) {
		var newDiv   = document.createElement('div');			// Create a new div and add it to the page body
	
		newDiv.setAttribute('id', dialogID);					// 		Assign the id and style newDiv before display
		newDiv.className      = 'dialog';
		newDiv.style.position = 'absolute';
		newDiv.style.width    = w      + 'px';
		newDiv.style.top      = topPos + 'px';
		newDiv.style.left     = '50%';
		newDiv.style.padding  = '18px';
		
		var leftPos             = parseInt( w / 2 ) * -1;
		newDiv.style.marginLeft = leftPos + 'px';
		
		if (textColor) {
			newDiv.style.color = textColor;
		}
		
		if (bgColor) {
			newDiv.style.backgroundColor = bgColor;
		}
		
		if (bgImg) {
			newDiv.style.backgroundImage = bgImg;
		}
		
		newDiv.style.display = 'none';
		document.body.appendChild(newDiv);						// 		Place the new div at the end of the element list
	
		newDiv.innerHTML = htmlText;								//		Populate the newDiv with HTML
	}
}

function openFlash(file, w, h, title) {
	
	queryString = 'video/flashPlayer.php?w=' + w + '&h=' + h + '&file=' + file + '&title=' + title;

	if(videoPopup) {
		videoPopup.close();
	}
	
	w = w + 36;
	h = h + 82;

	videoPopup = window.open(queryString, 'videoWindow', 'height=' +h+ ', width=' +w+ ', scrollbars=no, resizeable=no');

}
