//if check passes return true, else return false
function checkValue (elem, checkType, isRequired, msgID, optionalParam) {
  var result     = true;
  var fieldStyle = "alertField";
  
  if( isRequired && !checkRequired(elem))  {
	msg(msgID,"MISSING",elem.id,fieldStyle);
	result = false;
  } else {
    switch( checkType ) {
    case "email": 
      if( (trim(elem.value) != "") && !checkEmail(elem.value) ) {
        msg(msgID,"INVALID VALUE",elem.id,fieldStyle);
        result = false;
      }
      break;
    case "number":
      if( (trim(elem.value) != "") && !isNaN(elem.value) ) {
        msg(msgID,"INVALID VALUE",elem.id,fieldStyle);
        result = false;
      }
      break;
    case "username":
      if( (trim(elem.value) != "") && !checkUsername(elem.value) ) {
        msg(msgID,"INVALID VALUE",elem.id,fieldStyle);
        result = false;
      }
      break;
    case "password":
      if( (trim(elem.value) != "") && !checkPassword(elem.value,6,10) ) {
        msg(msgID,"INVALID VALUE",elem.id,fieldStyle);
        result = false;
      }
      break;
    case "match":
      if( !checkMatch(elem.value,optionalParam) ) {
        msg(msgID,"VALUE MISMATCH",elem.id,fieldStyle);
        result = false;
      }
      break;
    case "zip":
      if( (trim(elem.value) != "") && !checkZip(elem.value) ) {
        msg(msgID,"INVALID VALUE",elem.id,fieldStyle);
        result = false;
      }
      break;
    case "phone":
      if( (trim(elem.value) != "") && !checkPhonePart(elem.value, optionalParam) ) {
        msg(msgID,"INVALID VALUE",elem.id,fieldStyle);
        result = false;
      }
      break;
    case "CID":
      if( (trim(elem.value) != "") && !checkCID(elem.value,optionalParam) ) {
        msg(msgID,"INVALID VALUE",elem.id,fieldStyle);
        result = false;
      }
      break;
    case "CCNumber":
      if( (trim(elem.value) != "") && !checkCCNumber(elem.value,optionalParam) ) {
        msg(msgID,"INVALID VALUE",elem.id,fieldStyle);
        result = false;
      }
      break;
    default: 
    }
  }
  if( result && (checkType != "phone") ) { // if the check passes clear any error messages and alerts
    msg(msgID,"",elem.id,"");
  }
  
  return result;
} 

function checkAge(month, day, year, isRequired, msgID, optionalParam){
var fieldStyle = "alertField";
var result     = true;
if( isRequired && (!checkRequired(month) || !checkRequired(day) || !checkRequired(year)) )  {
 if(!checkRequired(month)){msg(msgID,"MISSING BIRTH DATE",year.id,fieldStyle);}
 if(!checkRequired(day)){msg(msgID,"MISSING BIRTH DATE",month.id,fieldStyle);}
 if(!checkRequired(year)){msg(msgID,"MISSING BIRTH DATE",day.id,fieldStyle);}
 result = false;
} else {
 var age = CalculateAge(month.value+day.value+year.value);
 if(age<13){
  msg(msgID,"We’re sorry; you must be 13 years old to belong to our mailing list.",year.id,fieldStyle);
  result = false;
 }
}
   return result;
}


function trim(str) {
  return str.replace(/^\s+|\s+$/g, '')
}

// displays any error messages and changes form field classes
function msg(alertID, alertMsg, fieldID, fieldStyle) {
  //check to make sure browser supports this method
  if( document.getElementById ) {
    //check to make sure this element exists
    if( document.getElementById(alertID) ) {
      //set the alert message
  	  document.getElementById(alertID).innerHTML = alertMsg;
    }
    if( document.getElementById(fieldID) ) {
      //set the field class
  	  document.getElementById(fieldID).className = fieldStyle;
    }
  }
}

function checkRequired(elem){
  var result = true;
  
  if( (elem != null) ) {
    if( elem.type.toLowerCase() == "select-one" ) {
      if( (elem.options[elem.selectedIndex].value == "") || (elem.options[elem.selectedIndex].value == "XX") ) {
        result = false;
      }
    } else {
      if( trim(elem.value) == "" ) {
        result = false;
      }
    }
  } else {
    result = false;
  }
  
  return result;
}

