/**
* Field Validation function -
* This will check all fields on the page that are of the class 'required_field' (used as a flag).
*
* @param	string	errorDialogName		Name/id of the error dialog div
*
* All flags for fields:
* <ul>
* <li> required_field - 			Script will check to make sure it is not empty. </li>
* <li> phone_field - 					Phone Number must have 10 numbers, be numeric only. '(', ')', '-', and '.' are removed. </li>
* <li> email_field - 					Email must have '@' and '.'.  Script cannot check if the email is already used in the DB. </li>
* <li> address_field - 				Address can contain numbers, letters, and special characters '#' and '-'. Periods are removed. </li>
* <li> zip_field - 						Zip code must have exactly 5 numbers, numbers only </li>
* <li> numeric_field - 				Numbers only allowed. </li>
* <li> alphanumeric_field - 	Only letters and numbers are allowed. </li>
* <li> alphabet_field - 			Only letters allowed. </li>
* <li> facility_name_field - 	Facility Name can only have letters, numbers, and special characters '&', '-', '#'.</li>
* <li> cc_number_field - 			Credit Card Number must contain 16 numbers. '-' characters are removed.</li>
* <li> mo_yr_date_field - 		Month-Year Date requires the date to be formatted like: 'MM/YY'.</li>
* </ul>
*
* Page requirements:
* - Page must include the common.fieldvalidation.js script, as well as contain some
* fields that have flags, such as "required_field".  Fields that are not required
* can still contain a flag like "phone_field", so that it will still check to
* make sure the information entered is valid.
* - Additionally, there must be a div on the page to hold an error message.
* The name of this field must be passed as a parameter
* so that an error message can be spawned on field validation fail.
* - Script must also have access to JQuery.
*
* Sample objects on page:
* <div class="error_dialog" name="validation_error" id="validation_error" style="display:none;">,
* <form method="post" action="" onSubmit="return ValidateRequiredFields()">
*
* @return boolean returns true if everything is in good order, and false if something is missing.
*
* ERROR FIELD HIGLIGHTING
* ***********************
* If you want fields to be highlighted on error, make sure to have
* var validator_modifyCssOnError = true;
* Somewhere in your page's code.
*
* ERROR DIALOG NAVIGATION
* ***********************
* Similarly, if you want the page to relocate to focus on the error dialog on an error, add
* validator_navigateToDialogOnError
*
*
* @author Rach
* @since 05/03/2010
*/

