<!--
/*
Author: Unknown
Description:
	1. Clien side validation, automation, & general script.
	Updated 07/14/2010, 1231702 - AB
	Updated openWin popup, expanding the default size.
	Updated 08/19/2011, 3037668 - AB
	Fixed bug with Preview.
	*/
//-->

<!--

function openWin(url) {
var winWidth = '800';
var winHeight = '480';
var allowScroll = 'yes';
if ((arguments[1]) && (arguments[2])) {
	winWidth = arguments[1];
	winHeight = arguments[2];
	if (arguments[3]) {
		allowScroll = arguments[3];
	}
	if (arguments[4]) {
		position = arguments[4];
	}
}
var load = window.open(url,'popupWin','scrollbars=' + allowScroll + ',menubar=no,width=' + winWidth +',height=' + winHeight + ',resizable=yes,toolbar=no,location=no,status=no');
}

function preVal(textarea){
	if (document.myform.textarea.value.length > 2000){
		alert("Please limit your explanation to 2000 characters.");
		return false;
	}
}
function validate(field) {
	var valid = "0123456789ex-/ ";
	var ok = "yes";
	var temp;
	for (var i=0; i<field.value.length; i++) {
		temp = "" + field.value.substring(i, i+1);
		if (valid.indexOf(temp) == "-1") {
			ok = "no";
		}
		if (ok == "no") {
			field.value="";
			//alert("Invalid entry!  Only numbers are accepted!");
			field.focus();
			field.select();
   	}
	}
}
function submitform(thisrecord,thisaction,thisstartrow,moreorless,thisinfo)
{
	//alert(thisstartrow);
	if(moreorless!=''){
	document.myform.action.value='';
	} else {
	document.myform.action.value=thisaction;
	}
	if (thisrecord!=''){
	document.myform.ID.value=thisrecord;
	}
	document.myform.startrow.value=thisstartrow;
	document.myform.info.value=thisinfo;
	document.myform.moreorless.value=moreorless;
	document.myform.submit();
}
function submitorderform(thisorder,thisdirection)
{
	document.myform.o.value=thisorder;
	document.myform.d.value=thisdirection;
	document.myform.submit();
}
function submithide(thishide)
{
	document.myform.hide.value=thishide;
	document.myform.submit();
}
function clearForm(){
			document.calform.sid.value='';
			//document.calform.sTroubleType.value='';
			document.calform.slastname.value='';
			document.calform.sfirstname.value='';
			document.calform.semail.value='';
			document.calform.sReqStatus.value='';
			document.calform.sStaff.value='';
			document.calform.datebox_start.value='';
			document.calform.datebox_end.value='';
			//document.calform.sshowclosed.value='';
			document.calform.sCSID.value='';
		 	document.calform.submit();
}

var counter = 0;
function monitor() {
	counter++;
	if(counter > 1) { return false; }
	return true;
}

function validate_date (stdate,nddate){
	var valid_start = stdate;
	var valid_end = nddate;
	var valid_this = document.crnconfirm.datebox_start.value;
	if (valid_this < valid_start){
		alert('You must select a date after the course start date!');
		return false;
	}	
	if (valid_this > valid_end){
		alert('You must select a date before the course end date!');
		return false;
	}	
}

function valButton(btn) {
    var cnt = -1;
    for (var i=btn.length-1; i > -1; i--) {
        if (btn[i].checked) {cnt = i; i = -1;}
    }
    if (cnt > -1) return btn[cnt].value;
    else return null;
}
function validateEval() {
var btn = valButton(form.group1);
if (btn == null) alert('No radio button selected');
else alert('Button value ' + btn + ' selected');
}
function validatecourseform() {
    valid = true;

    if ( document.courseform.onlineterm.value == "" )
    {
        alert ( "Please select a term!" );
        valid = false;
    }

    return valid;
}


// Form option element items manipulation.
function insertOptionBefore(num) {
	var elSel = document.getElementById('CRNSelect');
	if (elSel.selectedIndex >= 0) {
		var elOptNew = document.createElement('option');
		elOptNew.text = 'Insert' + num;
		elOptNew.value = 'insert' + num;
		var elOptOld = elSel.options[elSel.selectedIndex];
		try {
			elSel.add(elOptNew, elOptOld); // standards compliant; doesn't work in IE
		}
		catch(ex) {
			elSel.add(elOptNew, elSel.selectedIndex); // IE only
		}
	}
}

