/*-------------------------------------- CONFIRM EVENT ---------------------------------------------
Author:		Ross Crawford
Date:		31 01 2002
Description:
Function prompts user to confirm a specified event and returns true or false according to user selection.
confirmEvent('formname','< message >')
------------------------------------------------------------------------------------------------------------*/
function confirmEvent()
{
	var theForm = document.forms[arguments[0]];
	var confirmMsg = arguments[1];
	
	if( confirm(confirmMsg) )
	{
		return true;
	}else{
		return false;
	}
}
/*-------------------------------------- RANDOM NUMBER GENERATOR ---------------------------------------------
Author:		Ross Crawford
Date:		25 01 2002
Description:
Function generates an alpha or alpha/numeric number.
randAlphaNum('formname','0/1','field to recieve number','field to recieve number',etc)
------------------------------------------------------------------------------------------------------------*/
function randAlphaNum()
{
	var theForm = document.forms[arguments[0]];
	var varAlphaNumeric = arguments[1];
	var varRandomNum = '';
	var varRandNumeric = '';
	var varRandAlpha = '';
	var varTemp = '';
	
	varRandNumeric = Math.round( Math.random()*(9999999-1000000) )+1000000;	//	Random number.

	if(varAlphaNumeric == 1)	//	If arguments[1]=1 then append a letter to the front of the random number
	{
		varTemp = Math.round( Math.random()*(90-65) )+65;
		varRandAlpha = String.fromCharCode(varTemp);
		varRandomNum = varRandAlpha+'-'+varRandNumeric;
	}else{
		varRandomNum = varRandNumeric;
	}

	if( confirm('You are about to change this users password\r\rIn order to make this change permanent please submit the form') )
	{
		theForm.elements['frmValidPwd'].value = 'N';	// For DUDA: set the reset password value to N so that the new password will be emailed to the user.
		for(c=2; c < arguments.length; c++)	//	Loop through form elements passed in and set them equal to the random number.
		{
			theForm.elements[arguments[c]].value = varRandomNum;
		}
		alert('The password has been changed');
	}else{
		alert('The password has not been changed');
	}	
		
}
/*-------------------------------------- LIMIT TEXTAREA CONTENT ---------------------------------------------
Author:		Ross Crawford
Date:		29 11 2001
Description:
Function limits the number of characters that can be entered into a textarea (comment fields) so that the DB 
does not crash when trying to insert the value.
------------------------------------------------------------------------------------------------------------*/
function chkCommentMaxChar(thisForm, thisElement)
{
	var theElement = document.forms[thisForm].elements[thisElement];
	var theContents = theElement.value;
	var varMaxLength = 1999;
	if (theElement.value.length > varMaxLength) {
		alert('Please enter less content in the comment field\r\r NOTE: Text will be removed to fit maximum.');
		//	REMOVE OFFENDING CHARS
		theElement.value = theContents.slice(0,varMaxLength);
		return false;
	}
}
/*-------------------------------------- CHECK EXPIRY DATES ---------------------------------------------
Author:		Ross Crawford
Date:		29 11 2001
Description:
Ensure that the date entered is greater than the current date.
------------------------------------------------------------------------------------------------------------*/
function chkExpiryDate(thisForm, thisElement) 
{
	var theElement = document.forms[thisForm].elements[thisElement];
	var thisDate = theElement.value;
	var today = new Date();
	var day = '';
	var month = '';
	var year = '';
	var day1 = today.getDate();
	var month1 = today.getMonth() + 1;	//	increment the month by one because of month counter starting at 0
	var year1 = today.getYear();
	var errMsg = "";

	//	EXRACT DD,MM,YYYY
	for (c = 0; c <= thisDate.length; c++)
	{
		if(c < 2){day = day + thisDate.charAt(c); }
		if(c == 3 || c == 4){month = month +  thisDate.charAt(c); }
		if(c == 6 || c == 7 || c == 8 || c==9){year = year + thisDate.charAt(c); }
	}
	//	SET TESTING PARAMETERS	
	var dateEntered = parseInt(year+month+day);
	var correctDate = year1.toString();

	//	APPEND 0 TO MONTH if MONTH IS LESS THAN 10
	if(month1 < 10)
	{
		 correctDate = correctDate + '0'+month1.toString();
	}else{
		 correctDate = correctDate + month1.toString();
	}
	//	APPEND 0 TO DAY if DAY IS LESS THAN 10
	if (day1 < 10)
	{
		 correctDate = correctDate + '0'+day1.toString();
	}else{
		 correctDate = correctDate + day1.toString();
	}	
	
	//	TESTS FOR VALID DATE
	
	//if (dateEntered <= correctDate)
	//{
		//errMsg = 'Please enter a date greater than todays date.\n';
	//}
	if (year < 2000)
	{
		errMsg = errMsg + 'You can only enter a year greater than 2000.\n';
	}
	
	//	CHECK IF ERROR FOUND
	if (errMsg != '')
	{
		alert(errMsg+'The date must be in DD/MM/YYYY Format');
		theElement.focus();
		theElement.select();
		theElement.value = '';
		return false;
	}

}
/*-------------------------------------- CHECK VALUE GREATER THAN 0 ----------------------------------------
Author:		Ross Crawford
Date:		11 12 2001
Description:
Ensure that the entered value is greater than 0
------------------------------------------------------------------------------------------------------------*/
function chkGreaterThanZero(thisForm, thisElement)
{
	var theElement = document.forms[thisForm].elements[thisElement];
	var theContents = theElement.value;

	//	CHECK VALUE IS GREATER THAN 0
	if (theContents <= 0)
	{
		alert('This value must be greater than 0.');
//		theElement.select();	//	Cant select: as two field next to each other with the same greater than 0 requirement will cause an infinte select loop
		theElement.value = '';
		return false;
	}
}
/*-------------------------------------- CHECK NEWS FORM ---------------------------------------------------
Author:		Ross Crawford
Date:		11 12 2001
Description:
Validates the Create new and Edit News forms.
------------------------------------------------------------------------------------------------------------*/
function checkForm(whichForm)
{
	var msg = "";
	if (document.forms[whichForm].elements['req_Article_Title'].value == ""){
		msg = msg + 'Please Enter a Title for this Article\n';
	}
	if (document.forms[whichForm].elements['req_Article_Content'].value == ""){
		msg = msg + 'Please Enter Content for this Article\n';
	}
	if (document.forms[whichForm].elements['req_Active'].value == ""){
		msg = msg + 'Please select a status for this Article\n';
	}
	if (document.forms[whichForm].elements['expiryDate'].value == "(dd/mm/yyyy)" || document.forms[whichForm].elements['expiryDate'].value == ""){
		msg = msg + 'Please enter an expiry date for this article\n';
	}
	if (msg != ""){
		alert(msg);
		return false;
	}
}

