
function ExecuteValidation( step, validationGroup, errorSummaryElement )
{
	eval( "var results = ValidationStep" + step + validationGroup + "();" );

    var allValid = true;

    errorSummary = '<ul id="errorSummary">';
    var errorFocused = false;

	for ( var htmlName in results )
	{
		if ( !results[ htmlName ] )
		{
			allValid = false;
			errorSummary += "<li>" + validationErrors[ htmlName ] + "</li>";
		}

		SetValidationMessage( htmlName, validationErrors[ htmlName ], !results[ htmlName ] );

		if ( !results[ htmlName ] )
		{
			if ( !errorFocused )
			{
				try
				{
					document.getElementById( htmlName ).focus();
					errorFocused = true;
				}
				catch( er )
				{
				}
			}
		}

	}

	errorSummary += '</ul>';

	if ( errorSummaryElement )
	{
		$(document).ready( function(){ $( "#" + errorSummaryElement ).html( errorSummary ).effect( "highlight", {}, 1500 ) });
	}

	return allValid;
}

function SetValidationMessage( htmlName, message, isError )
{
	var setValidation = true;

	if ( typeof OnSetValidationMessage == 'function' )
	{
		setValidation = OnSetValidationMessage( htmlName, message, isError );
	}

	if ( setValidation )
	{
		if ( document.getElementById( htmlName + 'Validation' ) )
		{
			document.getElementById( htmlName + 'Validation' ).innerHTML = message;

			if( isError )
			{
				document.getElementById( htmlName + 'Validation' ).className = "error";
			}
			else
			{
				document.getElementById( htmlName + 'Validation' ).className = "";
			}
		}
	}
}

function ProcessClientValueOnServer( formName, stepName, inputName, validationIndex, currentValue )
{
	var ajaxUrl = "/ajax/formValidation/" + formName + "/" + stepName + "/" + inputName + "/" + validationIndex;

    $.ajax({
	  type: "POST",
	  url: ajaxUrl,
	  async: false,
	  timeout: 500,
	  data: $("input,select,textarea").serialize(),
	  dataType: "script",
	  error: function ( XMLHttpRequest, textStatus, errorThrown )
	  		{
			  	serverValidationValue = currentValue;
			}

	});

	return serverValidationValue;
}

function CreateErrorMessage( inputName, template )
{
	var message = template.replace( "{error}", validationErrors[ inputName ] );
	return message;
}

function SimulateButtonClick( buttonName, formName )
{
	clickedButton = buttonName;

    var newInput = document.createElement("input");
	newInput.setAttribute("type", "hidden");
	newInput.setAttribute("name", buttonName );
	newInput.setAttribute("value", "1");

	document.forms[ formName ].appendChild( newInput );
	document.forms[ formName ].submit();
}

function ToggleSelectOther( htmlName, testValue )
{
	var selectValue = document.getElementById( htmlName ).value;

	if ( document.getElementById( htmlName + "Other" ) )
	{
		document.getElementById( htmlName + "Other" ).style.display = ( selectValue == testValue ) ? "block" : "none";
	}
}

function LeftPad( contentToSize, padLength, padChar )
{
	var paddedString = contentToSize.toString();

	for( i = contentToSize.length + 1; i <= padLength; i++ )
	{
		paddedString = padChar + paddedString;
	}

	return paddedString;
}


function GetJsDate( dateName )
{
	var year = '0000';
	var month = '00';
	var day = '00';

	if ( document.getElementById( dateName + "_year" ) )
	{
		if ( document.getElementById( dateName + "_year" ).value == '-' )
		{
			return '0000-00-00';
		}

		year = LeftPad( document.getElementById( dateName + "_year" ).value, 4, '0' );
	}

	if ( document.getElementById( dateName + "_month" ) )
	{
		if ( document.getElementById( dateName + "_month" ).value == '-' )
		{
			return '0000-00-00';
		}

		month = LeftPad( document.getElementById( dateName + "_month" ).value, 2, '0' );
	}

	if ( document.getElementById( dateName + "_day" ) )
	{
		if ( document.getElementById( dateName + "_day" ).value == '-' )
		{
			return '0000-00-00';
		}

		day = LeftPad( document.getElementById( dateName + "_day" ).value, 2, '0' );
	}

	var returnVal = year + "-" + month + "-" + day;

	return returnVal;
}

