
function intOnly(i) {
	if(i.value.length>0) {
		i.value = i.value.replace(/[^\d]+/g, ''); 
	}
}
 
// ============
function preSubmit(frm, actionKey, params){
var errMsg = '';
	if (typeof( arguments[0])){ 	// prior to 3.3 we just passed actionkey and validation params
		var frm = arguments[0];	// now we passs form first! 
		actionKey=arguments[1];
		var paramsStart=2;
	}
	else {
		var frm = document.forms[0];	
		actionKey=arguments[0];
		var paramsStart=1;
	}
	// Button the user pressed


	actionKey=actionKey.toUpperCase();
	actionKey=actionKey.substring(0,4);	// get the first four letters of the buttons text			
	var res = false;
	// Just get confirmation before deletion

 	if (actionKey == 'DELE'){
 		res = window.confirm('Are you sure you want to delete this record?');
 		if (res == false ) { // if users clicks the popup windows cancel button  scan all 'action' buttons and set their value to Cancel
 			// Then we can submit the form as if the user clicked the form's 'Cancel' button
	 		for(f=0;f<frm.action.length;f++){ // 
	 			frm.action[f].value = 'Cancel'; // 
	 		}
 		}
	 	return(true);
 	} 	

 	if (actionKey=='CANC')	return(true);


	altTextLen=0;
	altTextErr = false;
	altTextErrText='';
	argLen = arguments.length ;
	// Scan the validation data ( arg[0] = the id of the button the user pressed
    // eg Register Me|email|isEmail|Email address missing or invalid
	for (var i=paramsStart;i < argLen; i++) {
		//alert(arguments[i]);
		// Break up each validation data set
		arData =  arguments[i].split('|');
		// break up the first param into the button(s) we need to validate
		arButtons = arData[0].split('/');
		// Scan all the buttons - usually only 1
		for (var b=0;b < arButtons.length; b++) {
			// make a 4-char Ucase versio n of the button
			valBtnKey=arButtons[b].toUpperCase();
			valBtnKey=valBtnKey.substring(0,4);	// get the first four letters of the val buttons text			
			// DO they match? If so we run the test

			if (valBtnKey==actionKey){   // eg SUBM==SUBM
  				fldName=arData[1];	//[1??] is the button/list of buttons we need to test
				//alert( fldName);
  				if (frm.elements[fldName] || frm.elements[fldName+'[]'] ){
					if (frm.elements[fldName+'[]'] ){
						frmElement= frm.elements[fldName+'[]'];
					}
					else frmElement= frm.elements[fldName];

	  				fldData = frmElement.value;
					fldDefault = frmElement.defaultValue;
					fldChecked = frmElement.checked;
					fldDisabled = frmElement.disabled;

	  				fldData = trim(fldData);
	  				funcName=arData[2];
	  				errText=arData[3];
					errSubText='';
					testParams=arData[4];
	  				ok=true;
	  				myErr='';
	                //alert('Checking field: ' +  fldName + ' - test is ['   + funcName + '] - data is [' + fldData  + '] fldChecked is [' + fldChecked +'] - testParams is [' + testParams + ']' );
		  			switch (funcName){
		  				case 'isAlphaNumeric':
		  					ok = isAlphaNumeric(fldData);
		  					break;
						case 'isLeadingAlphaNumeric':
		  					ok = isLeadingAlphaNumeric(fldData);
		  					break;

		  				case 'isAltText':
		  					altTextLen = altTextLen + fldData.length;
		  					altTextErrText = errText;
		  					break;
		  				case 'isDate':
		  					ok = isDate(fldData);
		  					break;
		  				case 'isFileName':
			  				ok = isFileName(fldData);
		  					break;
		  				case 'isChecked':
							ok = false;
							if ( frmElement.length > 1){
								for (x=frmElement.length-1; x > -1; x--) {
									if (frmElement[x].checked) ok = true;
								}
							}
							else if (frmElement.checked) ok = true;
		  					break;
		  				case 'isPassword':
		  					ok = (fldData.length >7 );
		  					break;
		  				case 'isPIN':
		  					ok = (fldData.length ==4 ) && isInteger(fldData);
		  					break;
		  				case 'isOptPostCode':
		  					if ( fldData.length > 0 ){
		  						var pcErrText = isPostCode(fldData);
		  						ok=  (pcErrText.length==0);
								if (pcErrText.length>0) errText=pcErrText;
							}
							else ok = true;
		  					break;
						case 'isUKPostCode':
							if (! fldDisabled ){
								var pcErrText = isPostCode(fldData);
								ok=  (pcErrText.length==0);
								if (pcErrText.length>0) errText=pcErrText;
							}
		  					break;
						case 'isPostCode':
							var pcErrText = isPostCode(fldData);
							ok=  (pcErrText.length==0);
							if (pcErrText.length>0) errText=pcErrText;
		  					break;
		  				case 'isYN':
		  					ok = (fldData=='Y' || fldData=='N');
		  					break;
		  				case 'notDefault':
							ok = (fldData.length > 0 && fldData != fldDefault) ;
		  					break;
						case 'isText':
							if (testParams) {
								ok = fldData.length > testParams;
    							if (! ok) errSubText = ' (' + fldData.length + ')';
							}
		  					else ok = fldData.length > 0;
		  					break;
						case 'indexNotZero':
                            ok = frmElement.selectedIndex > 0;
		  					break;
		  				case 'isRTEText':
							var s = FCKeditorAPI.GetInstance(fldName) ;
							if (s){
								fldData = s.GetXHTML();
								fldData = stripTags(fldData, true);
								if (testParams) {
									ok = fldData.length >= testParams;
									if (! ok) errSubText = ' (' + fldData.length + ' chars)';
								}
								else ok = fldData.length > 0;
							}
		  					break;
						case 'isNonZero':
		  					ok = (fldData > 0)  ;
		  					break;
		  				case 'isOptPhone':
		  					if ( fldData.length > 0 ) ok = isPhone(fldData);
		  					else ok = true;
		  					break;
						case 'isPhone':
		  					ok = (fldData.length > 0) && isPhone(fldData);
		  					break;
						case 'isOptNum':
		  					if ( fldData.length > 0 ) ok = isNumeric(fldData);
		  					else ok = true;
		  					break;
						case 'isNum':
		  					ok = (fldData.length > 0) && isNumeric(fldData);
		  					break;
		  				case 'isOptEmail':
		  					if ( fldData.length > 0 ) ok = isEmailAddr(fldData);
		  					else ok = true;
		  					break;
		  				case 'isEmail':
		  					ok = isEmailAddr(fldData);
		  					break;
					    case 'isMatch':
                            checkElement= frm.elements[testParams];
	  				        checkData = trim(checkElement.value);
                            ok =  ( fldData == checkData)  ;
						    break;
		  			}
					if (fldDisabled) ok = true; //??
		  			 //alert('Checked field: ' +  fldName + ' - test is ['   + funcName + '] - data is [' + fldData +'] - result is ' + ok );
		  			if (! ok) errMsg +=  ' - ' + errText  + errSubText + '\n';
				  }
			}
  		} // End of for loop parsing validators
 	}

	if (altTextErrText) { // There was an altText test - did it pass?	
		if (altTextLen < 1 ) errMsg +=  altTextErrText  + '\n';
	}
 	if (errMsg) {
		res=false
		alert( 'Data input errors...\n\n' + errMsg );
	}
 	else {
 	 	// Turn off the confirm exit check
	 	if (actionKey=='UPDA' || actionKey=='SAVE') window.onbeforeunload = null;
 		res=true;
 	}
 	return(res);
}
function checkPostCode(pcField){
  	pcData = pcField.value;
  	var postcodeRegEx = /[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}/i;
	if (postcodeRegEx.test(pcData)){
		var postcodeRegEx = /(^[A-Z]{1,2}[0-9]{1,2})([0-9][A-Z]{2}$)/i;
		pcData= pcData.replace(postcodeRegEx,"$1 $2");
 	}

  	pcField.value =pcData.toUpperCase();

}
// ===============
function isLeadingAlphaNumeric(checkStr){
// allow ONLY alphanumeric keys, no symbols or punctuation
var checkOK = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var allValid = false;
	if (checkStr.length < 1 ) return(false);
	// needs to only check for LEADING Ans
	ch = checkStr.charAt(0);
	for (j = 0;  j < checkOK.length;  j++){
		if (ch == checkOK.charAt(j)){
            allValid = true;
		  break;
		}
	}
 
	return(allValid)}

