
var arInputsToValidate = new Array ();
var arValidationErrors = new Array ();
var arCompareErrors = new Array ();


//----------------------------------------------------------------------
// Useful Form Actions
//----------------------------------------------------------------------

$(document).ready(function() {
	
	/**
	 * Handlers to give fieldset an active class 
	 * Triggers when any element inside is focused on
	 */
	$("fieldset").live('focusin', function(){
		$(this).addClass("active");
	});
	$("fieldset").live('focusout', function(){
		$(this).removeClass("active");
	});

	$("#Tip1").hover(function () {
		$(".Tip").show();		
	}, function() {
		$(".Tip").hide();	
	});

	
	// Check to see if we need a Password Strength plugin
	if ( $("input[name=Password]").next().attr("id") == 'password-strength' )
		$("input[name=Password]").passwordStrength();
		
		
	
	
});




//----------------------------------------------------------------------
// Useful Form Functions
//----------------------------------------------------------------------

function JS_Form_Validate( strFormID, bTrim )
{
	// Check to see if we are using a shit browser *cough* IE */cough*
	if ( !Modernizr.input.required || !Modernizr.inputtypes.email || !Modernizr.inputtypes.url || !Modernizr.inputtypes.tel )
	{
		var bIsValidated = false;
		var nItemsValidated = 0;
		
		// Get the items to be validated
		JS_Form_FindValidationItems(strFormID);
	
		
		// Loop through the items
		$(arInputsToValidate).each( function(i) {
			
			var bRequiredValid = true;
			var bTypeValid = true;
			var bConfirmValid = true;
			
			JS_Form_SetValidateOnDefocus(arInputsToValidate[i]);
			
			if ( bTrim )
			{	// Trim whitespace from the value
				var strValue = JS_Utils_Trim( arInputsToValidate[i].value );
				$(arInputsToValidate[i]).val(strValue);
			}

	
			// If it has a required field error attached
			if ( $(arInputsToValidate[i]).nextUntil('p','.required-field-error' ).length > 0 )
			{
				if ( $(arInputsToValidate[i]).attr("type") === "checkbox" )
				{
					// checkbox item
					if  ( (arInputsToValidate[i].checked) )
					{
						$(arInputsToValidate[i]).siblings(".required-field-error").css("display", "none") ;
					}
					else
					{
						$(arInputsToValidate[i]).siblings(".required-field-error").css("display", "block") ;
						bRequiredValid = false;
					}
				}

				// Check to see if we have data in the field
				if ( arInputsToValidate[i].value === '' || arInputsToValidate[i].value === 'http://' )
				{
					$(arInputsToValidate[i]).siblings(".required-field-error").css("display", "block") ;
					bRequiredValid = false;		
				}
				else
				{
					$(arInputsToValidate[i]).siblings(".required-field-error").css("display", "none");
	
				}
			}
			if ( $(arInputsToValidate[i]).nextUntil('p','.field-type-error' ).length > 0 )
			{
				$(arInputsToValidate[i]).siblings(".field-type-error").css("display", "none");
				
				if ( arInputsToValidate[i].value != "" )
				{
					strSearch = arInputsToValidate[i].name.toLowerCase();
					
					// is a valid email
					if ( strSearch.indexOf ( "email" ) > -1 )
					{
						if ( !JS_Form_IsEmail ( arInputsToValidate[i].value ) )
						{
							$(arInputsToValidate[i]).siblings(".field-type-error").css("display", "block");
							bTypeValid = false;		
						}						
					}
					
					// is a valid password
					if ( strSearch.indexOf ( "password" ) > -1 )
					{
						if ( !JS_Form_IsPassword ( arInputsToValidate[i].value ) )
						{
							$(arInputsToValidate[i]).siblings(".field-type-error").css("display", "block");
							bTypeValid = false;		
						}	
					}	
					
					// is a valid date
					if ( strSearch.indexOf ( "date" ) > -1 )
					{
						if ( !JS_Form_IsDate ( arInputsToValidate[i].value ) )
						{
							$(arInputsToValidate[i]).siblings(".field-type-error").css("display", "block");
							bTypeValid = false;		
						}	
					}
					
					// is a valid postcode
					if ( strSearch.indexOf ( "postcode" ) > -1 )
					{
						if ( !JS_Form_IsPostcode ( arInputsToValidate[i].value ) )
						{
							$(arInputsToValidate[i]).siblings(".field-type-error").css("display", "block");
							bTypeValid = false;		
						}	
					}
					
					// is a valid telephone number
					if ( strSearch.indexOf ( "telephone" ) > -1 )
					{
						if ( !JS_Form_IsTelephone ( arInputsToValidate[i].value ) )
						{
							$(arInputsToValidate[i]).siblings(".field-type-error").css("display", "block");
							bTypeValid = false;		
						}	
					}			
				}				
			}
			else if ( $(arInputsToValidate[i]).nextUntil('p','.confirm-value-error' ).length > 0 )
			{
				strFieldToMatch = arInputsToValidate[i].name.substring(8);
				
				if ( arInputsToValidate[i].value === '' || document.getElementById(strFieldToMatch).value !== arInputsToValidate[i].value )
				{
					$(arInputsToValidate[i]).siblings(".confirm-value-error").css("display", "block") ;
					bConfirmValid = false;
				}				
				else
				{
					$(arInputsToValidate[i]).siblings(".confirm-value-error").css("display", "none") ;			
				}
			}
			if ( bTypeValid && bRequiredValid && bConfirmValid )
				nItemsValidated++;
		});
	
	
		if ( nItemsValidated === arInputsToValidate.length ) bIsValidated = true;
	
		return bIsValidated;
	}
	else 
	{
		// These are to handle HTML5 validators
		$("input[data-minlength]").each(function(){
			if ( this.value.length < $(this).attr("data-minlength"))
			{
				this.setCustomValidity('Field must be ' + $(this).attr("data-minlength") + ' characters.' );
			}
			else
			{
				this.setCustomValidity('');
			}				
		});
		
		$(".confirmation").each(function(){
			strFieldName = $(this).attr("name").substring(8);
			
			if (this.value !== document.getElementById(strFieldName).value )
			{
				this.setCustomValidity('Confirmation field does not match');
			}
			else
			{
				this.setCustomValidity('');
			}
		});
		
	}
	
}



