String.prototype.trim = function()
{
	return this.replace(/^\s+|\s+$/, '');
};

if ( typeof window.buttonsForValidation === 'undefined' ) { window.buttonsForValidation = new Array(); };
if ( typeof window.validationGroups === 'undefined' ) { window.validationGroups = Array(); };
if ( typeof window.onSuccessCode === 'undefined' ) { window.onSuccessCode = Array(); };
if ( typeof window.validations === 'undefined' ) { window.validations = {}; };

/*
validations[ "PgAjax1212312" ] =
{
    "Username":
    {
        getJavascriptValueCode: "document.getElementById('Username').value",
        status: 'Untested', // Untested, Success, Fail, Pending
        groups:
        {
            "default":
            [
                {
                    validationFunction: "NotEmpty",
                    params: [],
                    status: 'Untested' // Untested, Success, Fail, Pending
                },
                {
                    validationFunction: "MaxWords",
                    params: [ 5 ],
                    status: 'Untested' // Untested, Success, Fail, Pending
                }
            ]
        }
    }
};
*/
function CheckValidationGroup( formReference, groupNameToValidate )
{
	ValidateGroup( formReference, groupNameToValidate );

	var inputs = validations[ formReference ];

    for( inputName in inputs )
    {
        if ( !inputName )
        {
        	continue;
		}

        var input = inputs[ inputName ];

        if ( !input )
        {
        	continue;
		}

        for( groupName in input.Groups )
        {
            if ( groupName == groupNameToValidate )
            {
                var group = input.Groups[ groupName ];

            	for( var i in group )
            	{
            		if( typeof( parseInt( i ) ) == 'number' )
            		{
            			var test = group[ i ];

            			if ( test.Status != "Success" && test.Status != 'Untested' )
            			{
							var simpleTabPanel = $( '[name=' + inputName + ']' ).parents( '.simple-tab-panel' );

							if ( simpleTabPanel.length )
							{
								$( 'a[href=#' + simpleTabPanel.attr( 'id' ) + ']' ).parents( 'li.simple-tab' ).addClass( 'error' );
							}

            				return false;
						}
					}
				}
            }
        }
    }

    return true;
}

function ValidateGroup( formReference, groupNameToValidate )
{
    var inputs = validations[ formReference ];

    for( var inputName in inputs )
    {
        if ( !inputName )
        {
        	continue;
		}

        var input = inputs[ inputName ];

        if ( !input )
        {
        	continue;
		}

        for( var groupName in input.Groups )
        {
            if ( groupName == groupNameToValidate )
            {
                ValidateInput( formReference, inputName, groupNameToValidate );
            }
        }
    }
}

function ValidateInput( formReference, inputName, groupNameToValidate )
{
    var input = validations[ formReference ][ inputName ];

    if ( !input )
    {
    	return;
	}

	input.Status = 'Untested';

    var validationsToRun = input.Groups[ groupNameToValidate ];
    var inputValue = eval( input.ValueCode );

    if ( !validationsToRun )
    {
    	return;
	}

    for( var i = 0; i < validationsToRun.length; i++ )
    {
        var validationToRun = validationsToRun[ i ];
        var conditionsPassed = true;

		for( var c = 0; c < validationToRun.Conditions.length; c++ )
		{
			var condition = validationToRun.Conditions[ c ];

			var conditionResult = eval( condition );

			if ( !conditionResult )
			{
				conditionsPassed = false;
				break;
			}
		}

        if ( conditionsPassed )
        {
        	var result = eval( validationToRun.Test );

        	if ( result )
        	{
        		validationToRun.Status = 'Success';
			}
			else
			{
				validationToRun.Status = 'Failed';
			}
		}
		else
		{
			validationToRun.Status = 'Untested';
		}
    }
}

