// Set RegEx Variables
var r_end      = /[a-z0-9]$/i;
var r_name     = /^[a-z \- ]*$/i;
var r_city     = /^[a-z .-]*$/i;
var r_phone    = /^\(?\d{3}\)?[ \-]?\d{3}[ \-]?\d{4}$/;
var r_phoneN   = /[() \-]/g;
var r_password = /^.{6,30}$/i;
var r_start    = /^[a-z0-9]/i;
var r_email    = /^[a-z0-9]+[-a-z0-9._'+]*@[-a-z0-9_']+(\.[-a-z0-9_']{1,})*\.[a-z0-9]{2,}/i;
var el;
var msg;


function v_name(input,f_or_l) { 
  if (!r_name.test(input.value)) {
    alert ('Please use only letters for your '+f_or_l+' Name'); 
    input.focus(); 
    return false;
  }
  if (input.value == '') {
    alert('Please enter your '+f_or_l+' Name');
    input.focus(); 
    return false;
  }
  return true;
}

function v_city(input, req) { 
  if ( req && (input.value == '')) {
    alert ('City is required'); 
    input.focus(); 
    return false;
  }
  if ((input.value != '') &&(!r_city.test(input.value))) {
    alert ('City is invalid'); 
    input.focus(); 
    return false;
  }
  return true;
}


function v_state(input) {
  profileForm = document.getElementById("profileForm");
  if (document.profileForm.getElementById("address.state").value == 'Unknown') {
    alert ('Please select a state');
    input.focus(); 
    return false;
  }
  return true;
}


function v_country(input) {
  if (input.value == 'Unknown') {
    alert ('Please select a country');
    input.focus(); 
    return false;
  }
  return true;
}



function v_phone(input, type, req) { 
  if ( req && (input.value == '')) {
    alert (type + ' Phone is required'); 
    input.focus(); 
    return false;
  }
  if ((input.value != '') &&(!r_phone.test(input.value))) {
    alert (type + ' ' + 'Phone is invalid'); 
    input.focus(); 
    return false;
  }
  input.value = input.value.replace(r_phoneN, '');
  return true;
}

function v_email(input) {
 msg="";
  email = input;
    if (!r_start.test(email)) {
      msg = "Email address must begin with a letter or number"; 
    } else if (email.indexOf('@', 1) == -1) {
      msg = "Email address must contain an \'@\' character"; 
    } else if (email.indexOf('.', email.indexOf('@', 0)) == -1) {
      msg = "Email address must contain a \'.\' character after the \'@\'"; 
    } else if (input.length  - email.indexOf('.', 0)  < 3 ) {
      msg = "Email address must have at least two characters after the  \'.\' character"; 
    } else if (!r_end.test(email)) { 
      msg = "Email address cannot end with a \" " +email.charAt(email.length - 1 )+ " \""; 
    } else if (!r_email.test(email)){
      msg = "Please use a valid email address";
    }

  if (msg) {
    alert (msg); 
    input.select();
    input.focus(); 
    return false;
  }
  return true;
}


function v_password(input) {
msg="";
  if (!r_password.test(input.value)) {
    msg='Password must be at least 6 characters';
  } else if (input.value == '') {
    msg = 'Please enter a Password';
  } else if (input.value.toLowerCase() == 'password' || input.value == '123456'){
    msg = 'You have entered an invalid password.'
  }
  if (msg) {
    alert (msg); 
    input.select();
    input.focus(); 
    return false;
  }
  return true;
}


function v_address(input) {
msg="";
normInput = input.value.toLowerCase()
//  if ((normInput.indexOf("p.o. box") != "-1" ) || (normInput.indexOf("po box") != "-1" ) || (normInput.indexOf("post office box") != "-1" )) {
//    msg = 'You cannot provide a P.O. Box as an address.'
//  } else 
	if (input.value == '') {
    msg = 'Please enter your address';
  } 
  if (msg) {
    alert (msg); 
    input.select();
    input.focus(); 
    return false;
  }
  return true;
}

function v_passmatch() {
  msg="";
 input = el.password1;
  if (el.password1.value != el.password2.value) {
    msg='Passwords must match'; 
  }
  if (msg) {
    alert (msg); 
    input.select();
    input.focus(); 
    return false;
  }
  return true;
}

function enhancedgender(input) {
  if (input.selectedIndex == 0) {
    alert('Please select your gender');
    input.focus();
    return false;
  }
  return true;
}

function checkage(inputMonth,inputDate,inputYear) {
 // Get our values and cast as integers
 var month = parseInt(inputMonth.value, 10);
 var date = parseInt(inputDate.value, 10);
 var year = parseInt(inputYear.value, 10);

 // Convert our month to zero-based index for javascript 
 // b/c EMP expects vals 1-12 from the reg form and js works w/ 0-11
 month = (month - 1);

 // Make sure we have some values
 if( isNaN(month) || isNaN(date) || isNaN(year) ){
   alert("Please enter your full date of birth.")
   return false;
 }

 // Now see if we have a valid date
 if(!IsValidDate(month,date,year) ){
   return false;
 }

 // See if the user is eighteen years old or not
 if( GetAge(month, date, year) < 18 ) {
   alert("We're sorry.  You are not eligible to sign up for MyPoints.")
   return false;
 }

 return true;
}

function v_zipcode(input) {
  if (input.value == '') {
    alert ('Please enter your Postal/Zip Code');
    input.focus(); 
    return false;
  }
  return true;
}

function enhancedzip(input) {
  if (!input.value) {
    alert('Zip code is required');
    input.focus();
    return false;
  }
  if (input.value.length < 5) {
    alert('Zip code must be at least 5 characters');
    input.focus();
    return false;
  }
  return true;

}

function v_vuser(){
  if(el.vuser != null && el.vuserName != null){
    if(!customValidation()) return false;
  }
  return true;
}
//**********************************************************
function profileValidation(myForm) {
  if (!v_name(myForm.firstName, 'First')) return false;
  if (!v_name(myForm.lastName, 'Last')) return false;
  if (!enhancedgender(myForm.genderCode)) return false;
  if (!v_phone(myForm.homePhone, 'Home', false)) return false;
  if (!v_phone(myForm.altPhone, 'Alternate', false)) return false;
  
  if (!v_city(myForm["address.city"], false)) return false;
//  if (!checkage(myForm.birthDateMonth,myForm.birthDateDay,myForm.birthDateYear)) return false;
  if (!enhancedzip(myForm["address.postalCode"])) return false;
return true;
}

function TrackSubmit() {
document.getElementById("submitTracker").src = 'https://www.mypoints.com/emp/u/a.do?cell=PDKs5dadc33PT_xZkA9s';
// alert ("src changed - click tracked:" + document.getElementById('submitTracker').src );
}

function SetACookie(cookieName,cookieValue,nDays) {
 var today = new Date();
 var expire = new Date();
 if (nDays==null || nDays==0) nDays=1;
 expire.setTime(today.getTime() + 3600000*24*nDays);
 document.cookie = cookieName+"="+escape(cookieValue) + ";expires="+expire.toGMTString();
}


function submitProfile() {
proForm = document.getElementById("profileForm");
// alert ("img should have loaded - submitting");
proForm.submit();
}


function profileValidator() {
    var agt=navigator.userAgent.toLowerCase();
	if ((agt.indexOf("msie") != -1)) {
	//alert ("IE");
	profileFormer = document.forms("profileForm");
	} else {
	profileFormer = document.getElementById("profileForm");
	}
	if (!v_name(profileFormer.firstName,'First')) return false;
	if (!v_name(profileFormer.lastName,'Last'))  return false;
	//if (!v_city(profileFormer["address.city"], true)) return false;
	if (!enhancedgender(profileFormer.genderCode)) return false;
	if (!enhancedzip(profileFormer["address.postalCode"])) return false;
	if (!IsValidDate(parseInt(profileFormer.birthDateMonth.options[profileFormer.birthDateMonth.selectedIndex].value,10)-1,profileFormer.birthDateDay.options[profileFormer.birthDateDay.selectedIndex].value,profileFormer.birthDateYear.options[profileFormer.birthDateYear.selectedIndex].value)) return false;
	//if (!v_phone(profileFormer.homePhone, 'Home', true)) return false;
	//if (!v_phone(profileFormer.altPhone, 'Alternate', false)) return false;
	//if (!v_address(profileFormer["address.street1"], true)) return false;
//  if (!v_address(profileFormer["address.street2"], false)) return false;
//  if (!checkage(profileFormer.birthYear)) return false;
//  if (!v_state(profileInfo)) return false;
//  if (!v_country(profileFormer["address.country"])) return false;
//	v_state();
	SetACookie("BTS_edit","Somevalue","60");
	submitProfile();
//	return true;
}




function enhancedValidator() {
el = document.signup;
  if (!v_name(document.getElementById("fname"),'First')) return false;
  if (!v_name(document.getElementById("lname"),'Last'))  return false;
  if (!checkage(el.birthDateMonth,el.birthDateDay,el.birthDateYear)) return false;
  //if (!v_email(el.email)) return false;
	if (!v_email(document.getElementById("email").value)) return false;
  if (!v_password(el.password1)) return false;
  if (!v_password(el.password2)) return false;
  if (!v_passmatch()) return false;
  if (!enhancedgender(el.genderCode)) return false;
  if (!enhancedzip(el.zipcode)) return false;
//  if (!v_zipcode(el.zipcode)) return false;
  if (!v_vuser()) return false;
//  el.submit()
  return true;
}


function passwordResetValidator(whichform) {
 el = document.forms[whichform];
  if (!v_password(el.oldPassword)) return false;
  if (!v_password(el.password1)) return false;
  if (!v_password(el.password2)) return false;
  if (!v_passmatch()) return false;
  el.submit()
//  return true;
}

function sendIt() {
  if (!enhancedValidator()) return false
  //append the hidden field to the form
  var el = document.signup;
  if (GetCookie ("cellVal"))  {
    //modify the cell hidden field
    el.cell.value = GetCookie ("cellVal")  //TODO: this step doesn't appear to be necessary.  check to see if we can remove it.
    if (GetCookie ("vUser")) {
      var oNewNode = document.createElement("INPUT");
      oNewNode.value = GetCookie ("vUser");
      oNewNode.type = "text";
      oNewNode.name = "vuser";
      oNewNode.id = "vuser";
      oNewNode.setAttribute("type","hidden"); 
      el.appendChild(oNewNode);
      //alert(el.vuser.value);
    }//end if vuser cookie  
  }//end if cellval cookie
  document.signup.submit()
}//end function

// function to enforce a maximum character length for a field
function CheckLength(oField,intMaxLength){
  if(!oField || !intMaxLength) return;

  var strValue = new String();
  strValue = oField.value;
  if(strValue.length > intMaxLength){
    oField.value = strValue.substr(0,intMaxLength);
  }else{
    return;
  }
}

// function to detect whether the 'Enter' key has been pressed
// (mostly useful when called from a form's onKeyPress event --> to submit the form if true)
function detectEnter(e)
{
  if(!e){ var e = window.event; }

  if (e.keyCode){
    var code = e.keyCode; 
  }else if (e.which){
    var code = e.which; 
  }
  
  if(code == 13){ //if generated character code is equal to ascii 13 (if enter key)
    return true; 
  }else{ 
    return false; 
  }
}