function JS_Form_FindValidationItems ( strFormID )
{
	var arValidationItems = $("#"+strFormID).find("p");
	var arValidationInputs = new Array();
	var arValidationSelects = new Array();
	var arValidationTextareas = new Array();		

	arInputsToValidate = new Array();

	// Loop through our input items to find the elements requiring validation
	$(arValidationItems).each( function(i) {
		if ( $(arValidationItems[i]).children(".required-field-error").length > 0 || 
				$(arValidationItems[i]).children(".field-type-error").length > 0 ||
				$(arValidationItems[i]).children(".confirm-value-error").length > 0		
			)
		{
			arValidationInputs = $(arValidationItems[i]).children("input");
			arValidationSelects = $(arValidationItems[i]).children("select");
			arValidationTextareas = $(arValidationItems[i]).children("textarea");				
			
			if ( ( arValidationInputs.length > 0 ) && arValidationInputs.length < 2 )
			{
				arInputsToValidate.push ( arValidationInputs[0] );
			}		
			if ( ( arValidationSelects.length > 0 ) && arValidationSelects.length < 2 )
			{
				arInputsToValidate.push ( arValidationSelects[0] );
			}		
			if ( ( arValidationTextareas.length > 0 ) && arValidationTextareas.length < 2 )
			{
				arInputsToValidate.push ( arValidationTextareas[0] );
			}					
		}
		
		
	});

}


function JS_Form_SetValidateOnDefocus ( objElement )
{
	var strFormID = $(objElement).parents("form").attr("id");
	
	objElement.onblur = function(){
		JS_Form_Validate( strFormID, true );
	}
	
	objElement.onkeyup = function(){
		JS_Form_Validate( strFormID, false );
	}
}