/*-------------------------------------- CHECK KEY ELEMENT ---------------------------------------------
Author:		Ross Crawford
Date:		10 01 2002
Description:
Checks that a field has a value before allowing to submit
return checkKeyElement('nameOfForm','dependantElement','keyElement');
the first argument MUST be the name of the form.
------------------------------------------------------------------------------------------------------------*/
function checkKeyElement()
{
	//	IF SELECTEDINDEX OF DEPENDANT ELEMENT INDEX GREATER THAN 0
	if(document.forms[arguments[0]].elements[arguments[1]].selectedIndex > 0)
	{
		//	IF KEY ELEMENT DOES NOT HAVE A VALUE RETURN FALSE
		if(document.forms[arguments[0]].elements[arguments[2]].selectedIndex == 0)
		{
			alert('You must select an ISP to search by status');
			return false;
		}
	}
}
/*-------------------------------------- CHECK CORRECT FNN HAS BEEN ADDED ---------------------------------------------
Author:		Ross Crawford
Date:		11 01 2002
Description:
Ensures that all elements have a value with the correct number of digits
return convFnn('nameOfForm','elementame1','elementame2', etc);
the first argument MUST be the name of the form.
------------------------------------------------------------------------------------------------------------*/
function checkaddCustomer()
{
	var theForm = document.forms[arguments[0]];
	var thisElement = '';
	var errorMsg = '';

	for(c = 1; c < arguments.length; c++)
	{
		thisElement = theForm.elements[arguments[c]].value;
		for(cn = 0; cn < thisElement.length; cn++)
		{
			if(thisElement.charAt(cn) != parseInt(thisElement.charAt(cn)) )
			{
				errorMsg = errorMsg + 'All Values must be Integers (1,15,10 etc)\n';
				break;
			}
		}
		if(errorMsg == '')
		{
			if(thisElement.value == ''){errorMsg = errorMsg + 'Please enter an FNN to continue\n';}
			if(c == 1 & thisElement.length < 1){errorMsg = errorMsg + 'Incorrect Area Code Format (xx)\n';}
			//if(c == 2 & thisElement.length < 4){errorMsg = errorMsg + arguments[c] +' must be 4 digits long\n';}
			//if(c == 3 & thisElement.length < 4){errorMsg = errorMsg + arguments[c] +' must be 4 digits long\n';}
		    if(c == 2 & thisElement.length < 4){errorMsg = errorMsg + 'Your Phone Number must be 10 digits long\n';}
			if(c == 3 & thisElement.length < 4){errorMsg = errorMsg + 'Your Phone Number must be 10 digits long\n';}
		
		}else{
			break;
		}
	}
	
	if(errorMsg.length > 0)
	{
		alert(errorMsg);
		return false;
	}
}
/*-------------------------------------- CHECK SCHEDULE FILE NAMES ---------------------------------------------
Author:		Ross Crawford
Date:		22 01 2002
Description:
Checks that the type of CSV selected is the same as the file selected to upload.

File naming convention MUST conform to TWSI_yyyymmdd.csv or PH2_yyyymmdd.csv

return scheduleCompareNames('nameOfForm','elementame1','elementame2');
the first argument MUST be the name of the form.
------------------------------------------------------------------------------------------------------------*/
function scheduleCompareNames()
{

	var theForm = document.forms[arguments[0]];

	var varElement1 = theForm.elements[arguments[1]].value;
	var varElement2 = theForm.elements[arguments[2]].value;
	
	if ( varElement1 == '' || varElement2 == '' )
	{
		alert('Please select values for both "Type of CSV" and "Path to CSV file".');
		return false;
	}else{

		if(varElement1 == '1')
		{
			varElement1 = 'ph2_';
		}else{
			varElement1 = '2wsi_';	
		}	

		var varElement2 = theForm.elements[arguments[2]].value.toLowerCase();

		if( varElement2.lastIndexOf('.csv') > 0 )
		{
			if( varElement2.lastIndexOf(varElement1) < 0 )
			{
				alert('File Name Error:\r\rYou have indicated that you are updating the '+varElement1+' values.\rThe file that you have selected to upload must be named "'+varElement1+'yyyymmdd.csv".');
				return false;
			}
		}else{
			alert('You can only upload ".csv" files\r\rPlease ensure that the file you select is a CSV file.')
			return false;
		}
	}
}

