// JavaScript Document
//Form Validation Scripts
/* TO LINK TO THIS CODE USE: 
<script language = "JavaScript" SRC = "#secure_site#scripts/validation.js"></script> 
*/

function testInclude()
{
	alert("test");
}

function confirmSubmit(statement)
{
	var OK=confirm(statement);
	if (OK)
		return true ;
	else
		return false ;
}

function validate_textfield(field,fieldnametext)
{
	var alertmsg="You must complete the " + fieldnametext + " field.";
	var postedValue="";
	with (field)
	{
		postedValue=trim(value);
		if (postedValue==null||postedValue=="")
	  	{
			alert(alertmsg);
			return false;
		}
		else 
		{
			return true;
		}
	}
	
}
function validate_select(field,fieldnametext)
{
	var alertmsg="You must complete the " + fieldnametext + " field."
	
		var selectedvalue=field.options[field.selectedIndex].value; 
		if (selectedvalue==null||selectedvalue=="")
	  	{
			alert(alertmsg);
			return false;
		}
		else 
		{			
			return true;
		}
}
function validate_radio(field,fieldnametext)
{
	var alertmsg="You must complete the " + fieldnametext + " field."
	with (field)
	{
		len=field.length;
		for(i=0; i<len; i++)
		{
			if (field[i].checked)
			{
				return true;
			}
		}
		alert(alertmsg);
		return false;
	}
	
}
//validates single checkbox
function getIfChecked(field)
{
    var isChecked=false;
    if (field.checked)
    {
       isChecked = true;
     }        
    return isChecked;
}
//this function works on a set of checkboxes with the same name. 
//returns true if any one of them is checked, othrwise false
function getIfCheckedMltpl(field)
{
	var boxes=field.length;
    var isChecked=false;
    for (i=0; i<boxes; i++)
    {
        if (field[i].checked)
        {
            isChecked = true;
            break;
        }
    }    
    return isChecked;
}

//Email Validation
function emailvalidate(form_id,fieldname) {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   var address = document.forms[form_id].elements[fieldname].value;
   if(reg.test(address) == false) 
   {
      alert('Invalid Email Address');
      return false;
   }
   else
   {
	  return true; 
   }
}

//not sure which email validation is better. This needs anlaysis
function validateEmail2(email) 
{
    if(email.length <= 0)// is required
	{
	  return false;
	}
    var splitted = email.match("^(.+)@(.+)$");
    if(splitted == null) return false;
    if(splitted[1] != null )
    {
      var regexp_user=/^\"?[\w-_\.]*\"?$/;
      if(splitted[1].match(regexp_user) == null) return false;
    }
    if(splitted[2] != null)
    {
      var regexp_domain=/^[\w-\.]*\.[A-Za-z]{2,4}$/;
      if(splitted[2].match(regexp_domain) == null) 
      {
	    var regexp_ip =/^\[\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\]$/;
	    if(splitted[2].match(regexp_ip) == null) return false;
      }// if
      return true;
    }
return false;
}

function validateUCSCemail(field,fieldnametext)
{
	var msg="You have not entered a valid UCCSC email address. Please try again."
	with(field)
	{
		if (value !=null && value!="")
		{
			var end = value.length - 9
			var addr = value.substr(end,9)
			if(addr !="@ucsc.edu")
			{
				alert(msg);
				return false;
			}
			else
			{
				return true;	
			}
		}
		else
		{
			return validate_textfield(field,fieldnametext);			
		}
	}
}

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;
}

//used in isDate function
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;
}

//used in isDate function
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 );
}

//used in isDate function
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 trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}


