// ====================================================================================================
// DateConversion.js
// added by Guy to service function updateParentField() above
// ====================================================================================================
// date processing and formatting

var strToday;
var datToday;
var strDay;
var intDay;
var strMonth;
var intMonth;
var strYear;
var intYear;
var strHours;
var strMinutes;
var strComputedDate1;
var datComputedDate1;
var strComputedDate2;
var datComputedDate2;

// this should be initialised from 2 hidden fields on web page
// these values are set by XSL but no back-end store are currently implemented
var datMaxDate = new Date(2000,1,1);
var datMinDate = new Date(2000,1,1);
var DateMax = new Array();
DateMax[0] = new String( "2000" );
DateMax[1] = new String( "01" );
DateMax[2] = new String( "01" );
var DateMin = new Array();
DateMin[0] = new String( "2000" );
DateMin[1] = new String( "01" );
DateMin[2] = new String( "01" );
var strMaxDate = new String( DateMax.join("-") );
var strMinDate = new String( DateMin.join("-") );

function ConvertToDate( InputField, DateDisplayField, TimeDisplayField, MonthDayPattern, FailureMessage )
{
	// format the date as ISO-8061 format (yyyy-mm-dd)
	var strInput = DateDisplayField.value.toUpperCase();
	if ( strInput.length == 1 )
	{
		if ( strInput == "T" )
		{
			// compute today's date
			ComputeDate( "T", 0 );
			InputField.value = strComputedDate1;
			DateDisplayField.value = strDisplayDate;
			TimeDisplayField.value = strDisplayTime;
			//SM: why this
			//InputField.title = strComputedDate2;
		}
		if ( strInput == "Y" )
		{
			// compute today's date
			ComputeDate( "-", 1 );
			InputField.value = strComputedDate1;
			DateDisplayField.value = strDisplayDate;
			TimeDisplayField.value = strDisplayTime;
			//SM: why this
			//InputField.title = strComputedDate2;
		}
	}
	if ( strInput.indexOf("+") == 1 )
	{
		// we have a T+n situation
		var p = new Number(strInput.indexOf("+"));
		var IncrementValue = parseInt(strInput.substring( p+1 ), 10);

		// compute new date T+1
		ComputeDate( "+", IncrementValue );
		InputField.value = strComputedDate1;
		DateDisplayField.value = strDisplayDate;
		TimeDisplayField.value = strDisplayTime;
		//SM: why this
		//InputField.title = strComputedDate2;
	}
	if ( strInput.indexOf("-") == 1 )
	{
		// we have a T-n situation
		var p = new Number(strInput.indexOf("-"));
		var DecrementValue = parseInt(strInput.substring( p+1 ), 10);

		// compute new date T+1
		ComputeDate( "-", DecrementValue );
		InputField.value = strComputedDate1;
		DateDisplayField.value = strDisplayDate;
		TimeDisplayField.value = strDisplayTime;
		//SM: why this
		//InputField.title = strComputedDate2;
	}
	// Check for a valid date being manually entered
	if (IsValidDate(DateDisplayField.value, MonthDayPattern))
	{
		if(TimeDisplayField==''){
			InputField.value=ConvertDateToStandard(DateDisplayField.value,'', MonthDayPattern);
		}
		else 
		{
			InputField.value=ConvertDateToStandard(DateDisplayField.value, TimeDisplayField.value, MonthDayPattern);
		}
	}
	else 
	{
		// allow user to empty a display field (eg for searches)
		if (DateDisplayField.value =='')
		{
			InputField.value='';
		}
		else {
			// Passed from page
			DateDisplayField.focus();
		}
	}
	//alert(InputField.value);
}
function ConvertDateToStandard(DateString, TimeString, MonthDayPattern )
{	
	//var strSeparator = DateString.substring(2,3) //find date separator
	var strSeparator = "\/"; //find date separator
	var intMonth;
	var intDay;
	
	//split date into month, day, year
	var arrayDate = DateString.split(strSeparator);
	if (MonthDayPattern=="dd MMMM")
	{
		intMonth = arrayDate[1];
		intDay = arrayDate[0];
	}
	else if (MonthDayPattern=="MMMM dd")
	{
		intMonth = parseInt(arrayDate[0]);
		intDay = parseInt(arrayDate[1]);
		// SM; UK and US patterns need to match functionality  - need to investigate
	}
	return (arrayDate[2] + "/" + intMonth + "/" + intDay + " " + TimeString);
}
function UpdateTime( InputField, TimeDisplayField )
{
	date=new Date(InputField.value);
	strDay = new String( date.getDate() );
	strMonth = new String( date.getMonth()+1 );
	strYear = new String( date.getFullYear() );

	InputField.value = strYear + "/" + strMonth + "/" + strDay + " " + TimeDisplayField.value;
}
function ComputeDate( Operator, numDays )
{
	if ( Operator == "T" )
	{
		datToday = new Date();
		intDay = new Number(datToday.getDate());
		intMonth = new Number(datToday.getMonth());
		intYear = new Number( datToday.getFullYear() );
		intHours = new Number( datToday.getHours() );
		intMinutes = new Number( datToday.getMinutes() );
		datComputedDate2 = new Date( intYear, intMonth, intDay, intHours, intMinutes );
	}

	if ( Operator == "+" )
	{
		datToday = new Date();
		intDay = new Number(datToday.getDate());
		intMonth = new Number(datToday.getMonth());
		intYear = new Number( datToday.getFullYear() );
		datComputedDate2 = new Date( intYear, intMonth, intDay+numDays );
	}

	if ( Operator == "-" )
	{
		datToday = new Date();
		intDay = new Number(datToday.getDate());
		intMonth = new Number(datToday.getMonth());
		intYear = new Number( datToday.getFullYear() );
		datComputedDate2 = new Date( intYear, intMonth, intDay-numDays );
	}
	strDay = new String( datComputedDate2.getDate() );
	strMonth = new String( datComputedDate2.getMonth()+1 );
	strYear = new String( datComputedDate2.getFullYear() );
	strHours = new String ( datComputedDate2.getHours() );
	if (datComputedDate2.getHours() < 10)
	{
		strHours = "0" + strHours;
	}
	strMinutes = new String ( datComputedDate2.getMinutes() );
	if (datComputedDate2.getMinutes() < 10)
	{
		strMinutes  = "0" + strMinutes ;
	}
	intDay = new Number(datComputedDate2.getDate());
	intMonth = new Number(datComputedDate2.getMonth());
	intYear = new Number( datComputedDate2.getFullYear() );
	if ( strDay.length == 1 ) strDay = "0" + strDay;
	if ( strMonth.length == 1 ) strMonth = "0" + strMonth;

	strComputedDate1 = strYear + "/" + strMonth + "/" + strDay + " " + strHours + ":" + strMinutes;
	strDisplayDate = strDay + "/" + strMonth + "/" + strYear;
	strDisplayTime = strHours + ":" + strMinutes;
	strComputedDate2 = RemoveTime( datComputedDate2.toLocaleString() );
	strHours = new String( datComputedDate2.getHours() );
	strMinutes = new String( datComputedDate2.getMinutes() );
	return true;
}
// added by Guy to service function updateParentField() above
function GetLocaleDateFromString( strDate )
{
	// used to create a tooltip from the server calendar SetDate feature
	var DateParts = GetDatePartsFromString( strDate )
	intYear = new Number( parseInt( DateParts[2],10 ) );
	intMonth = new Number( parseInt( DateParts[1], 10 ) - 1 );
	intDay = new Number( parseInt( DateParts[0], 10 ) );

	// compute date from its parts and return its locale format
	var datComputedDate = new Date( intYear, intMonth, intDay );
	return RemoveTime( datComputedDate.toLocaleString() );
}