function ProcessInlineValidationForInput( formReference, validationGroup, inputName )
{
	var input = window.validations[ formReference ][ inputName ];

	if ( !input )
	{
		return;
	}

	var validationsToCheck = input.Groups[ validationGroup ];

	if ( !validationsToCheck )
	{
		return;
	}

	var inputValue = eval( input.ValueCode );
	var failed = false;
	var allUntested = true;

	for( var i = 0; i < validationsToCheck.length; i++ )
	{
		var validationToCheck = validationsToCheck[ i ];

		if ( validationToCheck.Status != "Untested" )
		{
			allUntested = false;
		}

		switch ( validationToCheck.Status )
		{
			case 'Failed':
				document.getElementById( inputName + 'Validation' ).innerHTML = validationToCheck.ErrorMessage;
				i = 999;
				failed = true;
			break;
		}

		var cssClass = document.getElementById( inputName + 'Validation' ).className;
		cssClass = cssClass.replace( "pending" ,"" );
		cssClass = cssClass.replace( "failed", "" );
		cssClass = cssClass.replace( "success", "" );
		cssClass = cssClass.replace( "untested", "" );
		cssClass = cssClass + " " + validationToCheck.Status.toLowerCase();
		cssClass = cssClass.trim();

		document.getElementById( inputName + 'Validation' ).className = cssClass;
    }

    if ( !failed )
	{
		if ( allUntested )
		{
			document.getElementById( inputName + 'Validation' ).innerHTML = "";
		}
		else
		{
			document.getElementById( inputName + 'Validation' ).innerHTML = input.SuccessMessage;
		}
	}

	return !failed;
}

/**
* Analyse the validation state and update error handlers accordingly.
*/
function ProcessInlineValidation( formReference, validationGroup )
{
	var inputs = window.validations[ formReference ];
	var firstFailure = "";
	var simpleTabPanel = false;

	for( var inputName in inputs )
    {
        if ( !inputName )
        {
        	continue;
		}

        var input = inputs[ inputName ];

        if ( !input )
        {
        	continue;
		}

		if ( !input.Groups )
		{
			continue;
		}

		if ( !ProcessInlineValidationForInput( formReference, validationGroup, inputName ) )
		{
			if ( firstFailure == "" )
			{
				for( var groupName in input.Groups )
				{
					if ( groupName == validationGroup )
					{
						simpleTabPanel = $( firstFailureElement ).parents( '.simple-tab-panel' );
					}
				}

				firstFailure = inputName;
			}
		}
    }

    if ( firstFailure != "" )
    {
    	var firstFailureElement = document.getElementById( firstFailure );

    	if ( firstFailureElement )
    	{
			if ( !$( firstFailureElement ).is( ':visible' ) && simpleTabPanel && simpleTabPanel.length )
			{
				$( 'a[href=#' + simpleTabPanel.attr( 'id' ) + ']' ).click();
			}

    		firstFailureElement.focus();
		}
	}
}

function EnableFormButtons( formId )
{
	$( '#' + formId + ' .pg-button' ).removeClass( 'disabled' ).removeClass( 'processing' ).unbind( 'click.form-disable' );
}

function DisableFormButtons( formId )
{
	$( '#' + formId + ' .pg-button' ).bind( 'click.form-disable', function( event )
	{
		event.stopImmediatePropagation();
		alert( 'Sorry, this page is current processing. Please Wait...' );
		return false;
	} );
}

function OnButtonPushed( formReference )
{
	if ( typeof( SaveAllTinies ) == "function" )
	{
		SaveAllTinies();
	}

	var container = formReference;

    var buttonName = clickedButton;
    var buttonDetails = window.formButtons[ buttonName ];

	$( '#' + buttonName ).addClass( 'disabled' ).addClass( 'processing' );

    if ( buttonDetails.confirmMessage )
    {
        if ( !confirm( buttonDetails.confirmMessage ) )
        {
        	EnableFormButtons( container );
            return false;
        }
    }

    if ( buttonDetails.javascriptCondition )
    {
        var result = eval( buttonDetails.javascriptCondition );

        if ( !results )
        {
        	EnableFormButtons( container );
            return false;
        }
    }

    validationFunction = "TestForm" + formReference;

    if( !eval( validationFunction+"()" ) )
    {
    	EnableFormButtons( container );
        return false;
    }

    var ajaxed;
    ajaxed = false;

    if ( buttonDetails.ajaxFunctionCall )
    {
    	DisableFormButtons( container );

        ServerCall( buttonDetails.ajaxFunctionCall, [ buttonDetails.data ], function()
        {
        	EnableFormButtons( container );
		} );

        ajaxed = true;
    }

    if ( buttonDetails.eventCode )
    {
    	DisableFormButtons( container );

        SendApplicationEventToServer( buttonDetails.eventCode, buttonDetails.objectId, [ buttonDetails.data ], [], function()
        {
        	EnableFormButtons( container );
		},
		true,
		buttonDetails.appSessionKey );

        ajaxed = true;
    }

    if( ajaxed )
    {
		return false;
    }
    else
    {
    	DisableFormButtons( container );

		return true;
    }
}

