/*
    Name:   Global JavaScript functions
    Date:   2008 07 02
    Desc:   This file holds global JavaScript functions that can be used on all projects. 
            The functions will add programmers
    List:   Use this list to search for a function you may want to use
    
            Trim( str ) - Trims the string
            CheckEmpty( str ) - Checks if the string is empty or not
            FormatString( str, bln ) - formats the string to either lower/uppercase
            CompareStrings( str, str ) - compares two strings to see if they are equal. Formats strings to same case
            MakeTwoDigits( str ) - converts a 0/1 digit number to two digits (Add 0 to front).
            OpenWin( str, str, num, num, str ) - opens a new window based on url, name of window, width/height, and properties
            ProtectEmail( str, str, str, str ) - creates an anchor link to an E-Mail in the HTML but in a safe manner
            ReduceString( str, num ) - reduces a string by a number
            FormatFreToEngCurrency( str ) - formats the currency from French to English
            FormatCurrency( str, str ) - formats the currency based on the language
            ValidateEmail( str ) - validates the email using regular expressions
            ValidatePostalCode( str ) - validates the postal code using regular expression
            ValidateDate( _str ) - validates dates using regular expression
            ValidateNumeric( _str ) - validates the string for numeric values only using regular expression
            TestRegExp( str, regEx ) - tests the string using the regular expression
            GetAge( _str ) - retrieves the age based off a birthday
*/

/*
	Date:   2008 07 02
	Desc:   This function will Trim the string
	Param:  _strVal - the value to format
	Pre:    Parameter(s) must be a valid string
	Return: The string passed in will be returned with no extra blank spaces on the left and right
*/	
function Trim( _strVal ) {
	return _strVal.replace( /^\s+|\s+$/g, "" );
}	// Trim

/*
	Date:   2008 07 02
	Desc:   This function will check if the field is empty
	Param:  _strVal - the value to check
	Pre:    Parameter(s) must be a valid string	
	Return: true - strnig is empty, false - otherwise
*/
function CheckEmpty( _strVal )
{
	return ( Trim( _strVal ).length == 0 ) ? true : false;
}	// CheckEmpty

/*
	Date:   2008 07 02
	Desc:   This function will format the string to a specific case
	Param:  _strVal - the value to format
	        _blnWhichCase - 0: lowercase, 1: uppercase
	Pre:    _strVal must be a valid string. _blnWhichCase must be a boolean      
	Return: The string passed in either lowercase or uppercase (with Trim)
*/
function FormatString( _strVal, _blnWhichCase )
{
    var m_strVal = Trim( _strVal ); // Trim the string
    
    if( _blnWhichCase ) // uppercase
        m_strVal = m_strVal.toUpperCase();
    else
        m_strVal = m_strVal.toLowerCase();
    
    return m_strVal;
} // FormatString

/*
	Date:   2008 07 02
	Desc:   This function will compare two strings to see if they are equal
	Param:  _strVal1 - First string to compare
	        _strVal2 - Second string to compare
	Pre:    Parameter(s) must be a valid string
	Return: true - strings match, false - otherwise
*/
function CompareStrings( _strVal1, _strVal2 )
{
    var m_strVal1 = FormatString( _strVal1, true );   // format the first string 
    var m_strVal2 = FormatString( _strVal2, true );   // format the second string
    
    return ( m_strVal1 == m_strVal2 ) ? true : false;
} // CompareStrings

/*
	Date:   2008 07 02
	Desc:   This function will add a 0 to a one digit number. This is used for time or money values
	Param:  _strVal - The value to format
	Pre:    Parameter(s) must be a valid string and in the length range of 0 to 2.	
	Return: A two digit number.
*/
function MakeTwoDigits( _strVal )
{
    var m_strVal = Trim( _strVal ); // Trim the string
    
    if( CheckEmpty( m_strVal ) )    // add two "0"
    {
        m_strVal = "00";
    }
    else if( m_strVal.length == 1 )  // add 1 zero
    {
        m_strVal = "0" + m_strVal;
    } // if
    
    return m_strVal;
} // MakeTwoDigits

