﻿/**
 * ©2004 Environment Agency
 *
 * System: Global Javascript References
 * LastModified: @version 0.1 @author McDonald, Colin
 *
 * History
 * Date        	     Author                   Purpose
 * ----------  	     ------------------      -------------------------------------------------------
 * 17/12/2004   McDonald, Colin     Imported common javascript functions into central source
 * 06/05/2005   McDonald, Colin     Added function hideShowEABanner()
 * 23/03/2006   Matt West           Enhanced function getElementsByStyleClass() to work for multiple classes.
 *
 *
 *
 */

//      ================
//      Layout Variables
//      ================

	document.onkeypress = checkKeyPress;
	document.onkeydown = checkKeyDown;



// 	==========================================================
//	By default make all the styles readonly
//	These will be automatically when editMode is set to 1 or 0
//	Edit mode 0 = readonly  1 = edit
//	==========================================================

	var disabled = "DISABLED";
	var readonly = "readonly";
	var readOnlyStyle = "readOnlyTextField";
	var mandatoryStyle = "readOnlyTextField";
	var mandatoryNumericStyle  = "readOnlyNumericTextField";
	var optionalStyle = "readOnlyTextField";
	var optionalNumericStyle  = "readOnlyNumericTextField";
	var editMode = "0";
	var textArea = true;

	var Submitted = "";


function setPageLayout(){

	try{
		if (window.innerWidth == null) {
			iw = document.body.clientWidth;
			ih=document.body.clientHeight;
			document.getElementById('body01').style.height=(ih-150)+'px';
			document.getElementById('bottom').style.top=(ih-27)+'px';

		}
		else
		 {
			iw = window.innerWidth;
			ih = window.innerHeight;
			document.getElementById('body01').style.height=(ih-150)+'px';
			document.getElementById('bottom').style.top=(ih-27)+'px';

		}
	}catch(Error){}
}

//	==================================================
//	Must always know if the browser is or isn't IE 5.5
//	==================================================

	var isIE55 = checkIE();

        function checkIE()
        {
		if(navigator.userAgent.indexOf("MSIE 5.5") >= 0)
                {
                  return true;
                  }
                else if(navigator.userAgent.indexOf("MSIE 6.") >= 0)
                {
                  return true;
                  }
                  else
                  {
                    return false;
                    }
          }




//	=======================
//	FUNCTION: onPasteTextArea(txtArea, Max)
//	AUTHOR:   Author mark buttle
//	COMMENT:  Comment
//
//	USAGE
//
//	insert the following lines into you textarea (Ajust the 30 to limit the text size)
//	onkeydown="return checkTextArea(this,30)" onpaste="return onPasteTextArea(this,30)"
//	=======================
	var characterCodePressed = 0;
	function onPasteTextArea(txtArea, intMaxLength)
	{
		var intCurrLength, strClip ;
		var intClipLength, intAvailLength ;
		var blnReturn ;

		blnReturn = true ;
		intCurrLength = txtArea.value.length ;
		strClip = window.clipboardData.getData("Text") ;
		intClipLength = strClip.length ;
		intAvailLength = intMaxLength - intCurrLength ;

		if (intAvailLength > 0)
		{
			if (intAvailLength < intClipLength)
			{
				strClip = strClip.substr(0, intAvailLength) ;
				window.clipboardData.setData("Text",strClip) ;
			}
		}
		else
		{
			blnReturn = false ;
		}
		return blnReturn ;
	}

	function checkTextArea(txtArea, max){
		if(txtArea.value.length>=max){
			 var characterCode=""  //literal character code will be stored in this variable
			var evt
			 if(txtArea && txtArea.which){ //if which property of event object is supported (NN4)
				 evt= txtArea
				 characterCode = evt.which //character code is contained in NN4's which property
			 }
			 else{
				 evt= event
				 characterCode = evt.keyCode //character code is contained in IE's keyCode property
				 //window.status = "keycode=" + characterCode

				 if(characterCode==17){
				 	characterCodePressed=17;
				 	textArea = true;
				 	return true;
				 }
				 if(characterCodePressed==17 && characterCode==67){
				 	characterCodePressed = 0;
				 	textArea = true;
				 	return true;
				 }
				 if(characterCodePressed==17 && characterCode==36){
				 	characterCodePressed = 0;
					textArea = true;
				 	return true;
				 }

				 if(characterCodePressed==17 && characterCode==35){
				 	characterCodePressed = 0;
				 	return true;
				 }

				 if(characterCodePressed==17 && characterCode==86){
				 	characterCodePressed = 0;
					textArea = true;
				 	return true;
				 }
				 if(characterCodePressed==17 && characterCode==88){
				 	characterCodePressed = 0;
				 	textArea = true;
				 	return true;
				 }

				 if(characterCode==17 ||
				 	characterCode==8 ||
				 	characterCode==33 ||
				 	characterCode==34 ||
				 	characterCode==35 ||
				 	characterCode==37 ||
				 	characterCode==38 ||
				 	characterCode==39 ||
				 	characterCode==40 ||
				 	characterCode==45 ||
				 	characterCode==46){
				 	characterCodePressed = 0;
				 	textArea = true;
				 	return true;
				 }
			 }
			 characterCodePressed = 0;
			 textArea = false;
			 //window.status = "Returning False"
			return false;
		}
		characterCodePressed = 0;
		textArea = true;
		return true
	}



