//==============================================================================
// File Name:
//    REALTransValidate.js
//
// Purpose:
//    Validation functions:
//        IsDigit()
//        IsEmpty()
//        IsNull()
//        IsPositiveInteger()
//        IsValidDate()
//        IsValidDateMinMaxYear()
//        IsValidEmail()
//        IsValidPhoneNumber()
//        IsValidPostalCode()
//        IsValidPostalCodeUS()
//        IsValidSocialSecurityNumberUS()
//        IsValidTaxIDNumberUS()
//		  hasNonAlphaNum()
//		  hasNonAlphaNumNS()
//		  IsValidState()
//		  IsIntInRange()
//        hasPlsMnsEq(var )
//		  saveTime()
//        isSqFt()	
//        IsValidTime()
//        IsValidEIN() 
//        CheckInvalidChar()
//        Trim()	
//        LTrim()
//        RTrim()
//		  RemoveSpecialChars()
//- Notes ----------------------------------------------------------------------
//  1 Some of the functions in this file use functions found in the file
//    REALTransFormat.js.
//  2 Postal Code validation functions need to be written for:
//        IsValidPostalCodeCA() // Canada
//        IsValidPostalCodeGB() // United Kingdom (Great Britain)
//- Maintenance ----------------------------------------------------------------
// 08-27-2002 Amarchand S <amarchands@ocwen.co.in>
//		Modified IsValidSocialSecurityNumberUS()-- commented the if condition that 
//		raises an error when the area code is b/w 800 and 999. The function has been made
//		stringent as there is not gurantee that area code b/w 800 and 999 is not valid SSN.
// 08-03-2001. Scott Mullins <smullins@realtrans.com>
//		Added the ' character to the list of invalid characters in 
//		hasNonAlphaNumNS() and hasNonAlphaNum().
// 2 July 2001.  Teodoro Viteri <tviteri@ocwen.com>
//    Added IsValidTime().
// 25 January 2001. Mike Graves <mgraves@realtrans.com>
//	  modified the IsValidSocialSecurityNumberUS() function to
//		less stringent on the validation of the SSN.  There
//		was a problem with SSN'd starting about 700 so the code
//		for this check was commented out.		
// 20 October 2000.  Teodoro Viteri <tviteri@ocwen.com>
//    Added IsValidTaxIDNumberUS().
// 11 October 2000 Nellie Izmaylova <nizmaylo@ocwen.com>
//	  Added isSqFt(), thousands(), reverseIt()	
// 03 October 2000 Nellie Izmaylova <nizmaylo@ocwen.com>
//    Added saveTime(), validateTime()
// 24 August 2000 Nellie Izmaylova <nizmaylo@ocwen.com>
//    Added hasPlsMnsEq()
// 18 May 2000        Jay Green <jgreen@ocwen.com>
//    Added IsIntInRange().
// 12 May 2000        Thomas W Stetler <tstetler@realtrans.com>
//      needed to change default date minimum to 1900 upon a call
//      from users born before 1940 were being "invalidated" given
//      the date of birth
// 27 April 2000	  Thomas W Stetler <tstetler@realtrans.com>
//		Added hasNonAlphaNumNS()
// 09 April 2000	  Mike Graves <mgraves@realtrans.com>
//	  IsValidDate - changed the min year to 1940
// 28 Feburary 2000   Thomas W Stetler <tstetler@realtrans.com>
//    Altered IsValidEmail(), appearently something like "jp.mpg@mpg.com" is a valid email.
// 19 Janurary 2000   Thomas W Stetler <tstetler@realtrans.com>
//    Altered IsValidDateMinMaxYear().
// 14 Janurary 2000   Thomas W Stetler <tstetler@realtrans.com> 
//	  Added IsValidState().
// 13 Janurary 2000   Thomas W Stetler <tstetler@realtrans.com>
//    Added hasNonAlphaNum().
// 20 December 1999   Charles J. Coker <chuckc@realtrans.com>
//    Added IsDigit(). Modified IsValidSocialSecurityNumberUS() to include more
//    validation rules.
// 17 December 1999   Charles J. Coker <chuckc@realtrans.com>
//    Added IsEmpty(). Renamed IsValidDate() to IsValidDateMinMaxYear() and
//    added min_year and max_year to parameter list. Added a new IsValidDate()
//    which used default min_year and max_year values in a call to
//    IsValidDateMinMaxYear()
// 14 December 1999   Charles J. Coker <chuckc@realtrans.com>
//    Added IsValidPostalCode().
// 13 December 1999   Charles J. Coker <chuckc@realtrans.com>
//    Added IsValidPhoneNumber(), IsValidSocialSecurityNumberUS() and
//    IsValidPostalCodeUS(). Slight modification of IsEmpty().
// 13 December 1999   Michael Graves <mgraves@realtrans.com>
//    Original version of IsEmpty().
// 08 December 1999   Charles J. Coker <chuckc@realtrans.com>
//    Added IsPositiveInteger().
// 07 December 1999   Charles J. Coker <chuckc@realtrans.com>
//    Original version of IsValidDate().
// 09 October 2003	  Lakshmi M S <maralurl@ocwen.co.in>	
//    Added IsValidEIN() 
// 08 August 2004	  Lakshmi M S<maralurl@ocwen.co.in>
//    Added CheckInvalidChar() 
// 10 April 2006	  Lakshmi M S <Lakshmi.Maralur@ocwen.com>
//    Added RemoveSpecialChars()
// 18 Feb 2009       Manish Jain<manish.jain2@ocwen.com>
//    HD#400585:  IsValidEmail : Increase the Length of Post Dot.
// 11 Feb 2009		  Savitha N	<Savitha.Narayanappa@ocwen.com>
//	  HD400461:  IsValidDate() complete method definition changed
//==============================================================================
// 16 Feb 2009		  Priyadarshini Nair <priyadarshini.nair@ocwen.com>
//	  HD 399552 -  Rewrote the method IsValidEmail() for handling all the special characters including spaces.