// return an Array of parts (Year, Month, Day)
// can be used to create a date from int values
function GetDatePartsFromString( strDate )
{
	//Added regular expression matching - Paul
	var RegEx1 = /[-]/;
	var RegEx2 = /[\/]/;
	var DateParts = new Array();
	
    if (RegEx1.test(strDate))
	{
		DateParts = strDate.split( "-" );
	}
	
	if (RegEx2.test(strDate))
	{
		DateParts = strDate.split( "/" );
	}

	return DateParts;
}


// this is 'Sort of ISO' format yyyy-mm-dd instead of yyyymmddThhmmss
function FormatDateISO8061( strDate )
{
	var DateParts = GetDatePartsFromString( strDate )
	intYear = new Number( parseInt( DateParts[0],10 ) );
	intMonth = new Number( parseInt( DateParts[1], 10 ) );
	intDay = new Number( parseInt( DateParts[2], 10 ) );

	strMonth = ( intMonth < 10 ) ? "0" + intMonth.toString() : intMonth.toString();
	strDay = ( intDay < 10 ) ? "0" + intDay.toString() : intDay.toString();
	strYear = intYear.toString();
	return ( strYear + "-" + strMonth + "-" + strDay );
}



function RemoveTime( strDate )
{
	try
	{
		//var strTempdate = strDate.
		var DateParts = new Array();
		DateParts = strDate.split( " " );

		return DateParts[0] + " " + DateParts[1] + " " + DateParts[2];
	}
	catch( e )
	{
		return e.description;
	}
}


// GC: not yet wired to any event
// ===============================
// Min and Max checkings are kept separate by design 
// because either min or max might not be defined
// checks when date min is defined
function GetDateMin( InputFieldValue )
{	
	if (( InputFieldValue != null ) || ( InputFieldValue != "undefined" ) || ( strDateMin != "2000-01-01" ))
	{	
		// this means we have found a hidden field with a value 
		// or we have found a string with a modified value (init)
		// parses date max into its components
		DateMin = GetDatePartsFromString( InputFieldValue );
		
		// update max date from string
		intYear = parseInt( DateMin[0], 10 );
		intMonth = parseInt( DateMin[1], 10 ) - 1;
		intDay = parseInt( DateMin[2], 10 );
		datMinDate = new Date( intYear, intMonth, intDay );
	}

	return true;
}

