//------------------------------------------------------------------------------------------------------------
//	Author:		Michael Ritchson
//	Date:		8/8/2007 11:46 AM
//	Purpose:	Valides email addresses
//------------------------------------------------------------------------------------------------------------
//	HISTORY
//	#		    Developer				Date		Reason
//	11.1.1.TBD	Ravisankar				1/18/2008   C#-9852 Localpart wrongly validating the consecutive periods  
//	11.1.1.TBD	Ravisankar				1/25/2008   C#-11195 & 11203 Implemented Domain part validations
//------------------------------------------------------------------------------------------------------------
//  NONE
//------------------------------------------------------------------------------------------------------------

// Used for validation parameters
var VAL_NUM_LIST = '0123456789';
var VAL_LWR_LIST = 'abcdefghijklmnopqrstuvwxyz';
var VAL_UPR_LIST = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
//used for localization ,we are declaring the  variable and set the alert message and that is localizing
//in  asp and aspx pages .by sunil -9Th Mar-2009
var js_Email1='Invalid email address was supplied.';
var js_Email3='No fully qualified domain name was specified in the email address.';
var js_Email4='A fully qualified domain name must be specified in the email address.';
var js_Email5='Domain-part of email address cannot start with a Hyphen.';
var js_Email6='An invalid character was encountered for the Domain-part of email address.';

function EmailAddress()
{
    var _localPart, _domainPart, _address;
    _localPart = _domainPart = null;

    // Privileged members
    //---------------------------------------------------------------------
    this.crackAddress = function()
    {
        var bReturn = true;
        
        var arr = _address.split("@");
        if (arr.length != 2)
            bReturn = false;
        else
        {
            _localPart = arr[0];
            if (arr.length > 1) _domainPart = arr[1];
            else _domainPart = null;
        }//endif
        
        return bReturn;
    }
    
    this.validateLocalPart = function()
    {
        /*
        Without quotes, local-parts may consist of any combination of
        alphabetic characters, digits, or any of the special characters
        
           ! # $ % & ' * + - / = ?  ^ _ ` . { | } ~
        
        period (".") may also appear, but may not be used to start or end the
        local part, nor may two or more consecutive periods appear.  Stated
        differently, any ASCII graphic (printing) character other than the
        at-sign ("@"), backslash, double quote, comma, or square brackets may
        appear without quoting...
        
        (J. Klensin, RFC 3696 section 3, February 2004)
        */
        
        var nPeriodCount = 0;
        var sChar, nLocalPartLen;
        nLocalPartLen = _localPart.length;
        
        for (var i=0; i<nLocalPartLen; i++)
        {
            sChar = _localPart.charAt(i);
        
            // Keep track of consecutive periods
            if (sChar == ".")
            {
                // Make sure this period hasn't started the email address
                if (i == 0)
                    throw "Local-part of email address cannot start with a period.";
                else
                {
                    if (i == (nLocalPartLen-1))
                        throw "Local-part of email address cannot end with a period.";
                    else
                        nPeriodCount++;
                }
            }
            else
                nPeriodCount = 0; //11.1.1.TBD
            
            // If we found consecutive periods, failed validation
            if (nPeriodCount > 1) throw "You cannot have two consecutive periods in an email address.";
            
            // Make sure the character is valid for the local-part
            if (!email_isValidLocalPartChar(sChar)) throw "An invalid character was encountered for the local-part of email address.";
        }
    }
    
    this.validateDomainPart = function()
    {
       
       
        if (_domainPart != null)
        {
            var whitespace = new String(" \t\n\r");
            if (_domainPart.length > 0)
            {
                //Rtrim operation 11.1.1.TBD
                
                    var loopCount;
                    if (whitespace.indexOf(_domainPart.charAt(_domainPart.length-1)) != -1) {
	                    loopCount = _domainPart.length - 1;       // Get length of string
	                    while (loopCount >= 0 && whitespace.indexOf(_domainPart.charAt(loopCount)) != -1) { loopCount--; }
			               _domainPart = _domainPart.substring(0, loopCount+1);
	                }
	            //RtrimOperation
                checkInvalidDomain(_domainPart);//11.1.1.TBD
                var arr = _domainPart.split(".");
                if (arr.length < 2)
                    //throw "A fully qualified domain name must be specified in the email address.";Commented-by sunil-18Th Feb 2009
                    throw js_Email4;//localized alert message by sunil-18Th Feb 2009
                else
                {
                    for (var i=0; i<arr.length; i++)
                        {
                            if (arr[i].length <= 0) throw "An invalid domain name was specified in the email address."
                            if(i==arr.length-1)//11.1.1.TBD
                            checkInvalidExtension(arr[i]);//11.1.1.TBD}
                        }
                 }
            }
            else
                //throw "No fully qualified domain name was specified in the email address."; Commented: by sunil-18Th Feb 2009
                throw js_Email3;//localized alert message  by sunil-18Th Feb 2009
                
        }
    }

    // Constructor
    //---------------------------------------------------------------------
    
    // Validate the address' form
    if (arguments.length < 1) throw "You must provide an email address to emailAddress class in the form of xxx@xxx.xxx";
    if (arguments.length > 1) throw "You have provided too many arguments to the emailAddress class.";
    _address = arguments[0];

    // Crack the email address passed in to this class
    if (_address.length <= 0) throw "You must provide a valid email address. Email address passed was " + _address;
    //if (!this.crackAddress()) throw "Invalid email address was supplied.";Commented  by sunil-18Th Feb 2009
    if (!this.crackAddress()) throw js_Email1;//added localized variable as js_Email1 from getpreinfo.asp page  by sunil-18Th Feb 2009
    

    // Public members
    //---------------------------------------------------------------------
    this.localPart = _localPart;
    this.domainPart = _domainPart;
    this.address = _address;
    this.length = _address.length;
    
    // Public methods
    //---------------------------------------------------------------------
    this.validate = email_validateEmailAddress;
}