//==============================================================================
// Function Name:
//    IsValidSocialSecurityNumberUS()
//
// Purpose:
//    IsValidUSSocialSecurityNumberUS() checks to make sure that a string
//    contains a valid United States Social Security number.
//
// Known Limitations:
//  1 Only a pattern is validated, not the individual number.
//
// Parameters:
//    number_in     A string containing the United States Social Security number
//                  to be checked.
//
// Returns:
//    boolean       true = the string passes all validity tests.
//                  false = the string does not pass all validity tests.
//
// Errors/Exceptions:
//    None.
//==============================================================================

function IsValidSocialSecurityNumberUS(number_in)
{
    // Strip out everything except digits '0' through '9'.
    number_in = StripInteger(number_in);
    
    // Test for correct length.
    if (9 != number_in.length)
        return false;

    // Check for numbers in valid ranges.
    var area_number = parseInt(number_in.substr(0,3), 10);
    var group_number = parseInt(number_in.substr(3,2), 10);
    var serial_number = parseInt(number_in.substr(5,4), 10);

    // None of the number fields can contain all zeros, i.e., 000-XX-XXXX or
    // XXX-00-XXXX or XXX-XX-0000.
    if (0 == area_number)
        return false;
    if (0 == group_number)
        return false;
    if (0 == serial_number)
        return false;

    // We can't do any more validation of group numbers or serial numbers.
    // However, we can do some more checking on the area number.
    /*if ((650 <= area_number) && (699 >= area_number))
    {
        alert("Possibly an invalid United States Social Security number."
            + "\n\nThe Area number cannot be in the 650-699 range."
            + "\nThis number range is reserved for future use.");
        return false;
    }
    if ((700 <= area_number) && (728 >= area_number))
    {
        alert("Possibly an invalid United States Social Security number."
            + "\n\nThe Area numbers in the 700-728 range were"
            + "\nonly assigned to railroad workers and only"
            + "\nassigned prior to 1964.");
        return false;
    }
    if ((729 <= area_number) && (799 >= area_number))
    {
        alert("Possibly an invalid United States Social Security number."
            + "\n\nThe Area number cannot be in the 729-799 range."
            + "\nThis number range is reserved for future use.");
        return false;
    }
   
    if ((800 <= area_number) && (999 >= area_number))
    {
        alert("Possibly an invalid United States Social Security number."
            + "\n\nThe Area number cannot be in the 800-999 range."
            + "\nThis number range will never be used for social security"
            + " numbers.");
        return false;
    }
	*/
    return true;
}

//==============================================================================
// Function Name:
//    IsValidTaxIDNumberUS()
//
// Purpose:
//    IsValidTaxIDNumberUS() checks to make sure that a string
//    contains a valid United States Tax ID number.
//
// Known Limitations:
//  1 Only a pattern is validated, not the individual number.
//
// Parameters:
//    number_in     A string containing the United States Tax ID number
//                  to be checked.
//
// Returns:
//    boolean       true = the string passes all validity tests.
//                  false = the string does not pass all validity tests.
//
// Errors/Exceptions:
//    None.
//==============================================================================

function IsValidTaxIDNumberUS(number_in)
{
    // Strip out everything except digits '0' through '9'.
    number_in = StripInteger(number_in);
    
    // Test for correct length.
    if (9 != number_in.length)
        return false;

    return true;
}

//==============================================================================
// Function Name:
//    IsValidEIN()
//
// Purpose:
//    IsValidEIN() checks to make sure that a string
//    contains a valid EIN.
//
// Known Limitations:
//  1 Only a pattern is validated, not the individual number.
//
// Parameters:
//    number_in     A string containing the EIN to be checked.
//
// Returns:
//    boolean       true = the string passes all validity tests.
//                  false = the string does not pass all validity tests.
//
// Errors/Exceptions:
//    None.
//==============================================================================

function IsValidEIN(number_in)
{
    // Strip out everything except digits '0' through '9'.
    number_in = StripInteger(number_in);
    
    // Test for correct length.
    if (number_in.length!= 9)
        return false;

    return true;
}

//==============================================================================
// Function Name:
//    IsValidEmail()
//
// Purpose:
//    IsValidEmail() checks (as much as it can with it's limitations) to see
//    if an e-mail is valid.
//
// Known Limitations:
//  1 Only a very general pattern can be verified--there is no way to validate
//    a specific e-mail address other than sending mail to that address and
//    waiting to see if it bounces back as invalid.
//
// Parameters:
//    email_in     A string containing the e-mail address to validate.
//
// Returns:
//    boolean       true = the string fits the pattern of a valid e-mail
//                      address.
//                  false = the string does not fit the pattern of a valid
//                      e-mail address.
//
// Errors/Exceptions:
//    None.
//==============================================================================
/*
Commented by Priyadarshini Nair for HD 399552 - Email Validation
function IsValidEmail(email_in)
{
    var pos_at_sign = 0;
    var pos_dot = 0;
    
    
    // We need at least one character before the one commercial-at sign ('@').
    pos_at_sign = email_in.indexOf('@');
    if (1 > pos_at_sign)
        return false;

    // We can only have one commercial-at sign ('@').
    if (-1 != email_in.indexOf('@', (pos_at_sign + 1)))
        return false;

    // We need two or three characters after the last dot.
    pos_dot = email_in.lastIndexOf('.');
    if (((pos_dot + 3) > email_in.length) || (pos_dot + 5) < email_in.length)
        return false;
   
    // If we get this far, we've done all the validating we can do.
    return true;
}
*/