//	=======================
//	FUNCTION: fixDate(date)
//	AUTHOR:   Author...
//	COMMENT:  Comment...
//	=======================

	function fixDate(date) {

		var base = new Date(0);
		var skew = base.getTime();

		if (skew > 0) {

			date.setTime(date.getTime() - skew);

		}

	}

//	=======================
//	FUNCTION: confirmSelection(date)
//	AUTHOR:   Author...
//	COMMENT:  Comment...
//	=======================

	function confirmSelection() {
		if (document.form1.Index.value=="" || document.form1.Index.value==null)
		{
			alert("You must first select a row to edit");
			return false;
		}
		else
		{
			return true;
		}
	}

//	========================
//	FUNCTION: changeTheURL()
//	AUTHOR:   Author...
//	COMMENT:  Comment...
//	========================

function changeTheURL() {

	var newURL = 'piedc?Action=about&Page=NavBar';
	var winName = 'this';
	var intWidth = 800;
	var intHeight = 500;
	winOptions = 'width=' + intWidth + ',height=' + intHeight + ',statusbar=no,toolbar=no,personalbar=no,menubar=no,scrollbars=yes,resizable';
	var win ="";

	if(winName==null)winName="";

	if(winName!=""){
		win = window.open("", winName, winOptions);
	}
	else
	{
		win = window;
	}
	win.offscreenBuffering = true;
	win.location.href = newURL;
	win.focus();
	win.moveTo(100,100);
}

function changeTheURL(newURL) {

	var newURL = newURL;
	var winName = 'this';
	var intWidth = 800;
	var intHeight = 500;
	winOptions = 'width=' + intWidth + ',height=' + intHeight + ',statusbar=no,toolbar=no,personalbar=no,menubar=no,scrollbars=yes,resizable';
	var win ="";

	if(winName==null)winName="";

	if(winName!=""){
		win = window.open("", winName, winOptions);
	}
	else
	{
		win = window;
	}
	win.offscreenBuffering = true;
	win.location.href = newURL;
	win.focus();
	win.moveTo(100,100);
}

function changeTheURL(newURL, width, height) {

	var newURL = newURL;
	var winName = 'this';
	var intWidth = width;
	var intHeight = height;
	winOptions = 'width=' + intWidth + ',height=' + intHeight + ',statusbar=no,toolbar=no,personalbar=no,menubar=no,scrollbars=yes,resizable';
	var win ="";

	if(winName==null)winName="";

	if(winName!=""){
		win = window.open("", winName, winOptions);
	}
	else
	{
		win = window;
	}
	win.offscreenBuffering = true;
	win.location.href = newURL;
	win.focus();
	win.moveTo(100,100);
}
//	========================
//	FUNCTION: setConfirmAction()
//	AUTHOR:   McDonald, Colin
//	COMMENT:  Comment...
//	========================


function setConfirmAction(action, hrGlass, validate, message) {


	if (confirm(message)) {
		setAction(action, hrGlass, validate);
	} else {
		return false;
	}



}




//	========================
//	FUNCTION: setPageMessage()
//	AUTHOR:   Martin Brown
//	COMMENT:  Sets the page message using Javascript
//      severity can be Info, Error, Warning, Debug, Fatal
//	========================
function setPageMessage(message, severity){

   try{
   var td = document.getElementById("messageArea");
   	if (td!=null){
     		td.innerText = message;
   	}
   }catch(error){
       alert("Error in setPageMessage() : " + error.description );
   }
}


//	========================
//	FUNCTION: setAction()
//	AUTHOR:   Author...
//	COMMENT:  Comment...
//	========================

function setAction(action, hrGlass, validate)
{

	if(validate==null)validate=true;
	if(validate=="")validate=true;
	if(validate==true) {
		if(doValidation()==false){
			turnOff();
			hrGlass="false";
			Submitted="";
			return false;
		}
	}

	if(hrGlass==null)hrGlass="true";
	if(hrGlass=="true")turnOn();
	if(hrGlass=="false")Submitted="";

	if(Submitted==""){
		setPageMessage("Please wait", "Info");
		document.form1.Action.value = action;
		if(hrGlass=="true"){
			Submitted = "true";
		}

	}else
	{
		setPageMessage("Please wait", "Info");
		return false;
	}


	// Create a timestamp hidden textbox to this form
        addTimestamp(document.form1);


	document.form1.submit();
}