// checks whenever date max is defined
function GetDateMax( InputFieldValue )
{
	if (( InputFieldValue != null ) || ( InputFieldValue != "undefined" ) || ( strDateMax != "2000-01-01" ))
	{	
		// this means we have found a hidden field with a value 
		// or we have found a string with a modified value (init)
		// parses date max into its components
		DateMax = GetDatePartsFromString( InputFieldValue );
		
		// update max date from string
		intYear = parseInt( DateMax[0], 10 );
		intMonth = parseInt( DateMax[1], 10 ) - 1;
		intDay = parseInt( DateMax[2], 10 );
		datMaxDate = new Date( intYear, intMonth, intDay );
	}

	return true;
}


// compares the given date with a maximum date when this is defined
// return True/False or true if no date max is defined
function ValidateDateMax( strDate )
{
	// validates given date against max date ( date <= maxdate )
	// parses date max into its components
	var aDateToValidate = new Array();
	aDateToValidate = GetDatePartsFromString( strDate );
	var dDateToValidate = new Date( aDateToValidate[0], aDateToValidate[1]-1, aDateToValidate[2] );

	var sDateToValidate = Date.parse(dDateToValidate.toLocaleString());
	var sMaxDate = Date.parse(datMaxDate.toLocaleString());

	var DisplayDate1 = RemoveTime( dDateToValidate.toLocaleString() );
	var DisplayDate2 = RemoveTime( datMaxDate.toLocaleString() );

	if ( sDateToValidate > sMaxDate )
	{
		alert( "date is invalid: (greater than maximum date) " + DisplayDate1 + " GT " + DisplayDate2 );
		return false;
	}
	else
	{
		//alert( "date is valid: " + DisplayDate1 + " LTE " + DisplayDate2 );
		return true;
	}
}


// compares the given date with a minimum date when this is defined
// return True/False or true if no date min is defined
function ValidateDateMin( strDate )
{
	// validates given date against max date ( date <= maxdate )
	// parses date max into its components
	var aDateToValidate = new Array();
	aDateToValidate = GetDatePartsFromString( strDate );
	var dDateToValidate = new Date( aDateToValidate[0], aDateToValidate[1]-1, aDateToValidate[2] );

	var sDateToValidate = Date.parse(dDateToValidate.toLocaleString());
	var sMinDate = Date.parse(datMinDate.toLocaleString());

	var DisplayDate1 = RemoveTime( dDateToValidate.toLocaleString() );
	var DisplayDate2 = RemoveTime( datMinDate.toLocaleString() );

	if ( sDateToValidate < sMinDate )
	{
		alert( "date is invalid: (less than minimum date) " + DisplayDate1 + " GT " + DisplayDate2 );
		return false;
	}
	else
	{
		//alert( "date is valid: " + DisplayDate1 + " LTE " + DisplayDate2 );
		return true;
	}
}


// GC: can not implement this as yet !!!
function InitDates()
{
	//GetDateMin( document.all.DateMin.value );
	//GetDateMax( document.all.DateMax.value );
	//window.d1.focus();
	return true;
}


function DefaultDates(frmForm)
{
	if (frmForm)
	{
	   //alert("We have a form");
	    for(i=0;i<frmForm.length;i++)
	    {
		  //alert("checking field");
	      if(frmForm[i].name)
	      {
			//alert("field name " + frmForm[i].name);
			if (frmForm[i].name.substring(0,2) == "DA"){
				//alert("Date Field .. Converting" );
				//We have a date field.
				 ConvertToDate( frmForm[i] );
			}	
			else{
				//alert("Not a date");
			}		
	      }
	      else{
			//alert("No Name");
	      }
	    }
    }
    else
    {
		alert("No Form Supplied");
    }
	return true;
}

// GC: not implemented 
function ValidateForm(frmForm)
{
	return true;
}
function CheckMandatoryField(fldField)
{
	if (fldField.value == "")
	{
		strMandatoryFields += fldField.name + " ";
		alert(strMandatoryFields);
		return false;
	}
	else
	{
		if (fldField.value == "*")
		{
			strMandatoryFields += fldField.name + " ";
			alert(strMandatoryFields);
			return false;
		}
		return true;
	}
}

// ====================================================================================================
// KeyFilter.js
// added by Guy to block off diverse keyboard actions ( Function keys, and [A..Z] [0..9] )
// this code is expandable - just use the desired keys to be blocked off on the switch/case structure.
// ====================================================================================================
// this code will stop the F5 key - to block off the browser refresh (F5) 
// supports IE and needs testing on Netscape

