// emailpreferences.js



// Function to validate the email address
function validateEmail() {
	var email = document.getElementById("email").value;
	email = trimspaces(email);
	document.getElementById("email").value = email;
	
	// Any processing should be performed only if the User has changed the email 
	// address except in the 3 cases below
	// 1. when the user clicks on "Retrieve" with a blank email   -> if (email!="")
	// 2. When the user updates the email and gets the confirmation page -> updateFlag!=null && updateFlag!='Y'
	// 3. When the page is loaded with the email id pre-populated -> emailFound!='N'
	if (email!="") {
		var preEmailId = document.getElementById("preEmail").value;
		if (emailFound!= null && emailFound == 'N' && preEmailId==email && updateFlag!=null && updateFlag!='Y') {
			return false;	
		}
	}
	
	// remove the errors
	//document.getElementById('emailerror').innerHTML = '';
	var message = verifyEmail(email);
	if (message=='') // no error return true to submit
	{
		return true;
	} 
	else // Add the message to the div and display the div
	{	
		document.getElementById('emailerror').innerHTML = '<br/>'+message;
		document.getElementById('emailerror').style.display = 'inline';
		document.getElementById('javaerror').style.display = 'none';
		return false;
	}
}





//Function to validate the Email Preferences Update Action 
function validateUpdate() 
{
	var hiddenEmail = document.getElementById("preEmail").value;
	var email = trimspaces(document.getElementById("email").value);
	if (hiddenEmail != email) 
	{
		var message = "Please retrieve your e-mail preferences again if a different e-mail address has been entered.";
		document.getElementById("preferencesDiv").style.display = "none";
		document.getElementById('emailerror').innerHTML = '<br/>'+message;
		document.getElementById('emailerror').style.display = 'inline';
		document.getElementById('javaerror').style.display = 'none';
		return false;
	}
	
	
	
	// Check if the preferences have changed. User should not be allowed to update if he has not changed the
	// preferences
	if (checkChangedPreferences()==false) 
	{
		document.getElementById('updateerror').innerHTML = "If you would like to change your e-mail preferences, please choose other options before submitting this request.";
		document.getElementById('updateerror').style.display = 'inline';
		return false;	
	}


	document.getElementById('updateerror').innerHTML = '';
	var name = document.getElementById("name").value;
	name = trimspaces(name);
	document.getElementById("name").value = name;
	if (name==null || name=="") {
		document.getElementById('updateerror').innerHTML = "Please enter your name.";
		document.getElementById('updateerror').style.display = 'inline';
		document.getElementById("name").focus();
		return false;
	}
	
	if (checkForSpecialCharsandNumbers(name)==false)
	{
		document.getElementById('updateerror').innerHTML = "Please use valid characters for your name.";
		document.getElementById('updateerror').style.display = 'inline';
		document.getElementById("name").focus();
		document.getElementById("name").select();
		return false;
	}
	
	// Check if there are consecutive 2 periods or hyphens, these must be invalid
	var nameField=document.getElementById("name");
	var foundConsecutiveHyphens=nameField.value.indexOf("--");
	var foundConsecutivePeriods=nameField.value.indexOf("..");	
	if (foundConsecutiveHyphens!=-1 || foundConsecutivePeriods!=-1){
		document.getElementById('updateerror').innerHTML = "Please use valid characters for your name.";
		document.getElementById('updateerror').style.display = 'inline';
		document.getElementById("name").focus();
		document.getElementById("name").select();
		return false;
	}	
	
	if (countLetters(name) < 2)
	{
		document.getElementById('updateerror').innerHTML = "Please use valid characters for your name.";
		document.getElementById('updateerror').style.display = 'inline';
		document.getElementById("name").focus();
		document.getElementById("name").select();
		return false;
	}

	
	// Confirm the change
	if (confirm("This is to confirm that you are requesting to update your e-mail preferences. Click OK to submit changes."))
	{
		document.getElementById("commandId").value="changeEmailPref";
		return true;		
	} 
	else
	{
		return false;
	}
	
	return true;
}



// Function to check if the user has made any changes to the preferences
function checkChangedPreferences() 
{
	// Checking if user has changed the frequency
	var chFrequency = document.getElementById("frequency").value;
	if (chFrequency==null || chFrequency=='') 
	{
		return false;	
	}
	
	if (trimspaces(chFrequency)!="" && chFrequency != frequency) 
	{
		// User has changed the frequency
		return true;
	}
	
	// Checking if the user has changed the espenol
	var chespenolyes = document.getElementById("espenolyes").checked;
	if (espenol=='Y' && chespenolyes==false) 
	{
		// User changed espenol from Yes to No
		return true;
	}
	if (espenol=='N' && chespenolyes==true)
	{
		// User changed espenol from No to Yes
		return true;
	}
	
	// Checking if the user has changed the optout
	var choptoutyes = document.getElementById("optoutyes").checked;
	if (optout=='Y' && choptoutyes==false) 
	{
		// User changed optout from Yes to No
		return true;
	}
	if (optout=='N' && choptoutyes==true)
	{
		// User changed optout from No to Yes
		return true;
	}
	
	return false;
	
}