/*-------------------------------------- OPEN WINDOW FUNCTION ---------------------------------------------
Author:		Zareh Tashjian
Date:		12 01 2002
Description:
Opens a customisable pop up window that accepts parameters passed from calling page
------------------------------------------------------------------------------------------------------------*/

function popwin(url, name, width, height,scroll) { 
	var movey;
	var movex;
	var screenheight=600;
	var screenwidth=800;
	
	if (typeof(screen)!='undefined'){
		screenheight=screen.height;
		screenwidth=screen.width;
	}
	movex=Math.round((screenwidth-width)/2)-20;
	movey=Math.round((screenheight-height)/2)-60;
	//movex = 200;
	//movey = 100;
	n=window.open (url, name, 'status=0,scrollbars='+scroll+',width=' + width + ',height=' + height + ',left='+movex+',top='+movey + ',screenX=' + movex + ',screenY=' + movey);

  	//SIMV : Removed this check to fix error on IE4.0
	//       Doesn't seem to have disrupted the functionality
	//if (typeof(n)=='object'){
  	//	TId=setTimeout('n.focus()', 500);
 	//}
	//SIMV : Finished Removal
}
//-----------------------------------------------------------------------------------------------------------
/*-------------------------------------- CHECK REQUIRED FIELDS ---------------------------------------------
Author:		Ross Crawford
Date:		07 01 2002
Description:
Checks arguments passed in that are field names and then checks that each field in the list has a value.
function call description
return requiredFields('nameOfForm','fieldName','fieldDisplayName');
the first argument MUST be the name of the form.
------------------------------------------------------------------------------------------------------------*/
function requiredFields()
{
	var thisForm = arguments[0];
	
	var thisElementValue = thisForm.elements[arguments[1]].value;
	
	if(thisElementValue == null || thisElementValue.length < 1 || thisElementValue == "")
	{
		return "error";
	}else{
		return "none";
	}
}
/*------------------------------------------------- INTEGER CHECK ---------------------------------------------
Author:		Ross Crawford
Date:		18 10 2001
Description:
Checks if the value of a form field is an integer
------------------------------------------------------------------------------------------------------------*/
function check_isInteger()
{
	var theForm = arguments[0];
	var elementValue = theForm.elements[arguments[1]].value;
	var int_errorFound = false;
	
	for ( count = 0; count < elementValue.length; count++ ) 
	{ 
		var theElement = parseInt(elementValue.charAt(count));

		if ( theElement != elementValue.charAt(count))
		{
			int_errorFound = true;
			break;
		}
	}

	//	Test for errorFound
	if( int_errorFound == true)
	{
		return 'error';
	}else{
		return 'none'
	}
}
/*------------------------------------------------- EMAIL CHECK ---------------------------------------------
Author:		Ross Crawford
Date:		21 11 2001
Description:
Change a form element to see if it contains a valid email address. All chars except SPACES are allowed
Emails must contiain an @ sign and a . with the . appearing after the @.

If more characters are to be disallowed at them to the disAllowedChars array located at ln 15. ('32','<newNum>'
------------------------------------------------------------------------------------------------------------*/
function checkforEmail()
{
	var thisForm = arguments[0];
	
	var theElement = arguments[1];
	var elementValue = thisForm.elements[theElement].value;
	
	var atFound = false;
	var firstDotFound = false;
	var errMsg = 'Please enter a valid email address in:\r\r';
	var errorsFound = false;
	var disAllowedChars = new Array ('32');	//	ASCII values for banned characters
	var charFound = false;
	var numArguments = arguments.length;


	for ( count=0; count < elementValue.length; count++ ) 
	{ 
		for (cntr=0; cntr < disAllowedChars.length; cntr++) 
		{
			if (disAllowedChars[cntr] == elementValue.charCodeAt(count)){charFound = true; }
		}
		
		if ( elementValue.charAt(count) == '@' ){ atFound = true; }
		
		if (firstDotFound == false) 
		{
			if ( elementValue.charAt(count) == '.' & atFound == true  ){ firstDotFound = true; }			
		}
	}

	//	TEST FOR ERROR, IF FOUND BREAK ELSE CONTINUE
	if ( atFound != true || firstDotFound != true || charFound != false ) 
	{ 
		return 'error';
	}else{
		return 'none';
	}
}
/*-------------------------------------- CHECK FOR VALID DATE ---------------------------------------------
Author:		Ross Crawford
Date:		08 01 2002
Description:
Checks for a valid date
Requires:
	Function call must pass into function validDate(0 or 1,'form name','field names',etc)
	0 or 1 indicates wether these fields are required values.
	form name is the name of the form being acted on
	field names is a comma seperated list of strings
------------------------------------------------------------------------------------------------------------*/
function validDate()
{	
	var theForm = arguments[0];
	var theElement = arguments[1];
	var day = "";
	var month = "";
	var year = "";
	var thisDate = theForm.elements[theElement].value;
	var errors = false;
	var valDate_varTemp = '';

		//	TEST IS INTEGER

			//	EXRACT DD,MM,YYYY
			for (cn = 0; cn <= thisDate.length; cn++)
			{
				//	Day
				if(cn < 2)
				{
					//	REMOVE 0 from primary digit
					if(cn == 0 & thisDate.charAt(cn) != '0')
					{
						day = day + thisDate.charAt(cn); 
					}
					if(cn == 1)
					{
						day = day + thisDate.charAt(cn); 
					}
				}
				
				//	Month
				if(cn == 3 || cn == 4){
					//	REMOVE 0 from primary digit
					if(cn == 3 & thisDate.charAt(cn) != '0')
					{
						month = month +  thisDate.charAt(cn); 
					}
					if(cn == 4)
					{
						month = month +  thisDate.charAt(cn); 
					}
				}
				
				//	Year
				if(cn == 6 || cn == 7 || cn == 8 || cn==9)
				{
					year = year + thisDate.charAt(cn);
				}

				
			}
		

		//	TEST FOR ERRORS IN DATE FORMAT
		if(errors == false)
		{
			if(theElement == 0 & thisDate != '')
			{				
				if((day > 31) || (month > 12) || (year < 2000))
				{
					errors = true;
				}
				
			}
		}
	
	//	ALERT IF ERRORS WERE FOUND
	if(errors == true)
	{ 
		return 'error';
	}else{
		return 'none';
	}

}
/*-------------------------------------- CHECK AT LEAST ONE VALUE IS CHECKED ---------------------------------------------
Author:		Ross Crawford
Date:		24 01 2002
Description:
Check that at least one in a series of commonly named form elements has been selected.
------------------------------------------------------------------------------------------------------------*/
function checkOneSelected()
{
	var thisForm = arguments[0];
	var elementName = arguments[1];
	var elementsOfName = new Array();
	var oneFound = false;
	
	for (c = 0; c < thisForm.elements.length; c++)
	{
		varTest = thisForm.elements[c].name;
		
		if( varTest.indexOf(elementName) == 0)
		{
			if( thisForm.elements[varTest].checked != false)
			{
				oneFound = true;
			}
		}		
	}
	
	if(oneFound != true)
	{
		return 'error';
	}else{
		return 'none';
	}
}
/*-------------------------------------- CHECK PASSWORD ---------------------------------------------
Author:		Ross Crawford
Date:		12 03 2002
Description:
Checks that a password has been entered and that it conforms to a valid password policy.
------------------------------------------------------------------------------------------------------------*/
function checkPassword()
{
	var thisForm = arguments[0];
	var elementName = arguments[1];
	var nextElementName = '';
	
	for (c=0; c < thisForm.elements.length; c++ )
	{
		if (thisForm.elements[c].name == elementName)
		{
			nextElementName = thisForm.elements[c+1].name;
			break;
		}
	}	
	
	if ( thisForm.elements[elementName].value.length < 8 )
	{
		return 'error';
	}else{
		if ( thisForm.elements[nextElementName].value != thisForm.elements[elementName].value )
		{
			return 'error';
		}else{
			return 'none';
		}
	}	
	
}
/*-------------------------------------- GLOBAL FORM CHECK ---------------------------------------------
Author:		Ross Crawford
Date:		22 01 2002
Description:
Loops through array and splits arguments passed into 3 sections
1: Name of form element.
2: Name of form to Display on error.
3: Type of check to perform.
	3:1: Required
	3:2: Integer
	3:3: Email
	3:4: Date
	3:5: At least one (1) option must be selected (field name specified must be common element names i.e. checkboxlist_1)
	3:6: Password Validation
	3:7: Required Date
	3:8: Required Integer
------------------------------------------------------------------------------------------------------------*/
function gblChkFields()
{
	var thisForm = document.forms[arguments[0]];

	var elementName = '';
	var displayName = '';
	var testDataType = '';
	
	var varLoopCnt = 0;
	
	var outerLoopVal = arguments.length-1;	
	
	var counter = 0;
	var varTemp = 0;
	
	var thisArray = '';
	var varErrorsFound = '';
	var ErrorsFound = false;
	
//	alert(outerLoopVal);returnfalse;
//	alert(arguments.length-1);return false;
	
	// Get elements from arguments and split into 3 arrays.	
	for( mainCntr = 1; mainCntr <= outerLoopVal; mainCntr+=3 )
	{ 
		elementName = arguments[ mainCntr ];
		displayName =  arguments[mainCntr + 1]; 
		testDataType = arguments[mainCntr + 2];		
		
//			alert(elementName+' , '+displayName+' , '+testDataType+' , :'+c)
		//	Perform datatype test depending on argument 3
		switch (testDataType)
		{   			
			// 3:1: Requireds
			case '1' :
				varTemp = requiredFields(thisForm,elementName);
				 if( varTemp == 'error' )
				 {
				 	varErrorsFound = varErrorsFound + displayName +': is a required field. \r\r';
					ErrorsFound = true;
				 }
				 break;
				 
			//	3:2: Integer
			case '2' :			
				varTemp = check_isInteger(thisForm,elementName);
				if( varTemp == 'error' )
				{
					varErrorsFound = varErrorsFound + displayName +': must be an Integer. (i.e. 1,2,3,etc) no spaces. \r\r';
					ErrorsFound = true;
				}			
				 break;
			
			//	3:3: Email
			case '3' : 
				varTemp = checkforEmail(thisForm,elementName);
				if( varTemp == 'error' )
				{
					varErrorsFound = varErrorsFound + displayName +': must be valid. (i.e. yourName@yourIsp.com) \r\r';
					ErrorsFound = true;
				}
				 break;
			
			//	3:4: Date NEEDS FIXING
			case '4' : 
				varTemp = validDate(thisForm,elementName);
				if( varTemp == 'error' )
				{
					varErrorsFound = varErrorsFound + displayName +': Must be a valid date: (dd/mm/yyyy)\ndd = less than 32\nmm = less than 13\nyyyy = greater than 2000\nAll Integers \r\r';
					ErrorsFound = true;
				}
				 break;

			//	3:8: At least one (1) option must be selected
			case '5' :
				varTemp = checkOneSelected(thisForm,elementName);				
				if( varTemp == 'error' )
				{
					varErrorsFound = varErrorsFound + displayName +': At least one value present must be selected. \r\r';
					ErrorsFound = true;
				}
				 break;
			
			//	3:6: Password Validation
			case '6' : 
				varTemp = checkPassword(thisForm,elementName);				
				if( varTemp == 'error' )
				{
					varErrorsFound = varErrorsFound + displayName +': \r\r  a) Password must be at least 8 characters long \r  b) Confirm password must be the same as Password.\r\r';
					ErrorsFound = true;
				}
				 break;
			
			//	3:7: Required Date
			case '7' : 
				varErrorsFound = 'ERROR: Error Case 7 (Required Date) has no statements';
				ErrorsFound = true;
				 break;
			
			//	3:5: Required Integer
			case '8' : 
				varErrorsFound = 'ERROR: Error Case 5 (Required Integer) has no statements';
				ErrorsFound = true;
				 break;
		}
	}
	//	Test for error.
	if(ErrorsFound == true)
	{
		alert(varErrorsFound);
		ErrorsFound = false;
		return false;
	}
}