function NotEqualTo( value, compareTo )
{
	return ( value != compareTo );
}

function EqualTo( value, compareTo )
{
	return ( value == compareTo );
}

function NotEmpty( value )
{
	return ( value != "" );
}

// Used in some places to display the word count remaining.
var lastWordCount = 0;

function MinWords( value, minWords )
{
	CountWords( value );
	return ( lastWordCount >= minWords );
}

function MaxWords( value, maxWords )
{
	CountWords( value );
	return ( lastWordCount <= maxWords );
}

function CountWords( value )
{
	var y = value;
	var r = 0;

	a = y.replace(/\s/g,' ');
	a = a.split(' ');

	for (z=0; z<a.length; z++)
	{
		if ( a[z].length > 0 )
		{
			r++;
		}
	}

	lastWordCount = r;
}

function MinChars( value, minChars )
{
	return ( value.length >= minChars );
}

function MaxChars( value, maxChars )
{
	return ( value.length <= maxChars );
}

function CheckDateRange( value, min, max )
{
    if( max != 0 && value > max )
    {
        return false;
    }

    if( min != 0 && value < min )
    {
        return false;
    }

    return true;
}

function ValidEmail( value )
{
	var reg = /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i;
	if( !value.match( reg ) )
	{
		return false;
	}

	return true;

}

function ValidCreditCard( strNum )
{
   var nCheck = 0;
   var nDigit = 0;
   var bEven = false;

   for (n = strNum.length - 1; n >= 0; n--)
   {
      var cDigit = strNum.charAt (n);

      if ( IsDigit( cDigit ) )
      {
         var nDigit = parseInt(cDigit, 10);

         if (bEven)
         {
            if ((nDigit *= 2) > 9)
               nDigit -= 9;
         }
         nCheck += nDigit;
         bEven = ! bEven;
      }
      else
      {
         return false;
      }
   }
   return (nCheck % 10) == 0;
}

function IsDigit (c)
{
   var strAllowed = "1234567890";
   return (strAllowed.indexOf (c) != -1);
}

function IsNumeric( value )
{
	if ( value == null || !value.toString().match(/^[-]?\d*\.?\d*$/) )
	{
		return false;
	}

	return true;
}

function GreaterThan( value, compareTo )
{
	if ( !IsNumeric( value ) )
	{
		return false;
	}

	var fValue = parseFloat( value );

	return ( fValue > compareTo );
}


function SameAsField( value, field )
{
	var fieldValue = document.getElementById( field ).value;

	if( value != fieldValue )
	{
		return false;
	}

	return true;

}

function CheckFileTypes( value, types, required )
{
	if ( value == "" && required )
	{
		return false;
	}

	var typeArray = types.split(",");

	if ( types.length == 0 )
	{
		return true;
	}

	if ( value == "" )
	{
		return true;
	}

    var ext = value.substring( value.lastIndexOf( '.' ), value.length);

    var allowed = false;

    for ( var x = 0; x < typeArray.length; x++ )
    {
    	var lcaseTest = "." + typeArray[ x ];
    	lcaseTest = lcaseTest.toLowerCase();
    	var lext = ext.toLowerCase();

    	if ( lcaseTest == lext )
    	{
    		allowed = true;
		}
	}

	return allowed;
}

function ConfirmThis( value, message )
{
	if( value != "" )
	{
		return true;
	}
	else
	{
		return confirm( message );
	}
}

function GetRadioValue( radioGroupName )
{
	var radioButtons = document.getElementsByName( radioGroupName );
	for( var i = 0; i < radioButtons.length; i++ )
	{
		if( radioButtons[i].checked )
		{
			return radioButtons[i].value;
		}
	}
	return '';
}