// Function to count the number of alphabets in the field
function countLetters(txtFld) 
{
	var valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  	var temp;
  	var count = 0;
  	if (txtFld.length == 0)
	{
		errorCheck = 1;
	  	return false;
	}
  	for (var i=0; i<txtFld.length; i++)
	{
		temp = "" + txtFld.substring(i, i+1);
	  	if (valid.indexOf(temp) != "-1") 
	  	{
	  		count++;
	  	}
	}
  	return count;
}


// Function to Check for Numbers and Special characters
function checkForSpecialCharsandNumbers(txtFld) 
{
	var valid = "-.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ";
  	var ok = "yes";
  	var temp;
  	if (txtFld.length == 0)
	{
		errorCheck = 1;
	  	return false;
	}
  	for (var i=0; i<txtFld.length; i++)
	{
		temp = "" + txtFld.substring(i, i+1);
	  	if (valid.indexOf(temp) == "-1") ok = "no";
	}
  	if (ok == "no")
	{
		errorCheck = 2;
	  	return false;
	}
  	return true;
}


// Function to verify Email address.
function verifyEmail(email) {
	var message="The entered e-mail address has an incorrect format, please make the necessary changes and try again.";

	if (email.length == 0)
	{
		message = "Please enter your e-mail address."
		document.getElementById("email").focus();
	  	return message;
	}
	
	var atPos = email.indexOf("@");
	var emailName = email.substring(0,atPos);
	if (checkEmailNameValid(emailName)==false) 
	{
		document.getElementById("email").focus();
	  	return message;
	}
	
	var periodPos = emailName.indexOf(".");
	if (periodPos==0 || periodPos==atPos-1)
	{
		document.getElementById("email").focus();
	  	return message;
	}
	
	var consecutivePeriodPos = emailName.indexOf("..");
	if (consecutivePeriodPos!=-1)
	{
		document.getElementById("email").focus();
	  	return message;
	}
	
	var domainName = email.substring(atPos+1,email.length);
	if (checkDomainNameValid(domainName)==false) 
	{
		message = 'The domain name is not correct. You can use letters, numbers, hyphens and periods (example:  yourname@yourdomain.com).';
		document.getElementById("email").focus();
	  	return message;
	}
	
	periodPos = domainName.indexOf(".");
	if (periodPos==0)
	{
		message = 'The domain name is not correct. You can use letters, numbers, hyphens and periods (example:  yourname@yourdomain.com).';
		document.getElementById("email").focus();
	  	return message;
	}
	
	var lastChar = domainName.substring(domainName.length-1, domainName.length);
	if (lastChar=='.') 
	{
		message = 'The domain name is not correct. You can use letters, numbers, hyphens and periods (example:  yourname@yourdomain.com).';
		document.getElementById("email").focus();
	  	return message;
	}
	
	
	consecutivePeriodPos = domainName.indexOf("..");
	if (consecutivePeriodPos!=-1)
	{
		message = 'The domain name is not correct. You can use letters, numbers, hyphens and periods (example:  yourname@yourdomain.com).';
		document.getElementById("email").focus();
	  	return message;
	}
	
	// Return blank if the email passes all the validations
	return '';
}




// function to check the emal name part of the email Address
function checkEmailNameValid(emailName){
	var valid = "_-.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	// Defines the characters not allowed at the end of an e-mail name
	var charactersNotAllowedAtEnd = /^[^.]$/;	
  	var ok = "yes";
  	var temp;  	
  	var goodCharAtEnd=false;
  	
  	if (emailName.length == 0)
	{
		errorCheck = 1;
	  	return false;
	}
  	for (var i=0; i<emailName.length; i++)
	{
		temp = "" + emailName.substring(i, i+1);
	  	if (valid.indexOf(temp) == "-1") ok = "no";
	}
	
	// Verify that the last character is not invalid
	goodCharAtEnd=validateRegExp(emailName.substring(emailName.length-1,emailName.length),charactersNotAllowedAtEnd);	
	
  	if (ok == "no" || !goodCharAtEnd)
	{
		errorCheck = 2;
	  	return false;
	}	
  	return true;
}


// Validates a string against a regular expression
function validateRegExp(obj,string_validator){
	if(obj.search(string_validator) != -1){
		return true;
	} else {
		return false;
	}
}

// Funcion to check the domain name part of the email Address
function checkDomainNameValid(emailName)
{
	var valid = "-.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  	var ok = "yes";
  	var temp;
  	if (emailName.length == 0)
	{
		errorCheck = 1;
	  	return false;
	}
  	for (var i=0; i<emailName.length; i++)
	{
		temp = "" + emailName.substring(i, i+1);
	  	if (valid.indexOf(temp) == "-1") ok = "no";
	}
	
	var periodPos = emailName.indexOf(".");
	if (periodPos==0 || periodPos==-1){
		ok="no";
	}	
	
  	if (ok == "no")
	{
		errorCheck = 2;
	  	return false;
	}
  	return true;
}

// Function to remove leading and trailing spaces from the field
function trimspaces(field)
{
  var index;
  var precount = 0;
  var postcount = 0;
  var retfield = ""
  for (index=0;index<field.length;index++)
	{
	  if (field.charAt(index) == " " )
	  precount++;
	  else
	  break;
	}
  for ( index=field.length; index>0; index-- )
	{
	  if (field.charAt(index-1) == " " )
	  postcount++;
	  else
	  break;
	}
  if (field.length == precount)
  retfield = "";
  else
  retfield = field.substring(precount,(field.length-postcount));
  return retfield;
}