/*
	Date:   2009 02 12
	Desc:   This function will remove any leading 0's and make the string 1 digit
	Param:  _strVal - The value to format
	Pre:    Parameter(s) must be a valid string and in the length range of 0 to 2.	
	Return: A one digit number if there is a leading 0 in front of the two digit number.
*/
function MakeOneDigits( _strVal )
{
    var m_strVal = Trim( _strVal ); // Trim the string
    
    if( CheckEmpty( m_strVal ) )    // add two "0"
    {
        m_strVal = "0";
    }
    else if( m_strVal.length == 2 )  // check if there is a leading 0
    {
        var m_strTmp = m_strVal.substr( 0, 1 );
        
        if( m_strTmp == "0" )	m_strVal = m_strVal.substr( 1, 1 );
    } // if
    
    return m_strVal;
} // MakeOneDigits

/*
	Date:   2008 07 02
	Desc:   This function will open a new window
	Param:  _strURL - the url to go to
	        _strWinName - name of the window	
	        _numWidth - the width of the window
	        _numHeight - the height of the window
            _strWinProp - the properties of the window
	Pre:    _strURL must be a valid URL, _strWinName must be a valid string, _numWidth/_numHeight must be valid numbers, 
	        _strWinProp must be valid window properties	
	Return: Opens a new window based on 
*/
function OpenWin( _strURL, _strWinName, _numWidth, _numHeight, _strWinProp )
{	
    if( isNaN( _numWidth ) )    // conver to number
        _numWidth = parseInt( _numWidth );

    if( isNaN( _numHeight ) )    // conver to number
        _numHeight = parseInt( _numHeight );        

	if( _numWidth == 0 )	// if no width is set, use the screen width
		_numWidth = screen.availWidth;
	
	if( _numHeight == 0 ) // if no height is set, use the screen height
		_numHeight = screen.availHeight;
	
	if( !CheckEmpty( _strWinProp ) ) // add to the window property
	    _strWinProp += "," + "width=" + _numWidth + ",height=" + _numHeight;;	

	OpenWin = window.open( _strURL, _strWinName , _strWinProp ); 
} // OpenWin

/*
    Date:   2008 07 02
    Desc:   This will write out our email address to avoid spam bots
    Param:  _strEmailName - name of email, ex: name
            _strEmailDomain - name of the domain, ex: domain.com
            _strEmailLink - the representation text of the email
            _strEmailSubject - the subject of the email, ex: fun
    Pre:    Parameter(s) must be valid strings
    Return: A safe way of displaying the emails in the source file.
    Example: hello@world.com?subject=Hello World
*/
function ProtectMail( _strEmailName, _strEmailDomain, _strEmailLink, _strEmailSubject )
{
    var m_strDefaultDomain = "";    // PLACE A DEFAULT DOMAIN HERE
    var m_strFinalEmail = ""; // final email string
    var m_strFinalHTML = "";  // final html string to write
    
    // final manipulation of the variables
    var m_strFinalEmailName = Trim( _strEmailName );
    var m_strFinalEmailDomain = Trim( _strEmailDomain );
    var m_strFinalEmailLink = Trim( _strEmailLink );
    var m_strFinalEmailSubject = Trim( _strEmailSubject );

    if( m_strFinalEmailDomain.length == 0 )   // use the default
        m_strFinalEmailDomain = m_strDefaultDomain;
    
    if( m_strFinalEmailName.length > 0 || m_strFinalEmailDomain.length > 0 )  // these param must be at least 1 in length
    {
        m_strFinalEmail = m_strFinalEmailName + "@" + m_strFinalEmailDomain;
        
        m_strFinalHTML = "<a href=\"mailto:" + m_strFinalEmail;
        
        if( m_strFinalEmailSubject.length > 0 )   // give the email a subject line
            m_strFinalHTML += "?subject=" + m_strFinalEmailSubject;
        
        m_strFinalHTML += "\">";
        
        if( m_strFinalEmailLink.length > 0 )   // use this link name
            m_strFinalHTML += m_strFinalEmailLink;
        else
            m_strFinalHTML += m_strFinalEmail;
        
        m_strFinalHTML += "</a>";
    } // if
    
    document.write( m_strFinalHTML );
} // ProtectMail

/*
	Date:   2008 07 02
	Desc:   Reduces the string based on the given size. This is primarily used for splitting strings
	Param:  _strVal - the value to format
	        _numLength - the length to reduce (cut off on the right)
	Pre:    _strVal must be a valid string, _numLength must not be greater than the _strVal's length
	Return: A reduced string of _strVal based on the _numLength. If the _numLength is greater than the _strVal's length,
	        return _strVal.
*/
function ReduceString( _strVal, _numLength )
{
    var m_strVal = _strVal; // return this variable
    
    if( _strVal.length > _numLength )   // reduce the string
    {
        m_strVal = m_strVal.substring( 0, ( m_strVal.length - _numLength ) );
    } // if
    
    return m_strVal;
} // ReduceString