//==============================================================================
// Function Name:
//    IsValidEmail()
//
// Purpose:
//    IsValidEmail() checks (as much as it can with it's limitations) to see
//    if an e-mail is valid.
// Parameters:
//    email_in     A string containing the e-mail address to validate.
//
// Returns:
//    boolean       true = the string fits the pattern of a valid e-mail
//                      address.
//                  false = the string does not fit the pattern of a valid
//                      e-mail address.
//
// Errors/Exceptions:
//    None.
//==============================================================================

function IsValidEmail(value)
{
	//var emailRegEx =/^(?:\w+\.?)*\w+@(?:\w+\.)+\w+$/;
	//var emailRegEx =/^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$/;
	var emailRegEx =/^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,64}))@((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|([0-9a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,10})$/;
	if(value.match(emailRegEx))
		return true;
	else
		return false;
}

//==============================================================================
// Function Name:
//    IsDigit()
//
// Purpose:
//    IsDigit() checks to see if the input character is a digit in the range
//    from '0' to '9'.
//
// Known Limitations:
//    None.
//
// Parameters:
//    ch_value
//
// Returns:
//    boolean       true = the character is a valid digit.
//                  false = the string is not a valid digit.
//
// Errors/Exceptions:
//    None.
//==============================================================================

function IsDigit(ch_value)
{
    if ((ch_value >= '0') && (ch_value <= '9'))
        return true;
    else
        return false;
}

//==============================================================================
// Function Name:
//    IsValidPostalCode()
//
// Purpose:
//    IsValidPostalCode() checks to make sure that a string contains a
//    valid postal code.
//
// Known Limitations:
//    None.
//
// Parameters:
//    code_in     The string containing the postal code to test for validity.
//    country     The two-letter ISO 3166 country code -- the codes can be found
//                       at http://www.hellasport.gr/common/en_ccodes.htm
//
// Returns:
//    boolean       true = the string contains a valid postal code.
//                  false = the string does not contain a valid postal code.
//
// Errors/Exceptions:
//    None.
//==============================================================================

function IsValidPostalCode(code_in, country)
{
    // Convert country code to uppercase.
    country = country.toUpperCase();

    switch (country)
    {
        case "US": // United States
            return IsValidPostalCodeUS(code_in);
            break;
        case "CA": // Canada
            alert("Postal codes for Canada are not supported at this time."
                + "\n\nPlease notify REALTrans if you get this error message.");
            // return IsValidPostalCodeCA(code_in);
            break;
        case "GB": // United Kingdom (Great Britain)
        case "UK": // United Kingdom (Great Britain)
            // Note: "UK" does not comply with the ISO 3166 standard for country
            // codes.
            alert("Postal codes for United Kingdom (Great Britain) are not"
                + " supported at this time."
                + "\n\nPlease notify REALTrans if you get this error message.");
            // return IsValidPostalCodeGB(code_in);
            break;
        default:
            // If we get here, we don't handle postal codes for the specified
            // country.
            alert("Postal codes for " + county + " are not supported at this"
                + " time."
                + "\n\nPlease notify REALTrans if you get this error message.");
            break;
    }
    return false;
}

//==============================================================================
// Function Name:
//    IsValidPostalCodeUS()
//
// Purpose:
//    IsValidPostalCodeUS() checks to make sure that a string contains a
//    valid United States postal code.
//
// Known Limitations:
//    None.
//
// Parameters:
//    code_in     A string containing a postal code to check for validity.
//
// Returns:
//    boolean       true = the string contains a valid postal code.
//                  false = the string does not contain a valid postal code.
//
// Errors/Exceptions:
//    None.
//==============================================================================

function IsValidPostalCodeUS(code_in)
{
    // Strip all non-digit characters from number_in.
    code_in = StripInteger(code_in);

    // US Zip Codes are five digits; Zip+4 Codes are nine digits.
    if ((5 == code_in.length) || (9 == code_in.length))
        return true;

    return false;
}

//==============================================================================
// Function Name:
//    IsValidDate()
//
// Purpose:
//    IsValidDate() checks to make sure that a date is in some variation of
//    MMDDYYYY format. The minimum year value default to 1900. If you need 
//	  to use other values, make your call to
//    IsValidDateMinMaxYear() instead of IsValidDate().
//
// Parameters:
//    date_in       The string containing the date to be checked.
//
// Returns:
//    boolean       true = the string contains a valid MMDDYYYY date.
//                  false = the string does not contain a valid MMDDYYYY date.
//Supported delimiters:
//    [-./]
//
// Errors/Exceptions:
//    None.
//
//HD400461: Complete definition changed and Function comments updated on Feb 12 2009
//==============================================================================

function IsValidDate(date_in)
{    
	var min_year = 1900; // minimum year
	date_in = Trim(date_in);
	
	if(/^\d{2}\d{2}\d{4}$/.test(date_in)) //test for 8 digit date without any delimiter
		date_in = date_in.substr(0, 2) + "-" + date_in.substr(2, 2) + "-" + date_in.substr(4, 4);	
	if(/^\d(\-|\/|\.)\d\1\d{4}$/.test(date_in)) //Single digit month & day(m/d/yyyy)
		date_in = '0' + date_in.substr(0, 2) + '0' + date_in.substr(2, 6);
	if(/^\d(\-|\/|\.)\d{2}\1\d{4}$/.test(date_in)) //Single digit month(m/dd/yyyy)
		date_in = '0' + date_in;
	if(/^\d{2}(\-|\/|\.)\d\1\d{4}$/.test(date_in)) //Single digit day(mm/d/yyyy)
		date_in = date_in.replace(date_in.substr(0, 5), date_in.substr(0, 3) + '0' + date_in.substr(3,2));
	
	if(date_in.length == 10)
	{
		var RegExPattern = /^(?=\d)(?:(?:(?:(?:(?:0?[13578]|1[02])(\/|-|\.)31)\1|(?:(?:0?[1,3-9]|1[0-2])(\/|-|\.)(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})|(?:0?2(\/|-|\.)29\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))|(?:(?:0?[1-9])|(?:1[0-2]))(\/|-|\.)(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2}))($|\ (?=\d)))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\ [AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/;
		if(RegExPattern.test(date_in))//validate date
		{
			if(date_in.substr(6,4) >= min_year) // minimum year check
				return true;
		}
    }
    return false;
}

//==============================================================================
// Function Name:
//    IsValidDateMinMaxYear()
//
// Purpose:
//    IsValidDate() checks to make sure that a date is in some variation of
//    MMDDYYYY format.
//
// Known Limitations:
//  1 This function only performs simple checks for valid dates. It will not
//    catch some invalid dates, e.g., days that don't or didn't exist like
//    5 October 1752.
//
// Parameters:
//    date_in       The string containing the date to be checked.
//    min_year      The minimum value for the year.
//    max_year      The maximum value for the year.
//
// Returns:
//    boolean       true = the string contains a valid MMDDYYYY date.
//                  false = the string does not contain a valid MMDDYYYY date.
//
// Errors/Exceptions:
//    None.
//
// Altered on Janurary 19 2000 by Thomas W Stetler
//	function wouldn't have worked for input like "2/9/2000" but
//  would expect the user to enter "02/09/2000" which might be
//  unrealistic,  so I've altered this function to approve one digit
//  months and one digit days.
// Altered on 9/6/2000 by Teodoro Viteri
//  function enhanced to check for an actual number on the variable containing
//  the days.  Before, 01-xx-2000 was an OK date, now, the error is trapped.
//==============================================================================

function IsValidDateMinMaxYear(date_in, min_year, max_year)
{
	if(!IsValidDate(date_in))	//Added by Savitha for HD400461
		return false;
		
    var month_in;        // valid range: 01 through 31
    var day_in;          // valid range: 01 through 12
    var year_in;         // valid range: min_year through max_year
    var max_day;         // maximum day number for a given month

	//find delimiter
	var delimiter;
	var i; //index
	i = 0;

	while ((i < date_in.length) && IsDigit(date_in.charAt(i))) {
		i++;
	}
	// if we found something that's not a digit it's possibly a delimiter
	if (i < date_in.length) {		
		delimiter = date_in.charAt(i);
		//split into month/day/year strings, via delimiter
		var TempArray = date_in.split(delimiter);		
		month_in = TempArray[0];		
		if (month_in.length == 1)
			month_in = '0' + month_in; //to change '1' into '01' for Janurary, '2' into '02' for Feburary....
		day_in = TempArray[1];		
		if (day_in.length == 1)
			day_in = '0' + day_in; // to change '1' into '01' for 1st day of month....
		//Lavanya has modified to fix the defect 3265. Date: 08/31/2006
		//*************************************************************		
		if(TempArray.length == 2)
			return false;
		//*************************************************************
		year_in = TempArray[2];
	} else if (i == 8) { //8 is the magic number for a valid date without delimiters
		month_in = date_in.substr(0, 2);
		day_in = date_in.substr(2, 2);
		year_in = date_in.substr(4, 4);
	} else 
		return false;
	
	// The month must be between 1 and 12 inclusive.
	//Lavanya has modified to fix the defect 3265. Date: 08/31/2006
	//*************************************************************    
    if(month_in.length==2)
    {
		if ((month_in < 1) || (month_in > 12))		
			return false;		
    }
    else
    {
		return false;
    }
            
    // The year must be between min_year and max_year inclusive.        
	if(year_in.length == 4)		
	{
		if ((year_in < min_year) || (year_in > max_year) || isNaN(year_in))
			return false;	
	}
	else
	{
		return false;
	}	
	//*************************************************************
	
    switch (month_in)
    {
        case '01':
        case '03':
        case '05':
        case '07':
        case '08':
        case '10':
        case '12':
            max_day = 31;
            break;
        case '04':
        case '06':
        case '09':
        case '11':
            max_day = 30;
            break;
        case '02':
            max_day = 28;
            if (0 == (year_in % 4))
            {
                max_day++;
            }
            if (0 == (year_in % 100))
            {
                max_day--;
            }
            if (0 == (year_in % 400))
            {
                max_day++;
            }
            break;
    } // switch
    // The day must be between 1 and max_day inclusive.
   	//Lavanya has modified to fix the defect 3265. Date: 08/31/2006
	//*************************************************************      
    if(day_in.length == 2)
    {
		if((day_in < 1) || (day_in > max_day) || isNaN(day_in))
			return false;
    }
    else
    {
		return false;
    }
    //*************************************************************
    return true;
}

//==============================================================================
// Function Name:
//    IsPositiveInteger()
//
// Purpose:
//    IsPositiveInteger() checks a string to see if it is a positive integer,
//    i.e., it only contains the values '0' through '9'.
//
// Known Limitations:
//  1 IsPositiveInteger() works only with decimal numbers. It will allow invalid
//    characters '8' and '9' for octal numbers and will not accept valid
//    characters 'A' through 'F' for hexadecimal numbers.
//
// Parameters:
//    str_value     A string containing the value to be tested.
//
// Returns:
//    boolean       true = the string contains a positive integer.
//                  false = the string does not contain a positive integer.
//
// Errors/Exceptions:
//    None.
//==============================================================================

function IsPositiveInteger(str_value)
{
    var digit;
    for (x = 0; x < str_value.length; x++)
    {
        digit = str_value.charAt(x);
        if ((digit < '0') || (digit > '9'))
            return false;
    }
    return true;
}
//==============================================================================
// Function Name:
//    IsEmpty()
//
// Purpose:
//    IsNull() checks to see if a string does not contain any non-white-space
//    characters, i.e., it is an empty string for all practical purposes.
//
// Known Limitations:
//    None.
//
// Parameters:
//    string_in     The string to be checked.
//
// Returns:
//    boolean       true = the string is empty.
//                  false = the string is not empty.
//
// Errors/Exceptions:
//    None.
//
//	Altered Jan 19 2000 - Mike Graves - renamed variable from string_is_empty to
//		value_is_empty because variable name was inconsistent and causing runtime
//		error.
//==============================================================================

function IsEmpty(in_string)
{
    var value_is_empty = true;

    // The '\S' indicates all NON-whitespace characters 
    var string_obj  = new RegExp("\\S","g");

    if (string_obj.test(in_string))
        value_is_empty = false;

    return value_is_empty;
}

//==============================================================================
// Function Name:
//    IsNull()
//
// Purpose:
//    IsNull() checks to see if a string does not contain any characters,
//    i.e., it is a null string.
//
// Known Limitations:
//    None.
//
// Parameters:
//    string_in     The string to be checked.
//
// Returns:
//    boolean       true = the string is null.
//                  false = the string is not null.
//
// Errors/Exceptions:
//    None.
//==============================================================================

function IsNull(string_in)
{
    if (0 == string_in.length)
        return true;
    return false;
}

//==============================================================================
// Function Name:
//    IsValidPhoneNumber()
//
// Purpose:
//    IsValidPhoneNumber() checks to make sure that a string contains a valid
//    United States or Canada phone number.
//
// Known Limitations:
//  1 Works only with United States and Canada phone numbers.
//  2 It is assumed that if there are more than ten digits, everything after ten
//    digits is part of an extension and thus, considered valid.
//
// Parameters:
//    number_in     The phone number string to validate.
//
// Returns:
//    boolean       true = the phone number is valid.
//                  false = the phone number is not valid.
//
// Errors/Exceptions:
//    None.
//- Valid Formats --------------------------------------------------------------
//    Valid formats are:
//        (760) 930-4561     14 characters
//        760-930-4561       12 characters
//        7609304561         10 characters
//    The first and fourth digits cannot be '0' or '1'.
//==============================================================================

function IsValidPhoneNumber(number_in)
{
    var temp_string = "";
    
    // Strip out everything that is not a character in the range '0' to '9'.
    temp_string = StripInteger(number_in);

    // We need a minimum of 10 digits.
    if (temp_string.length < 10)
        return false;
    
    // Make sure that the first digit of the area code and the first digit
    // of the prefix fall in the range 2 to 9.
    if ((temp_string.charAt(0) < '2') || (temp_string.charAt(3) < '2'))
        return false;

    return true;
}

//==============================================================================
// function name:
//				hasNonAlphaNum(EnteredString, fieldname)
//
// purpose:
//			to test if the string entered by users (passed
//			in by the first parameter) contains only valid
//			characters.  These valid characters are: any
//			alphanumeric and - (dash) and _ (underscore), if
//			there are any character outside the valid set then
//			an alert is called with the mention of the fieldname
//			(passed in by second parameter) that contains the invalid
//			character.
//
//	Parameter:
//			1) EnteredString - String, entered by a user and needs
//								to be tested for validity
//
//
//	Reuturns: The Entered String if passed else return blank line;
//==============================================================================
	function hasNonAlphaNum(EnteredString) 
	{
		//InvalidChars = "[^ \t\n\v\f\rA-Za-z0-9_\-]";
		var InvalidChars = /[\~\!\@\#\$\%\^\&\*\(\)\'\+\{\}\[\]\|\/\:\;\<\>\?\\\,\.\`\=\"]/;
		if (InvalidChars.exec(EnteredString) != null) {
			return '';
		}
		return EnteredString;
	}
//==============================================================================
//
// function name:
//			hasNonAlphaNumNS(EnteredString)
//
// purpose:
//			Test the string for any invalid ASCII character and white spaces
//			technically only alphanumeric characters plus underscore and dashes
//			are allowed.
//	Parameter:
//			1) EnteredString - String, entered by a user and needs
//								to be tested for validity
//
//
//	Reuturns: The Entered String if passed else return blank line;
//==============================================================================

	function hasNonAlphaNumNS(EnteredString) 
	{
		var InvalidChars = /[\~\!\@\#\$\%\^\&\*\(\)\'\+\{\}\[\]\|\/\:\;\<\>\?\\\,\.\`\=\"]/;
		//var ValidChars = /[A-Za-z0-9]/;
		if (InvalidChars.exec(EnteredString) != null) {
			return '';
		}
		return EnteredString;
	}

//==============================================================================
//
// function name:
//			IsValidState(StateAbbrString)
//
// purpose:
//			Test to see the state abbrevation is a valid state and
//			if invalid trigger an alert.
//
// Parameter
//		1) StateAbbrString - the 2 letter state abbrevation which
//					needs to be checked.
//
// Returns
//		true if first parameter is a valid state 
//		false if first parameter isn't a valid state
//==============================================================================
	function IsValidState(StateAbbrString)
	{
		StateAbbrString = StateAbbrString.toUpperCase();
		switch(StateAbbrString) {
			case 'AZ': break;
			case 'AL': break;
			case 'AR': break;
			case 'AK': break;
			case 'AS': break;
			case 'CA': break;
			case 'CO': break;
			case 'CT': break;
			case 'DC': break;
			case 'DE': break;
			case 'GA': break;
			case 'GU': break;
			case 'FM': break;
			case 'FL': break;
			case 'HI': break;
			case 'IA': break;
			case 'ID': break;
			case 'IL': break;
			case 'IN': break;
			case 'KS': break;
			case 'KY': break;
			case 'LA': break;
			case 'MA': break;
			case 'ME': break;
			case 'MD': break;
			case 'MH': break;
			case 'MI': break;
			case 'MS': break;
			case 'MN': break;
			case 'MO': break;
			case 'MT': break;
			case 'NE': break;
			case 'NV': break;
			case 'NM': break;
			case 'NC': break;
			case 'ND': break;
			case 'NY': break;
			case 'NH': break;
			case 'NJ': break;
			case 'MP': break;
			case 'OH': break;
			case 'OR': break;
			case 'OK': break;
			case 'PA': break;
			case 'PR': break;
			case 'PW': break;
			case 'RI': break;
			case 'SC': break;
			case 'SD': break;
			case 'TN': break;
			case 'TX': break;
			case 'UT': break;
			case 'VI': break;
			case 'VT': break;
			case 'VA': break;
			case 'WA': break;
			case 'WV': break;
			case 'WI': break;
			case 'WY': break;
			default:
				{
				window.alert('Invalid state abbreviation entered.');
				return false;
				}
		}
		return true;
	}

//==============================================================================
//==============================================================================
function IsValidNumberFormat(number_in, type)
{
    var digit, point_count;

	if (type == 'Int')
		return IsPositiveInteger(number_in);
	else if (type == 'Float'){
		point_count = 0;
		for (x = 0; x < number_in.length; x++)
		{
			digit = number_in.charAt(x);
			if (digit == '.')
				point_count++;
			if (!IsDigit(digit)) {
				if ( ((digit=='.') && (point_count > 1)) || (digit!='.') ){
					return false;
				}
			}
		}
		return true;
	}
	else if (type == 'Money') {
		point_count = 0;
		for (x = 0; x < number_in.length; x++)
		{
			digit = number_in.charAt(x);
			if (digit == '.')
				point_count++;
			if (!(IsDigit(digit) || digit == '$' || digit == ',' ||digit == '-' || (digit == '.' && point_count < 2)))
				return false;
		}
		return true;
	}
}

//==============================================================================
//
// function name:
//			IsIntInRange(obj, lo, hi)
//
// purpose:	
//			Determines if the objects value is within a specified range.
//			The check is inclusive of the hi and lo params.
//
//	Parameters:
//			1) obj	-	The object to check.
//			2) lo	-	The low end of the range.
//			3) hi	-	The high end of the range.
//
//	Reuturns: True if within the range, false if not.
//==============================================================================
function IsIntInRange(obj, lo, hi) { 
	var num = obj.value;
 
	if( num >= lo && num <= hi )
		// If ok, return true.
		return true;
	else {
		// If not ok, set focus back to the offending obj and return false.
		alert("Invalid Entry!  Value must be between " + lo + " and " + hi );
		
		obj.value='';
		 obj.focus();
		
				
		return false;
	}
} 

//==============================================================================
//
// function name:
//			hasPlsMnsEq(EnteredString) 
//
// purpose:
//			Test the string for "+", "-", "=". The rest is not allowed
// Parameter:
//			1) EnteredString - String, entered by a user and needs
//								to be tested for validity
//
//
//	Reuturns: The Entered String if passed,
//            else - blank line;
//==============================================================================

	function hasPlsMnsEq(EnteredString) 
	{
		var ValidChars = /[+\=\-]/;
		if (ValidChars.exec(EnteredString) == null) {
				return '';
			}
		return EnteredString;
	}
//===================================================================	
// function name: saveTime(objName, objAMPM, objHidden)
// Purpose: validate time entered into a text box, concatenate it
//          with values in a drop-down representing AM or PM and
//          save validated value
// Parameters: objName - input text box containing a string or integer 
//                       entered by a user
//             objAMPM - select containing AM or PM values
//             objHidden - hidden input box containing string repre-
//             senting the resulting time
// Returns: Boolean true is passed validation and saved values, false-
//             otherwise
// Uses:    function validateTime(objName);
//			
function saveTime(objName, objAMPM, objHidden){
	if (!validateTime(objName,objAMPM)) {return false;}
	else {
	objHidden.value=objName.value + ' ' + objAMPM.value;
	}
return true;	
}
//---------------------------------------------------------------------
// function name: validateTime
// Purpose: helper function for saveTime(objName, objAMPM, objHidden),
//          validates user input
// Parameters: objName - input text box containing a string or integer 
//                       entered by a user
//             objAMPM - select containing values of 'AM' / 'PM'
// Returns: boolean true if passed, false - otherwise

function validateTime(objName, objAMPM){
var strObj = objName.value;
if (strObj.length < 4) {
	alert("You must enter at least a four digit number");
	objName.focus();
	objName.select();
return false;
}
var myArray = strObj.split(':');
//if the input contains no colon
if (myArray[1] == null) {
	//if (strObj.length == 5) {
	//alert("You must enter at least a four digit number.");
	//objName.focus();
	//objName.select();
	//return false;
	//}
	//var hour = parseInt(strObj.substr(0,2));
	var hour = parseFloat(strObj.substr(0,2));
	if (hour < 0  || hour > 23) {
		alert("Hour must be between 0 and 23.");	
		objName.value=strObj.substr(0,2)+':'+strObj.substr(2,2);
		//objName.focus();
		//objName.select();
		return false;}
	//var min = parseInt(strObj.substr(2,2));
	var min = parseFloat(strObj.substr(2,2));
	if (min < 0 || min > 59) {
		alert ("Minute must be between 0 and 59.");
		objName.value=strObj.substr(0,2)+':'+strObj.substr(2,2);
		//objName.focus();
		//objName.select();
		return false;}
if (hour > 12 && hour < 24){
	hour = hour - 12;
	var strHour = hour.toString();
	if (strHour.length==1){
		strHour = '0' + strHour;}
	var strMin = min.toString();
	if (strMin.length==1) {strMin='0'+strMin;}	
	objName.value=strHour+':'+strMin;
	objAMPM.selectIndex=1;
	objAMPM.value='PM';
return true;	
}
if (hour==24||hour==0){
	var strHour = '12';
	var strMin = min.toString();
	if (strMin.length==1) {strMin='0'+strMin;}	
	objName.value=strHour+':'+strMin;
	objAMPM.selectedIndex=0;
	objAMPM.value='AM';
return true;
}
if (hour > 9 && hour < 13){
	var strHour = hour.toString();
	var strMin = min.toString();
	if (strMin.length==1) {strMin='0'+strMin;}
	objName.value=strHour+':'+strMin;
	return true;
	}
if (hour > 0 && hour < 10){
	var strHour = '0' + hour.toString();
	var strMin = min.toString();
	if (strMin.length==1) {strMin='0'+strMin;}
	objName.value=strHour+':'+strMin;
	return true;
	}
objName.value=strObj.substr(0,2)+':'+strObj.substr(2,2);
return true;		
}
//if a colon found
else
{
	//var hour = parseInt(myArray[0]);
	var hour = parseFloat(myArray[0]);
	// the follwing statement handles a case when a colon is entered first
	if (isNaN(hour)) {
	alert("Please enter hour.");
	//objName.focus();
	//objName.select();
	return false;}
	
	if (hour < 0  || hour > 23) {
		alert("Hour must be between 0 and 23.");	
		objName.value=myArray[0]+':'+myArray[1];
		//objName.focus();
		//objName.select();
		return false;}
	//var min = parseInt(myArray[1]);
	var min = parseFloat(myArray[1]);
	// a case where a colon is entered last
	if (isNaN(min)) {
	alert("Please enter minutes.");
	//objName.focus();
	//objName.select();
	return false;}
	if (min < 0 || min > 59) {
		alert ("Minute must be between 0 and 59.");
		objName.value=myArray[0]+':'+myArray[1];
		//objName.focus();
		//objName.select();
	return false;}

if (hour > 12 && hour < 24){
	hour = hour - 12;
	var strHour = hour.toString();
	if (strHour.length==1){	strHour = '0' + strHour;}
	var strMin = min.toString();
	if (strMin.length==1) {strMin='0'+strMin;}
	objName.value=strHour+':'+strMin;
	objAMPM.selectedIndex=1;
	objAMPM.value='PM';
	return true;
	}
if (hour==24||hour==0){
	var strHour = '12';
	var strMin = min.toString();
	if (strMin.length==1) {strMin='0'+strMin;}
	objName.value=strHour+':'+strMin;
	objAMPM.selectedIndex=0;
	objAMPM.value='AM';
	return true;
	}	
if (hour > 9 && hour < 13){
	var strHour = hour.toString();
	var strMin = min.toString();
	if (strMin.length==1) {strMin='0'+strMin;}
	objName.value=strHour+':'+strMin;
	return true;
	}
if (hour >0 && hour < 10){
	var strHour = '0' + hour.toString();
	var strMin = min.toString();
	if (strMin.length==1) {strMin='0'+strMin;}
	objName.value=strHour+':'+strMin;
	return true;
	}
}
}


//-----------------------------------------------------------------------
// function (sub) name: setTime
// Purpose: retrieves time value and sets values for objHourMin and 
//			objAMPM for input and validation
// Parameters: objHourMin - user input
//			   objAMPM - select containing AM or PM values
// 
//function setTime(objHourMin, objAMPM, strHidden){
//	if (strHidden!=''){
//		var strHourMin = strHidden.substr(0,5);
//			objHourMin.value=strHourMin;
//		var strAMPM = strHidden.substr(6,2);
//			objAMPM.value=strAMPM;
//		if (strAMPM=='AM'){
//			objAMPM.selectedIndex=0;}
//		else if (strAMPM=='PM') {
//			objAMPM.selectedIndex=1;}
//	}
//	else{
//		objHourMin.value='00:00';
//		objAMPM.selectedIndex=0;
//		objAMPM.value='AM';
//	}			
//}
//-----------------------------------------------------------------------



function reverseIt(str) {
   if (!str) return; // nothing to change
   var rstr = '';
   for (i=str.length-1;i>=0;i--) rstr += str.charAt(i);
  
   return rstr;
}
function thousands(str) {
   var saveStr = "" + str;
   
   if (saveStr.length < 4) return str;
   var revStr = reverseIt(saveStr);
    
   var newStr = '';
   for (var i=0;i<revStr.length;i++) {
      if (i>0 && (i%3)==0) newStr += ',';
   

      newStr += revStr.charAt(i);
      
   }
   return reverseIt(newStr); 
}
//
//
//
//
//
//
function isSqFt(initValSqFt) {
	var digitSqFt = initValSqFt.toString();
	var regex = /[^0-9]/g;
	digitSqFt = digitSqFt.replace(regex,''); // remove everything, but digits
	digitSqFt = parseInt(digitSqFt);
	if (isNaN(digitSqFt)) {return '';}
	return thousands(digitSqFt);
}

//-----------------------------------------------------------------------
// function (sub) name: IsValidTime
// Purpose: retrieves time value and sets values for objHourMin and 
//			objAMPM for input and validation
// Parameters: timeStr - user input
//			   strAMPM - select containing AM or PM values
//------------------------------------------------------------------------
function IsValidTime(timeStr, strAMPM) {

	// Checks if time is in HH:MM format.
	var errorMsg="";
	
	var timePat = /^(\d{1,2}):(\d{2})?$/;
	var matchArray = timeStr.match(timePat);
			
	if (matchArray == null) {
		errorMsg = "Time is not in a valid format.";
		return errorMsg;
	}
	hour = matchArray[1];
	minute = matchArray[2];
	 	 
	if (hour < 1 || hour > 12) {
		errorMsg = "Hour must be between 1 and 12.";
		return errorMsg;
	}
	 
	if (minute<0 || minute > 59) {
		errorMsg = "Minute must be between 0 and 59.";
		return errorMsg;
	}
	/*
	if( timeStr.length ==5){
      if((timeStr.substr(0,2))=='12' ){
		if (strAMPM == "AM"){
			errorMsg = "Time is not in a valid format.";
		}
      }
      if((timeStr.substr(0,2))=='00' ){
		if (strAMPM == "PM"){
			errorMsg = "Time is not in a valid format.";
		}
      }
    } 
    */            
	return errorMsg;
}

//==============================================================================
//
// function name:
//			CheckInvalidChar(in_obj)
//
// purpose:
//			Checks whether the string contains special characters whose decimal 
//			value is less than 32 or greater than 127
//
//	Parameter:
//			1) EnteredString - String, entered by a user and needs
//								to be tested for validity
//
//
//	Returns: True  - If Decimal value of each character in the String is between 
//					 32 and 127
//			 False - If String Decimal value of each character in the String less 
//				     than 32 and greater than 127. 		 
//==============================================================================

function CheckInvalidChar(in_obj)
{
	var CheckStr,count,StrLen,AsciiChar;
	CheckStr = in_obj.value;	
	StrLen = CheckStr.length;	
	pos=0;	
	while(pos < StrLen)		
	{			
		AsciiChar = parseInt(CheckStr.charCodeAt(pos));
		if(AsciiChar < 32 || AsciiChar >127)
		{
			alert('Invalid character used, No special characters please');
			if (IE){
				  in_obj.style.background = '#f88080';
				  in_obj.style.color =  '#ffff00';		
				  in_obj.focus();
				}
			return false;	
		}
		pos = pos+1;		
	}	
	if (IE){
			in_obj.style.background = '#ffffff';
			in_obj.style.color =  '#000000';			
			
	}
	return true;
}

//==============================================================================
//
// function name:
//			Trim(VALUE)
//
// purpose:
//			Removes the extra spaces from the string value
//			
//
//Parameter:
//			1) EnteredString - String, entered by a user and needs
// 			    to be tested for validity
//
//
//Returns: The String value without any spaces preceeding or succeeding the string value
// Date    :  01/11/2005
//Author : Ananda Sreenivas

//========================================================================================
function Trim(TRIM_VALUE)
{
	if(TRIM_VALUE.length < 1)
	{
		return"";
    }
    TRIM_VALUE = RTrim(TRIM_VALUE);
    TRIM_VALUE = LTrim(TRIM_VALUE);
	if(TRIM_VALUE=="")
	{
		return "";
    }
   	else{
           return TRIM_VALUE;
        }
}

//==============================================================================
//
// function name:
//			RTrim(VALUE)
//
// purpose:
//			Removes the extra spaces to the right of string value
//			
//
//Parameter:
//			1) EnteredString - String, entered by a user and needs
// 			    to be tested for validity
//
//
//Returns: The String value without any spaces to the right of  the string value
// Date    :  01/11/2005
//Author : Ananda Sreenivas

//========================================================================================

function RTrim(VALUE)
{
	var w_space = String.fromCharCode(32);
	var v_length = VALUE.length;
	var strTemp = "";
    if(v_length < 0)
    {
    	return"";
    }
    var iTemp = v_length -1;
    while(iTemp > -1)
    {
    	if(VALUE.charAt(iTemp) == w_space){}
   		else
   		{
    		strTemp = VALUE.substring(0,iTemp +1);
    		break;
    	}
    	iTemp = iTemp-1;
    }
    return strTemp;
 }

//==============================================================================
//
// function name:
//			LTrim(VALUE)
//
// purpose:
//			Removes the extra spaces to the right of string value
//			
//
//Parameter:
//			1) EnteredString - String, entered by a user and needs
// 			    to be tested for validity
//
//
//Returns: The String value without any spaces to the left of  the string value
// Date    :  01/11/2005
//Author : Ananda Sreenivas
//========================================================================================

function LTrim(VALUE)
{
	var w_space = String.fromCharCode(32);
    if(v_length < 1)
    {
    	return"";
    }
    var v_length = VALUE.length;
    var strTemp = "";
    var iTemp = 0;
   	while(iTemp < v_length)
   	{
   		if(VALUE.charAt(iTemp) == w_space){}
   		else
   		{
			strTemp = VALUE.substring(iTemp,v_length);
        	break;
        }
        iTemp = iTemp + 1;
    }
    return strTemp;
}
function validateEmail(str)
{
		var flag=false;
		if(IsValidEmail(Trim(str)))
		{
			var emailReg = "^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[a-zA-Z]$";
			var regex = new RegExp(emailReg);
			flag = regex.test(Trim(str));
			
			
		}
			
		return flag;
			
}
//==============================================================================
//
// function name:
//			RemoveSpecialChars(Value)
//
// purpose:
//			Removes special characters present in the input string.
//			
//
//	Parameter:	String Value
//
//
//	Returns: String value without special characters
//					 
//					 
//				      		 
//==============================================================================
function RemoveSpecialChars(Value)
{
	var count,StrLen,AsciiChar,strRetVal,chkPresent;
	StrLen = Value.length,chkPresent;	
	pos=0;
	strRetVal="";
	while(pos < StrLen)		
	{			
		chkPresent = 1;
		AsciiChar = parseInt(Value.charCodeAt(pos));		
		if(AsciiChar > 47 && AsciiChar < 58) //Numbers 1-9
		{			
			chkPresent = 0;
		}
		else
		{
			if(AsciiChar > 64 && AsciiChar < 91) //Alpabets with UpperCase
			{				
				chkPresent = 0;
			}
			else
			{
				if(AsciiChar > 96 && AsciiChar < 123) //Alpabets with LowerCase
				{			
					chkPresent = 0; 
				}	
			}
		}
		
		if(chkPresent == 0)
		{
			if(strRetVal == "")
			{
				strRetVal = Value.charAt(pos);
			}
			else
			{
				strRetVal += Value.charAt(pos);
			}
		}
		pos = pos+1;		
	}		
	return strRetVal;
}
//==============================================================================

//======== End of REALTransValidate.js =========================================
//==============================================================================