function removeOption(num) {
	if (num == 'all') {
		var elSel = document.getElementById('CRNSelect');
		var i;
		for (i = elSel.length; i!=0; i--) {
			elSel.remove(i);
		}
	} else {
	var elSel = document.getElementById('CRNSelect');
		elSel.remove(num);
	}
}

function appendOptionLast(val,text) {
	var elOptNew = document.createElement('option');
	elOptNew.text = text;
	elOptNew.value = val;
	
	var elSel = document.getElementById('CRNSelect');

	try {
		elSel.add(elOptNew, null); // standards compliant; doesn't work in IE
	}
	catch(ex) {
		elSel.add(elOptNew); // IE only
	}
}


/*	Created 20081211 By Anthony Bautista Jr.

	This function creates an AJAX request and processes a JSON response.
	
	Takes: two overloaded arguments described as; arguments[0] as focusOn a string of "first" or
	"empty"	which configures the script to focus on the first input element or the first input
	element	with an empty value. arguemnts[1] as type a string of "text" or "any" which configures
	the script to consider character-based form elements or any form input element including; checkbox,
	radio, select.
	Defaults: arguments[0] as focusOn = empty, arguments[1] as type = string.
*/ 
var http = false;
if(navigator.appName == "Microsoft Internet Explorer") {
	http = new ActiveXObject("Microsoft.XMLHTTP");
} else {
	http = new XMLHttpRequest();
}

function returnCRNs(term) {
	try {
		if (arguments[1] == 'debug') {
			debug = true;
		} else {
			debug = false;
		}
	} catch (err) {
		debug = false;
	}
	
	removeOption('all');
	appendOptionLast('1','Please wait...');
	document.getElementById('CRNSelect').selectedIndex = 1;
	document.getElementById('CRNSelect').className = "red";
	document.getElementById('CRNSelect').disabled = false;
	
	if (document.getElementById('termSelect').selectedIndex == 0) {
		removeOption('1');
		document.getElementById('typeSelect').selectedIndex = 0;
		document.getElementById('typeSelect').disabled = true;
		document.getElementById('CRNSelect').className = "red";
		document.getElementById('CRNSelect').disabled = true;
	} else {
		document.getElementById('typeSelect').selectedIndex = 1;
		http.open("GET", "request.cfm?app=returnCRNs&term=" + term + "&now=" + new Date(), true);
		http.onreadystatechange=function() {
			if(http.readyState == 4) {
				// Process JSON.
				myRegex = /({\W*\n*\W*("|')[a-zA-Z0-9]*\W*("|')\W*:\W*(\[("|')[a-zA-Z0-9]*\W*("|')\W*){1}(,\W*("|')[a-zA-Z0-9]*\W*("|'))*\W*\]\n*\W*})/;
				if(myRegex.test(http.responseText)) {
					var result = eval("(" + http.responseText + ")");
					for (var i=0; i<result.CRNs.length; i++) {
						appendOptionLast(result.CRNs[i],result.CRNs[i]);
					}
				}
				if (debug) {
					document.getElementById('foo').innerHTML = http.responseText;
				}
				removeOption('1');
				document.getElementById('CRNSelect').disabled = false;
				document.getElementById('CRNSelect').className = null;
			}
		}
		http.send(null);
	}
}

function showTypes() {
	if (document.getElementById('CRNSelect').selectedIndex == 0) {
		document.getElementById('typeSelect').selectedIndex = 0;
		document.getElementById('typeSelect').disabled = true;
	} else {
		document.getElementById('typeSelect').disabled = false;
	}
}

function showTypes2(thisEl,nextEl) {
	if (document.getElementById(thisEl.id).selectedIndex == 0) {
		document.getElementById(nextEl).selectedIndex = 0;
		document.getElementById(nextEl).disabled = true;
		document.getElementsByName('select')[0].disabled = true;
	} else {
		document.getElementById(nextEl).disabled = false;
	}
}