//checks if field value is a date. Will accept the following date formats: mm/dd/yyyy, mm/dd/yy, m/d/yyyy, m/d/yy
//specify the recommended date format as the 3rd argument
function isDate(dtStr,fieldname, dateformat, field)
{	
	
	var strMonthArray = new Array(12);
	strMonthArray[0] = "January";
	strMonthArray[1] = "February";
	strMonthArray[2] = "March";
	strMonthArray[3] = "April";
	strMonthArray[4] = "May";
	strMonthArray[5] = "June";
	strMonthArray[6] = "July";
	strMonthArray[7] = "August";
	strMonthArray[8] = "September";
	strMonthArray[9] = "October";
	strMonthArray[10] = "November";
	strMonthArray[11] = "December";
	
	var strMonthArray2 = new Array(12);
	strMonthArray2[0] = "Jan";
	strMonthArray2[1] = "Feb";
	strMonthArray2[2] = "Mar";
	strMonthArray2[3] = "Apr";
	strMonthArray2[4] = "May";
	strMonthArray2[5] = "Jun";
	strMonthArray2[6] = "Jul";
	strMonthArray2[7] = "Aug";
	strMonthArray2[8] = "Sep";
	strMonthArray2[9] = "Oct";
	strMonthArray2[10] = "Nov";
	strMonthArray2[11] = "Dec";
	//replace commas with space	
	dtStr=dtStr.replace(',',' ');
	var t='';
	var prevT='';
	var newStr='';
	strLength=dtStr.length;
	//remove extra spaces or slashes
	dtStr=trim(dtStr);
	for(x=0; x < strLength; x++)
	{
		t=dtStr.charAt(x);
		if (t==' ' || t=='/')
		{
			if (prevT!=' ' && prevT!='/')
			{
				newStr=newStr + t;
			}		
		}
		else
		{
			newStr=newStr + t;
		}
		prevT=t;
	}
	dtStr=newStr.replace(/ /g,'/');
	var temp=new Array();
	var temp2=new Array();
	//create array of date parts
	temp=dtStr.split('/');
	//if day of month is before month, switch locations in array
	for (x=0; x<12; x++)
	{		
		if (temp[1]==strMonthArray[x] || temp[1]==strMonthArray2[x])
		{
			temp2[0]=temp[1];
			temp2[1]=temp[0];
			temp2[2]=temp[2];
			temp=temp2;
			break;
		}
	}
	//convert month to number if not already
	for (x=0; x<12; x++)
	{		
		if (temp[0]==strMonthArray[x] || temp[0]==strMonthArray2[x])
		{
			temp[0]=x+1;
			break;
		}
	}
	dtStr=temp.join('/');
	field.value=dtStr;
	
	var dtCh= "/";
	var minYear=1900;
	var maxYear=2100;
	var daysInMonth = DaysArray(12);
	var pos1=dtStr.indexOf(dtCh);
	var pos2=dtStr.indexOf(dtCh,pos1+1);
	var alertText = "";
	if (pos1 > -1)
	{
		var strMonth=dtStr.substring(0,pos1)
		if (pos2 > -1)
		{		
			var strDay=dtStr.substring(pos1+1,pos2)
			var strYear=dtStr.substring(pos2+1)
		}
		else
		{
			var strDay="1"
			var strYear=dtStr.substring(pos1+1)			
		}
	}
	if (pos1==-1 ){
		alertText="The date format should be : " + dateformat + " for the " + fieldname + " field";
		alert(alertText);
		return false
	}
	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)
	
	if(strYr.length==2)
	{		
		strYr="20" + strYr;
	}
	else
	{
		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 (strMonth.length<1 || month<1 || month>12)
	{
		alertText="Please enter a valid month for the " + fieldname + " field";
		alert(alertText);
		return false;
	}
	
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month])
	{
		alertText="Please enter a valid day or just enter the month and year for the " + fieldname + " field";
		alert(alertText);
		return false
	}
	
	if ( year==0 || year<minYear || year>maxYear)
	{
		alertText="Please enter a valid 4 digit year between "+minYear+" and "+maxYear + " for the " + fieldname + " field";
		alert(alertText);
		return false
	}
	if ((pos2 > 0 && dtStr.indexOf(dtCh,pos2+1)!=-1) || isInteger(stripCharsInBag(dtStr, dtCh))==false)
	{		
		alertText="Please enter a valid date for the " + fieldname + " field";
		alert(alertText);
		return false
	}	
	return true
}

