/* scformvalidation.js
 *
 *  GII's form validation Javascript, common to all applications.
 * 	REMEMBER: No function overloading in JS; see below. - NS 
 *
 */

/*****************************************************************

	START UTILITY METHODS USED BY THE OTHER METHODS
	START UTILITY METHODS USED BY THE OTHER METHODS
	START UTILITY METHODS USED BY THE OTHER METHODS
	
******************************************************************/

/**
*	Remove all non-numbers from the input
*/
function stripNonNumbers( _input ) {

	var result = "";
	var l = _input.length;
	var i = 0;

	for ( i=0; i<l; i++ ) {
		var c = _input.substr(i,1);
		if ( !isNaN( parseInt( c ) ) ) { result += c; }
	}

	return result;
}

/**
*	Remove leading zeros from the input
*/
function trimLeadingZeros( n ) {

	while ( true ) {

		if ( ( n.length > 1 ) && ( n.indexOf( "0" ) === 0 ) ) {
			 n = n.substr( 1 );
		}
		else {
			break;
		}
	}
	return n;
}

/**
*	Confirm that the input is an integer value
*/
function validateInt( n ) {

	if ( ( n === null ) || ( n === undefined ) || ( n.length < 1 ) ) {
		return false;
	}
	n = trimLeadingZeros( n );
	return ( "" + parseInt(n) ) == n;
}

/**
*	Validates that the input is an integer number
*	And also that the number falls between the range _min and _max
*/
function scIsValidInt( n, _min, _max ) {

	if ( isNaN( n ) ) {
		return false;
	}

	if ( ( n === null ) || ( n === undefined ) || ( n.length < 1 ) ) {
		return false;
	}
	
	n = trimLeadingZeros( n );
	if ( ( "" + parseInt(n) ) != n )
		return false;
		
	if ( isNaN( _min ) ) _min = 1;
	if ( isNaN( _max ) ) _max = 1000;

	n = n*1;
	if ( n < _min || n > _max )
		return false;
		
	return true;
}

function scIsNonNegative( n ) {

	if ( ( n === null ) || ( n === undefined ) || ( n.length < 1 ) || ( isNaN( n ) ) ) {
		return false;
	}
			
	return n >= 0;
}

function scIsValidPercentage( p, _min, _max ) {

	if ( isNaN( _min ) ) _min = 0;
	if ( isNaN( _max ) ) _max = 100;

	if ( p.length <= 0 ) 
		return false;
		
	if ( isNaN( p ) || Number( p ) < _min || Number( p ) > _max ) 
		return false;
	
	return true;
}

/**
*	The regular expression should evaluate whether the argument is
*	any number of integers, followed by a decimal point, followed by 
*	two integers. Any other format should fail.
*/
function scValidPrice( p ) { 

	if ( ( p == null ) || ( p == undefined ) || ( p.length < 1 ) ) 
		return false;

	isprice = /^\d{1,}\.\d{2}$/;
	return isprice.test( p );
} 

/**
*	
*	
*	
*/
function scContainsInvalidChars() { 

	if ( arguments.length < 2 )
		return false;
		
	var s = arguments[0];
	for ( i=1; i<arguments.length; i++ ) {
	
		if ( s.indexOf( arguments[i] ) != -1 ) {
			return true;
		}
	}
	return false;
} 

/**
*	Set the passed in form field to a blank value
*/
function blankBox( box ) {

	box.value = "";
}

/**
*	Jump to the URL of the chosen <select> menu item
*/
function MM_jumpMenu( targ, selObj, restore ){ //v3.0

	eval( targ + ".location='" + selObj.options[selObj.selectedIndex].value + "'" );
	if ( restore ) { selObj.selectedIndex=0; }
}


/*****************************************************************

	START VALIDATION METHODS USED BY FORMS
	START VALIDATION METHODS USED BY FORMS
	START VALIDATION METHODS USED BY FORMS
	
******************************************************************/


/**
*	The _min and _max values should be cents
*/
function scIsValidPrice( p, _min, _max ) { 

	if ( !scValidPrice( p ) )
		return false; 
	
	// at this point we have input in correct format
	// let's remove the decimal point and compare as cents integers
	p = p * 100;
	if ( ( p < _min ) || ( p > _max ) )
		return false;
		
	return true;
} 