//	========================
//	FUNCTION: addTimestamp()
//	AUTHOR:   Martin Brown
//	COMMENT:  Adds a hidden textbox to request called timestamp
//                this contains current milliseconds and can be used
//                by the server to determine whether request was caused
//                by a refresh.
//	========================
function addTimestamp(form){

	var d = new Date();
	var timestamp = document.createElement("input");
	timestamp.name = "Timestamp";
	timestamp.type = "hidden";
	timestamp.value = d.getTime();
	form.appendChild( timestamp );

}



//	========================
//	FUNCTION: setDeleteAction()
//	AUTHOR:   Author...
//	COMMENT:  Comment...
//	========================

function setDeleteAction(action)
{
	var rslt = confirm("Do you wish to delete this record?");
	if(rslt==true){
		turnOn();
		document.form1.Action.value = action;

		// Create a timestamp hidden textbox to this form
        	addTimestamp(document.form1);

		document.form1.submit();
	}
}

//	========================
//	FUNCTION: checkKeyPress()
//	AUTHOR:   MBrown
//	COMMENT:  Intercept the backspace key and if focus isnt within text area or input then cancel it
//	========================
function checkKeyDown(evt) {
    try{
    	var rv = true;
	evt = (evt) ? evt : ((event) ? event : null);
	var kc = evt.keyCode;
	// window.status = "keycode=" + kc;
	var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
	if (node) {
		try{
			// Test to see if the node is readonly, if so don't allow any action to follow through
			if(kc==8){
				str = node.className.toLowerCase();
				if(str.indexOf("readonly")>-1){return false}
			}

		}catch(err){}
		if (node.nodeName=="TEXTAREA"){
			return textArea;
		}
	}

	if (kc==8){

		if (node) {
			rv = false;




			if (node.nodeName=="TEXTAREA"){
		           // allow textareas to perform backspace
			   rv =  true;
			}else if (node.nodeName=="INPUT"){
			   if (node.type=="text" || node.type=="password"){
			     // allow textboxes and passwords to perform backspace
			     rv = true;
			   }else{
			     window.status = "Backspace disabled in " + node.type + " control";
			   }
			}

		}
	}
    }catch(error){
	textArea = true;
	alert("Error in checkKeyDown() : " + error.description);
    }
    return (rv);
}


//	========================
//	FUNCTION: checkKeyPress()
//	AUTHOR:   Author...
//	COMMENT:  Comment...
//	========================

function checkKeyPress(evt) {



  var validated = true;

	evt = (evt) ? evt : ((event) ? event : null);

	try{
		var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
		if (node) {
			if (node.nodeName=="TEXTAREA"){
				return textArea;
			}
		}
		//window.status = node.nodeName

	}catch(e){}



	try{


			if(defaultAction !="")
                        {
				if (evt)
                                {
					var kc = evt.keyCode;
                                        if(kc==13){

                                                if(document.form1.Page.value == 'home')
                                                {
                  					validated = validateHomePage();
                                                }
                                                else if(document.form1.Page.value == 'proposalType')
                                                {
                  					validated = validateProposalType();
                                                }
                                                else if(document.form1.Page.value == 'localDevelopmentScheme')
                                                {
                  					validated = validateLocalDevelopmentScheme();
                                                }
                                                else if(document.form1.Page.value == 'decisionTopicList')
                                                {
                  					validated = validateDecisionTopicList();
                                                }
                                                else if(document.form1.Page.value == 'developmentTypeList')
                                                {
                  					validated = validateDevelopmentTypeList();
                                                }
                                                else if(document.form1.Page.value == 'documentTypeList')
                                                {
                  					validated = validateDocumentTypeList();
                                                }
                                                else if(document.form1.Page.value == 'externalPartyTypeList')
                                                {
                  					validated = validateExternalPartyTypeList();
                                                }
                                                else if(document.form1.Page.value == 'externalPartyTypeEdit')
                                                {
                  					validated = validateExternalPartyTypeEdit();
                                                }
                                                 else if(document.form1.Page.value == 'foulDrainageTypeList')
                                                {
                  					validated = validateFoulDrainageTypeList();
                                                }
                                                 else if(document.form1.Page.value == 'foulDrainageTypeEdit')
                                                {
                  					validated = validateFoulDrainageTypeEdit();
                                                }
                                                else if(document.form1.Page.value == 'lddStageList')
                                                {
                  					validated = validateLddStageList();
                                                }
                                                else if(document.form1.Page.value == 'lddStageEdit')
                                                {
                  					validated = validateLddStageEdit();
                                                }
                                                if (validated != false)
                                                {

							if(Submitted==""){
								setPageMessage("Please wait", "Info");
								turnOn();
								document.form1.Action.value = defaultAction;
								Submitted = "true";
							}
                                                	else
							{
							        setPageMessage("Please wait", "Info");
								return false;
							}

							// Create a timestamp hidden textbox to this form
        						addTimestamp(document.form1);
							document.form1.submit();
							return false;

                                                }

                                        }
				}

			}

	}catch(e){}

}