/*
	Date:   2008 07 02
	Desc:   Formats a French currency string to English
	Param:  _strVal - the value to format
	Pre:    Parameter(s) must be valid strings and must be in french format. ie: 9 999,00 $
	Return: English format of the currency
*/
function FormatFreToEngCurrency( _strVal )
{
    var m_strVal = _strVal;
    var m_strCents = "";    // cents
    var m_strDollars = "";  // dollars
    var m_arrCurrency;      // array for seperating dollars and cents    
    
    // remove whitespace, dollar sign, and replace "," with ".". Format should now be: 9999.00
    m_strVal = m_strVal.replace( /\s/g, "" );
    m_strVal = m_strVal.replace( /\$/g, "" );
    m_strVal = m_strVal.replace( /\,/g, "." );
    
    return FormatCurrency( m_strVal, "E" );
} // FunctionFreToEndCurrency

/*
	Date:   2008 07 02
	Desc:   Formats the string to the right currency output based on language
	Param:  _strVal - the value to format
	        _strLang = the language to format
	Pre:    Parameter(s) must be valid strings. _strVal must be a valid currency in english format, ie: 9,999.00 or 9999.00
	Return: Eng - $9,999.00, Fre - 9 999,00 $
*/
function FormatCurrency( _strVal, _strLang )
{
    var m_strSepCents = "";    // seperator for cents
    var m_strSepThousand = ""; // seperator for thousands
    var m_strVal = _strVal; // return this string
    var m_strCents = "";    // cents
    var m_strDollars = "";  // dollars
    var m_arrCurrency;      // array for seperating dollars and cents
    var m_numThousandCount = 3; // how many digits make up a thousand for loop
    
    if( CompareStrings( _strLang, "F" ) )   // french seperators
    {
        m_strSepCents = ",";
        m_strSepThousand = " ";
    }
    else    // English
    {
        m_strSepCents = ".";
        m_strSepThousand = ",";
    } // if
    
    if( m_strVal.indexOf( "." ) >= 0 )  // there is a cent value
    {
        m_arrCurrency = m_strVal.split( "." );
        m_strDollars = m_arrCurrency[ 0 ];
        m_strCents = m_arrCurrency[ 1 ];
    }
    else    // only dollars
    {
        m_strDollars = m_strVal;
    } // if
    
    m_strVal = "";  // reset the value;
    
    // remove all these in the string
    m_strDollars = m_strDollars.replace( /\,/g, "" );
    m_strDollars = m_strDollars.replace( /\$/g, "" );
    
    m_strCents = MakeTwoDigits( m_strCents );

    while( m_strDollars.length > m_numThousandCount )    // loop until we have three digits or less
    {
        m_strVal = m_strSepThousand + m_strDollars.substring( ( m_strDollars.length - m_numThousandCount ), m_strDollars.length ) + m_strVal;
        m_strDollars = m_strDollars.substring( 0, ( m_strDollars.length - m_numThousandCount ) );
    } // while
    
    m_strVal = m_strDollars + m_strVal; // add remaining digits
    m_strVal += m_strSepCents + m_strCents; // add the cents in
    
    if( CompareStrings( _strLang, "F" ) )   // add dollar sign at end
    {
        m_strVal += " " + "$";
    }
    else    // add dollar sign at beginning
    {
        m_strVal = "$" + m_strVal;
    } // if
    
    return m_strVal;
} // FormatCurrency

/* Validation using Regular Expression */

/*
    Date:   2008 07 02
    Desc:   Checks for valid Emails
    Param:  _strVal - value to check
    Pre:    Parameter(s) must be valid strings
    Return: true - valid email, false - otherwise
*/
function ValidateEmail( _strVal )
{
    var m_regExp = /^([\?!/]*)+\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
    
    return TestRegExp( _strVal, m_regExp );
} // ValidateEmail