function cancelRefresh1()
{
	//Cancel F5 and only allow backspace in text type controls

	var k = window.event.keyCode;
	var s = window.event.srcElement.type;

	
	if ( window.event && window.event.keyCode == 116 )
	    {
	       //Cancel F5 by changing it to a backspace
		   window.event.keyCode = 8;
		}
	if ( s == "text" && k != 116 )
	    {
	       //we are in a textbox and keycode is NOT F5
		   return true;
		}
	else if ( s == "textarea" && k != 116 )
	     {
	        //we are in a textarea and keycode is NOT F5
			return true;
		 }
	else if ( s == "password" && k != 116 )
	     {
	        //we are in a password box and keycode is NOT F5
			return true;
		}		
	
	else if ( window.event && window.event.keyCode == 8 ) 
	     {
	        //Cancel Backspace (coz we are not in text, textarea or password)
		    window.event.cancelBubble = true;
		    window.event.returnValue = false;
		    return false;
	     }
}

function DateKeyFilter()
{
	// Cancel any keys to be typed in date textboxes
	// except keys defined in KeyFlags below
	// editing keys and Function keys are allowed through
	// currently, following keys are allowed through 0..9 t T + - / . :

	var k = window.event.keyCode;
	var s = window.event.srcElement.type;

	//window.alert( window.event.keyCode );
	
	// these keys are allowed to be typed - just add a keyCode definition to cater for new key to be let through
	var KeyFlag1	= window.event && window.event.keyCode == 116;  // t
	var KeyFlag2	= window.event && window.event.keyCode == 84;   // T
	var KeyFlag3	= window.event && window.event.keyCode == 43;   // +
	var KeyFlag4	= window.event && window.event.keyCode == 45;   // -
	//var KeyFlag5	= window.event && window.event.keyCode == 46;   // .
	var KeyFlag6	= window.event && window.event.keyCode == 47;   // / 
	var KeyFlag7	= window.event && window.event.keyCode == 58;   // :
	var KeyFlag8	= window.event && ( window.event.keyCode >= 48 && window.event.keyCode <= 57 );  // numbers 0..9
	var KeyFlag9	= window.event && window.event.keyCode == 124;  // | - used for IS ONE OF searches
	var KeyFlag10	= window.event && window.event.keyCode == 109;  // m
	var KeyFlag11	= window.event && window.event.keyCode == 77;   // M
	var KeyFlag12	= window.event && window.event.keyCode == 121;  // y
	var KeyFlag13	= window.event && window.event.keyCode == 89;   // Y
	var KeyFlag14	= window.event && window.event.keyCode == 113;  // q
	var KeyFlag15	= window.event && window.event.keyCode == 81;   // Q
	var KeyFlag16	= window.event && window.event.keyCode == 99;   // c
	var KeyFlag17	= window.event && window.event.keyCode == 67;   // C
	var KeyFlag18	= window.event && window.event.keyCode == 104;  // h
	var KeyFlag19	= window.event && window.event.keyCode == 72;   // H
	var KeyFlag20	= window.event && window.event.keyCode == 119;  // w
	var KeyFlag21	= window.event && window.event.keyCode == 87;   // W
	var KeyFlag22	= window.event && window.event.keyCode == 100;  // d
	var KeyFlag23	= window.event && window.event.keyCode == 68;   // D
	
	var KeyFlag = KeyFlag1 || KeyFlag2 || KeyFlag3 || KeyFlag4  || KeyFlag6 || KeyFlag7 || KeyFlag8 || KeyFlag9 || KeyFlag10 || KeyFlag11 || KeyFlag12 || KeyFlag13 || KeyFlag14 || KeyFlag15 || KeyFlag16 || KeyFlag17 || KeyFlag18 || KeyFlag19 || KeyFlag20 || KeyFlag21 || KeyFlag22 || KeyFlag23;
			   
	if ( KeyFlag )
	    {
	        //let through authorised keys
			return true;
		}		
	
	else
	     {
	        //cancel undesirable keys
		    window.event.cancelBubble = true;
		    window.event.returnValue = false;
		    return false;
	     }
}

function TimeKeyFilter()
{
	// Cancel any keys to be typed in date textboxes
	// except keys defined in KeyFlags below
	// editing keys and Function keys are allowed through
	// currently, following keys are allowed through 0..9  :

	var k = window.event.keyCode;
	var s = window.event.srcElement.type;

	//window.alert( window.event.keyCode );
	
	// these keys are allowed to be typed - just add a keyCode definition to cater for new key to be let through

	var KeyFlag1 = window.event && window.event.keyCode == 124;  // |	
	var KeyFlag2 = window.event && window.event.keyCode == 58;   // :
	var KeyFlag3 = window.event && ( window.event.keyCode >= 48 && window.event.keyCode <= 57 );  // numbers 0..9
	
	var KeyFlag = KeyFlag1 || KeyFlag2 || KeyFlag3;
			   
	if ( KeyFlag )
	    {
	        //let through authorised keys
			return true;
		}		
	
	else
	     {
	        //cancel undesirable keys
		    window.event.cancelBubble = true;
		    window.event.returnValue = false;
		    return false;
	     }
}