// email
function checkEmail (strng) {
  var result = true;
  var emailFilter=/^.+@.+\..{2,3}$/;
  var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/; //test email for illegal characters
  
  if ( !(emailFilter.test(strng)) || strng.match(illegalChars) ) { 
    result = false;
  }
  return result;    
}

// phone number - strip out delimiters and check for 10 digits
function checkFullPhone (strng) {
  var result = true;
  var stripped = strng.replace(/[\(\)\.\-\ ]/g, ''); //strip out acceptable non-numeric characters
  
  if( (isNaN(stripped)) || !(stripped.length == 10) ) {
    result = false;
  }
  return result;
}

// phone number - used for each individual phone field
function checkPhonePart(strng, partlength) {
  var result = true;

  if( (isNaN(strng)) || !(strng.length == partlength) ) {
    result = false;
  }
  return result;
}

// phone number - check all 3 fields of a phone
function checkPhone( prefix, isRequired ) {
  var result = true;
  var msgID = "msg_" + prefix;
  var fieldID = "";
  var partlength = Array(0,3,3,4); //  THIS VARIABLE HOLDS THE LENGTH OF THE CORRESPONDING PHONE PART - VALUE AT INDEX 1 IS NOT USED
  
  for(i=3; i>0; i--) {  // LOOP THRU ALL 3 PHONE FIELDS STARTING W/THE LAST
    fieldID = prefix + i; // CALCULATE THE CURRENT FIELD ID
    if( !checkValue( (document.getElementById(fieldID)), "phone", isRequired, msgID, partlength[i]) ) { 
      result = false; 
    } else {
	  msg(false,"",document.getElementById(fieldID).id,"");  // VALUE VALIDATES, CLEAR ITS BOX OF ANY STYLE WARNINGS
	}
  }
  if( result ) {  // ALL 3 FIELDS VALIDATE, CLEAR ANY WARNING MESSAGES
    msg(msgID,"",false,"");
  }
  
  return result;
}
// checks if date passed is valid
// will accept dates in following format:
// isDate(dd,mm,ccyy), or
// isDate(dd,mm) - which defaults to the current year, or
// isDate(dd) - which defaults to the current month and year.
// Note, if passed the month must be between 1 and 12, and the
// year in ccyy format.
function isValidDate (day,month,year) {
    var today = new Date();
    year = ((!year) ? today.getFullYear():year);
    month = ((!month) ? today.getMonth():month-1);
    
    if (!day) return false
    
    var test = new Date(year,month,day);
    if ( (test.getFullYear() == year) && (month == test.getMonth()) && (day == test.getDate()) ) {
        return true;
    } else {
        return false;
    }
}

// valid date - check all 3 fields of a date
function checkDate( msgID, elemDay, elemMonth, elemYear ) {
	var result		= true;
	var fieldStyle = "alertField";
	
	if( isValidDate(elemDay.value, elemMonth.value, elemYear.value) ) {
		var today		= new Date();
		var this_month	= today.getMonth() + 1;
		var this_year	= today.getFullYear();
		var this_day	= today.getDate();
	
	  	if ( this_year == elemYear.value ){
			if (this_month > elemMonth.value){
				msg("","",elemDay.id,"");
				msg("","",elemYear.id,"");
				msg(msgID,"INVALID MONTH",elemMonth.id,fieldStyle);
				result = false;
			} else if ( (this_month >= elemMonth.value) && (this_day > elemDay.value) ){
				msg("","",elemMonth.id,"");
				msg("","",elemYear.id,"");
				msg(msgID,"INVALID DAY",elemDay.id,fieldStyle);
				result = false;
			} 
		} else {
			msg("","",elemMonth.id,"");
			msg("","",elemDay.id,"");
			msg(msgID,"",elemYear.id,"");
		}	
	} else {
		result = false;
		msg("","",elemMonth.id,fieldStyle);
		msg("","",elemDay.id,fieldStyle);
		msg(msgID,"INVALID DATE",elemYear.id,fieldStyle);
	}

	return result;
}

// password - between 6-8 chars, uppercase, lowercase, and numeral
function checkPassword (strng, minlength, maxlength) {
  var result = true;
  var illegalChars = /[\W_]/; // allow only letters and numbers
    
  if ((strng.length < minlength) || (strng.length > maxlength)) {
    result = false;
  } else if (illegalChars.test(strng)) {
    result = false;
  } else if (!((strng.search(/(a-z)+/)) && (strng.search(/(A-Z)+/)) && (strng.search(/(0-9)+/)))) {
    result = false;
  }  
  return result;    
}    


