/*
Modified from:-
Copyright ¿ 2007 Silverpop Systems, Inc.  All rights reserved.
WARNING: This file contains methods which are a published Silverpop API for use in custom Web Forms, changes must be approved and communicated by the Product team.
The following are common validation routines used by any screens that need to validate user input.
*/

//Checks if an email address is valid, modified from http://javascript.internet.com/forms/check-email.html
function f_isValidEmail(a_sEmail, field)
{
   if (a_sEmail != null && a_sEmail != "")
   {
      /* The following pattern is used to check if the entered e-mail address
         fits the user@domain format.  It also is used to separate the username
         from the domain. */
      var emailPat=/^(.+)@(.+)$/;
      /* The following string represents the pattern for matching all special
         characters.  We don't want to allow special characters in the address.
         These characters include ( ) < > @ , ; : \ " . [ ]    */
      var specialCharsUser="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
      var specialCharsDomain="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]\\'";

      /* The following string represents the range of characters allowed in a
         username or domainname.  It really states which chars aren't allowed. */
      var validCharsUser="\[^\\s" + specialCharsUser + "\]";
      var validCharsDomain="\[^\\s" + specialCharsDomain + "\]";
      /* The following pattern applies if the "user" is a quoted string (in
         which case, there are no rules about which characters are allowed
         and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
         is a legal e-mail address. */
      var quotedUser="(\"[^\"]*\")";
      /* The following pattern applies for domains that are IP addresses,
         rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
         e-mail address. NOTE: The square brackets are required. */
      var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
      /* The following string represents an atom (basically a series of
         non-special characters.) */
      var atomUser=validCharsUser + '+';
      var atomDomain=validCharsDomain + '+';
      /* The following string represents one word in the typical username.
         For example, in john.doe@somewhere.com, john and doe are words.
         Basically, a word is either an atom or quoted string. */
      var wordUser="(" + atomUser + "|" + quotedUser + ")";
      // The following pattern describes the structure of the user
      var userPat=new RegExp("^" + wordUser + "(\\." + wordUser + ")*$");
      /* The following pattern describes the structure of a normal symbolic
         domain, as opposed to ipDomainPat, shown above. */
      var domainPat=new RegExp("^" + atomDomain + "(\\." + atomDomain +")*$");


      /* Finally, let's start trying to figure out if the supplied address is
         valid. */

      /* Begin with the coarse pattern to simply break up user@domain into
         different pieces that are easy to analyze. */
      var matchArray=a_sEmail.match(emailPat);
      if (matchArray==null)
      {
        /* Too many/few @'s or something; basically, this address doesn't
           even fit the general mould of a valid e-mail address. */
      	callAlertWithField("Ooops - The format of your email address is not valid - Please try again", field);
      	return false;
      }
      var user=matchArray[1];
      var domain=matchArray[2];

      // See if "user" is valid
      if (user.match(userPat)==null)
      {
          // user is not valid
          callAlertWithField("Ooops - The username part of your email address is not valid - Please try again", field);
          return false;
      }

      /* if the e-mail address is at an IP address (as opposed to a symbolic
         host name) make sure the IP address is valid. */
      var IPArray=domain.match(ipDomainPat);
      if (IPArray!=null)
      {
          // this is an IP address
      	  for (var i=1;i<=4;i++)
           {
      	    if (IPArray[i]>255)
             {
      	        callAlertWithField("Ooops - The IP address of your email address is not valid - Please try again", field);
      		     return false;
      	    }
          }
          return true;
      }

      // Domain is symbolic name
      var domainArray=domain.match(domainPat);
      if (domainArray==null)
      {
      	callAlertWithField("Ooops - The domain part of your email address is not valid - Please try again", field);
         return false;
      }

      /* domain name seems valid, but now make sure that it ends in a
         three-letter word (like com, edu, gov) or a two-letter word,
         representing country (uk, nl), and that there's a hostname preceding
         the domain or country. */

      /* Now we need to break up the domain to get a count of how many atoms
         it consists of. */
      var atomPat=new RegExp(atomDomain,"g");
      var domArr=domain.match(atomPat);
      var len=domArr.length;
      var topDomain = domArr[domArr.length-1];
      if ( topDomain.length<2 ) // the address must be greater than 1 char
      {
         callAlertWithField("Ooops - The domain part of your email address is not valid - Please try again", field);
         return false;
      }

      // Make sure there's a host name preceding the domain.
      if (len<2)
      {
         var errStr="Ooops - The domain part of your email address is not valid - Please try again";
         callAlertWithField(errStr, field);
         return false;
      }
   }

   // If we've gotten this far, everything's valid!
   return true;
}
//Checks if a value is a number
function f_isNumeric(a_sNumber, field)
{
   myString = "0123456789";

   for(i = 0; i < a_sNumber.length; i++)
   {
      if(myString.indexOf(a_sNumber.charAt(i)) == -1)
      {
         callAlertWithField("Your Telephone number is invalid - it should be all digits with no spaces - please check and try again", field);
         return(false);
      }
   }
   return(true);
}
function f_isGold(a_sNumber, field)
{
   myString = "0123456789";

   for(i = 0; i < a_sNumber.length; i++)
   {
      if(myString.indexOf(a_sNumber.charAt(i)) == -1)
      {
         callAlertWithField("Your Gold Card number is invalid - it should be 19 digits long - please check and try again", field);
         return(false);
      }
   }
   return(true);
}