function TextKeyFilter()
{
	// Validates on all search parameters except Dates which use the KeyFilter() method
	// Does not allow invalid characters, 
	// Does not allow comma's to be typed as they will cause errors
	// Allows 0 - 9, a-z, A-Z and | for OR

	
	var k = window.event.keyCode;
	var s = window.event.srcElement.type;

	//window.alert( window.event.keyCode );
	
	// these keys are allowed to be typed - just add a keyCode definition to cater for new key to be let through
	var KeyFlag1 = window.event && window.event.keyCode == 124;  // |
	var KeyFlag2 = window.event && ( window.event.keyCode >= 48 && window.event.keyCode <= 57 );  // numbers 0..9
	var KeyFlag3 = window.event && ( window.event.keyCode >= 65 && window.event.keyCode <= 90 );  // numbers a..z
	var KeyFlag4 = window.event && ( window.event.keyCode >= 97 && window.event.keyCode <= 122 );  // numbers A..Z
	var KeyFlag5 = window.event && window.event.keyCode == 46;   // .
	var KeyFlag6 = window.event && window.event.keyCode == 47;   // /
	var KeyFlag7 = window.event && window.event.keyCode == 58;   // :
	var KeyFlag8 = window.event && window.event.keyCode == 32;   // space
	var KeyFlag9 = window.event && window.event.keyCode == 13;   // Carriage return
	
	
	var KeyFlag = KeyFlag1 || KeyFlag2 || KeyFlag3 || KeyFlag4 || KeyFlag5 || KeyFlag6 || KeyFlag7 || KeyFlag8 || KeyFlag9;
			   
	if ( KeyFlag )
	    {
	        //let through authorised keys
			return true;
		}		
	
	else
	     {
	        //cancel undesirable keys
		    window.event.cancelBubble = true;
		    window.event.returnValue = false;
		    return false;
	     }
}

function NumericKeyFilter()
{
	// Validates on all search parameters except Dates which use the KeyFilter() method
	// Does not allow invalid characters, 
	// Does not allow comma's to be typed as they will cause errors
	// Allows 0 - 9, . and | for OR

	var k = window.event.keyCode;
	var s = window.event.srcElement.type;

	//window.alert( window.event.keyCode );
	
	// these keys are allowed to be typed - just add a keyCode definition to cater for new key to be let through
	var KeyFlag1 = window.event && window.event.keyCode == 124;  // |
	var KeyFlag2 = window.event && ( window.event.keyCode >= 48 && window.event.keyCode <= 57 );  // numbers 0..9
	var KeyFlag3 = window.event && window.event.keyCode == 46;   // .
	
	var KeyFlag = KeyFlag1 || KeyFlag2 || KeyFlag3;
			   
	if ( KeyFlag )
	    {
	        //let through authorised keys
			return true;
		}		
	
	else
	     {
	        //cancel undesirable keys
		    window.event.cancelBubble = true;
		    window.event.returnValue = false;
		    return false;
	     }
}

function TelephoneKeyFilter()
{
	// Validates on all search parameters except Dates which use the KeyFilter() method
	// Does not allow invalid characters, 
	// Does not allow comma's to be typed as they will cause errors
	// Allows 0 - 9, space and | for OR

	var k = window.event.keyCode;
	var s = window.event.srcElement.type;

	//window.alert( window.event.keyCode );
	
	// these keys are allowed to be typed - just add a keyCode definition to cater for new key to be let through
	var KeyFlag1 = window.event && window.event.keyCode == 124;  // |
	var KeyFlag2 = window.event && ( window.event.keyCode >= 48 && window.event.keyCode <= 57 );  // numbers 0..9
	var KeyFlag3 = window.event && window.event.keyCode == 46;   // .
	var KeyFlag4 = window.event && window.event.keyCode == 32;   // space
	
	var KeyFlag = KeyFlag1 || KeyFlag2 || KeyFlag3 || KeyFlag4;
			   
	if ( KeyFlag )
	    {
	        //let through authorised keys
			return true;
		}		
	
	else
	     {
	        //cancel undesirable keys
		    window.event.cancelBubble = true;
		    window.event.returnValue = false;
		    return false;
	     }
}