//returns javascript date object. Useful when comparing user entered dates
function getJSdate(dtStr)
{
	var dtCh= "/";
	var pos1=dtStr.indexOf(dtCh);
	var pos2=dtStr.indexOf(dtCh,pos1+1);
	if (pos1 > -1)
	{
		var strMonth=dtStr.substring(0,pos1)
		if (pos2 > -1)
		{		
			var strDay=dtStr.substring(pos1+1,pos2)
			var strYear=dtStr.substring(pos2+1)
		}
		else
		{
			var strDay="1"
			var strYear =dtStr.substring(pos1+1)			
		}
		var myDate=new Date();
		myDate.setFullYear(strYear,strMonth-1,strDay);
		return myDate;
	}
	else
	{
		return -1;
	}
}

/* this function excepts times with format hh:mm am or pm in either upper or lower case
	with or without spaces. am or pm is required. To make optional */
	function isTime(timestring, ampm)
	{	
		// regular expression to match required time format
		if (ampm == 1)
		{
    		re = /^\d{1,2}:\d{2}\s*([aApP][mM]){1}$/;
		}
		else
		{
			re = /^\d{1,2}:\d{2}\s*([aApP][mM])?$/;
		}
    	if(timestring != '' && !timestring.match(re)) {
      	alert("You must use the format: hh:mm am");      	
      	return false;		
    	}	
		return true;	
	}
	
//returns location without named anchors. Useful when redirecting to filed due to user input error multiple times
function getLocNoPound()
{	
	var loc=location.href;
	var	temp=loc.split('#');
		loc=temp[0];
		return(loc);
}

function isZip(s) 
{
     // Check for correct zip code
     reZip = new RegExp(/(^\d{5}$)|(^\d{5}-\d{4}$)/);
	
     if (!reZip.test(s)) 
	 {
          alert("The ZIP code you entered is not valid");
          return false;
     }

	return true;
}

function isStateAbr(s)
{
	if(s.length == 2)
	{
		var valid_state = new RegExp(/^(AK|AL|AR|AZ|CA|CO|CT|DC|DE|FL|GA|HI|IA|ID|IL|IN|KS|KY|LA|MA|MD|ME|MI|MN|MO|MS|MT|NB|NC|ND|NH|NJ|NM|NV|NY|OH|OK|OR|PA|RI|SC|SD|TN|TX|UT|VA|VT|WA|WI|WV|WY)$/i);
		if (!valid_state.test(s))
		{
			alert("The state code you entered is not valid");
			return false;
		}
		else return true;
	}
	else 
	{
		alert("The state code you entered is not valid");
		return false;		
	}
}

//Function gives year in date as 2 digits, translate to 4 digits, otherwise retruns unchanged
//requires this years year in 2 digits and the date to be formatted
function getFormattedDate(thisYear_2Digit,datestring)
{
	datestringArray=datestring.split("/");	
	 
	if (datestringArray.length == 2 || datestringArray.length == 3)
	{		
		if (datestringArray.length == 3)
		{
			datestringMonth = datestringArray[0];
			datestringYear = datestringArray[2];
		}
		else if (datestringArray.length == 2)
		{
			datestringMonth = datestringArray[0];
			datestringYear = datestringArray[1];
		}	
		
		//if values are numbers, and length is 2, translate
		if (! isNaN(datestringMonth)&& ! isNaN(datestringYear))
		{			
			if (datestringYear.length == 2) 
			{
				if (datestringYear > (parseInt(thisYear_2Digit)+10))
				{
					datestringYear=parseInt(datestringYear) + 1900;
				}
				else
				{
					datestringYear=parseInt(datestringYear)+2000;
				}
				datestring=datestringMonth + "/" + datestringYear;				
			}						
		}				
	}	
	
	return datestring;
}