////// test Script for FNN Ranges Validation ////////////////////////////////
//////////// See if can be added to the library /////////////////////////////////////


	function validate(string) {
	    if (!string) return false;
	    var Chars = "0123456789/";
	
	    for (var i = 0; i < string.length; i++) {
	       if (Chars.indexOf(string.charAt(i)) == -1)
	          return false;
	    }
	    return true;
	} 
	
	
	
	function check()
	{
	
		if (document.adminform.start.value.length < 10)
		{
		alert('Please enter a 10 digit FNN Start Number');
		return false;
		}
		else if (document.adminform.finish.value.length < 10)
		{
		alert('Please enter a 10 digit FNN End Number');
		return false;
		}
		else if (!validate(document.adminform.start.value))
		{
		alert('Please enter numeric values only into the FNN start ranges');
		return false;
		}
		else if (!validate(document.adminform.finish.value))
		{
		alert('Please enter numeric values only into the FNN finish ranges');
		return false;
		}
		else if (document.adminform.finish.value <=  document.adminform.start.value)
		{
		alert('The FNN Finish Number should be greater than the FNN Start Number');
		return false;
		}
		else if (document.adminform.fnn_name.value=='')
		{
		alert('Please enter an FNN Name');
		return false;
		}
		else if (document.adminform.comment.value=='')
		{
		alert('Please enter an FNN Comment');
		return false;
		}

	}
	
////// End test Script for FNN Ranges Validation ////////////////////////////////	


// function to toggle the images on the side menu
// Note: This is just a test script.....needs to be finalised...

  var thisimg;
  function toggle(thisimg)
  	{   
		document.images['opta'].src='images/optaoff.gif';
		document.images['optb'].src='images/optboff.gif';
   		document.images['optc'].src='images/optcoff.gif';
		document.images['optd'].src='images/optdoff.gif';
		document.images[thisimg].src='images/'+thisimg+'on.gif';
	//alert(thisimg);
	}