function ExecuteValidation( formId, validationGroup )
{
	$( 'li.simple-tab.error' ).removeClass( 'error' );

	var valid = CheckValidationGroup( formId, validationGroup );

	var validationProcessors = window.validations[ formId ].ValidationProcessors;

	for( var i = 0; i < validationProcessors.length; i++ )
	{
		eval( validationProcessors[ i ] + "( formId, validationGroup )" );
	}

	return valid;
}

function FocusOnInvalidInput()
{
	var errorFocused = false;
	var input, jqInput, simpleTabPanel, simpleTab;

	for( var i = 0, count = FocusOnInvalidInput.arguments.length; i < count; i++ )
	{
		try
		{
			input = document.getElementById( FocusOnInvalidInput.arguments[i] );
			simpleTab = false;

			if( typeof $ === 'function' )
			{
				jqInput = $( input );

				simpleTabPanel = jqInput.parents( '.simple-tab-panel' );
				if( simpleTabPanel.length )
				{
					simpleTab = $( 'a[href=#'+simpleTabPanel.attr( 'id' )+']' );
					simpleTab.parents( 'li.simple-tab' ).addClass( 'error' );
				}
				else
				{
					simpleTab = false;
				}

				if( !errorFocused )
				{
					if( simpleTab )
					{
						simpleTab.click();
					}
					jqInput.focus();
				}
			}
			else if( !errorFocused )
			{
				input.focus();
			}
			errorFocused = true;
		}
		catch( er ) {}
	}
}

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, allowMultiple )
{
	var emailsToCheck = new Array();

	if( allowMultiple )
	{
		var seperators = new Array( "\r\n", "\n", ";", "," );

		for( var i = 0 ; i < seperators.length ; i++ )
		{
			if( value.indexOf( seperators[ i ] ) > 0 )
			{
				emailsToCheck = value.split( seperators[ i ] );
				break;
			}
		}
	}

	if( emailsToCheck.length == 0 )
	{
		emailsToCheck.push( value );
	}

	for( var k = 0 ; k < emailsToCheck.length ; k++ )
	{
		emailsToCheck[k] = emailsToCheck[k].trim();
	}

	var valid = true;
	var testsPerformed = false;
	var reg = new RegExp( "^[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" );

	for( var j = 0 ; j < emailsToCheck.length ; j++ )
	{
		testsPerformed = true;

		if( !reg.test( emailsToCheck[j] ) )
		{
			valid = false;
		}
	}

	if( testsPerformed )
	{
		return valid;
	}
	else
	{
		return false;
	}
}

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 LessThan( 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 '';
}