//	========================
//	FUNCTION: checkEnter()
//	AUTHOR:   Author...
//	COMMENT:  Comment...
//	========================

function checkEnter(e, allowSubmit, action){

	 //e is event object passed from function invocation
	 var characterCode=""  //literal character code will be stored in this variable
	 if(allowSubmit==null)allowSubmit=false;

	 if(e && e.which){ //if which property of event object is supported (NN4)
	 e = e
	 characterCode = e.which //character code is contained in NN4's which property
	 }
	 else{
	 e = event

	 characterCode = e.keyCode //character code is contained in IE's keyCode property
	 }
	 if((characterCode == 13) && (allowSubmit==true)){ //if generated character code is equal to ascii 13 (if enter key)
		document.form1.Action.value = action

		// Create a timestamp hidden textbox to this form
        	addTimestamp(document.form1);

		document.form1.submit() //submit the form
		return false
	 }else if((characterCode == 13) && (allowSubmit==false))
	 {
		 return false
	 }else if(characterCode == 27){
		 return false
	 }
	 else{
		 return true
	 }
}

//	========================
//	FUNCTION: easynet()
//	AUTHOR:   Author...
//	COMMENT:  Comment...
//	========================

function easynet(){
	openNormalWindow("http://intranet.ea.gov/");
}

//	========================
//	FUNCTION: EAWeb()
//	AUTHOR:   Author...
//	COMMENT:  Comment...
//	========================

function EAWeb(){
	window.open("http://www.Environment-Agency.gov.uk");
}


//	========================
//	FUNCTION: printFunction()
//	AUTHOR:   Author...
//	COMMENT:  Comment...
//	========================

function printFunction(){

	var rslt = confirm("Do wish to print this screen?");
	if(rslt==true){
		window.print();
	}


}



//	=======================================
//	FUNCTION: setActionIndex(action, index)
//	AUTHOR:   Author...
//	COMMENT:  Comment...
//	=======================================

function setActionIndex(action, index, validate) {

	if(validate==null)validate=true;
	if(validate=="")validate=true;

	if(validate==true) {
		if(doValidation()==false){
			turnOff();
			Submitted="";
			return false;
		}

	}



	if(Submitted==""){
		turnOn();
		setPageMessage("Please wait", "Info");
		document.form1.Action.value = action;
		document.form1.Index.value = index;
		Submitted = "true";

	}else
	{
		setPageMessage("Please wait", "Info");
		return false;
	}


	// Replaced the following 3 lines with section above in order to protect app against
	// double requests. mbr 9/8/2006
	//turnOn();
	//document.form1.Action.value = action;
	//document.form1.Index.value = index;

	// Create a timestamp hidden textbox to this form
        addTimestamp(document.form1);

	document.form1.submit();
}



//	====================
//	FUNCTION: turnOn()
//	AUTHOR:   Author...
//	COMMENT:  Comment...
//	====================

function turnOn() {

	document.body.style.cursor = "wait";

}

//	====================
//	FUNCTION: turnOff()
//	AUTHOR:   Author...
//	COMMENT:  Comment...
//	====================

function turnOff() {

	document.body.style.cursor = "default";

}

//	=================================
//	FUNCTION: setFilterAction(filter)
//	AUTHOR:   Author...
//	COMMENT:  Comment...
//	=================================

function setFilterAction(filter) {

	turnOn();
	document.form1.Action.value = "Filter";
	document.form1.Index.value = filter;

	// Create a timestamp hidden textbox to this form
        addTimestamp(document.form1);

	document.form1.submit();

}

//	================================
//	FUNCTION: setLayout()
//	AUTHOR:   Ray Hanson.
//	COMMENT:  Essential layout code.
//	================================

function setLayout(value) {


	if (this.editMode==0) {
		readonly = "";
		readOnlyStyle = "readOnlyTextField";
		optionalStyle = "optionalTextField";
		mandatoryStyle = "mandatoryTextField";
		optionalNumericStyle  = "optionalNumericTextField";
		mandatoryNumericStyle = "mandatoryNumericTextField";
		disabled = "";
	}

	//document.getElementById("eaAppTopPanel").style.width = document.body.clientWidth + 3;
	if (value =="hide") {
		document.getElementById("eaAppTopPanel").style.height = document.body.clientHeight - 20;
	}
	else
	{
		document.getElementById("eaAppTopPanel").style.height = document.body.clientHeight - 147;
	}
}


