﻿// JScript File

// Tests to see if the 1st value is less than or equal to the 2nd value, assuming both values are ints. 
// If either is not an int, the function returns false.
function isValueALessThanOrEqualToValueB_int( valueA, valueB )
{
	if( !isInt( valueA ) || !isInt( valueB ) )
		return false;
	
	var iSizeMin = parseInt( valueA );
	var iSizeMax = parseInt( valueB );
	
	if( iSizeMin < 0 || iSizeMax < 0 || iSizeMin > iSizeMax )
		return false;
	
	return true;
}

// Tests to see if the 1st value is less than or equal to the 2nd value, assuming both values are doubles.
// If either is not a double, the function returns false.
function isValueALessThanOrEqualToValueB_double( valueA, valueB )
{
	if( isNaN( valueA ) || isNaN( valueB ) )
		return false;
	
	var dblSizeMin = parseFloat( valueA );
	var dblSizeMax = parseFloat( valueB );
	
	if( dblSizeMin < 0 || dblSizeMax < 0 || dblSizeMin > dblSizeMax )
		return false;
	
	return true;
}

function CustomValidateFileUpload(source, arguments)
{
	if( trim( arguments.Value ) == '' )
		arguments.IsValid = false;
	else
		arguments.IsValid = true;
}

function CustomValidatePdfUpload(source, arguments)
{
	// Match xxx.pdf at end of word, ignoring case.
	var regex = new RegExp(/.\.pdf$/i);
	
	arguments.IsValid = regex.test( arguments.Value );

}

function listenForEscape( e )
{
		if( document.all ) // IE.
			e = window.event;
		   
		var key;

		if( document.layers )
			key = e.which; // Mozilla etc.
		else
			key = e.keyCode ; // IE.

		if( key == 27 ) // ESC = 27
			window.close();
}

function openModalWindow( path, name, features )
{
	if (window.showModalDialog) // IE
	{
		//window.showModalDialog('xpopupex.htm','name', 'dialogWidth:255px;dialogHeight:250px');
		window.showModalDialog( path, name, features);
	} 
	else // Mozilla
	{
		window.open( path, name, features + ',modal=yes');
	}
}

// Determines if the specified dropdownlist control has it's default (first?) item selected.
function isDropDownDefaultSelected( ddl, defaultValue )
{
	if( ddl.options[ ddl.selectedIndex ].value == defaultValue )
		return true;
	else
		return false;
}

/*
// Used by ASL CheckBoxValidator controls that need to validate an ASP.NET CheckBox control.
function CheckBoxValidatorEvaluateIsValid(val)
{
	var control = document.getElementById(val.controltovalidate);
	var mustBeChecked = val.mustBeChecked == 'true' ? true : false;

	return control.checked == mustBeChecked;
}


// Used by ASL CheckBoxListValidator controls that need to validate an ASP.NET CheckBoxList control.
function CheckBoxListValidatorEvaluateIsValid(val)
{
	var control = document.getElementById(val.controltovalidate);
	var minimumNumberOfSelectedCheckBoxes = parseInt(val.minimumNumberOfSelectedCheckBoxes);

	var selectedItemCount = 0;
	var liIndex = 0;
	var currentListItem = document.getElementById(control.id + '_' + liIndex.toString());
	
	while (currentListItem != null)
	{
		if (currentListItem.checked) selectedItemCount++;
			liIndex++;
			
		currentListItem = document.getElementById(control.id + '_' + liIndex.toString());
	}

	return selectedItemCount >= minimumNumberOfSelectedCheckBoxes;
}
*/

// Validates that the length of a textarea's text does not exceed MaxLen.
function imposeMaxLength(Object, MaxLen)
{
  return (Object.value.length <= MaxLen);
}


// Pads the LHS of specified string with the specified char upto the specified total length.
function padLeft ( str, maxLen, padChar )
{
	// Quit if nothing to do.
	if ( ( (! maxLen ) || ( maxLen < 1 ) ) || ( (! str ) || str == '' || str.length >= maxLen ) )
		return str;

	// This is string of 100 spaces
	var padding = '                                                                                                    ';

	if ( padChar )
	{
		// replace the SPACES defined here with the given character(s)
		padding = padding.replace( / /g, padChar );
	}
	
	// Add some padding.
	var s = padding + str;
	
	// Get just the necessary part of the padding plus all the original string.
	return s.substring(s.length - maxLen);

}