function EmailKeyFilter()
{
	// Validates on all search parameters except Dates which use the KeyFilter() method
	// Does not allow invalid characters, 
	// Does not allow comma's to be typed as they will cause errors
	// Allows 0 - 9, a-z, A-Z, @, ., - _ and | for OR

	var k = window.event.keyCode;
	var s = window.event.srcElement.type;

	//window.alert( window.event.keyCode );
	
	// these keys are allowed to be typed - just add a keyCode definition to cater for new key to be let through
	var KeyFlag1 = window.event && window.event.keyCode == 124;  // |
	var KeyFlag2 = window.event && ( window.event.keyCode >= 48 && window.event.keyCode <= 57 );  // numbers 0..9
	var KeyFlag3 = window.event && ( window.event.keyCode >= 65 && window.event.keyCode <= 90 );  // numbers a..z
	var KeyFlag4 = window.event && ( window.event.keyCode >= 97 && window.event.keyCode <= 122 );  // numbers A..Z
	var KeyFlag5 = window.event && window.event.keyCode == 46;   // .
	var KeyFlag6 = window.event && window.event.keyCode == 64;   // @
	var KeyFlag7 = window.event && window.event.keyCode == 45;   // -
	var KeyFlag8 = window.event && window.event.keyCode == 95;   // _
	
	
	var KeyFlag = KeyFlag1 || KeyFlag2 || KeyFlag3 || KeyFlag4 || KeyFlag5 || KeyFlag6 || KeyFlag7 || KeyFlag8;
			   
	if ( KeyFlag )
	    {
	        //let through authorised keys
			return true;
		}		
	
	else
	     {
	        //cancel undesirable keys
		    window.event.cancelBubble = true;
		    window.event.returnValue = false;
		    return false;
	     }
}



// this function does RequiredFieldValidation + checks for properly formed email address
// this function does not check for existence of the mail box on any servers though.

function ValidateEmail( EMail )
{
	try
	{
		if ( EMail != null && EMail.name.toUpperCase() == 'EM_EMAIL' && EMail.type.toUpperCase() == 'TEXT' )
		{
			//var EMail = eval(document.all.EM_EMAIL);
			var HasValue = ( ( EMail.value != "undefined" ) || ( EMail.value != undefined ) || ( EMail.value != "" ) );
			var EMailLen = ( HasValue == true ) ? EMail.value.length : 0;

			switch( EMailLen )
			{
				case undefined:
							//alert("email is undefined");
							//return false;
							//break;

				case 0:
							alert("email must be informed");
							return false;
							break;

				case 1:
							//alert("email is 1");
							//return false;
							//break;

				case 2:
							alert("email length is insufficient");
							return false;
							break;

				default:
							// process here the validation
							var ValExp = /^[\w-.\w-]+@[\w-]+\.(com|net|org|edu|mil|co.uk|fr|de)$/;
							var re = new RegExp( ValExp );
							if ( re.test(EMail.value) )
							{
								//alert("email validation: email is valid !");
								return true;
							}
							else
							{
								alert("email validation: email is invalid !");
								return false;
							}
							break;
			}
		}
	}
	catch( e )
	{
		alert("email not valid");
		return false;
	}
}
// GC: sets the focus on the first editable element in page
// place a javascript call to this function on ASPX pages as follows:
// <Body OnLoad="JavaScript:SetFocusOnFirstEditableElement();">
// Note: make sure the main panel of the form has the same name as the one chosen below (or vice-versa)
// we pick up any input control with type=text or type=checkbox - any select listbox starting with CL_ 
// further we test for Not Readonly then we focus and exit the loop

function SetFocusOnFirstEditableElement()
{
	var CtrlCollection = document.getElementById("Detail").elements;
	var Ctrl;

	// enable this alert to view chosen control properties
	//window.alert( "control type: " + Ctrl.type + "  -  control name (substr): " + Ctrl.name + "  -  readonly: " + Ctrl.getAttribute("readonly") );

	for ( var c=0; c < CtrlCollection.length; c++ )
	{
		Ctrl = CtrlCollection[c];
		if (Ctrl.type && Ctrl.name){
			var CType = new String(Ctrl.type);
			var CName = new String(Ctrl.name.toUpperCase());
			CName = CName.substring(0,3);
			CType = CType.toUpperCase();
			//window.alert( "control type: " + CType + "  -  control name (substr): " + CName + "  -  readonly: " + Ctrl.getAttribute("readonly") );
			 
			//if ( ( CType == 'TEXT' || CType == 'CHECKBOX' || CName == 'CL_' || CName == 'XX_' ) && !Ctrl.getAttribute("readonly") )
			if ( ( CType == 'TEXT' || CType == 'CHECKBOX' || CType == 'SELECT-ONE' ) && !Ctrl.getAttribute("readonly") )
			{
				//window.alert( "control type: " + CType + "  -  control name (substr): " + CName + "  -  readonly: " + Ctrl.getAttribute("readonly") );
				Ctrl.focus();
				break;
			}		
		}
	}
}			
// Checks Mandatory Fields 
// when form is posted (buttons clicked)
function CheckMandatoryFields()
{
	//alert( "page checked for mandatory fields" );
	// pick up controls and check flag
	if ( ParseMandatoryElements() )
	{
		//alert("All mandatory fields have values.");
		return true;
	}
	else
	{
		alert("At least one mandatory field has no value. Please complete all fields marked with an *. " + strMandatoryFields);
		return false;
	}
}