//	================================================================
//	FUNCTION:	writeUserDetails(user, role).
//	COMMENT:	Writes user details (name and role) to the status bar.
//	DATE:	21st September 2004.
//	AUTHOR:	Ray Hanson.
//	================================================================

	function writeUserDetails(user, role) {




		if (user != "" && role != "") {
                var roleDescr = "";
                  	if(role == '1')
                        {
                          roleDescr = "System Administrator";
                        }
                  	if(role == '2')
                        {
                          roleDescr = "PLO";
                        }
                  	if(role == '3')
                        {
                          roleDescr = "Consultee";
                        }
                  	if(role == '4')
                        {
                          roleDescr = "Contaminated Land Consultee";
                        }
                  	if(role == '5')
                        {
                          roleDescr = "Read Only User";
                        }
                        if(role == '6')
                        {
                          roleDescr = "Pre-Application Consultee";
                        }
                  	if(role == '7')
                        {
                          roleDescr = "Area PLO";
                        }
                  	if(role == '8')
                        {
                          roleDescr = "Regional PLO";
                        }

			window.defaultStatus = "User: " + new String(user).toUpperCase() + ".  Role: " + new String(roleDescr).toUpperCase() + ".";

		} else if (user != "" && role == "") {

			window.defaultStatus = "User: " + new String(user).toUpperCase() + ".  Role: UNKNOWN.";

		} else if (user == "" && role != "") {

			window.defaultStatus = "User: UNKNOWN.  Role: " + new String(role).toUpperCase() + ".";

		} else {

			window.defaultStatus = "User: UNKNOWN.  Role: UNKNOWN.";

		}

	}


//	================================
//	FUNCTION: writeStatusBar()
//	AUTHOR:   Ray Hanson.
//	COMMENT:  Essential layout code.
//	================================

function writeStatusBar(str){

	if(str==null){str="";}
	window.status = str;

}


//	================================
//	FUNCTION: hideShowActionPanel()
//	AUTHOR:   Mark Buttle.
//	COMMENT:  Hides/ Shows Left hand action panel.
//	================================
function hideShowActionPanel() {

	if (document.getElementById("actionPanel").className == "eaAppActionPanel") { // Hide Left Hand Menu

	document.getElementById("actionPanel").className = "eaAppActionPanelHidden";
	document.getElementById("eaAppMainPanel").style.left = 0;
	document.getElementById("eaAppMainPanel").style.width = isIE55 ? 776 : 765;
	document.getElementById("hideShowActionPanel").innerHTML = "Show Left Hand Menu";
	document.getElementById("hideShowActionPanel").title = "Show Left Hand Menu";
	document.form1.ActionPanelStatus.value = "hide";

	} else { // Show Left Hand Menu

		document.getElementById("actionPanel").className = "eaAppActionPanel";
		document.getElementById("eaAppMainPanel").style.left = 132;
		document.getElementById("eaAppMainPanel").style.width = isIE55 ? 644 : 633;
		document.getElementById("hideShowActionPanel").innerHTML = "Hide Left Hand Menu";
		document.getElementById("hideShowActionPanel").title = "Hide Left Hand Menu";
		document.form1.ActionPanelStatus.value = "show";
	}
}

//	================================
//	FUNCTION:  hideShowEABanner()
//	AUTHOR:    Colin McDonald.
//	COMMENT:  Hides/ Shows Left hand action panel.
//	================================

function hideShowEABanner() {

	if (document.getElementById("hideShowEABanner").title == "Hide EA Banner") {
		document.getElementById("eaAppHeader").style.visibility = "hidden";
		document.getElementById("hideShowEABanner").innerHTML = "Show EA Banner";
		document.getElementById("hideShowEABanner").title = "Show EA Banner";
		document.getElementById("eaStaticButtonBar").style.top = 0;
		document.getElementById("eaAppTopPanel").style.top = 20;
		document.getElementById("eaAppTopPanel").style.height = document.body.clientHeight - 20;
		document.form1.EABannerStatus.value = "hide";

	}
	else
	{
		document.getElementById("eaAppHeader").style.visibility = "visible";
		document.getElementById("hideShowEABanner").innerHTML = "Hide EA Banner";
		document.getElementById("hideShowEABanner").title = "Hide EA Banner";
		document.getElementById("eaStaticButtonBar").style.top = 132;
		document.getElementById("eaAppTopPanel").style.top = 152;
		document.getElementById("eaAppTopPanel").style.height = document.body.clientHeight - 147;
		document.form1.EABannerStatus.value = "show";
	}
}

//	========================================================
//	FUNCTION: setMenuAction(action, hourGlass, setSubmitted)
//	AUTHOR:   Author...
//	COMMENT:  Comment...
//	========================================================


function setMenuActionExtra(action, hourGlass, setSubmitted, validate) {
	
		document.form1.Action.value = action;


		document.form1.submit();

}