// Attempts to parse a Date & Time from 5 dropdownlists.
function parseDateTimeFromDropDowns( ddlDay, ddlMonth, ddlYear, ddlHour, ddlMinute )
{
	var dtDate = parseDateFromDropDowns( ddlDay, ddlMonth, ddlYear );
	var dtTime = parseTimeFromDropDowns( ddlHour, ddlMinute );
	
	if( dtDate == null || dtTime == null )
		return null;
	else
		return new Date( dtDate.getFullYear(), dtDate.getMonth(), dtDate.getDate(), dtTime.getHours(), dtTime.getMinutes(), 0 );
}


// Attempts to parse a Date from 3 dropdownlists.
function parseDateFromDropDowns( ddlDay, ddlMonth, ddlYear )
{
	var day = ddlDay.options[ddlDay.selectedIndex].value;
	var month = ddlMonth.options[ddlMonth.selectedIndex].value;
	var year = ddlYear.options[ddlYear.selectedIndex].value;
	
	var sDate = day + '/' + month + '/' + year;
	
	if( isDate( sDate ) )
		return new Date( year, parseInt( month, 10 ) - 1, day );
	else
		return null;
}


// Attempts to build a time from 2 dropdownlists.
function parseTimeFromDropDowns( ddlHour, ddlMinute )
{
	var hour =  ddlHour.options[ddlHour.selectedIndex].value;
	var minute = ddlMinute.options[ddlMinute.selectedIndex].value;
	var sTime = padLeft( hour, 2, '0' ) + ':' + padLeft( minute, 2, '0' );
	
	if( isTime( sTime ) )
		return new Date( 1, 0, 1, hour, minute );
	else
		return null;
}


// Parses a date string from dd/MM/yyyy format. Returns null if any error occurs.
function parseDateFromTextBox( value )
{
	if(!isDate(value))
		return null;
	
	var arr = value.split('/');
	if(arr.length != 3)
		return null;
	
	var day = parseInt( arr[0], 10 );
	var month = parseInt( arr[1], 10 );
	var year = parseInt( arr[2], 10 );
	
	if(isNaN(day) || day < 1 || day > 31) // Valid Day of Month?
		return null;
		
	if(isNaN(month) || month < 1 || month > 12) // Valid Month of year?
		return null;
		
	if(isNaN(year) || year < 1 || year > 9999) // Valid year?
		return null;
		
	return new Date( year, month - 1, day );
}


// Parses a time string from HH:mm format. Returns null if any error occurs.
function parseTimeFromTextBox( value )
{
	if(!isTime(value))
		return null;
	
	var arr = value.split(':');
	if(arr.length != 2)
		return null;
	
	var hour = parseInt( arr[0], 10 );
	var minute = parseInt( arr[1], 10 );
	
	if(isNaN(hour) || hour < 0 || hour > 23) // Valid Hour?
		return null;
		
	if(isNaN(minute) || minute < 0 || minute > 59) // Valid Minute?
		return null;
		
	return new Date( 0, 0, 0, hour, minute );
}


// Toggles the visibility of the specified toggle control.
function toggleTagVisibility(toggleCtl, toggleCtlText, tagId, hiddenFieldId)
{
	var tag = document.getElementById( tagId );
	var hiddenField = document.getElementById( hiddenFieldId );
	
	if( tag.style.display == '' )
	{
		tag.style.display = 'none';
		hiddenField.value = 'false';
		if (toggleCtl.tagName == 'A')
			toggleCtl.innerText = toggleCtlText.replace( '{0}', 'Show' );
		else
			toggleCtl.value = toggleCtlText.replace( '{0}', 'Show' );
	}
	else
	{
		tag.style.display = '';
		hiddenField.value = 'true';
		if (toggleCtl.tagName == 'A')
			toggleCtl.innerText = toggleCtlText.replace( '{0}', 'Hide' );
		else
			toggleCtl.value = toggleCtlText.replace( '{0}', 'Hide' );
	}
}