function showForm(thisEl) {
	try {
		if (document.getElementById(thisEl).selectedIndex == 1) {
			document.getElementById('Internal').style.display = 'block';
			document.getElementById('External').style.display = 'none';
			document.coursePageInternal.submitForm[0].onclick = function() {return SetPreviewTarget(true);}
			document.coursePageInternal.submitForm[2].onclick = function() {return SetPreviewTarget(true);}
		} else if(document.getElementById(thisEl).selectedIndex == 2) {
			document.getElementById('Internal').style.display = 'none';
			document.getElementById('External').style.display = 'block';
			document.coursePageExternal.submitForm[0].onclick = function() {PreviewExternalURL(); return false;}
			document.coursePageExternal.submitForm[2].onclick = function() {PreviewExternalURL(); return false;}
				if(document.getElementsByName('externalLink')[0].value == '') {
					document.getElementsByName('externalLink')[0].value = 'http://';
					//document.getElementsByName('submitForm')[0].type = 'button';
				}
		} else {
			document.getElementById('Internal').style.display = 'none';
			document.getElementById('External').style.display = 'none';
		}
	}
	catch(err) {
		//sample redirect for session timeout for JSON - location.href = 'http://www.sddccd.edu';
		// Do nothing (for broswer compatibility).
	}
}

/*	Created 20080612 By Anthony Bautista Jr.

	This function sets a form field focus and does not generate an error if a form element is not
	found in the document.
	
	Takes: two overloaded arguments described as; arguments[0] as focusOn a string of "first" or
	"empty"	which configures the script to focus on the first input element or the first input
	element	with an empty value. arguments[1] as type a string of "text" or "any" which configures
	the script to consider character-based form elements or any form input element including; checkbox,
	radio, select.
	Defaults: arguments[0] as focusOn = empty, arguments[1] as type = text.
*/ 
	function setFormFocus() {
		try {
			// Sets configuration based on overloaded argurments.
			focusOn = 'empty';
			type = 'text';
			if(arguments) {
				argCount = arguments.length;
				if ((argCount > 0) && (arguments[0] == 'first')) {
					focusOn = 'first';
					argCount = argCount-1;
				}
				if ((argCount > 0) && (arguments[1]=="any")) {
					type = "any";
					argCount = argCount-1;
				}
			}
			// Sets the form field focus for input based on configuration.
			el = document.getElementsByTagName('input');
			elCount = el.length;
			for (i=0; i < elCount; i++) {
				if ((focusOn == 'empty') && (type == 'text')) {
					if ((!el[i].value) && ((el[i].type == 'text') || el[i].type=='password')) {
						el[i].focus();
						break;
					}
				} else if ((focusOn == 'first') && (type == 'text')) {
					if ((el[i].type == 'text') || (el[i].type=='password')) {
						el[i].focus();
						break;
					}
				} else if ((focusOn == 'empty') && (type == 'any')) {
					if (!el[i].value) {
						el[i].focus();
						break;
					}
				} else {
					el[i].focus();
					break;
				}
			}
		}
		catch(err) {
		//sample redirect for session timeout for JSON - location.href = 'http://www.sddccd.edu';
		// Do nothing (for broswer compatibility).
		}
	}
	