// username - 4-10 chars, uc, lc, and underscore only.
function checkUsername (strng, minlength, maxlength) {
  var result = true;
  var illegalChars = /\W/; // allow letters, numbers, and underscores
    
  if ((strng.length < minlength) || (strng.length > maxlength)) {
    result = false;
  } else if (illegalChars.test(strng)) {
    result = false;
  } 
  return result;
}   

// zip - check for 5 digits
function checkZip(strng) {
  var result = true;
  
  if( !(strng.length == 5) ) {
    result = false;
  }
  return result;
}    

// string match
function checkMatch(strng,comparestr) {
  var result = true;
   
  if (strng != comparestr) {
     result = false;
  }
  return result;
}  

function checkRadio(formObj,radioname) {
 var result = false;
 var el = formObj.elements;
 
 for(var i = 0 ; i < el.length ; i++) {
  if( (el[i].type == "radio") && (el[i].name == radioname) ) {
   //alert("NAME: " +el[i].name + " TYPE: " + el[i].type);
   if( el[i].checked ) { result = true; }
  }
 }
 return result;
 
}

// check CID against credit card type
function checkCID(strng,ccType) {
  var result = true;
  
  if( !isNaN(strng) ) {
    if( ccType == "American Express" ) { 
      if( strng.length != 4 ) {
        result = false;
      }    
    } else {
      if( strng.length != 3 ) {
        result = false;
      }
    }
  } else {
    result = false;
  }

  return result;
}

function checkCCNumber(strng,ccType) {
  var result = true;

  switch( ccType ) {
  case "PacSun Private Label":
    if( (strng.length != 11) || (strng.substring(0,1) != "0") ) {
      result = false;
    }
    break;
  case "MasterCard":
    if( (strng.length != 16) || (strng.substring(0,1) != "5") ) {
      result = false;
    } 
    break;
  case "Visa":
    if( (strng.length != 16) || (strng.substring(0,1) != "4") ) {
      result = false;
    } 
    break;
  case "American Express":
    if( (strng.length != 15) || (strng.substring(0,1) != "3") ) {
      result = false;
    } 
    break;
  case "Discover":
    if( (strng.length != 16) || (strng.substring(0,1) != "6") ) {
      result = false;
    } 
    break;
  default: result = false;
  }

  return result;
}


/******************************************************************************
 * method: CalculateAge
 *
 * author: Jason Geissler
 *
 * date: April 15, 2003
 *
 * parameters: date
 *
 * purpose: Calculates an age for a date
 *****************************************************************************/
var format = ""; // Can be Years, Months, Days for age 
 
function CalculateAge(date) {
  var slashIndex = date.indexOf("/");
  var birthday, birthmonth, birthyear;
  
  if (slashIndex != -1) { // With slashes
    var segments = date.split("/");
    birthmonth = segments[0];
    birthday = segments[1];
    birthyear = segments[2];
  }
  else {                  // No slashes
    birthmonth = date.substring(0, 2);
    birthday = date.substring(2, 4);
    birthyear = date.substring(4, date.length);
  }
  
  var today = new Date();
  var thisDay = today.getDate();        // Returns the day of the month
  var thisMonth = today.getMonth() + 1; // Need to add a one since the month is zero based - January
  var thisYear = today.getFullYear();   // Returns the year
  
  var yearsDiff = CalculateYear(birthyear, thisYear);
  var monthsDiff = CalculateMonth(birthmonth, thisMonth);
  var daysDiff = CalculateDay(birthday, thisDay);
  format = "Years"; // set the format to years
  
  // For the year is greater than zero
  if (yearsDiff > 0) {
    if (monthsDiff > 0) {    // Month is greater than zero so return we have our age
      return yearsDiff;
    }
    else if (monthsDiff < 0) { // Month is less than zero so return the age minus 1
      if (yearsDiff != 1) {
        return yearsDiff - 1;
      }
      else {
        if (monthsDiff == -11) { // Turn of the year
          if (daysDiff >= 0) {   // greater than one month
            format = "Months";
            return 1;
          }
          else {                // less than one month
            format = "Days";
            return thisDay - (31 - birthday);
          }
        }
        else {
          format = "Months";    // Next year but not quite a year old
          if (daysDiff >= 0) {
            return thisMonth + (12 - birthmonth);
          }
          else {
            return thisMonth + (12 - birthmonth) - 1;
          }
        }
      }      
    }  
    else {                 // We are in the persons birth month
      if (daysDiff >= 0) { // Today is greater or equal to the person's birthdate
        return yearsDiff;
      }
      else if (daysDiff < 0 && yearsDiff != 1) { // Today is less than the person's birthdate
        return yearsDiff - 1;
      }
      else {
        format = "Months";
        return 11;
      }
    }
  }
  else {  // For the year equaling zero or same year as birthdate
    format = "Months";
    if (monthsDiff > 0) { // Later in the same year
      if (daysDiff >= 0) {
        return monthsDiff;
      }
      else {
        if (monthsDiff != 1) {
          return monthsDiff - 1;
        }
        else {
          format = "Days";
          return thisDay + (DaysInMonth(birthmonth, birthyear) - birthday);
        }
      }
    }
    else {  // Same month as birth month
      format = "Days";
      if (daysDiff == 0) {
        return 1; // Today's the birthdate
      }
      else {
        return daysDiff;
      }
    }
  }              
}