// loops through the controls of the given Form 
// searching for any field with a TagName = TI_MANDATORY
function ParseMandatoryElements()
{
	//alert ("Parsing Mandatory Elements");
	var CtrlCollection = document.getElementById("Detail").elements;
	var Ctrl;
	var ValidFlag = true;
	var focusfield = null;

	//alert ("Fields :" + CtrlCollection.length);
	for ( var c=0; c < CtrlCollection.length; c++ )
	{
		
		Ctrl = CtrlCollection[c];
		//alert("Name : " + Ctrl.id);
		if ( Ctrl.TagName == 'TI_MANDATORY' )
		{
			//alert ("Parsing Mandatory Field :" + Ctrl.id );
			//window.alert( "control id: " + Ctrl.id + " - TagName: " + Ctrl.TagName + " - type: " + Ctrl.type + " - readonly: " + Ctrl.getAttribute("readonly") );
			ValidFlag &= CheckFieldIsValid( Ctrl );
			if(ValidFlag == 0 && focusfield==null)
			{				
				focusfield = Ctrl.id;
				Ctrl.focus();
			}
		}
	}
	return ValidFlag;
}

// control validation
function CheckFieldIsValid( ctrl )
{
	switch( ctrl.type.toLowerCase() )
	{
		case 'text':
			if ( ctrl.value == '' )
				{
					
					return false;
				
				}
			else
				{
				if ( ctrl.value == '*' )
				{
					
					return false;
				
				}
				return true;
				}
			break;

		case 'checkbox':
			if ( !ctrl.checked )
				{
					
					return false;
				
				}
			else
				return true;
			break;

		default:
			
			//alert("field type :" + ctrl.type.toLowerCase());
			if ( ctrl.value == '' )
				{
					
					return false;
				
				}
			else
				{
				if ( ctrl.value == '*' )
				{
					
					return false;
				
				}
				return true;
				}
			break;	}
}
function InsertDateAndSignature(FieldId)
{
	// precede minutes with 0 if less than 10
	ComputeDate("T",0);
	
	// SM: Get initials from hidden input
	var strInitials = document.getElementById("hdnUserInitials").value
	if (strMinutes < 10)
	{
		strMinutes = "0" + strMinutes;
	}

	var currentTime = strHours + ":" + strMinutes;
	document.getElementById(FieldId).value = strComputedDate1 + " " + currentTime + " " + strInitials + " ";
}