//----------------------------------------------------------------------
//----------------------------------------------------------------------

function JS_Form_ConfirmDelete ()
{
	return confirm ( "Are you sure you want to delete this item? \nThere is no undo!" );
}

function JS_Form_Confirm ( strMessage )
{
	return confirm ( strMessage );
}

//----------------------------------------------------------------------
//----------------------------------------------------------------------

// Sets the focus if the element is found
function JS_Form_SetFocus ( strElement )
{
	var txtElement = document.getElementById ( strElement );
	if ( txtElement ) txtElement.focus();
	else alert ( strElement + " not found" );
}


// make any disabled items enabled
function JS_Form_EnableInputs ( strFormID )
{
	var objForm = document.getElementById ( strFormID );
	
	if ( objForm )
	{
		var nElementsCount = objForm.elements.length;
		
		for ( var x=0; x<nElementsCount; x++ )
		{
			objForm.elements[x].disabled = false;
		}
	}
}


//----------------------------------------------------------------------
//----------------------------------------------------------------------

function JS_Form_AutoPostback ( strFormID )
{
	if ( !strFormID ) strFormID = String ( document.forms[0].id );
	
	var objForm = document.getElementById ( strFormID );
	objForm.onsubmit();
	objForm.submit();
}


function JS_Form_ChangeOrdinal ( nRecordID, strDirection )
{
	var objOrdinalHolder = document.getElementById ( "hidChangeOrdinal" );
	var objDirectionHolder = document.getElementById ( "hidChangeOrdinalDirection" );
	
	if (objOrdinalHolder) objOrdinalHolder.value = nRecordID;
	if (objDirectionHolder) objDirectionHolder.value = strDirection;
	
	//JS_Form_AutoPostback("Form1");
	
	return false;
}

//----------------------------------------------------------------------
//----------------------------------------------------------------------

function JS_Form_SelectAll ( strElement )
{
	var objElement = document.getElementById ( strElement );
	var arInputs = objElement.getElementsByTagName ( "input" );
	
	for ( var i=0; i<arInputs.length; i++ )
	{
		arInputs[i].checked = true;
	}	
}

function JS_Form_DeselectAll ( strElement )
{
	var objElement = document.getElementById ( strElement );
	var arInputs = objElement.getElementsByTagName ( "input" );
	
	for ( var i=0; i<arInputs.length; i++ )
	{
		arInputs[i].checked = false;
	}	
}

//----------------------------------------------------------------------
//----------------------------------------------------------------------

function JS_Form_CheckLimit ( objElement, nRecordLimit, bShowSpan )
{	
	// perform limit
	if ( objElement.value.length > nRecordLimit ) objElement.value = objElement.value.substring(0, nRecordLimit);
	
	// create message
	var nRemaining = nRecordLimit-objElement.value.length;
	strText  = "Remaining<br/>" + nRemaining + "/" + nRecordLimit;		
	
	// update limiter text
	var arSpans = JS_Utils_GetParent(objElement).getElementsByTagName("span");
	var objSpan;
	
	for ( var i=0; i<arSpans.length; i++ )
	{
		if ( arSpans[i].className == "Limiter" ) objSpan = arSpans[i];
	}
	
	// write message 
	objSpan.innerHTML = strText;
	
	// show / hide span
	if ( bShowSpan ) objSpan.style.display = "block";
	else objSpan.style.display = "none";
}

//----------------------------------------------------------------------
//----------------------------------------------------------------------