/******************************************************************************
 * method: CalculateYear
 *
 * author: Jason Geissler
 *
 * date: April 15, 2003
 *
 * parameters: birthYear, thisYear
 *
 * purpose: Calculates the year based on the offsets between the birthyear and 
 *          thisYear
 *****************************************************************************/
function CalculateYear(birthYear, thisYear) {
  return thisYear - birthYear;
}  

/******************************************************************************
 * method: CalculateMonth
 *
 * author: Jason Geissler
 *
 * date: April 15, 2003
 *
 * parameters: birthMonth, thisMonth
 *
 * purpose: Calculates the month based on the offsets between the birthMonth and 
 *          thisMonth
 *****************************************************************************/
function CalculateMonth(birthMonth, thisMonth) {
  return thisMonth - birthMonth;
} 

/******************************************************************************
 * method: CalculateDay
 *
 * author: Jason Geissler
 *
 * date: April 15, 2003
 *
 * parameters: birthday, thisday
 *
 * purpose: Calculates the month based on the offsets between the birthDay and 
 *          thisDay
 *****************************************************************************/
function CalculateDay(birthDay, thisDay) {
  return thisDay - birthDay;
} 

/******************************************************************************
 * method: DaysInMonth
 *
 * author: Jason Geissler
 *
 * date: April 15, 2003
 *
 * parameters: birthday, thisday
 *
 * purpose: Calculates the days in the month based on month (year for leap year
 *
 *****************************************************************************/
function DaysInMonth(month, year) {
  month -= 0;
  if (month == 2) {
    var leapYear = IsLeapYear(year);
  }
  
  switch (month) {
    case 1:
    case 3:
    case 5:
    case 7:
    case 8:
    case 10:
    case 12:
      return 31;
    case 4:
    case 6:
    case 9:
    case 11:
      return 30;
    case 2:
      if (leapYear) {
        return 29;
      }
      else {
        return 28;
      }
  }
}
/******************************************************************************
 * method: IsLeapYear
 *
 * author: Jason Geissler
 *
 * date: April 28, 2002
 *
 * parameters: year
 *
 * purpose: Checks to see if the year is a leap year, we can do this
 *          with 4 digit years
 *****************************************************************************/
function IsLeapYear(year) {
  var betweenYears = 4;                  // We also know that there is 4 years between leap years
  var leapYear = 2000;
  year = leapYear - year;                // Set year to the difference see if it's divisible by 4
  var remainder = year % betweenYears;

  if (remainder == 0) {
    return true;
  }
  return false;
}


/******************************************************************************
 * method: HandleSlashes
 *
 * author: Jason Geissler
 *
 * date: September 12, 2002
 *
 * parameters: date
 *
 * purpose: Inserts a "/" into a date based on date size
 *****************************************************************************/
function HandleSlashes(date) {
  date = date.substring(0, 2) + "/" + date.substring(2, 4) + "/" + date.substring(4, date.length);  
  return date;
}


/******************************************************************************
 * method: HandleDashes
 *
 * author: Jason Geissler
 *
 * date: September 12, 2002
 *
 * parameters: date
 *
 * purpose: Inserts a "-" into a date based on date size
 *****************************************************************************/
function HandleDashes(date) {
  date = date.substring(0, 4) + "-" + date.substring(4, 6) + "-" + date.substring(6, date.length);
  return date;
}