function setMenuAction(action, hourGlass, setSubmitted, validate) {
	

	//if(validate==null)validate=true;
	//if(validate=="")validate=false;

	//if(validate==true) {
	//	if(doValidation()==false){
	//		turnOff();
	//		Submitted="";
	//		return false;
	//	}
	//}

	setSubmitted ="true";
	if(hourGlass=="")hourGlass = "true";
	
	if (hourGlass != "false") turnOn();
	if (Submitted == "") {
		setPageMessage("Please wait", "Info");
		document.form1.Action.value = action;

		// Create a timestamp hidden textbox to this form
        	addTimestamp(document.form1);

		document.form1.submit();
		if (setSubmitted != "false") Submitted = "true";
	} else
	{
		setPageMessage("Please wait", "Info");
		return false;
	}
}



//	========================================================
//	FUNCTIONS: To Handle Mandatory fields
//	========================================================



//	=========================================================
//	FUNCTION: validate()
//	AUTHOR:   Author Mark Buttle
//	COMMENT:  Comment. Main Class to be called to check forms
//			   form for mandatory fields
//	=========================================================
function doValidation(){
	// Check the validation for fields with the following mandatory classes
	// Check to see if the form is in edit mode first!
	if(editMode==1){
		if(checkMandatoryFields(getElementsByStyleClass("mandatoryTextField"))==false)return false;
		if(checkMandatoryFields(getElementsByStyleClass("mandatoryNumericTextField"))==false)return false;
	}
	return true;
}


//	========================================================
//	FUNCTION: getElementsByStyleClass(className)
//	AUTHOR:   Mark Buttle
//            Matt West
//	COMMENT:  Works for multiple classes
//	========================================================

function getElementsByStyleClass (className) {
	  var all = document.all ? document.all :
		document.getElementsByTagName('*');
	  var elements = new Array();
	  for (var e = 0; e < all.length; e++) {
			var classNames = all[e].className.split(" ");
			for (var i = 0; i < classNames.length; i++) {
				if (classNames[i] == className) {
				  elements[elements.length] = all[e];
				}
			}
		}
	  return elements;
	}

//	========================================================
//	FUNCTION: validationMessage(theElement)
//	AUTHOR:   Author..Mark Buttle
//	COMMENT:  Comment The validation message and action
//	========================================================
function validationMessage(theElement){
		alert("You must complete all the form details before being able to save : " + theElement.name + " is incomplete.");
		if (theElement.focus) {
			theElement.focus();
		}
		if (theElement.select) {
			theElement.select();
		}
		return true;
	}

//	========================================================
//	FUNCTION: checkMandatoryFields(elements)
//	AUTHOR:   Author..Mark Buttle
//	COMMENT:  Comment The validation routine to check an array
//			  of elements for invalid entry
//	========================================================

function checkMandatoryFields(elements){

		var bRadioChecked;
		var sElementGroupName;
		var theElement;

		for (var iElement = 0; iElement < elements.length;iElement++)
		   {
			  theElement = elements[iElement];
			  //alert(theElement.name + "  -  " + theElement.type)
			  // <INPUT TYPE="TEXT">
			  if (theElement.type == "text")
			  {
				 if (theElement.value == "")
				 {
					validationMessage(theElement);
					return false;
				 }
			  }

			  // <INPUT TYPE="SELECT">
			  if (theElement.type == "select-one")
			  {
				 if (theElement.value == 0 || theElement.value == -1 || theElement.value == "")
				 {
					validationMessage(theElement);
					return false;
				 }
			  }

			  // <INPUT TYPE="CHECKBOX">
			  if (theElement.type == "checkbox")
			  {

				 if (theElement.value == 0 || theElement.value == -1 || theElement.value == "")
				 {
					validationMessage(theElement);
					return false;
				 }
			  }

			  // <INPUT TYPE="TEXTAREA">
			  if (theElement.type == "textarea")
			  {
				 if (theElement.value == "")
				 {
					validationMessage(theElement);
					return false;
				 }
			  }
		   }
		   return true;
	}


//	========================================================
//	FUNCTION: chkNumericLen(elements)
//	AUTHOR:   Author..Mark Buttle
//	COMMENT:  Comment check for valid numeric values
//	========================================================

	function chkNumericLen(objName,minval,maxval,len)
	{
		var checkStr = objName;
		if(checkStr.value.length ==0)return true;
		if(checkStr.value.length < len || checkStr.value.length > len)
		{
			alert(objName.name + " can only be " + len + " digits");
			checkStr.select();
			checkStr.focus();
			return false;
		}
		else
		{
			chkNumeric(objName,minval,maxval);
		}
	}