/*
    Date:   2008 07 02
    Desc:   Checks for valid Postal Code
    Param:  _strVal - value to check
    Pre:    Parameter(s) must be valid strings
    Return: true - valid postal code, false - otherwise
*/
function ValidatePostalCode( _strVal )
{
    var m_regExp = /^([A-CEGHJ-NPR-TVXY]\d[A-CEGHJ-NPR-TV-Z])\s?(\d[A-CEGHJ-NPR-TV-Z]\d)$/;
    var m_strVal = FormatString( _strVal, 1 );  // make sure the string is upper case
    
    return TestRegExp( m_strVal, m_regExp );
} // ValidatePostalCode

/*
    Date:   2009 02 11
    Desc:   Checks for Validate Dates
    Param:  _strVal - value to check
    Pre:    Parameter(s) must be valid date ( accepted formats: mm dd yyyy, mm/dd/yyyy, mm.dd.yyyy, mm-dd-yyyy )
    Return: true - valid date, false - otherwise
*/
function ValidateDate( _strVal )
{
	var m_regExp = /^(\d{1,2})[\s\.\/-](\d{1,2})[\s\.\/-](\d{4})$/;
	
	if( !TestRegExp( _strVal, m_regExp ) )	return false;	// return if failed
  	var m_arrResult = _strVal.match( m_regExp );
  	var m_numMonth = parseInt( MakeOneDigits( m_arrResult[1] ) );
  	var m_numDay = parseInt( MakeOneDigits( m_arrResult[2] ) );
  	var m_numYear = parseInt( m_arrResult[3] );
  	var m_numTmpDay = 0;
  	
  	// return false if these conditions are not met
  	if( m_numMonth < 1 || m_numMonth > 12 || m_numYear < 1900 || m_numYear > 2100) return false;
  	
  	// retrieve number of days in a month
  	if( m_numMonth == 2 )	// February
  	{
          m_numTmpDay = ( ( m_numYear % 4) == 0 ) ? 29 : 28;
  	}
  	else if( m_numMonth == 4 || m_numMonth == 6 || m_numMonth == 9 || m_numMonth == 11 )	// April, June, September, November
  	{
          m_numTmpDay = 30;
  	}
  	else	// Jan, March, May, July, August, October, December
  	{
          m_numTmpDay = 31;
  	} // if
  	
  	return ( m_numDay >= 1 && m_numDay <= m_numTmpDay );
}	// ValidateDate

/*
    Date:   2009 02 11
    Desc:   Checks the string for numeric values only
    Param:  _strVal - value to check
    Pre:    Parameter(s) must be a valid string
    Return: true - string is numeric, false - otherwise
*/
function ValidateNumeric( _strVal )
{
    var m_regExp = /^\d+$/;
    
    return TestRegExp( _strVal, m_regExp );
} // ValidateNumeric

/*
    Date:   2009 02 11
    Desc:   Checks the string for valid phone number (10 digit number)
    Param:  _strVal - value to check
    Pre:    Parameter(s) must be a valid string
    Return: true - string is a phone number, false - otherwise
*/
function ValidatePhoneNo( _strVal )
{   
    return ( ValidateNumeric( _strVal ) && _strVal.length == 10 );
} // ValidatePhoneNo

/*
    Date:   2008 07 02
    Desc:   Tests the string using a reg exp
    Param:  _strVal - value to check
            _regExp - regular expression
    Pre:    Parameter(s) must be valid strings
    Return: true - string passed regular expression, false - otherwise
*/
function TestRegExp( _strVal, _regExp )
{
    return _regExp.test( _strVal );
} // TestRegExp

/*
    Desc: This will calculate the pets age. Need this to move the user to the correct thank you screen.
    Param: _strBirthday - birthday of the pet
*/
/*
    Date:   2009 02 12
    Desc:   This will calculate the pets age. Need this to move the user to the correct thank you screen.
    Param:  _strBirthday - birthday of the pet
    Pre:    Parameter(s) must be valid date
    Return: Age based off the birthday
*/
function GetAge( _strBirthday )
{

    var m_objDateNow = new Date();
    var m_objDateBorn = new Date( _strBirthday.replace( /-/g, "/" ) );
    var m_numYearDiff = m_objDateNow.getFullYear() - m_objDateBorn.getFullYear();
    
    m_objDateBorn.setFullYear( m_objDateBorn.getFullYear() + m_numYearDiff );
    
    // decrease the year difference if current date is less than born date 
    if( m_objDateNow < m_objDateBorn )  m_numYearDiff -= 1;
    
    return m_numYearDiff;
}   // GetAge