function isAlphaNumeric(checkStr){
// allow ONLY alphanumeric keys, no symbols or punctuation
var checkOK = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 &,./-";
var allValid = true;
	if (checkStr.length < 1 ) return(false);
	// needs to only check for LEADING Ans
	for (i = 0;  i < checkStr.length;  i++){
		ch = checkStr.charAt(i);
		for (j = 0;  j < checkOK.length;  j++){
			if (ch == checkOK.charAt(j)) break;
		}
		if (j == checkOK.length){
			allValid = false;
			break;
		}
	}
	return(allValid)
}
// ===============
function isFileName(fileName){
	// must be something!
	if(fileName.length < 1) return(false);
	// look for valid extensions
	dots = fileName.split(".")
	//get the part AFTER the LAST period.
	myFileType = dots[dots.length-1];
	myFileType = myFileType.toUpperCase();
	if (myFileType != 'JPG' && myFileType != 'GIF' ) return (false);
	return(true);
}
// ===============
function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}
// ===============
function isPhone(sText){
var ValidChars = "0123456789 +";
var IsNumber=true;
var Char;
   for (i = 0; i < sText.length && IsNumber == true; i++){
      Char = sText.charAt(i);
      if (ValidChars.indexOf(Char) == -1)
         {
         IsNumber = false;
         }
      }
   return IsNumber;
}
// ===============
function isNumeric(sText){
var ValidChars = "0123456789.-";
var IsNumber=true;
var Char;
   for (i = 0; i < sText.length && IsNumber == true; i++){
      Char = sText.charAt(i);
      if (ValidChars.indexOf(Char) == -1)
         {
         IsNumber = false;
         }
      }
   return IsNumber;
}
// ============
function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one. If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}
// ==============
function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
// ==========
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}
// ========
function isDate(dtStr){
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;
	
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
 
	if (pos1<1){
		dtCh='-'; // if / doesnt work try -
		pos1=dtStr.indexOf(dtCh)
	}
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strDay=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		return false
	}