// This allows us to output HTML <object> tags for Flash movies that prevent user from having to "click to activate this control" in Internet Explorer 6.
function writeObjectTag( width, height, clientId, src, cssClass )
{
	document.write( '\n<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="https://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0"' );
	if (height > 0 && width > 0)
		document.write( ' height="' + height + '" width="' + width + '"' );
	
	if( clientId != '' )
		document.write( ' id="' + clientId + '"' );
	
	if( cssClass != '' )
		document.write( ' class="' + cssClass + '"' );
	
	//document.write( ' id="' + clientId + '" class="' + cssClass + '"' );
	document.write( '>' );
	document.write( '\n<param name="movie" value="' + src + '">' );
	document.write( '\n<param name="quality" value="high">' );
	document.write( '\n<embed pluginspage="https://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" quality="high" type="application/x-shockwave-flash" ' );
	if (height > 0 && width > 0)
		document.write( ' height="' + height + '" width="' + width + '"' );
	document.write( ' src="' + src + '">' );
	document.write( '\n</embed>' );
	document.write( '\n</object>' );
}


// Determines if the specified string represents an integer.
function isInt( s )
{
	var i = parseInt (s);

	if( isNaN( i ) )
		return false;

	i = i.toString();
	if( i != s )
		return false;

	return true;
}


// Used by ASP.NET CustomValidator controls that need to validate an integer textbox.
function CustomValidateIsInt(source, arguments)
{
	arguments.IsValid = isInt( arguments.Value );
}


// Same as VB IsNumeric() function.
function isNumeric( sText )
{
	return !isNaN( sText );
} // EOF IsNumeric()


// Used by ASP.NET CustomValidator controls that need to validate a number textbox.
function CustomValidateIsNumeric(source, arguments)
{
	arguments.IsValid = isNumeric( arguments.Value );
}


// Validates a string is a valid email address.
function isEmailAddress( str )
{
	if( str.replace( ' ', '' ) == '' )
		return false;
		
	var filter=/^.+@.+\..{2,3}$/;
	return (filter.test(str));
}


// Used by ASP.NET CustomValidator controls that need to validate an email address in a textbox.
function CustomValidateEmailAddress(source, arguments)
{
	arguments.IsValid = isEmailAddress( arguments.Value );
}


// Validates a string as a UK Postcode.
function isPostcode (toCheck)
{
	// Permitted letters depend upon their position in the postcode.
	var alpha1 = "[abcdefghijklmnoprstuwyz]";                       // Character 1
	var alpha2 = "[abcdefghklmnopqrstuvwxy]";                       // Character 2
	var alpha3 = "[abcdefghjkstuw]";                                // Character 3
	var alpha4 = "[abehmnprvwxy]";                                  // Character 4
	var alpha5 = "[abdefghjlnpqrstuwxyz]";                          // Character 5

	// Array holds the regular expressions for the valid postcodes
	var pcexp = new Array ();

	// Expression for postcodes: AN NAA, ANN NAA, AAN NAA, and AANN NAA
	pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1,2})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));

	// Expression for postcodes: ANA NAA
	pcexp.push (new RegExp ("^(" + alpha1 + "{1}[0-9]{1}" + alpha3 + "{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));

	// Expression for postcodes: AANA  NAA
	pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1}" + alpha4 +"{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));

	// Exception for the special postcode GIR 0AA
	pcexp.push (/^(GIR)(\s*)(0AA)$/i);

	// Standard BFPO numbers
	pcexp.push (/^(bfpo)(\s*)([0-9]{1,4})$/i);

	// c/o BFPO numbers
	pcexp.push (/^(bfpo)(\s*)(c\/o\s*[0-9]{1,3})$/i);

	// Load up the string to check
	var postCode = toCheck;

	// Assume we're not going to find a valid postcode
	var valid = false;
	
	// Check the string against the types of post codes
	for( var i=0; i < pcexp.length; i++ )
	{
		if (pcexp[i].test(postCode))
		{
			// The post code is valid - split the post code into component parts
			pcexp[i].exec(postCode);

			// Copy it back into the original string, converting it to uppercase and
			// inserting a space between the inward and outward codes
			postCode = RegExp.$1.toUpperCase() + " " + RegExp.$3.toUpperCase();

			// If it is a BFPO c/o type postcode, tidy up the "c/o" part
			postCode = postCode.replace (/C\/O\s*/,"c/o ");

			// Load new postcode back into the form element
			valid = true;

			// Remember that we have found that the code is valid and break from loop
			break;
		}
	}
	
	// Return with either the reformatted valid postcode or the original invalid postcode.
	if (valid) {return postCode;} else return 'false';
}