function ValidateRequiredFields( errorDialogName )
{
	var useDebug = ( typeof( rDebug ) != "undefined" && rDebug );

	try
	{
		if ( botCheckField != undefined && document.getElementById( botCheckField ).value != "" )
		{
			// Fail, don't do anything
			return false;
		}
	}
	catch( error )
	{
	}

	// Set default error dialog name
	if ( errorDialogName == undefined )
	{
		errorDialogName = "validation_error";
	}
	/****************************************************************************/
	/*                               INITIALIZATION                             */
	/****************************************************************************/
	// This stores the error messages that will be put into an unordered-list
	// if the data validation fails.
	var invalidDataList = new Array();	// Holds the text data for use in the error dialog
	var invalidFieldList = new Array();	// Holds the NAME/ID attributes of bad data, for use in the highlighting function
	var allFieldList = new Array();			// Holds the NAME/ID of all fields, for use in the highlighting function
	invalidDataList.length = 0;
	invalidFieldList.length = 0;
	allFieldList.length = 0;

	// Get fields to check by flags
	try { var requiredFields = $( ".required_field" ); } 						catch (error) { ; }
	try { var phoneFields = $( ".phone_field" ); } 									catch (error) { ; }
	try { var emailFields = $( ".email_field" ); } 									catch (error) { ; }
	try { var addressFields = $( ".address_field" ); } 							catch (error) { ; }
	try { var zipFields = $( ".zip_field" ); } 											catch (error) { ; }
	try { var numericFields = $( ".numeric_field" ); } 							catch (error) { ; }
	try { var alphaNumericFields = $( ".alphanumeric_field" ); } 		catch (error) { ; }
	try { var alphabetFields = $( ".alphabet_field" ); } 						catch (error) { ; }
	try { var facilityFields = $( ".facility_name_field" ); } 			catch (error) { ; }
	try { var ccNumberFields = $( ".cc_number_field" ); } 					catch (error) { ; }
	try { var moYrDateFields = $( ".mo_yr_date_field" ); } 					catch (error) { ; }

	/****************************************************************************/
	/*                            CHECK ALL THE FIELDS                          */
	/****************************************************************************/
	/* ******************************************************** REQUIRED FIELDS */
	// Check to make sure required fields contain information
	var i, prettyText;
	for ( i=0; i < requiredFields.length; i++ )
	{
		allFieldList[ allFieldList.length++ ] = requiredFields[i].id;

		if ( !requiredFields[i].value )
		{
			// Missing data, append error message to the array
			prettyText = MD_Prettify_Text( requiredFields[i].id );
			invalidDataList[ invalidDataList.length++ ] = "Please check the \"" + prettyText + "\" field. It must be filled out.";
			invalidFieldList[ invalidFieldList.length++ ] = requiredFields[i].id;
		}
	} // for ( i=0; i<requiredFields.length; i++ )

	/* *********************************************************** PHONE NUMBER */
	// Check to make sure any phone fields are valid phone numbers
	for ( i=0; i < phoneFields.length; i++ )
	{
		allFieldList[ allFieldList.length++ ] = phoneFields[i].id;

		if ( phoneFields[i].value != "" )	// Ignore when blank, since it will have the "required fields" error if it's required
		{
			// Remove the usual special characters ( ) - and .
			// Regular Expression "g" = global match, [()-. ] = find any character between the brackets
			// http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_replace2
			phoneFields[i].value = phoneFields[i].value.replace( /[()-. ]/g, "" );

			// Now check to see if it meets the minimum length.
			if ( phoneFields[i].value.length != 10 )
			{
				// Too short
				prettyText = MD_Prettify_Text( phoneFields[i].id );
				invalidDataList[ invalidDataList.length++ ] = "Please check the \"" + prettyText + "\" field. It must contain 10 numbers.  It is currently " + phoneFields[i].value.length + " numbers.";
				invalidFieldList[ invalidFieldList.length++ ] = phoneFields[i].id;
			}

			// Now check to see if phone number is all numbers
			else if ( isNaN( phoneFields[i].value ) )
			{
				prettyText = MD_Prettify_Text( phoneFields[i].id );
				invalidDataList[ invalidDataList.length++ ] = "Please check the \"" + prettyText + "\" field. It must only contain numbers.";
				invalidFieldList[ invalidFieldList.length++ ] = phoneFields[i].id;
			}
		}
	} // for ( i=0; i<phoneFields; i++ )


	/* ********************************************************** EMAIL ADDRESS */
	// Check to make sure email fields contain an @ and .
	for ( i=0; i < emailFields.length; i++ )
	{
		allFieldList[ allFieldList.length++ ] = emailFields[i].id;

		if ( emailFields[i].value != "" )	// Ignore when blank, since it will have the "required fields" error if it's required
		{
			if ( emailFields[i].value.indexOf( '@' ) == -1 || emailFields[i].value.indexOf( '.' ) == -1 )
			{
				// Missing the @ or .
				prettyText = MD_Prettify_Text( emailFields[i].id );
				invalidDataList[ invalidDataList.length++ ] = "Please check the \"" + prettyText + "\" field. Email address is invalid.";
				invalidFieldList[ invalidFieldList.length++ ] = emailFields[i].id;
			}
		}
	} // for ( i=0; i<emailFields; i++ )

	/* **************************************************************** ADDRESS */
	// Check address - can have numbers, letters, # signs, dashes, and periods are replaced by spaces.
	for ( i=0; i < addressFields.length; i++ )
	{
		allFieldList[ allFieldList.length++ ] = addressFields[i].id;

		if ( addressFields[i].value != "" )	// Ignore when blank, since it will have the "required fields" error if it's required
		{
			// Get rid of periods
			var ctr=0;	// Protect against infinite loops
			while ( addressFields[i].value.indexOf( '.' ) != -1 && ctr < 20 )
			{
				ctr++;
				addressFields[i].value = addressFields[i].value.replace( /[.]/, "" );
			}

			// Now make sure there are no numbers or special characters.
			var regExpr = /[!`~@$%^&*()_\+=;:\\/|?.,<>]/;
			if ( regExpr.test( addressFields[i].value ) )
			{
				prettyText = MD_Prettify_Text( addressFields[i].id );
				invalidDataList[ invalidDataList.length++ ] = "Please check the \"" + prettyText + "\" field. It can only contain letters, numbers, #, and - signs";
				invalidFieldList[ invalidFieldList.length++ ] = addressFields[i].id;
			}
		}
	} // for ( i=0; addressFields; i++ )

	/* *************************************************************** ZIP CODE */
	for ( i=0; i < zipFields.length; i++ )
	{
		allFieldList[ allFieldList.length++ ] = zipFields[i].id;

		if ( zipFields[i].value != "" )	// Ignore when blank, since it will have the "required fields" error if it's required
		{
			/*
			// Doesn't make sense for Canadian vs US zips
			if ( zipFields[i].value.length < 7 )
			{
				prettyText = MD_Prettify_Text( zipFields[i].id );
				invalidDataList[ invalidDataList.length++ ] = "Please check the \"" + prettyText + "\" field. It must contain 5-6 numbers.  It is currently " + zipFields[i].value.length + " numbers.";
				invalidFieldList[ invalidFieldList.length++ ] = zipFields[i].id;
			}
			*/
			/*
			Canadian zips can have letters, so ignore this for now
			else if ( isNaN( zipFields[i].value ) )
			{
				prettyText = MD_Prettify_Text( zipFields[i].id );
				invalidDataList[ invalidDataList.length++ ] = "Please check the \"" + prettyText + "\" field. It must only contain numbers.";
				invalidFieldList[ invalidFieldList.length++ ] = zipFields[i].id;
			}*/
		}
	} // for ( i=0; i < zipFields.length; i++ )

	/* **************************************************************** NUMERIC */
	// Check to make sure these fields contain only numbers
	for ( i=0; i < numericFields.length; i++ )
	{
		allFieldList[ allFieldList.length++ ] = numericFields[i].id;

		if ( numericFields[i].value != "" )	// Ignore when blank, since it will have the "required fields" error if it's required
		{
			if ( isNaN( numericFields[i] ) )
			{
				prettyText = MD_Prettify_Text( numericFields[i].id );
				invalidDataList[ invalidDataList.length++ ] = "Please check the \"" + prettyText + "\" field. It must only contain numbers.";
				invalidFieldList[ invalidFieldList.length++ ] = numericFields[i].id;
			}
		}
	} // for ( i=0; i < numericFields.length; i++ )

	/* ********************************************************** ALPHA-NUMERIC */
	// Check to make sure these fields contain either numbers or letters, but no special characters
	for ( i=0; i < alphaNumericFields.length; i++ )
	{
		allFieldList[ allFieldList.length++ ] = alphaNumericFields[i].id;

		if ( alphaNumericFields[i].value != "" )	// Ignore when blank, since it will have the "required fields" error if it's required
		{
			// First replace any periods with blankness, just to be nice, hmmk? :)
			var ctr=0;	// Protect against infinite loops
			while ( alphaNumericFields[i].value.indexOf( '.' ) != -1 && ctr < 20 )
			{
				ctr++;
				alphaNumericFields[i].value = alphaNumericFields[i].value.replace( /[.]/, "" );
			}

			// Now check to make sure there are no special characters
			var regExpr = /[!`~@#$%^&*()_\-\+=;:\\/|?.,<>]/g;
			if ( regExpr.test( alphaNumericFields[i].value ) )
			{
				prettyText = MD_Prettify_Text( alphaNumericFields[i].id );
				invalidDataList[ invalidDataList.length++ ] = "Please check the \"" + prettyText + "\" field. It must only contain only numbers and letters.";
				invalidFieldList[ invalidFieldList.length++ ] = alphaNumericFields[i].id;
			}
		}
	} // for ( i=0; i < alphaNumericFields.length; i++ )

	/* *************************************************************** ALPHABET */
	// Check to make sure tehse fields contain just alphabetical characters, no numbers or special characters
	for ( i=0; i < alphabetFields.length; i++ )
	{
		allFieldList[ allFieldList.length++ ] = alphabetFields[i].id;

		if ( alphabetFields[i].value != "" )	// Ignore when blank, since it will have the "required fields" error if it's required
		{
			// Get rid of periods
			var ctr=0;	// Protect against infinite loops
			while ( alphabetFields[i].value.indexOf( '.' ) != -1 && ctr < 20 )
			{
				ctr++;
				alphabetFields[i].value = alphabetFields[i].value.replace( /[.]/, "" );
			}

			// Now make sure there are no numbers or special characters.
			var regExpr = /[!`~@#$%^&*()_\-\+=;:\\/|?.,<>]|[0-9]/;
			if ( regExpr.test( alphabetFields[i].value ) )
			{
				prettyText = MD_Prettify_Text( alphabetFields[i].id );
				invalidDataList[ invalidDataList.length++ ] = "Please check the \"" + prettyText + "\" field. It must only contain letters.";
				invalidFieldList[ invalidFieldList.length++ ] = alphabetFields[i].id;
			}
		}
	} // for ( i=0; i < alphabetFields.length; i++ )

	/* ********************************************************** FACILITY NAME */
	// Check to see if the facility names are valid - Can have letters, numbers, and the special characters: &, -, #, !
	for ( i=0; i < facilityFields.length; i++ )
	{
		allFieldList[ allFieldList.length++ ] = facilityFields[i].id;

		if ( facilityFields[i].value != "" )	// Ignore, since it will have the "required fields" error if it's required
		{
			// Get rid of periods
			var ctr=0;	// Protect against infinite loops
			while ( facilityFields[i].value.indexOf( '.' ) != -1 && ctr < 20 )
			{
				ctr++;
				facilityFields[i].value = facilityFields[i].value.replace( /[.]/, "" );
			}

			var regExpr = /[`~@$%^*()_+=;:\+|?.,<>]/;
			if ( regExpr.test( facilityFields[i].value ) )
			{
				prettyText = MD_Prettify_Text( facilityFields[i].id );
				invalidDataList[ invalidDataList.length++ ] = "Please check the \"" + prettyText + "\" field.  It can only have letters, numbers, &, -, and # signs.";
				invalidFieldList[ invalidFieldList.length++ ] = facilityFields[i].id;
			}
		}
	} // for ( i=0; i < facilityFields.length; i++ )

	/* ***************************************************** CREDIT CARD NUMBER */
	// Check to see if the facility names are valid - Can have letters, numbers, and the special characters: &, -, #
	for ( i=0; i < ccNumberFields.length; i++ )
	{
		allFieldList[ allFieldList.length++ ] = ccNumberFields[i].id;

		if ( ccNumberFields[i].value != "" )	// Ignore, since it will have the "required fields" error if it's required
		{
			// Get rid of periods
			ccNumberFields[i].value = ccNumberFields[i].value.replace( /[-]|[\s]/g, "" ); // replace space and dashes

			// Now ccNumberFields to see if it meets the minimum length.
			var regExpr = /[0-9X]/;
			if ( ccNumberFields[i].value.length != 16  && ccNumberFields[i].value.length != 15)
			{
				// Too short
				prettyText = MD_Prettify_Text( ccNumberFields[i].id );
				invalidDataList[ invalidDataList.length++ ] = "Please check the \"" + prettyText + "\" field. It must contain 16 numbers.  It is currently " + ccNumberFields[i].value.length + " numbers.";
				invalidFieldList[ invalidFieldList.length++ ] = ccNumberFields[i].id;
			}
			else if ( !regExpr.test( ccNumberFields[i].value ) )
			{
				prettyText = MD_Prettify_Text( ccNumberFields[i].id );
				invalidDataList[ invalidDataList.length++ ] = "Please check the \"" + prettyText + "\" field.  It can only have numbers.";
				invalidFieldList[ invalidFieldList.length++ ] = ccNumberFields[i].id;
			}
		}
	} // for ( i=0; i < ccNumberFields.length; i++ )

	/* ******************************************************** MONTH/YEAR DATE */
	for ( i=0; i < moYrDateFields.length; i++ )
	{
		allFieldList[ allFieldList.length++ ] = moYrDateFields[i].id;

		if ( moYrDateFields.value != "" ) // Ignore, since it will have the "required fields" error if it's required
		{
			// Make sure it's in a "MM/YY" format
			var regExpr = /[0-9]{2}\/[0-9]{2}/;

			if ( !regExpr.test( moYrDateFields[i].value ) && moYrDateFields[i].length > 0)
			{
				prettyText = MD_Prettify_Text( moYrDateFields[i].id );
				invalidDataList[ invalidDataList.length++ ] = "Please check the \"" + prettyText + "\" field.  It must have the format 'MM/YY'.";
				invalidFieldList[ invalidFieldList.length++ ] = moYrDateFields[i].id;
			}
		}
	} // for ( i=0; i < moYrDateFields.length; i++ )

	/****************************************************************************/
	/*              FINISH UP - CREATE ERROR DIALOG, OR RETURN TRUE             */
	/****************************************************************************/

	// If there is invalid data, create error dialog and return false to cancel the form post.
	if ( invalidDataList.length > 0 )
	{
		errorDialogName = "#" + errorDialogName;

		var inner = "<h3><span>Unable to process</span></h3><ul>";
		inner +=		"<p>Please review the issues and resolve them before re-submitting.</p>";

		for ( var i=0; i<invalidDataList.length; i++ )
		{
			inner += "<li>" + invalidDataList[i] + "</li>";
		}

		try
		{
			$(errorDialogName).html( inner );
			$(errorDialogName).slideDown( 'slow', function() { ; } );
			var args = { "error_count" : invalidDataList.length };
			Modal_ResizeWindow( args );
		}
		catch ( error )
		{
			//	alert( "Error creating error message in div " + errorDialogName + ":\n" + error );
		}

		if ( typeof( validator_modifyCssOnError ) != 'undefined' && validator_modifyCssOnError )
		{
			HighlightFields( allFieldList, invalidFieldList );
		}

		if ( typeof( validator_navigateToDialogOnError ) != "undefined" && validator_navigateToDialogOnError )
		{
			window.location = "#error_dialog_nav";
		}

		return false;
	}

	return true;
}

function ClearValidationLog()
{
	var invalidDataList = new Array();	// Holds the text data for use in the error dialog
	var invalidFieldList = new Array();	// Holds the NAME/ID attributes of bad data, for use in the highlighting function
	var allFieldList = new Array();			// Holds the NAME/ID of all fields, for use in the highlighting function
	invalidDataList.length = 0;
	invalidFieldList.length = 0;
	allFieldList.length = 0;
	try
	{
		RD_Clear_Log();
	}
	catch ( error ) { ; }
}

/**
* Takes the id/name field and formats it to camcel case, removes _'s, and
* any special prefixes/suffixes that might be associated with the name.
*
* @param	string	uglyText		The unformatted text
*
* @return	string	prettyText	Returns the formatted text
*
* @author Rach
* @since 05/03/2010
*/
function MD_Prettify_Text( uglyText )
{
	// Replace common characters and strings that appear in our field names
	uglyText = uglyText.replace( /[_\[\]]/g, " " );	// Remove numbers and special characters
	uglyText = uglyText.replace( " input", "" );
	uglyText = uglyText.replace( "input ", "" );
	uglyText = uglyText.replace( "pra ", "" );
	uglyText = uglyText.replace( "create ", "" );
	uglyText = uglyText.replace( "patch", "" );
	uglyText = uglyText.replace( "ee", "" );
	uglyText = uglyText.replace( "undefined", "" );
	uglyText = uglyText.replace( "embedded", "" );
	uglyText = uglyText.replace( "inquiry", "" );
	uglyText = uglyText.replace( /[0-9]/g, "" );	// Remove numbers and special characters

	// Split into an array
	var textArray = uglyText.split( ' ' );
	var prettyText = "";

	// Convert to camel case
	prettyText += textArray[0].substring(0,1).toUpperCase() + textArray[0].substring(1,textArray[0].length)
	for ( var i=1; i<textArray.length; i++ )
	{
		prettyText += " " + textArray[i].substring(0,1).toUpperCase() + textArray[i].substring(1,textArray[i].length);
	}

	return prettyText;
}

/**
* Resets all fields back to the default color, and highlights the fields
* marked in invalidFieldList.
* Specifically for use in page.sales.facilitysettings.php
*
* @param 	string-array	allFieldList			List of all fields the validator checked over
* @param	string-array	invalidFieldList	List of all the fields that were marked as having invalid data
*
* @author Rach
* @since 05/05/2010
*/
function HighlightFields( allFieldList, invalidFieldList )
{
	var objClass;
	var newClass;
	// Reset all fields back to default background
	for ( i in allFieldList )
	{

		// Remove red background class
		$('#' + allFieldList[i]).parent().removeClass( 'bg_red_large' );
		$('#' + allFieldList[i]).parent().removeClass( 'bg_red_medium' );
		$('#' + allFieldList[i]).parent().removeClass( 'bg_red_small' );

		//objClass = $('#' + allFieldList[i]).parent().attr( 'class' );
		objClass = document.getElementById( allFieldList[i] ).parentNode.className;

		if ( typeof( objClass ) != "undefined" )
		{
			// Add white background class (simply removing the red background didn't seem to work; explicitly telling it to change it now)
			if ( objClass.indexOf('large') != -1 ) 						{ newClass = "bg_white_large";	}
			else if ( objClass.indexOf('medium') != -1 )		 	{ newClass = "bg_white_medium"; }
			else if ( objClass.indexOf('mediumlarge') != -1 ) {	newClass = "bg_white_large"; }
			else if ( objClass.indexOf('small') != -1 ) 			{	newClass = "bg_white_small"; }

			newClass = objClass + " " + newClass;
			newClass = newClass.replace( "bg_red_large", "" );
			newClass = newClass.replace( "bg_red_medium", "" );
			newClass = newClass.replace( "bg_red_mediumlarge", "" );
			newClass = newClass.replace( "bg_red_small", "" );

			// Change background color
			//$('#' + allFieldList[i]).parent().attr( 'class', newClass );
			document.getElementById( allFieldList[i] ).parentNode.className = newClass;
			// Change font color
			//$('#' + allFieldList[i]).css( 'color', '#a0a0a0' );
		}
	}

	// Mark the error fields
	for ( i in invalidFieldList )
	{
		//RD_Append_Log( "\nold class: " + document.getElementById( invalidFieldList[i] ).className );
		objClass = document.getElementById( invalidFieldList[i] ).parentNode.className;
		//objClass = $('#' + invalidFieldList[i]).parent().attr( 'class' );

		if ( typeof ( objClass ) != "undefined" )
		{
			if ( objClass.indexOf('large') != -1 ) 						{ newClass = "bg_red_large"; }
			else if ( objClass.indexOf('medium') != -1 ) 			{ newClass = "bg_red_medium"; }
			else if ( objClass.indexOf('mediumlarge') != -1 ) {	newClass = "bg_red_large"; }
			else if ( objClass.indexOf('small') != -1 ) 			{ newClass = "bg_red_small"; }

			newClass = objClass + " " + newClass;

			// Change background color
			//$('#' + invalidFieldList[i]).parent().attr( 'class', newClass );
			document.getElementById( invalidFieldList[i] ).parentNode.className = newClass;
			// Change font color
			//document.getElementById( invalidFieldList[i] ).color = "#000000";
			//$('#' + invalidFieldList[i]).css( 'color', '#000000' );
		}
	}
}