/**
*	Determine if the _currentValue input is a valid URL.
*	If _min and _max values are passed in, we use those - otherwise we have reasonable defaults
*
* 	TODO we have 4 different versions of valid_url and 2 are in use.  We need to pick one and 
*	search through all files to see where the loser is being used.
*/
function valid_url( _currentValue, _min, _max ) {

	if ( isNaN( _min ) ) _min = 5;
	if ( isNaN( _max ) ) _max = 256;

	if ( ( _currentValue.length < _min ) || ( _currentValue.length > _max ) )
		return false;

	var v = new RegExp(); 
	v.compile( "^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$" ); 
	return v.test( _currentValue );
}

function sc_valid_url( _url, _min, _max ) { 

	if ( _url < _min  || _url > _max  )
		return false;

	var v = new RegExp(); 
	v.compile("^(https?|ftp|file)://.+$"); 
	if ( !v.test( _url ) ) 
		return false; 

	return true;
} 

/*

function valid_url( _url, _min, _max ) { 

	if ( _url < _min  || _url > _max  )
		return false;

	var v = new RegExp(); 
	//v.compile("^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$"); 
	//v.compile("/^[a-z]+:\/\//i"); 
	v.compile("^(https?|ftp|file)://.+$"); 
	if ( !v.test( _url ) ) 
		return false; 

	return true;
} 

function valid_url( _url ) { 

	if ( _url < 5  || _url > 256  )
		return false;
		
	var v = new RegExp(); 
	v.compile("^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$"); 
	if ( !v.test( _url ) ) 
		return false; 
	
	return true;
}

*/

/**
*	Determine if the _currentValue input is a valid phone number.
*	If _min and _max values are passed in, we use those - otherwise we have reasonable defaults
*/
function valid_phone( _currentValue, _min, _max ) {

	if ( isNaN( _min ) ) _min = 8;
	if ( isNaN( _max ) ) _max = 32;

	_currentValue = stripNonNumbers( _currentValue );
	if ( ( _currentValue.length < _min ) || ( _currentValue.length > _max ) ) { return false; }
	else { return true; }
}

function valid_email( _currentValue, _min, _max ) {

	if ( isNaN( _min ) ) _min = 5;
	if ( isNaN( _max ) ) _max = 256;

	var _emailError = isEmail( _currentValue, _min, _max );
	if ( _emailError.length > 0 ) { return false; }
	else { return true; }
}

function isEmail( _input, min, max ) {

	_input = _input + "";

	var err = "";
	var blankSpace = " ";
	var foundAt = false;
	var foundDot = false;

	var l = _input.length;
	var i = 0;

	if ( ( _input.length < (min) ) || ( _input.length > (max) ) ) {
		err = "Email address must use between " + min + " and " + max + " characters.";
		return err;
	}

	for ( i=0; i<l; i++ ) {
		var c = _input.substr(i,1);

		if ( c == blankSpace ) {
			err = "Email address cannot contain spaces.";
			return err;
		}
		if ( c == "@" ) { foundAt = true; }
		if ( c == "." ) { foundDot = true; }
	}

	if ( foundAt === false ) { err = "Email address must contain an \'@\' symbol to be valid.";  }
	if ( foundDot === false ) { err = "Email address must contain a \'.\' symbol to be valid.";  }

	return err;
}

function isValidDate() {

	if( validateInt(this.year) === false ) { return false; }
	if( validateInt(this.month) === false ) { return false; }
	if( validateInt(this.date) === false ) { return false; }

	if ( ( this.year > 0 ) && ( this.year < 3000 ) ) {}
	else { return false; }
	if ( ( this.month >= 0 ) && ( this.month <= 12 ) ) {}
	else { return false; }
	if ( ( this.date >= 0 ) && ( this.date <= 31 ) ) {}
	else { return false; }

	return true;
}

function dateToString() {

	return this.year + "/" + this.month + "/" + this.date;
}

function compareDate( _date ) {

	if ( ( this.year*1 == _date.year*1 ) &&
	     ( this.month*1 == _date.month*1 ) &&
	     ( this.date*1 == _date.date*1 ) ) { return 0; }

	if ( this.year*1 < _date.year*1 ) { return -1;}
	if ( this.year*1 > _date.year*1 ) { return 1; }

	if ( this.month*1 < _date.month*1 ) { return -1; }
	if ( this.month*1 > _date.month*1 ) { return 1; }

	if ( this.date*1 < _date.date*1 ) { return -1; }
	if ( this.date*1 > _date.date*1 ) { return 1; }

	return 0;
}