// Public methods (implementation)
//------------------------------------------------------------------------------------------------------
function email_validateEmailAddress()
{
    // First, make sure the entire length doesn't exceed 320 characters (RFC 3696 Section 3)
    if (this.address.length <= 320)
    {
        // Make sure the local part and the domain part are within the maximum characters before continuing
        // (RFC 3696 section 3)
        if (this.localPart.length <= 64)
        {
            // Validate length of domain part but make sure we don't validate if none was provided
            var bContinue = true;
            if (this.domainPart != null && this.domainPart.length > 255) bContinue = false;
            
            // Domain-part checked out, continue
            if (bContinue)
            {
                this.validateLocalPart();
                this.validateDomainPart();
            }
            else
                throw "Domain-part of email address exceeds the maximum length of 255 characters.";
        }
        else
            throw "Local-part of email address exceeds the maximum length of 64 characters.";
    }
    else
        throw "Email address exceeds the maximum length of 320 characters.";
}

// Global Functions
//------------------------------------------------------------------------------------------------------
function email_isValidLocalPartChar(sChar)
{
    var bValid;
    var arrChars = new Array("!", "#", "$", "%", "&", "'", "*", "+", "-", "/", "=", "?", 
                            "^", "_", "`", ".", "{", "|", "}", "~");
    
    bValid = isAlphanum(sChar);
    if (!bValid)
    {
        for (var i=0; i<arrChars.length; i++)
        {
            bValid = (arrChars[i] == sChar);
            if (bValid) break;
        }
    }
    
    return bValid;
}

function isValid(parm, val) 
{
    if (parm == "") return true;
    for (i=0; i<parm.length; i++) 
    {
        if (val.indexOf(parm.charAt(i),0) == -1) return false;
    }
    return true;
}
//11.1.1.TBD
function checkInvalidDomain(domainPart)
{ 
   for (var i=0; i<domainPart.length; i++)
        {
            sChar = domainPart.charAt(i);
        
            // Keep track of consecutive periods
            if (sChar == ".")
            {
                // Make sure this period hasn't started the email address
                if (i == 0)
                    throw "Domain-part of email address cannot start with a period.";
                else
                {
                            if(domainPart.charAt(i+1)=="-")
                            throw "Invalid Domain Part"
                            if(domainPart.charAt(i-1)=="-") 
                            throw "Invalid Domain Part"
                                   
                 }
            }
            if (sChar == "-")
            {
                // Make sure this period hasn't started the email address
                if (i == 0)
                    //throw "Domain-part of email address cannot start with a Hyphen.";
                    throw js_Email5;//localized alert message.
                    
             }
                        
            // Make sure the character is valid for the local-part
            if (!email_isValidDomainPartChar(sChar)) throw js_Email6;//"An invalid character was encountered for the Domain-part of email address.-Commentd by  by sunil-18Th Feb 2009";//localized alert message  by sunil-18Th Feb 2009
        }
}
function checkInvalidExtension(Extn)
{
    for(var i=0;i<Extn.length;i++)
    {
        
        if(!isAlpha(Extn.charAt(i)))
            throw "Invalid Domain Part";
    }
}
function email_isValidDomainPartChar(sChar)
{
    var bValid;
    var arrChars = new Array("-","." );
    bValid = isAlphanum(sChar);
    if (!bValid)
    {
       for (var i=0; i<arrChars.length; i++)
        {
            bValid = (arrChars[i] == sChar);
            if (bValid) break;
        }
    }
    
    return bValid;
}

//11.1.1TBD
function isNum(parm) {return isValid(parm,VAL_NUM_LIST);}
function isLower(parm) {return isValid(parm,VAL_LWR_LIST);}
function isUpper(parm) {return isValid(parm,VAL_UPR_LIST);}
function isAlpha(parm) {return isValid(parm,VAL_LWR_LIST+VAL_UPR_LIST);}
function isAlphanum(parm) {return isValid(parm,VAL_LWR_LIST+VAL_UPR_LIST+VAL_NUM_LIST);} 