// Used by ASP.NET CustomValidator controls that need to validate a postcode in a textbox.
function CustomValidatePostcode(source, arguments)
{
	arguments.IsValid = isPostcode( arguments.Value ) != 'false';
}


// Used by ASL CheckBoxValidator controls that need to validate an ASP.NET CheckBox control.
function CheckBoxValidatorEvaluateIsValid(val)
{
	var control = document.getElementById(val.controltovalidate);
	var mustBeChecked = val.mustBeChecked == 'true' ? true : false;

	return control.checked == mustBeChecked;
}


// Used by ASL CheckBoxListValidator controls that need to validate an ASP.NET CheckBoxList control.
function CheckBoxListValidatorEvaluateIsValid(val)
{
	var control = document.getElementById(val.controltovalidate);
	var minimumNumberOfSelectedCheckBoxes = parseInt(val.minimumNumberOfSelectedCheckBoxes);

	var selectedItemCount = 0;
	var liIndex = 0;
	var currentListItem = document.getElementById(control.id + '_' + liIndex.toString());
	
	while (currentListItem != null)
	{
		if (currentListItem.checked) selectedItemCount++;
			liIndex++;
			
		currentListItem = document.getElementById(control.id + '_' + liIndex.toString());
	}

	return selectedItemCount >= minimumNumberOfSelectedCheckBoxes;
}


// Removes whitespace characters from the ends of the specified string. Equivalent of Visual Basic Trim() function.
function trim( str )
{
   return str.replace(/^\s*|\s*$/g, '' );
}


// Returns a reference to a client-side control whose ID property was generated by ASP.NET.
function findControl( parentID, childID, childPosition )
{	
	// ctl00_cph_repApplicantSearchResults_ctl01_chkReceivePropertyDetails 
	// ctl00_cph_repPropertySearchResults_ctl02_chkSendDetails 
	
	// Build the control's client-side ID, e.g. 'repChildren__ctl1_ddlChildrenTitle'.
	var sID = parentID + '_ctl' + padLeft(childPosition, 2, '0') + '_' + childID;
	
	// Return a reference to that control.
	return document.getElementById( sID );
}


// Determines if the specified variable is a valid JavaScript object.
// Useful for determining if a particular HTML control exists on the page.
function isObject( a )
{
	return( a && typeof( a ) == 'object' ) || isFunction( a );
}	


// Determines if the specified variable is a JavaScript Function.
function isFunction( a )
{
	return typeof( a ) == 'function';
}


// Determines if the specified variable is a JavaScript Array or not.
function isArray( Variable )
{
	if( (typeof( Variable ) == 'object') && (Variable.constructor == Array) )
		return true;
	else
		return false;
}


// Calculates the age in whole years on the current date.
function age( dob )
{
	var Now = new Date();
	
	// Get the difference in years.
	var iAge = Now.getFullYear() - dob.getFullYear(); 
	
	if( Now.getMonth() < dob.getMonth() || ( Now.getMonth() == dob.getMonth() && Now.getDate() < dob.getDate() ) )
		iAge--;
	
	return iAge;
}


// Calculates the age in whole years on the specified date.
function ageAt( dob, onDate )
{
	// Get the difference in years.
	var iAge = onDate.getFullYear() - dob.getFullYear(); 
	
	if( onDate.getMonth() < dob.getMonth() || ( onDate.getMonth() == dob.getMonth() && onDate.getDate() < dob.getDate() ) )
		iAge--;
	
	return iAge;
}


// Determines if the specified string represents an integer.
function isInt( s )
{
	var i = parseInt (s);

	if( isNaN( i ) )
		return false;

	i = i.toString();
	if( i != s )
		return false;

	return true;
}

function isPositiveInt( s )
{
	if( isInt( s ) && s > 0 )
		return true;
	else
		return false;
}