function getGIIDateNow() {

	var now = new Date();
	var newDate = new GIIDate( now.getFullYear(), now.getMonth() + 1, now.getDate() );
	return newDate;
}

function GIIDate( y, m, d ) {

	y += ""; m += ""; d += "";
	this.year = y;
	this.month = trimLeadingZeros( m );
	this.date = trimLeadingZeros( d );

	this.compareDate = compareDate;
	this.isValidDate = isValidDate;
	this.getGIIDateNow = getGIIDateNow;
	this.toString = dateToString;
}

/*****************************************************************

	BELOW HERE IS VALIDATION FROM NICK, AND IT SHOULD PROBABLY BE ROLLED IN WITH THE REST
	BELOW HERE IS VALIDATION FROM NICK, AND IT SHOULD PROBABLY BE ROLLED IN WITH THE REST
	BELOW HERE IS VALIDATION FROM NICK, AND IT SHOULD PROBABLY BE ROLLED IN WITH THE REST
	
******************************************************************/

function validateNewsletterForm( f, min, max ) {

	var _error_start = "Sorry, but there was a problem with the information you entered.  Please correct the following errors:\n\n";
	var _error_mid = "";
	var _error_end = "Click OK to continue.";
	var _tab = "- ";
	var _focusField = null;

	if ( !valid_email( f.email.value, min, max ) ) {
		if ( _focusField === null ) { _focusField = f.email; }
		_error_mid += _tab + 'Please enter a valid e-mail address where where the newsletter will be sent.\n';
	}

	if ( _error_mid.length > 0 ) {
		window.alert ( _error_start + _error_mid + "\n" + _error_end );
		_focusField.focus();
		return false;
	}

	return true;
}


/* ------------------------------------
 *  FORM MANAGER validation
 * ------------------------------------
 *
 * This is temporary.  John created these functions to provide client-side validation
 * for forms whose goal is to generate an email to the user.  These belong ultimately
 * as part of a Form Manager plugin, and they should be integrated with the existing
 * validation code we have above.  In the meantime, they're here under temporary names.
 * - NS 9 February 2009
 */

 function scpFormMgr_validateForm( f ) {

 	var _error_start = "Sorry, but there was a problem with the information you entered.  Please correct the following errors before continuing:\n\n";
 	var _error_mid = "";
 	var _error_end = "Click OK to continue.";
 	var _tab = "- ";
 	var _focusField = null;

 	var requiredFields = f.requiredFields.value;
 	var requiredFieldsLabels = f.requiredFieldsLabels.value;
 	arrayOfStrings = requiredFields.split( "," )
	arrayOfLables = requiredFieldsLabels.split( "," )
 	var numRequiredFields = arrayOfStrings.length;
 	var fieldName;
 	var fieldLabel;

 	var formElements = f.elements;
 	var numFormElements = f.elements.length;

 	for ( i=0; i<numRequiredFields; i++ ) {

 		fieldName = arrayOfStrings[i];
 		fieldLabel = arrayOfLables[i];
 		for ( j=0; j<numFormElements; j++ ) {
 			if ( fieldName == formElements[j].name ) {
 				if ( ( formElements[j].value.length == 0 ) || ( formElements[j].value == null ) )  {
 					if ( _focusField == null ) _focusField = formElements[j];
 					_error_mid += _tab + "Enter " + fieldLabel + ".\n";
 				}
 			}
 		}
 	}

 	if ( _error_mid.length > 0 )
 	{
 		alert ( _error_start + _error_mid + "\n" + _error_end );
 		_focusField.focus();
 		return false;
 	}

 	return true;
 }

function scpFormMgr_activateForm( f ) {

 	if ( scpFormMgr_validateForm( f ) )  {

 		f.action = "/mysitecaddy/actions.sitecaddy.websitecaddy.email.do";
 		f.submit();
 	}
}

function scpFormMgr_activateFormEmail( f, appPath ) {

 	if ( scpFormMgr_validateForm( f ) )  {
 	
		if ( appPath != null && appPath.length > 0 ) {
 			f.action = appPath +"/actions.sitecaddy.websitecaddy.form.email.do";
 		} 
 		else {
 			f.action = "/mysitecaddy/actions.sitecaddy.websitecaddy.form.email.do";
 		}
 		f.submit();
 	} 
 	else {
 		return false;
 	}
}