function InsertTime(FieldId)
{
	// function to prefix content of a form element with the given id, with the current local date
	ComputeDate("T",0);
	
	// precede minutes with 0 if less than 10
	if (strMinutes < 10)
	{
		strMinutes = "0" + strMinutes;
	}

	var currentTime = strHours + ":" + strMinutes;
	
	// SM: Get initials from hidden input
	var strInitials = document.getElementById("hdnUserInitials").value
	document.getElementById(FieldId).value = currentTime;
	
}
function DaysInMonth(WhichMonth, WhichYear)
{	
  var DaysInMonth = 31;
  if (WhichMonth == 4 || WhichMonth == 6 || WhichMonth == 9 || WhichMonth == 11) DaysInMonth = 30;
  if (WhichMonth == 2 && (WhichYear/4) != Math.floor(WhichYear/4))	DaysInMonth = 28;
  if (WhichMonth == 2 && (WhichYear/4) == Math.floor(WhichYear/4))	DaysInMonth = 29;
  return DaysInMonth;
}
//function to change the available days in a months
function ChangeOptionDays(Which, DateFormat)
{
	if (document.getElementById) { 
		DaysObject = document.getElementById(Which + '_Day');
		MonthObject = document.getElementById(Which + '_Month');
		YearObject = document.getElementById(Which + '_Year');
		TimeObject = document.getElementById(Which + '_Time');
		CheckBoxObject= document.getElementById(Which + '_CheckBox');
		DateBoxObject = document.getElementById(Which);
	} 
	else if (document.layers) { 
		DaysObject = document.layers[Which + '_Day'];
		MonthObject = document.layers[Which + '_Month'];
		YearObject = document.layers[Which + '_Year'];
		TimeObject = document.layers[Which + '_Time'];
		CheckBoxObject= document.layers[Which + '_CheckBox'];
		DateBoxObject = document.layers[Which]; 
	} 
	else if (document.all) { 
		DaysObject = document.all[Which + '_Day'];
		MonthObject = document.all[Which + '_Month'];
		YearObject = document.all[Which + '_Year'];
		TimeObject = document.all[Which + '_Time'];
		CheckBoxObject= document.all[Which + '_CheckBox'];
		DateBoxObject = document.all[Which];
	} 
	Day= DaysObject[DaysObject.selectedIndex].text;
	Month = MonthObject[MonthObject.selectedIndex].value;
	Year = YearObject[YearObject.selectedIndex].text;
	DaysForThisSelection = DaysInMonth(Month, Year);
	CurrentDaysInSelection = DaysObject.length;
	if (Day!='--' && Year!='--' && Month!='--' ) {
	if (CurrentDaysInSelection > DaysForThisSelection)
	{
		for (i=0; i<(CurrentDaysInSelection-DaysForThisSelection); i++)
		{
			DaysObject.options[DaysObject.options.length - 1] = null;
		}
	}
	if (DaysForThisSelection > CurrentDaysInSelection)
	{
		for (i=0; i<(DaysForThisSelection-CurrentDaysInSelection); i++)
		{
			NewOption = new Option(DaysObject.options.length + 1);
			DaysObject.add(NewOption);
		}
	}
	if (DaysObject.selectedIndex < 0) DaysObject.selectedIndex == 0;
	DateBoxObject.value=formatDate(new Date(Year, (Month-1), Day), DateFormat);
	if (CheckBoxObject)
	{
		if (CheckBoxObject.checked)
		{
			DaysObject.disabled=false;MonthObject.disabled=false;YearObject.disabled=false;
		}
		else
		{
			DaysObject.disabled=true;MonthObject.disabled=true;YearObject.disabled=true;DateBoxObject.value='';
		}
	}
	} else {DateBoxObject.value=''}	
}
/// <summary>
/// Function to Check for valid UK Date
/// </summary>
/// <param name="strToCheck"></param>
/// <returns></returns>
function IsValidDate(strToCheck, MonthDayPattern)
{
	var objDatePattern ;
	var strSeparator = strToCheck.substring(2,3) //find date separator
	var intMonth;
	var intDay;
	
	//split date into month, day, year
	var arrayDate = strToCheck.split(strSeparator);
    var arrayLookup = { '01' : 31,'03' : 31, '04' : 30,'05' : 31,'06' : 30,'07' : 31, '08' : 31,'09' : 30,'10' : 31,'11' : 30,'12' : 31}
	if (MonthDayPattern=="dd MMMM")
	{
		intMonth = parseInt(arrayDate[1]);
		intDay = parseInt(arrayDate[0]);
		objDatePattern = new RegExp("^(?:(?:0?[1-9]|1\\d|2[0-8])(\\/|-)(?:0?[1-9]|1[0-2]))(\\/|-)(?:[1-9]\\d\\d\\d|\\d[1-9]\\d\\d|\\d\\d[1-9]\\d|\\d\\d\\d[1-9])$|^(?:(?:31(\\/|-)(?:0?[13578]|1[02]))|(?:(?:29|30)(\\/|-)(?:0?[1,3-9]|1[0-2])))(\\/|-)(?:[1-9]\\d\\d\\d|\\d[1-9]\\d\\d|\\d\\d[1-9]\\d|\\d\\d\\d[1-9])$|^(29(\\/|-)0?2)(\\/|-)(?:(?:0[48]00|[13579][26]00|[2468][048]00)|(?:\\d\\d)?(?:0[48]|[2468][048]|[13579][26]))$");
		
	}
	else if (MonthDayPattern=="MMMM dd")
	{
		intMonth = parseInt(arrayDate[0]);
		intDay = parseInt(arrayDate[1]);
		// SM; UK and US patterns need to match functionality  - need to investigate
		objDatePattern = new RegExp("^(((0?[13578]|1[02])\/([0-2]?\d|3[01])|(0?[469]|11)\/([0-2]?\d|30)|0?2\/([01]?\d|2[0-8]))\/(19|20)?\d{2}|0?2\/([01]?\d|2[0-9])\/(19|20)?([024568][048]|[13579][26]))$");
	}
	if ( ! objDatePattern.test(strToCheck))
	{
		return false;
	}
	//check if month value and day value agree
	if(arrayLookup[intDay] != null) 
	{
		if(! (intDay <= arrayLookup[intDay] && intDay != 0))
		{
			return false; //not found in lookup table, bad date
		}
	}

	//check for February (bugfix 20050322)
	var intMonth = parseInt(intMonth);
	if (intMonth == 2) 
	{
		var intYear = parseInt(arrayDate[2]);
		if( !((intYear % 4 == 0 && intDay <= 29) || (intYear % 4 != 0 && intDay <=28) && intDay !=0) )
		{
			return false; //Feb. as invalid number of days
		}
	}
	return true;
}

  // Date Convertion functions
  function formatDate(vDate, vFormat){ 
    var vDay              = addZero(vDate.getDate()); 
    var vMonth            = addZero(vDate.getMonth()+1); 
    var vYearLong         = addZero(vDate.getFullYear()); 
    var vYearShort        = addZero(vDate.getFullYear().toString().substring(3,4)); 
    var vYear             = (vFormat.indexOf('yyyy')>-1?vYearLong:vYearShort) 
    var vHour             = addZero(vDate.getHours()); 
    var vMinute           = addZero(vDate.getMinutes()); 
    var vSecond           = addZero(vDate.getSeconds()); 
    var vDateString       = vFormat.replace(/dd/g, vDay).replace(/MM/g, vMonth).replace(/y{1,4}/g, vYear) 
    vDateString           = vDateString.replace(/hh/g, vHour).replace(/mm/g, vMinute).replace(/ss/g, vSecond) 
    return vDateString 
  } 
  function addZero(vNumber){return ((vNumber < 10) ? '0' : '') + vNumber;} 
