// Global variable defaultEmptyOK defines default return value 
// for many functions when they are passed the empty string. 
// By default, they will return defaultEmptyOK.
// Most of these functions have an optional argument emptyOK
// which allows you to override the default behavior for 
// the duration of a function call.
var defaultEmptyOK = false;

//VARIABLE DECLARATIONS
var mPrefix = "You did not enter a value into the ";
var mSuffix = " field. This is a required field. Please enter it now.";
var whitespace = " \t\n\r";
var iEmail = "This field must be a valid student Franklin email address (like foo@email.franklin.edu). Please enter it now.";

//Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function dropDownMenu(field) {
	var myindex=field.selectedIndex;
	if (myindex==0) {
		alert("\nYou must make a selection from the drop-down menu.");
		field.focus();
		return false;
	} else {
		return true;
    }
}

function checkEmpty(field,s) {
	var errorMsg = "";
	var value = field.value;
	
  	if(isEmpty(value)){
		errorMsg = s + " is required.";
		alert(errorMsg);
     	field.focus();
      	return false;
	} else {
		return true;
	}
}
  
function checkDigit(field,s) {
	var errorMsg = "";
	var value = field.value;
	
  	if(isEmpty(value)){
		errorMsg = s + " is required.";
	} else {
		if(!isInteger(value)){
			errorMsg = s + " must be an integer.";
		}
	}
	
	if(errorMsg != '') {
      alert(errorMsg);
      field.focus();
      return false;
    }
	return true;
}
  
//Check whether string s is empty.
function isEmpty(s) {
	return ((s == null) || (s.length == 0));
}
    
// Notify user that contents of field theField are invalid.
// String s describes expected contents of theField.value.
function warnInvalid (theField, s) {   
    theField.focus();
    theField.select();
    alert(s);
    return false;
}

// Returns true if string s is empty or 
// whitespace characters only.
function isWhitespace(s) {
    var i;
    // Is s empty?
    if (isEmpty(s)) 
          return true;
    for(i = 0; i < s.length; i++) {   
    	var c = s.charAt(i);
        if(whitespace.indexOf(c) == -1) 
        	return false;
    }
    return true;
}
     
// Notify user that required field theField is empty.
// String s describes expected contents of theField.value.
function warnEmpty (theField, s) {
      theField.focus();
      alert(mPrefix + s + mSuffix);
                  
      return false;
}

function checkString (theField, s, emptyOK)  {
	  // Next line is needed on NN3 to avoid "undefined is not a number" error
      // in equality comparison below.
      if (checkString.arguments.length == 2) emptyOK = defaultEmptyOK;
      if ((emptyOK == true) && (isEmpty(theField.value))) return true;
      if (isWhitespace(theField.value))
         return warnEmpty (theField, s);
      else return true;
}

// isEmail (STRING s [, BOOLEAN emptyOK])
function isEmail (s) {
	if (isEmpty(s)) 
         if (isEmail.arguments.length == 1) return defaultEmptyOK;
         else return (isEmail.arguments[1] == true);
     
    if (isWhitespace(s)) return false;
      
    // there must be >= 1 character before @, so we
    // start looking at character position 1 
    // (i.e. second character)
    var i = 1;
    var sLength = s.length;
      
    // do some preliminary checks for @. or ..  .@ or ending on .
    if(s.indexOf("@.") >= 0  || s.indexOf("..") >= 0  ||  s.charAt(sLength - 1) == "." )
    	return false;
      
    // look for @
    while ((i < sLength) && (s.charAt(i) != "@")) i++;

    if ((i >= sLength) || (s.charAt(i) != "@")) return false;
    else i += 2;
      
    // look for .'s
    while ((i < sLength) && (s.charAt(i) != ".")) i++;
    
    // there must be at least one character after the .
    if ((i >= sLength - 1) || (s.charAt(i) != ".")) return false; 
    else return true;
}

// checkEmail (TEXTFIELD theField [, BOOLEAN emptyOK==false])
//
// Check that string theField.value is a valid Email.
function checkEmail (theField, emptyOK) {
	if (checkEmail.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    else if (!isEmail(theField.value, false)) 
    	return warnInvalid (theField, iEmail);
    else return true;
}

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 = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31;
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30;}
		if (i==2) {this[i] = 29;}
   } 
   return this;
}