return true
}

function isEmailAddr(address) {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   //var address = document.forms[form_id].elements[email].value;
   return(reg.test(address));
}
function XisEmailAddr(str){
var at="@"
var dot="."
var lat=str.indexOf(at)
var lstr=str.length
var ldot=str.indexOf(dot)
if (str.indexOf(at)==-1)return false
if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr)return false
if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr)return false
if (str.indexOf(at,(lat+1))!=-1)return false
if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot)return false
if (str.indexOf(dot,(lat+2))==-1)return false
if (str.indexOf(" ")!=-1)return false
return true;
}

// ==============
function checkMaxLength (textarea, evt, maxLength) {

    var elID = textarea.id;
    if(elID){
        var elWarn = document.getElementById(elID + '_warn');
        if (elWarn){
            len = textarea.value.length ;
            if (len >  parseInt(maxLength*.9)){
                var left =    maxLength - len;
                if (left < 0 ) left = 0;
                verb = (left==0) ? 'Run' : 'Running';
                //elWarn.innerHTML=  verb + ' out of room! ' + left + ' characters left';
                elWarn.innerHTML=   left + ' characters left!';
                elWarn.style.visibility = 'visible';
            }
            else {
                elWarn.innerHTML= '';
                elWarn.style.visibility = 'hidden';
            }
        }
    }

    // ignore shift click for select
    if (textarea.selected && evt.shiftKey)  return true;
    if (evt.ctrlKey)  return true;
    var allowKey = false;

  if (textarea.selected && textarea.selectedLength > 0) allowKey = true;
  else {
  		var keyCode =  document.layers ? evt.which : evt.keyCode;
  	 	// Look for special keys
  		if ( ! isAlphaNum(keyCode)) return true;
  		allowKey = (textarea.value.length < maxLength);
  }
  if ( textarea.value.length > maxLength) {
  		textarea.value = textarea.value.substring(0,maxLength);
  }
  textarea.selected = false;

  return allowKey;
}
function isAlphaNum(keyCode){
	if ( (keyCode>=48 && keyCode <= 90) || keyCode >= 144 || keyCode==13 || keyCode==32 ) return true;
	else return false;
}
function isPostCode(test){ //check postcode format is valid
 size = test.length
 test = test.toUpperCase(); //Change to uppercase
 while (test.slice(0,1) == " ") //Strip leading spaces
  {test = test.substr(1,size-1);size = test.length
  }
 while(test.slice(size-1,size)== " ") //Strip trailing spaces
  {test = test.substr(0,size-1);size = test.length
  }
 if (size < 1){ //Code must exist
   return("Please enter a valid postcode");
  }
  if (size < 6 || size > 8){ //Code length rule
   return(test + " is not a valid postcode - wrong length");
  }
 if (!(isNaN(test.charAt(0)))){ //leftmost character must be alpha character rule
   return(test + " is not a valid postcode - cannot start with a number");
  }
 if (isNaN(test.charAt(size-3))){ //first character of inward code must be numeric rule
   return(test + " is not a valid postcode - alpha character in wrong position");
  }
 if (!(isNaN(test.charAt(size-2)))){ //second character of inward code must be alpha rule
   return(test + " is not a valid postcode - number in wrong position");
  }
 if (!(isNaN(test.charAt(size-1)))){ //third character of inward code must be alpha rule
   return(test + " is not a valid postcode - number in wrong position");
  }
 if (!(test.charAt(size-4) == " ")){//space in position length-3 rule
   return(test + " is not a valid postcode - no space or space in wrong position");
   }
 count1 = test.indexOf(" ");count2 = test.lastIndexOf(" ");
 if (count1 != count2){//only one space rule
   return(test + " is not a valid postcode - only one space allowed");
  }
return('');
}
// ============
function trim(inputString) {
   // Removes leading and trailing spaces from the passed string. Also removes
   // consecutive spaces and replaces it with one space. If something besides
   // a string is passed in (null, custom object, etc.) then return the input.
   if (typeof inputString != "string") { return inputString; }
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
   while (ch == " ") { // Check for spaces at the beginning of the string
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length-1, retValue.length);
   while (ch == " ") { // Check for spaces at the end of the string
      retValue = retValue.substring(0, retValue.length-1);
      ch = retValue.substring(retValue.length-1, retValue.length);
   }
   while (retValue.indexOf("  ") != -1) { // Note that there are two spaces in the string - look for multiple spaces within the string
      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); // Again, there are two spaces in each of the strings
   }
   return retValue; // Return the trimmed string back to the user
} // Ends the "trim" function