function JS_Form_IsEmail ( _input )
{
     var regEx = /^[_a-z0-9-\'_+#%]+(\.[_a-z0-9-\'_+#%]+)*@[a-z0-9-\'_+#%]+(\.[a-z0-9-\'_+#%]{2,})+$/i
     return regEx.test ( _input );	 
}

function JS_Form_IsPassword ( _input )
{
	return _input.length >= 6;
}

function JS_Form_IsDate ( _input )
{
     var regEx = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/
     return regEx.test ( _input );	
}

function JS_Form_IsPostcode ( _input )
{
     var regEx = /^[a-zA-Z]{1,2}[0-9][0-9A-Za-z]{0,1} {0,1}[0-9][A-Za-z]{2}$/
     return regEx.test ( _input );	
}

function JS_Form_IsTelephone ( _input )
{
	if ( _input != '' )
	{
		 var regEx = /^(((\+44\s?\d{4}|\(?0\d{4}\)?)\s?\d{3}\s?\d{3})|((\+44\s?\d{3}|\(?0\d{3}\)?)\s?\d{3}\s?\d{4})|((\+44\s?\d{2}|\(?0\d{2}\)?)\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?$/
	     return regEx.test ( _input );	
	}
	else return true;
}

/*
function JS_Form_IsURL ( _input )
{
	if ( _input == "http://" ) return true;
	else
	{
		var regEx = /x ^(http|https|ftp)\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&amp;%\$#\=~])*$ /
		return regEx.test ( _input );
	}	
}
*/


function JS_Form_UpdateTimeFloat( strFieldName )
{
	var fTime = 0.00;
	
	// Get hours and minutes
	var nHours = document.getElementById( 'Time_' + strFieldName + '_Hrs' ).value;
	var nMinutes = document.getElementById( 'Time_' + strFieldName + '_Mins' ).value;

	fTime = parseFloat(JS_Utils_TimeToDecimal( nHours + ':' + nMinutes ));
	
	document.getElementById( strFieldName ).value = fTime;
}

//----------------------------------------------------------------------
//----------------------------------------------------------------------

function JS_Form_CopyFieldValue ( strSourceID, strDestinationID )
{
	var objSource = document.getElementById ( strSourceID );
	var objDestination = document.getElementById ( strDestinationID );
	
	if ( objSource )
	{
		if ( objDestination )
		{
			objDestination.value = objSource.value;
		}
		else
		{
			alert ( "Sorry, could not find element with ID '" + strDestinationID + "'" );
		}
	}
	else
	{
		alert ( "Sorry, could not find element with ID '" + strSourceID + "'" );
	}
}

//----------------------------------------------------------------------
//	Password Strength Function
//----------------------------------------------------------------------



$.fn.passwordStrength = function( options ){
	return this.each(function(){
		var that = this;that.opts = {};
		that.opts = $.extend({}, $.fn.passwordStrength.defaults, options);

		that.div = $(that.opts.targetDiv);
		that.defaultClass = that.div.attr('class');

		that.percents = (that.opts.classes.length) ? 100 / that.opts.classes.length : 100;

		v = $(this)
		.keyup(function(){
			if( typeof el == "undefined" )
			this.el = $(this);
			var s = getPasswordStrength (this.value);
			var p = this.percents;
			var t = Math.floor( s / p );

			if( 100 <= s )
			t = this.opts.classes.length - 1;

			this.div
			.removeAttr('class')
			.addClass( this.defaultClass )
			.addClass( this.opts.classes[ t ] );
		})

	});

	function getPasswordStrength(H){
		var D=(H.length);

		// Added below to make all passwords less than 4 characters show as weak
		if (D<4) { D=0 }
		
		if(D>5){
			D=5
		}
		var F=H.replace(/[0-9]/g,"");
		var G=(H.length-F.length);
		if(G>3){G=3}
		var A=H.replace(/\W/g,"");
		var C=(H.length-A.length);
		if(C>3){C=3}
		var B=H.replace(/[A-Z]/g,"");
		var I=(H.length-B.length);
		if(I>3){I=3}
		var E=((D*10)-20)+(G*10)+(C*15)+(I*10);
		if(E<0){E=0}
		if(E>100){E=100}
		return E
	}	
};
$.fn.passwordStrength.defaults = {
	classes : Array('is10','is20','is30','is40','is50','is60','is70','is80','is90','is100'),
	targetDiv : '#password-strength',
	cache : {}
}