function checkDate(field){
	var daysInMonth = DaysArray(12);
	var pos1=field.value.indexOf(dtCh);
	var pos2=field.value.indexOf(dtCh,pos1+1);
	var strMonth=field.value.substring(0,pos1);
	var strDay=field.value.substring(pos1+1,pos2);
	var strYear=field.value.substring(pos2+1);
	strYr=strYear;
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1);
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1);
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1);
	}
	month=parseInt(strMonth);
	day=parseInt(strDay);
	year=parseInt(strYr);
	if (pos1==-1 || pos2==-1){
		alert("The date format should be : mm/dd/yyyy");
		field.focus();
		return false;
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month");
		field.focus();
		return false;
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day");
		field.focus();
		return false;
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear);
		field.focus();
		return false;
	}
	if (field.value.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(field.value, dtCh))==false){
		alert("Please enter a valid date");
		field.focus();
		return false;
	}
	return true;
}

//Original JavaScript code by Chirp Internet: www.chirp.com.au
// Please acknowledge use of this code by including this header.
function checkTime(field) {
	var errorMsg = "";

	// regular expression to match required time format
	re = /^(\d{1,2}):(\d{2})(:00)?([ap]m)?$/;
  
	if(field.value != '') {
		if(regs = field.value.match(re)) {
			if(regs[4]) {
				// 12-hour time format with am/pm
				if(regs[1] < 1 || regs[1] > 12) {
					errorMsg = "Invalid value for hours: " + regs[1];
				}
			} else {
				// 24-hour time format
				if(regs[1] > 23) {
					errorMsg = "Invalid value for hours: " + regs[1];
				}
			}
			if(!errorMsg && regs[2] > 59) {
				errorMsg = "Invalid value for minutes: " + regs[2];
			}
		} else {
			errorMsg = "Invalid time format" ;
		}
	} else {
		if(field.name == 'stime')
			errorMsg = "Start Time is required.";
		if(field.name == 'etime')
			errorMsg = "End Time is required.";
	}

	if(errorMsg != "") {
		alert(errorMsg);
		field.focus();
		return false;
	}
  
	return true;
}

function checkLength(field, s, length) {
  	if(field.value.length > length) {
  		errorMsg = "Please enter the "+s+" less then "+length+" characters.";
		alert(errorMsg);
     	field.focus();
      	return false;
    } else {
		return true;
	}
}

function isUsernameOnly(s) {
	// Search through string's characters one by one
	// until we find an @ character. If we find one, return false;
	// if we don't, return true.
	for (var i = 0; i < s.value.length; i++) {
		// Check that current character isn't @
		if (s.value.charAt(i) == "@") {
    		return false;
		}
	}
	// No character is @
	return true;
}

function isArray(testObject) {   
    return testObject && typeof testObject === 'object' && typeof testObject.length === 'number';
}

function checkbox_checker(items, msg) {
	// set var checkbox_choices to zero
	var checkbox_choices = 0;
	var checkbox_defaultchoices = 0;

	if (!isArray(items)) {
		if (items.checked && !items.defaultChecked) checkbox_choices = checkbox_choices + 1;
	} else {
		// Loop from zero to the one minus the number of checkbox button selections
		for (var counter = 0; counter < items.length; counter++) {
			// If a checkbox has been selected it will return true
			// (If not it will return false)
			if (items[counter].checked ) {
				checkbox_choices = checkbox_choices + 1; 
			}

			if (items[counter].defaultChecked) { 
				checkbox_defaultchoices = checkbox_defaultchoices + 1; 
			}	
		}
	}
	if(checkbox_choices == 0 || checkbox_choices == checkbox_defaultchoices) {
		alert(msg);
		return false;
	}

	return true;
}

function checkPhoneNumber(field) {
	var errorMsg = "Please enter your 10-digit phone number";
	var patt = /(\d{3})\D*(\d{3})\D*(\d{4})/;
	
	if (field.value != '') {
		if (regs = field.value.match(patt)) {
			field.value = "(" + regs[1] + ")-" + regs[2] + "-" + regs[3];
		} else {
			alert(errorMsg);
			return false;
		}
	}
	
	return true;	
}