function CalculateStrength( obj )
{
	var name = "#" + $( obj ).attr( "id" );
	var strength = 0;
	var id = $(obj).attr( "id" );
	var value = $( obj ).val();
	var length = value.length;
	if ( length > 0 )
	{
		// Score based on length
		strength = parseInt( length / 3 );

		// Limit length score to 4 points
		if( strength > 4 )
		{
			strength = 4;
		}

		// find out if we have numbers
		var upperCase = value.replace( /[^A-Z]/g, "" );
		var lowerCase = value.replace( /[^a-z]/g, "" );
		var numbers = value.replace( /[^0-9]/g, "" );
		var symbols = value.replace( /[a-zA-Z0-9]/g, "" );

		// Check for mixed case
		if( upperCase.length > 0 && lowerCase.length > 0 )
		{
			strength++;
		}

		// Check for numbers
		if( numbers.length > 0 )
		{
			strength++;

			// Give extra points for using more than 2 numbers, but only if the password isnt mostly numeric
			if( numbers.length > 2 && length >= ( numbers.length * 2 ) )
			{
				strength++;
			}
		}

		// Check for symbols
		if( symbols.length > 2 )
		{
			strength++;

			// Give extra points for using more than 2 numbers, but only if the password isnt mostly symbolic
			if( symbols.length > 2 && length >= ( symbols.length * 2 ) )
			{
				strength++;
			}
		}

	}

	// Display the appropriate strength indicator
	if( strength > 5 )
	{
		$( name + "PasswordStrengthMedium" ).fadeOut("short", function()
		{
			$( name + "PasswordStrengthWeak" ).fadeOut("short", function()
			{
				$( name + "PasswordStrengthStrong" ).fadeIn();
			} );
		} );
	}
	else if( strength > 3 )
	{
		$( name + "PasswordStrengthStrong" ).fadeOut("short", function()
		{
			$( name + "PasswordStrengthWeak" ).fadeOut("short", function()
			{
				$( name + "PasswordStrengthMedium" ).fadeIn();
			} );
		} );
	}
	else if( length > 0 )
	{
		$( name + "PasswordStrengthStrong" ).fadeOut("short", function()
		{
			$( name + "PasswordStrengthMedium" ).fadeOut("short", function()
			{
				$( name + "PasswordStrengthWeak" ).fadeIn();
			} );
		} );
	}
	else
	{
		$( name + "PasswordStrengthStrong" ).fadeOut( "short" );
		$( name + "PasswordStrengthMedium" ).fadeOut( "short" );
		$( name + "PasswordStrengthWeak" ).fadeOut( "short" );
	}
}

function ReplaceSelectItems( selectId, selectOptions )
{
	var previousValue = document.getElementById( selectId ).value;

    document.getElementById(selectId).options.length = 0;

    for( var i = 0; i < selectOptions.length; i++ )
    {
        var item = selectOptions[ i ];
        var newOption = new Option( item.value, item.key );
        document.getElementById( selectId ).options[ i ] = newOption;
    }

    document.getElementById( selectId ).value = previousValue;

    if ( window.selectValues )
    {
	    if ( window.selectValues[ selectId ] )
	    {
	        document.getElementById( selectId ).value = window.selectValues[ selectId ];
	    }
	}
}

function GetCaretPosition( ctrl )
{
	var caretPos = 0;	// IE Support

	if ( document.selection )
	{
		ctrl.focus();
		var sel = document.selection.createRange();

		if ( sel.text.length > 0 )
		{
			sel.moveEnd( 'character', -sel.text.length );
		}

		sel.moveStart ('character', -ctrl.value.length);
		caretPos = sel.text.length;
	}
	// Firefox support
	else
	{
		if (ctrl.selectionStart || ctrl.selectionStart == '0')
		{
			caretPos = ctrl.selectionStart;
		}
	}

	return caretPos;
}

function IsNumberKey( evt, allowDecimal, allowNegative )
{
	if ( evt.which )
	{
		var charCode = evt.which;
	}
	else if ( typeof event != 'undefined' )
	{
		var charCode = event.keyCode;
	}
	else
	{
		return true;
	}

	if ( !allowNegative )
	{
		if ( charCode == 45 )
		{
			return false;
		}
	}
	else
	{
		var control = ( evt.target ) ? evt.target : evt.srcElement;

		if ( charCode == 45 && ( GetCaretPosition( control ) != 0 ) )
		{
			return false;
		}
	}

	if( !allowDecimal && charCode == 46 )
	{
		return false;
	}

	if ( charCode > 31 && ( charCode < 48 || charCode > 57 ) && charCode != 46 && charCode != 45 )
	{
		return false;
	}

	return true;
}

function GetCommaSeparatedValueList( jQueryInputList )
{
	var values = '';
	$( jQueryInputList ).each( function()
	{
		values += this.value + ',';
	} );
	return values.replace( /(^,)|(,$)/g, '' );
}