//	========================================================
//	FUNCTION: chkNumeric(elements)
//	AUTHOR:   Author..Mark Buttle
//	COMMENT:  Comment check for valid numeric values
//	========================================================

	function chkNumeric(objName,minval,maxval)
	{
		// only allow 0-9 be entered, plus any values passed
		// (can be in any order, and don't have to be comma, period, or hyphen)
		// if all numbers allow commas, periods, hyphens or whatever,
		// just hard code it here and take out the passed parameters
		var checkOK = "0123456789."
		var checkStr = objName;
		var allValid = true;
		var decPoints = 0;
		var allNum = "";

		for (i = 0;  i < checkStr.value.length;  i++)
		{
			ch = checkStr.value.charAt(i);
			for (j = 0;  j < checkOK.length;  j++)
				if (ch == checkOK.charAt(j))break;
				if (j == checkOK.length)
				{
					allValid = false;
					break;
				}
				if (ch != ",")allNum += ch;
		}
		if (!allValid)
		{
			alertsay = "Please enter only these values \"";
			alertsay = alertsay + checkOK + "\" in the \"" + checkStr.name + "\" field.";
			alert(alertsay);

			objName.select();
			objName.focus();

			return false;
		}

		// set the minimum and maximum
		var chkVal = allNum;
		var prsVal = allNum;

		if (chkVal != "" && !(prsVal >= minval && prsVal <= maxval))
		{
			alertsay = "Please enter a value greater than";
			alertsay = alertsay + "\"" + minval + "\" and less than";
			alertsay = alertsay + "\"" + maxval + "\" in the \"" + checkStr.name + "\" field.";
			alert(alertsay);

			objName.select();
			objName.focus();

			return false;
		}
	}


//	=========================================================
//	FUNCTION: setupSwapImage(imageID)
//	AUTHOR:   Matt West
//	COMMENT:  Swaps an image given an event on an img tag.
//            Used for mouse roll-overs.
//
//	USAGE:    Given your html is:
//
//              <img src="refreshicon.gif" id="myrefreshimage"/>
//
//            you should provide two images called
//            refreshicon-hover.gif and refreshicon.gif.
//
//            WARNING: Your gif filename must NOT contain hyphens ("-") !
//
//            Call setupSwapImage() from your page init().
//
//	=========================================================

function setupSwapImage(imageID) {
	var image = document.getElementById(imageID);
	if (image == null) {
		throw new Error("setupSwapImage(): imageID \"" + imageID + "\" not found.");
	}
	if (document.all) {
		image.onmouseover = swapImage;
		image.onmouseout = swapImage;
	} else {
		image.addEventListener('mouseover', swapImage, false);
		image.addEventListener('mouseout', swapImage, false);
	}
}

//	=========================================================
//	FUNCTION: swapImage(e)
//	AUTHOR:   Matt West
//	COMMENT:  Swaps an image given an event on an img tag.
//            Used for mouse roll-overs.
//
//	USAGE:    See setupSwapImage() above.
//
//            Given your html is:
//
//              <img src="refresh.gif" id="myrefresh"/>
//
//            you should provide two images called
//            refresh-hover.gif and refresh.gif.
//
//            Borrowed and adapted from the excellent
//            http://www.webstandards.org
//	=========================================================

function swapImage(e) {
	e = (e) ? e : event;
	var thisI = (e.srcElement) ? e.srcElement : e.target;
	var filename = /*thisI.id; TODO */ getFilenameStem(thisI.src);
	if ((thisI.status != 'a') && (thisI.status != 'p')) {
//		alert("swapImage(): thisI.src=" + thisI.src + ", thisI.id=" + thisI.id + ", filename=" + filename);
		thisI.src = 'images/button/' + filename + '-hover.gif';
		thisI.status = 'a';
	} else if (thisI.status != 'p') {
		thisI.src = 'images/button/' + filename + '.gif';
		thisI.status = '';
	}
}

function getFilenameStem(longFilename) {
	// e.g. longFilename = "http://something/dps3Web/images/buttons/refresh.gif"
	// or maybe "http://something/dps3Web/images/buttons/refresh-hover.gif"
	var parts = longFilename.split("/");

	var shortFilename = parts[parts.length - 1]; // e.g.  shortFilename = "refresh.gif"

	shortFilename = shortFilename.split(".")[0];

	if (shortFilename.contains("-")) {
		return shortFilename.substring(0, shortFilename.indexOf("-"));
		// e.g.  return "refresh" if shortFilename was "refresh-hover"
	}
	return shortFilename; // e.g.  return "refresh"
}


// Pre-requisite for the following new methods for String objects
new String(); // forces the prototype object to be created in JavaScript 1.1

//	=========================================================
//	FUNCTION: string.contains(substring)
//	AUTHOR:   Matt West
//	COMMENT:  Does 'this' string contain the given substring?
//            This method is case sensitive.
//            Return <code>true</code> if the string contains
//            the given substring,
//            or <code>false</code> otherwise.
//            I am fed up of saying foo.indexOf(bar) != -1.
//	=========================================================
String.prototype.contains = function(s) {
	return this.indexOf(s) != -1;
};