function dataChanged(formName) {
	if (gDataChanged) return(true); // Set by functions in admin-page.js
    var result = false;	// assume no change
    var output = '';
    what = document.forms[formName];
    if (! what ) return(false); // no change there then
    for (var i=0, j=what.elements.length; i<j; i++) {
        myType = what.elements[i].type;
        
        if (myType == 'checkbox' || myType == 'radio') {
            if (what.elements[i].checked != what.elements[i].defaultChecked) {
                output += what.elements[i].name + ' is still checked' + '\n';
                result = true;
            }
        }
        if (myType == 'hidden' || myType == 'password' || myType == 'text'  ) {
            if (what.elements[i].value != what.elements[i].defaultValue) {
                output += what.elements[i].name + ' has changed from "' + what.elements[i].defaultValue + '"' + '\n' + 'to\n' + what.elements[i].value;
                result = true;
            }
        }
        if ( myType == 'textarea') {
           	var oEditor = FCKeditorAPI.GetInstance(what.elements[i].name) ; // look for FCKEditor
           	if (oEditor)result = oEditor.IsDirty()  ;  
           	else{
           		if (what.elements[i].value != what.elements[i].defaultValue) {
                	output += what.elements[i].name + ' has changed from defaultValue"' + what.elements[i].defaultValue + '"' + '\n' + 'to value"\n' + what.elements[i].value + '"';
                	result = true;
                }
            }
        }
        if (myType == 'select-one' || myType == 'select-multiple') {
            for (var k=0, l=what.elements[i].options.length; k<l; k++) {
                if (what.elements[i].options[k].selected != what.elements[i].options[k].defaultSelected) {
                    output += what.elements[i].name + ' option ' + k + ' has  changed from ' + what.elements[i].options[k].selected  + ' to ' +  what.elements[i].options[k].defaultSelected + '\n';
                    result = true;
                }
            }
        }
    }
    
 	 
    return result;
}
function confirmExit(){
 
	if (dataChanged('dataForm')){
    	return ('You have not saved changes you have made to the data.');  
    }
 
}
function stripTags(text, convertEntities){
	var res = text.replace(/(<([^>]+)>)/ig,""); 
	if (convertEntities){
		 res = res.replace(/&amp;/g,'&');
		 res = res.replace(/&nbsp;/g,' ');
	}
	return (res);
}
 
function entersubmit(event,ourform) {
	alert()
  if (event && event.which == 13)
    ourform.submit();
  else
    return true;}
// =========
function gotFocus(el) {
	 xbSetElClass(el,'fieldFocus');
}
function lostFocus(el) {
	 xbSetElClass(el,'fieldBlur');
}

var formAction = String("");
var gDataChanged = false;
 