// Used by ASP.NET CustomValidator controls that need to validate an integer textbox.
function CustomValidateIsInt(source, arguments)
{
	arguments.IsValid = isInt( arguments.Value );
}

// Used by ASP.NET CustomValidator controls that need to validate an integer in a textbox is greater than zero.
function CustomValidateIsPositiveInt(source, arguments)
{
	arguments.IsValid = isPositiveInt( arguments.Value );
}

// Same as VB IsNumeric() function.
function isNumeric( sText )
{
	return !isNaN( sText );
} // EOF IsNumeric()


// Used by ASP.NET CustomValidator controls that need to validate a number textbox.
function CustomValidateIsNumeric(source, arguments)
{
	arguments.IsValid = isNumeric( arguments.Value );
}


// Validates a string is a valid email address.
function isEmailAddress( str )
{
	if( str.replace( ' ', '' ) == '' )
		return false;
		
	var filter=/^.+@.+\..{2,3}$/;
	return (filter.test(str));
}


// Used by ASP.NET CustomValidator controls that need to validate an email address in a textbox.
function CustomValidateEmailAddress(source, arguments)
{
	arguments.IsValid = isEmailAddress( arguments.Value );
}


// Validates a string as a time.
function isTime(timeStr)
{
	// Checks for the following valid time format:
	// HH:mm
	var timePat = /^(\d{2}):(\d{2})$/;
	var matchArray = timeStr.match(timePat); // Is the format OK?
	
	if(matchArray == null )
		return false;

	var hour = parseInt( matchArray[1], 10 );
	var minute = parseInt( matchArray[2], 10 );
	
	if(isNaN(hour) || hour < 0 || hour > 23) // Valid Hour?
		return false;
	
	if(isNaN(minute) || minute < 0 || minute > 59) // Valid Minute?
		return false;
	
	return true; // Yes, it's a time!
}


// Used by ASP.NET CustomValidator controls that need to validate a time.
function CustomValidateTime(source, arguments)
{
	arguments.IsValid = isTime( arguments.Value );
}


// Validates a string as a date.
function isDate(dateStr)
{ 
	// Checks for the following valid date formats: 
	// DD/MM/YYYY DD-MM-YYYY
	// 2 Digit Year pattern.
	// var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2}|\d{4})$/; 
	// 4 Digit Year pattern.
	var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/; 

	var matchArray = dateStr.match(datePat); // Is the format OK? 
	if (matchArray == null)
	{
		//alert("Date is not in a valid format.") 
		return false; 
	} 
	//month = matchArray[1]; // parse date into variables 
	//day = matchArray[3]; 
	day = matchArray[1];
	month = matchArray[3];
	year = matchArray[4]; 
	if (month < 1 || month > 12)
	{
		// check month range 
		//alert("Month must be between 1 and 12."); 
		return false; 
	} 
	if (day < 1 || day > 31)
	{
		//alert("Day must be between 1 and 31."); 
		return false; 
	} 
	if ((month==4 || month==6 || month==9 || month==11) && day==31)
	{
		//alert("Month "+month+" doesn't have 31 days!") 
		return false;
	} 
	if (month == 2)
	{
		// check for february 29th 
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)); 
		if (day>29 || (day==29 && !isleap))
		{
			//alert("February " + year + " doesn't have " + day + " days!"); 
			return false; 
		} 
	} 
	return true; // date is valid if we get this far.
}


// Used by ASP.NET CustomValidator controls that need to validate a date.
function CustomValidateDate(source, arguments)
{
	arguments.IsValid = isDate( arguments.Value );
}


// Determines if the value of the ASP.NET control is not an empty string or whitespace.
function isPopulated(source, arguments)
{
	if( trim( arguments.Value ) == '' )
		arguments.IsValid = false;
	else
		arguments.IsValid = true;
}


// Determines if the specified string is null, empty or whitespace.
function isNullOrEmptyOrWhiteSpace( str )
{
	if( isNullOrEmpty( str ) )
		return true;
	
	else if( trim( str ) == '' )
		return true;
	
	else
		return false;
}


// Determines if the specified string is null or empty.
function isNullOrEmpty( str )
{
	if( str == null )
		return true;
		
	else if( str == '' )
		return true;
	
	else
		return false;
}