/*	Created 20090325 By Anthony Bautista Jr.

	This function prompts the user to submit a form as a "save" to prevent the lost of data
	due to session time-outs.
	
	Takes: no arguments.
	Defaults: none.
	Returns: nothing;
*/ 
	var millisec=0
	var seconds=900
	
	function RemindSave() {
		if (millisec<=0) {
			millisec=9;
			seconds-=1;
		}
		if (seconds<=-1) {
			millisec=0;
			seconds+=1;
			document.getElementById('message').innerHTML = 'You must save your work to ensure your changes are not lost.';
			document.getElementById('message').className = 'Red';
			document.body.className = 'red';
			document.getElementById('main').style.backgroundColor = '#FF0000';
			if (confirm("If you don't save your work, it could be lost.  Do you want to save now?")) {
				document.coursePageInternal.submit('save');
			}
		} else {
			millisec-=1;
			setTimeout("RemindSave()",100);
		}
	}
	
	function ConfigureInfoPageForm() {
	}
	
	function PreviewExternalURL() {
		urlField = document.getElementsByName('externalLink')[0];
		if ((urlField.value != "") && (urlField.value != 'http://')) {
			window.open(urlField.value,'previewPopup','dialog,modal,scrollbars=yes,resizable=yes,width=800,height=600,left=362,top=284');
		} else {
			alert('Please enter a valid website URL.');
			urlField.focus();
		}
	}

	function SetPreviewTarget() {
		if (arguments[0] == true) {
			//alert('true');
			document.coursePageInternal.target = "previewPopup";
			//alert('Please enter a valid website URL.');
			document.coursePageInternal.onSubmit = window.open(document.coursePageInternal.action,'previewPopup','dialog,modal,scrollbars=yes,resizable=yes,width=800,height=600,left=362,top=284');
			//return true;
		} else {
			//alert('false');
			document.coursePageInternal.target = "_self";
			//document.coursePageInternal.removeAttribute("target");
			return true;
		}
	}

	function growElement(elId) {
		//actualHeight = 0;
		actualHeight = document.getElementById(elId).contentWindow.document.getElementsByTagName('iframe')[0].contentWindow.document.body.scrollHeight + 54;		if (actualHeight > 200) {
			var elThis = document.getElementById(elId);
			elThis.style.height = actualHeight;
		}
	}

	function ValidateField(formFieldValue,validation) {
		var theResult = false;
		var thePattern = "";
		switch(validation) {
			case "AnyRequired":
				if (formFieldValue != "") {
					theResult = true;
				} else {
					theResult = false;
				}
				break;
			case "Email":
				thePattern = /^[a-zA-Z0-9_]+([-+.'][a-zA-Z0-9_]+)*@[a-zA-Z0-9_]+([-.][a-zA-Z0-9_]+)*\.[a-zA-Z0-9_]+([-.][a-zA-Z0-9_]+)*$/;
				if (!thePattern.test(formFieldValue)) {
					theResult = false;
				} else {
					theResult = true;
				}
				break;
			default:
				// Specific validation type not defined.  Cannot validate.
				theResult = false;
		}
		return theResult;
	}
	
	function ValidateForm(formObject) {
		var theResult = false;
		var anyErrors = 0;
		var theErrorMessage = "";
		var errorsArray = new Array();

		if (typeof(formObject) == 'object') {
			switch(formObject.name)	{
				// Validate CIP Faculty Contact form.
				case "EmailFaculty":
					// Sender Name
					if(!ValidateField(formObject.SenderName.value,'AnyRequired')) {
						errorsArray[anyErrors] = new Array()
						errorsArray[anyErrors][0] = "Please enter your name.";
						anyErrors++;
						document.getElementById('lblSenderName').className = 'Red';
					} else {
						document.getElementById('lblSenderName').className = '';
					}
					// Email Address
					if(!ValidateField(formObject.SenderEmail.value,'Email')) {
						errorsArray[anyErrors] = new Array()
						errorsArray[anyErrors][0] = "Please enter a valid email address.";
						anyErrors++;
						document.getElementById('lblSenderEmail').className = 'Red';
					} else {
						document.getElementById('lblSenderEmail').className = '';
					}
					// Email Subject
					if(!ValidateField(formObject.MailSubject.value,'AnyRequired')) {
						errorsArray[anyErrors] = new Array()
						errorsArray[anyErrors][0] = "Please enter your email subject.";
						anyErrors++;
						document.getElementById('lblMailSubject').className = 'Red';
					} else {
						document.getElementById('lblMailSubject').className = '';
					}
					// Email Message
					if(!ValidateField(formObject.MailMessage.value,'AnyRequired')) {
						errorsArray[anyErrors] = new Array()
						errorsArray[anyErrors][0] = "Please enter your message to the Instructor.";
						anyErrors++;
						document.getElementById('lblMailMessage').className = 'Red';
						//document.getElementById('frmMailMessage').style.borderColor = 'Red';
					} else {
						document.getElementById('lblMailMessage').className = '';
					}
					
					if (anyErrors) {
						for (i=0; i < anyErrors; i++) {
							theErrorMessage = theErrorMessage + (i+1) + ') ' + errorsArray[i][0] + '\n';
						}
						theResult = false;
						
						if (document.getElementById('appMessage')) {
							document.getElementById('appMessage').innerHTML = '<img style="vertical-align:text-bottom;" src="images/Error_16x16.gif" border="0" alt="Error" /> &nbsp;Please resolve issues below in red.';
							document.getElementById('appMessage').className = 'Red';
						}
						
						if (1 == 1) {
							if (anyErrors != 1) {
								alert('There were ' + anyErrors + ' errors:\n\n' + theErrorMessage);
							} else {
								alert('There was 1 error:\n\n' + theErrorMessage);
							}

						} else {
							document.getElementById('frmResultMessage').innerHTML = 'Please resolve issues below in red.';
							document.getElementById('frmResultMessage').className = 'Red';
						}
					} else {
						// No errors.  Form fields validated successfully.
						theResult = true;
					}
					break;
				default:
					// Specific form not defined.  Cannot validate.
					theResult = false;
			}
		} else {
			// Input not an object.  Cannot validate.
			theresult = false;
		}
		return theResult;
	}
	
// -->