//Checks if valid date
var dtCh= "/";
var minYear=1900;
var maxYear=2100;
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 f_isValidDate(dtStr, field)
{
   if (dtStr.length != 10)
   {
	callAlertWithField("Your date of birth should be entered as dd/mm/yyyy", field);
	return(false);
   }
	var daysInMonth = DaysArray(12);
	var pos1=dtStr.indexOf(dtCh);
	var pos2=dtStr.indexOf(dtCh,pos1+1);
	var strDay=dtStr.substring(0,pos1);
	var strMonth=dtStr.substring(pos1+1,pos2);
	var strYear=dtStr.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)
	{
		callAlertWithField("Your date of birth should be entered as dd/mm/yyyy", field);
		return(false);
	}
	if (strMonth.length<1 || month<1 || month>12)
	{
		callAlertWithField("Please enter a valid month for your date of birth", field);
		return(false);
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month])
	{
		callAlertWithField("Please enter a valid day for your date of birth", field);
		return(false);
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear)
	{
		callAlertWithField("Please enter a valid 4 digit year for your date of birth between "+minYear+" and "+maxYear, field);
		return(false);
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false)
	{
		callAlertWithField("Please enter a valid date for your date of birth", field);
		return(false);
	}
   return(true);
}

function callAlert(alertMessage)
{
	if (typeof spAlert == "undefined")
		alert(alertMessage);
	else
		spAlert(alertMessage);
}

function callAlertWithField(alertMessage, field)
{
    if (typeof spAlert == "undefined") {
        alert(alertMessage);
    }
    else {
        var okFunc = null;
        if (field) {
            okFunc = hitch({
                field: field,
                ok: function() {
                    this.field.focus();
                    this.field.select();
               	}
            }, 'ok');
        }
	spAlert(alertMessage, null, null, null, null, okFunc);
    }
}
function getFormElementByName(formName,elementName)
{
      var elements = document.getElementsByName(elementName);
      var element;
      for (var j=0; j < elements.length; j++)
      {
         if ( elements[j].form && elements[j].form.name == formName )
         {
            element = elements[j];
            break;
         }
      }
      return element
}

//Validates the form called 'form'
function f_validateForm(a_sFormName)
{
   if (typeof(a_sFormName) == "undefined")
   {
      a_sFormName = "form";
   }
   var l_okay = true;

   for (var j=0; j < document.forms[a_sFormName].elements.length; j++)
   {
      var l_element = document.forms[a_sFormName].elements[j];

      var sFieldNameRequired = l_element.name + "_REQUIRED";
      //var elRequired = document.forms[a_sFormName].elements[sFieldNameRequired];
      var elRequired = getFormElementByName(a_sFormName,sFieldNameRequired);

      if ( l_element.value == "" &&
          ((elRequired && elRequired.value == "T") || l_element.getAttribute("required") == "T"))
      {
        alert("Please fill in all the fields marked with an asterisk");
        return false;
      }

      //text areas can only be 255 in size
      if(l_element.type == "textarea")
      {
         if (l_element.value.length > 4000)
         {
            alert("Please limit your entries to 4000 characters");
            return false;
         }
      }
      var sFieldNameDataType = l_element.name + "_DATATYPE";
      //var elDataType = document.forms[a_sFormName].elements[sFieldNameDataType];
      var elDataType = getFormElementByName(a_sFormName,sFieldNameDataType);

      if (elDataType)
      {
         if (l_element.value != "")
         {
            if (elDataType.value == "date")
            {
               l_okay = f_isValidDate(l_element.value);
            }
            if (elDataType.value == "numeric")
            {
               l_okay = f_isNumeric(l_element.value);
            }
			if (elDataType.value == "goldcard")
            {
               l_okay = f_isGold(l_element.value);
            }

            if (elDataType.value == "email")
            {
               l_okay = f_isValidEmail(l_element.value);
            }
            if (!l_okay)
            {
               l_element.focus();
               return false;
            }
         }
      }
   }
   return true;
}