//	=========================================================
//	FUNCTION: string.containsIgnoreCase(substring)
//	AUTHOR:   Matt West
//	COMMENT:  Does 'this' string contain the given substring?
//            This method is not case sensitive.
//            Return <code>true</code> if the string contains
//            the given substring,
//            or <code>false</code> otherwise.
//	=========================================================
String.prototype.containsIgnoreCase = function(s) {
	return this.toUpperCase().indexOf(s.toUpperCase()) != -1;
};

//	=========================================================
//	FUNCTION: string.startsWith(substring)
//	AUTHOR:   Matt West
//	COMMENT:  Does this string start with the given substring?
//            Return <code>true</code> if the string starts
//            with the given substring,
//            or <code>false</code> otherwise.
//	=========================================================
String.prototype.startsWith = function(s) {
	return this.substring(0, s.length) == s;
};

//	=========================================================
//	FUNCTION: string.endsWith(substring)
//	AUTHOR:   Matt West
//	COMMENT:  Does this string end with the given substring?
//            Return <code>true</code> if the string ends
//            with the given substring,
//            or <code>false</code> otherwise.
//	=========================================================
String.prototype.endsWith = function(s) {
	return this.substring((this.length - s.length), this.length) == s;
};

//	=========================================================
//	FUNCTION: validateNGR
//	AUTHOR:   Paul Shaw
//	COMMENT:  Is an NGR Valid?
//            Return <code>true</code> valid
//            or <code>false</code> otherwise.
//	=========================================================

function validateNGR(ngr)
{
	// check the length of the NGR
	if (ngr.length > 15)
	{
		return false;
	}
	// check the co-ordinates don't contain characters
	var numeric = ngr.substr(2,ngr.length -2);
	try
	{
		var number = Number(numeric);
		if (isNaN(number))
		{
			return false;
		}
	}
	catch(e)
	{
		return false;
	}
	// check that the first two characters are valid letters
	var prefix = ngr.substr(0,2);

	if (prefix.toUpperCase() == "SW")
	{
		return true;
	}
	if (prefix.toUpperCase() == "SX")
	{
		return true;
	}
	if (prefix.toUpperCase() == "SY")
	{
		return true;
	}
	if (prefix.toUpperCase() == "SZ")
	{
		return true;
	}
	if (prefix.toUpperCase() == "TV")
	{
		return true;
	}
	if (prefix.toUpperCase() == "SR")
	{
		return true;
	}
	if (prefix.toUpperCase() == "SS")
	{
		return true;
	}
	if (prefix.toUpperCase() == "ST")
	{
		return true;
	}
	if (prefix.toUpperCase() == "SU")
	{
		return true;
	}
	if (prefix.toUpperCase() == "TQ")
	{
		return true;
	}
	if (prefix.toUpperCase() == "TR")
	{
		return true;
	}
	if (prefix.toUpperCase() == "SM")
	{
		return true;
	}
	if (prefix.toUpperCase() == "SN")
	{
		return true;
	}
	if (prefix.toUpperCase() == "SO")
	{
		return true;
	}
	if (prefix.toUpperCase() == "SP")
	{
		return true;
	}
	if (prefix.toUpperCase() == "TL")
	{
		return true;
	}
	if (prefix.toUpperCase() == "TM")
	{
		return true;
	}
	if (prefix.toUpperCase() == "SH")
	{
		return true;
	}
	if (prefix.toUpperCase() == "SJ")
	{
		return true;
	}
	if (prefix.toUpperCase() == "SK")
	{
		return true;
	}
	if (prefix.toUpperCase() == "TF")
	{
		return true;
	}
	if (prefix.toUpperCase() == "TG")
	{
		return true;
	}
	if (prefix.toUpperCase() == "SC")
	{
		return true;
	}
	if (prefix.toUpperCase() == "SD")
	{
		return true;
	}
	if (prefix.toUpperCase() == "SE")
	{
		return true;
	}
	if (prefix.toUpperCase() == "TA")
	{
		return true;
	}
	if (prefix.toUpperCase() == "NX")
	{
		return true;
	}
	if (prefix.toUpperCase() == "NY")
	{
		return true;
	}
	if (prefix.toUpperCase() == "NZ")
	{
		return true;
	}
	if (prefix.toUpperCase() == "OV")
	{
		return true;
	}
	if (prefix.toUpperCase() == "NS")
	{
		return true;
	}
	if (prefix.toUpperCase() == "NT")
	{
		return true;
	}
	if (prefix.toUpperCase() == "NU")
	{
		return true;
	}
	if (prefix.toUpperCase() == "NR")
	{
		return true;
	}

	return false;

}





