//(c)Alex Barnard 2000-2004
//--------------------------------------------------------------------------------
var CONST_NUMBER="0123456789"
var CONST_DATE=",./"+CONST_NUMBER
var CONST_TIME=".:apm"+CONST_NUMBER
var CONST_FORMAT_TIME="T"
var CONST_FORMAT_DATE="D"
var CONST_FORMAT_POSTCODE="A"
var CONST_FORMAT_PHONE="P"
var CONST_FORMAT_EMAIL="E"
var CONST_FORMAT_URL="U"
var CONST_FORMAT_CHARACTER="C"
var CONST_FORMAT_INT="N"
var CONST_FORMAT_FLOAT="F"
var CONST_FORMAT_MEMO="M"
var CONST_FORMAT_BOOLEAN="B"
var CONST_FORMAT_ID="I"
var CONST_FORMAT_YESNO="Y"
//var CONST_FORMAT_TICKBOX="X"
var CONST_FORMAT_NEW_FIELD="_X_NEW"
var JAVASCRIPT_CHECK_FIELD="Xjava_processed"

var g_Remove_=/_/g
var g_day,g_month,g_year
var g_hPWin=0
var g_currentFormElement

function fnSetFocus(theField){
	if(theField.type!="hidden")
	{
		theField.focus()
		if(theField.type=="text")
			theField.select()
	}	
	return true
}	
//--------------------------------------------------------------------------------
function checkFor(txt,sTest,flg)
{
	if(!txt.length) 
		return !flg
	
	for(var i = 0; i < txt.length; i++ )	
	{
		var	cChar=txt.charAt(i).toLowerCase()
		if (sTest.indexOf(cChar)<0)
			if (sTest.indexOf(cChar.toUpperCase())<0)
				return false
	}	
	return true
} 
//--------------------------------------------------------------------------------
function fnChkNumber(theField,isFloat,flgReq)
{
	var sTest=","+CONST_NUMBER
	if(isFloat)sTest+="."
	if(!checkFor(theField.value,sTest,flgReq)){
		alert(fnGetFieldName(theField.name)+" requires Numerical entry")
		fnSetFocus(theField)
		return false
	}
	return true
}		
//--------------------------------------------------------------------------------
function keyPress(theField,theFormat,e,param)
{	//get keypressed	
	var c = document.layers ? e.which 
            : document.all ? event.keyCode
            : e.which;
	var cc=String.fromCharCode(c)

	switch(theFormat){
		case CONST_FORMAT_TIME:
			 return checkFor(cc,CONST_TIME)
		case CONST_FORMAT_DATE:
			if(checkFor(cc,CONST_DATE)){
				if(c>=44&&c<=47){
					c=0
					for(var i=0;i<theField.value.length;i++)//loop along text entered
						if(theField.value.charAt(i)>=","&&theField.value.charAt(i)<="/")//if charcter found in text, set inc cntr
							c++
					return (c<2)		//false if delimiter found > twice
				}
				return true
			}
			
		case CONST_FORMAT_POSTCODE:
			return /\w+|\s+/.test(cc)
	
		case CONST_FORMAT_PHONE:
			return /[\d ext]/.test(cc)
			
		case CONST_FORMAT_EMAIL:
			return /[\w.@\-&]/.test(cc)
		
		case CONST_FORMAT_URL:
			return /[\w:./\-&%]/.test(cc)
				
		case CONST_FORMAT_CHARACTER:
			return true
		
		case CONST_FORMAT_INT:
			return checkFor(cc,CONST_NUMBER+",")		
		
		case CONST_FORMAT_MEMO:
			return (theField.value.length<param)
		
		case CONST_FORMAT_FLOAT:
			if(checkFor(cc,CONST_NUMBER+",.")){
				if(c==46)//check if decimal point added
					if(theField.value.indexOf(".")>=0)
						return false

				return true
			}	
	}
	return false
}
//--------------------------------------------------------------------------------
function fnChkText(theField,flgReq)
{
	return true
}		
//--------------------------------------------------------------------------------
function fnUpperCase(theField){
	theField.value=theField.value.toUpperCase()
}
//--------------------------------------------------------------------------------
function fnMakeFirstUpper(theField){
	var words=theField.value.replace(/([’"`])/g,"'").toLowerCase().split(" ");
	var arr
	for(var i=0;i<words.length;i++){
		arr=words[i].match(/(^([a-z]))|(\W[a-z][a-z]?)/g)
		if(arr)
			for(j=0;j<arr.length;j++){
				if(/[']/.test(arr[j])){
					if((/['][a-z][a-z]/.test(arr[j])))
						arr[j]=arr[j].substr(0,arr[j].length-1)
					else
						arr[j]=" "
				}else		
					if(arr[j].length>2)
						arr[j]=arr[j].substr(0,arr[j].length-1)
				
				words[i]=words[i].replace(arr[j],arr[j].toUpperCase())
//			alert(words[i]+" ["+arr[j]+"]")
		}
	}
	theField.value=words.join(" ")
	return true
}	//’
//--------------------------------------------------------------------------------
function fnChkPassword(theField){
	var msg=""
	if(theField.value.search(/[ ]/)>=0)
		msg+="\nmust not contain spaces"
	if(theField.value.length<5)
		msg+="\nmust be 5 characters or more"
	if(msg){
		alert("     Password Error\n______________________\n"+msg)
		fnSetFocus(theField)		
		return false
	}	
	return true	
}		
	
//--------------------------------------------------------------------------------
function fnChkDate(theField,flgReq)
{	var flgErr
	var sName=theField.name
	var d = theField.value;

	var r=/\s/g
	
	if(!flgReq && !d)
		return true
		
	d=d.replace(r,"")
	r=/\D/g
	d=d.replace(r,"/")
	r=d

	var o = d.indexOf("/");
	if ( o < 1 )
		flgErr=true	
	else
	{	
		var day = parseInt(d.substring(0,o),10);
		
		d = d.substring( o+1, d.length );
		o = d.indexOf("/");
		if ( o < 1 )
			flgErr=true
		else	
		{
			var month = parseInt(d.substring(0,o),10);
			var year = parseInt(d.substring( o+1, d.length ),10)
			if(!year)
				flgErr=true
			if (year>100&&year<1000)	
				flgErr=true
		}
	}
	
	if(flgErr)
	{
		alert("You must enter "+fnGetFieldName(sName)+" as dd/mm/yyyy    (day/month/year).")
		fnSetFocus(theField)
		return false
	}	
				
	//check date entered is valid			
	if (month == 2 )	//if February
	{
		//if leap g_year (century / 400) OR (g_year / 4)
		if (( year % 100 ==0 && year % 400==0)||( year % 4==0 && year % 100 !=0))	
		{
			//if leap g_year check Feb <=29 g_days
			if ( day > 29 )
			{
				alert("Invalid Date\nFebruary has only 29 days in "+year)
				fnSetFocus(theField)
				return false
			}	
		}
		else
			//ordinary g_year - check Feb <=28 g_days
			if ( day > 28 )
			{
				alert("Invalid Date\nFeburary has only 28 days in "+year)
				fnSetFocus(theField)
				return false
		 	}
		}	 
		//check g_months with only 30 g_days
	else if ( (month == 4) || (month == 6) || (month == 9) || (month == 11) )	
		{
			//if >30 g_days
			if ( day > 30 )
			{
				alert("Invalid Date\nMonth "+month+" has only 30 days")
				fnSetFocus(theField)
				return false
			}
		}
		else if(month>12)
		{
			alert("Invalid Date\nIncorrect month entered. Must be in the range 1-12.")
			fnSetFocus(theField)
			return false
		}
	if(day<10)day="0"+day.toString()	
	if(month<10)month="0"+month.toString()
	if(year<10)year="200"+year.toString()
	theField.value=day+"/"+month+"/"+year
	return true
}
//----------------------------------------------------------------------------
function fnChkPhone(pField,pflgReq){
	if(!pField.value&&!pflgReq)
		return true
	if(/[^0-9 ext]|(^[^\d ])|([^\d ]$)|(((\de)|e[\d ])|([\d ]x)|(x[\d ])|([\d ]t)|(t\d))/.test(pField.value)){
		alert(fnGetFieldName(pField.name)+" requires a Phone Number entry\ne.g. 0121 2020202 ext 115")
		fnSetFocus(pField)
		return false
	}
	return true
}
//------------------------------------------------------------------------------
function fnChkEmail(pField,pflgReq){	

	if(!pField.value&&!pflgReq)
		return true
	pField.value=pField.value.toLowerCase()
	var f1 = /(@.*@)|(@\.)|(^@)|(\.@)|(@$)|(^\.)|(\.\.)|(\.$)/;
	var f2 = /^.+\@[a-z0-9\-\.]+\.([a-z]{2,4}|[0-9]{1,3})$/;
	if (!f1.test(pField.value) && f2.test(pField.value)) 
		return true
	
	alert("                    Invalid Email Address\n\nYou have entered an incorrectly formatted email address.\n\nPlease check your email address");
	fnSetFocus(pField)
	return false;
}
//--------------------------------------------------------------------------------
function fnChkPostcode(pField,pflgReq)	{
	var f=/\s{2,}/g
	var pc=pField.value.replace(f," ")
	if(!pc&&!pflgReq)
		return true
	f=/^([a-z]{1,2}\d{1,2}[a-z]?)[ ](\d\d?[a-z]{2})$/i
	if(!f.test(pc)){
		alert("                   Invalid Postcode\n\nRequired format : [AaOoa OAA]\n\nA = Character (A-Z),  0 = Digit (0-9),  a o = Optional\n\ne.g. A1 2BC,  D34 5EF,  GH6 7IJ,  KL8M 9NO");
		fnSetFocus(pField)
		return false;
	}
	pField.value=pc.toUpperCase()
 	return true;
}
//------------------------------------------------------------------------------------
function fnChkWordCount(theTextArea,minUnit,maxUnit,flgChars)
{
	var sName=fnGetFieldName(theTextArea.name)
	var txt=theTextArea.value
	var tlen=0
	
	if(flgChars){
		var sUnit="character"
		var len=txt.length
		tlen=maxUnit
	}else{
	    var sUnit="word"
		var words=txt.split(" ")
		var len=words.length
	}	

	if(len<minUnit){
		alert("Your entry MUST contain MORE than "+minUnit+" "+sUnit+"s.")
		fnSetFocus(theTextArea)
		return false
	}	
					
	if(len>maxUnit) {
		if(!flgChars)
			for(var j=0;j<maxUnit;j++)
				tlen+=words[j].length+1

		if(confirm("You have exceded the recommended maximum number of "+sUnit+"s for "+sName+",\nClick [OK] if you want to enter and automatically remove the excess text\nClick [cancel] to edit your text to reduce the number of "+sUnit+"s to less than "+maxUnit+".")){
			theTextArea.value=txt.substring(0,tlen-3)+"..."
			return true
		}
		else{	
			alert("Cut the execss, as marked from '|--->'\ninto the computer's clipboard, before submiting form.")
			theTextArea.value=txt.substring(0,tlen)+"|--->"+txt.substring(tlen,txt.length)
			fnSetFocus(theTextArea)
			if(document.all){
				var tr=theTextArea.createTextRange()
				if(tr.findText("|--->")){
					tr.scrollIntoView()
					tr.moveEnd("textedit")	
					tr.select()
				}
				
			}else	
				theTextArea.select()
							
			return false				
		}	
	}
	return true
}
//--------------------------------------------------------------------------------
function fnGetFieldName(theField){
//	var removenew=eval("/"+CONST_FORMAT_NEW_FIELD+"/g")
	
	var sName=theField.substr(2).replace(eval("/"+CONST_FORMAT_NEW_FIELD+"/g"),"")	
	sName=sName.replace(g_Remove_," ")
	if(sName.substr(0,3)=="ID ")
		sName=sName.substr(3)

	return "["+sName+"]"
}
//-----------------
function fnChkForm(theForm,flgForceReq)
{
	var flgErr=false
	var iPassPtr=-1
	var chk=0
	var objEg
	var objE
	var sBox
	var iNotFilled=0
	var iFilledField=0
	var err=""
	var firstField=-1
	var maxE=theForm.elements.length
	var fType
	var sName
	var flgReq

	for(var i=0;i<maxE;i++){
		objE=theForm.elements[i]
		if(objE.name.substring(0,1)!="X")
			if(objE.name.indexOf(CONST_FORMAT_NEW_FIELD)>=0)
				if(objE.type!="hidden")
					if(objE.name.substring(0,1)!=CONST_FORMAT_BOOLEAN)
						if(objE.value!="")
							iFilledField++			
						else	
							if(objE.name.indexOf("1")>=0){
								iNotFilled++
								err+="\n"+fnGetFieldName(objE.name)
								if(firstField<0)
									firstField=i
							}
	}						

	if(iFilledField&&iNotFilled){
		alert("________________________________________________\n\nThe form was not submitted because the following\nrequired field(s) for the New Record are empty\n________________________________________________\n"+err)
		fnSetFocus(theForm.elements[firstField])
		return false
	}	

    for(var i=0;i<maxE;i++){
		objE=theForm.elements[i]
		fType=objE.name.substring(0,1)		
		sName=fnGetFieldName(objE.name)
		flgReq=flgForceReq

		if (!flgReq)
			flgReq=parseInt(objE.name.substring(1,2),10)

		if(fType!="X"&&objE.name.indexOf(CONST_FORMAT_NEW_FIELD)<0){
			if(objE.type=="text" || objE.type=="file"){// || objE.type=="hidden")
				if(objE.value=="" && flgReq){
					alert("You need to make an entry for "+sName)
					fnSetFocus(objE)
					return false
				}
				if(objE.type!="hidden"){
					if(fType==CONST_FORMAT_DATE)
						if(!fnChkDate(objE,flgReq))
							return false
	
					if(fType==CONST_FORMAT_FLOAT)
						if(!fnChkNumber(objE,true,flgReq))
							return false
	
					if(fType==CONST_FORMAT_INT)
						if(!fnChkNumber(objE,false,flgReq))
							return false
					
					if(fType==CONST_FORMAT_TIME)
						if(!fnChkTime(objE))
							return false
	
					if(sName.search(/email/i)>=0)	
						if(!fnChkEmail(objE,flgReq))
							return false
							
					if(sName.search(/phone/i)>=0||sName.search(/fax/i)>=0||sName.search(/mobile/i)>=0)	
						if(!fnChkPhone(objE))
							return false
		
					if(sName.search(/postcode/i)>=0)	
						if(!fnChkPostcode(objE))
							return false
	
					if(sName.search(/password/i)>=0)
						if(!fnChkPassword(objE))
							return false
					}		
			}	

			if(objE.type=="select-one"){
				if(objE.selectedIndex<0 && flgReq)
					flgErr=true
				else				
					if(objE.options[objE.selectedIndex].value=="" && flgReq)
						flgErr=true
						
				if(flgErr){
					if(sName.substring(0,3)=="ID ")
						sName=sName.substring(3,sName.length)
					alert("You need to make an entry for "+sName);
					objE.focus()
					return false
				}
			}	
		
			if(objE.type=="radio"||objE.type=="checkbox"){	
				objEg=eval("theForm."+objE.name)
				chk=false
				if(!objEg.length)
					chk=objEg.checked
				else	
					for(var j=0;j<objEg.length;j++){
						if(objEg[j].checked)
								chk=true
					}
					if (!chk && flgReq){
						if(objE.type=="checkbox")
							alert("You must tick the '"+sName+"' box.")
						else	
							alert("You must give an answer to "+sName)
						fnSetFocus(objE)
						return false
					}	
		
			}	
	
			if(objE.type=="password"){
				if(objE.value=="" && flgReq){
					alert("You need to make an entry for "+sName)
					fnSetFocus(objE)
					return false
				}
			
				if(iPassPtr<0)
					iPassPtr=i
				else
					if(objE.value!=theForm.elements[iPassPtr].value){
						alert("Your password does not Verify.  Re-Enter your Password");
						objE.value=""
						theForm.elements[iPassPtr].value=""
						fnSetFocus(theForm.elements[iPassPtr])
						return false
					}		
			}
				
			if(objE.type=="textarea"){
				if(!objE.value){
					if(flgReq){
						alert("You must make an entry for "+sName)
						fnSetFocus(objE)
						return false				
					}	
				}	
			}			
		}
	}
	fnStampFormProcessed(theForm)
	return true
}
function fnStampFormProcessed(theForm){
	if(theForm.elements[JAVASCRIPT_CHECK_FIELD])
		theForm.elements[JAVASCRIPT_CHECK_FIELD].value=1
}		
//------------------------------------------------------------------------------------
function fnChkTime(theTimeField)
{
	var v=theTimeField.value.toLowerCase()
	var flg=true
	for(var i=0;i<v.length;i++)
	{
		if(!checkFor(v, CONST_TIME,true))
			{flg=false;break}
	}
	if(flg)
	{	
		var m=0
		var h=parseInt(v)
		if(isNaN(h))
			flg=false
		else	
		{
			h=h.toString()
			if(isNaN(v.substr(h.length,1)))
				m=1
			m=parseInt(v.substr(h.length+m,2))

			var last2chr=v.substr(v.length-2)
			if(isNaN(last2chr)){
				if(last2chr=="am"||last2chr=="pm"){
					if(v.indexOf("am")==h.length||v.indexOf("pm")==h.length)	
						m=0
					h=parseInt(h)		
					flg=!(h<0||h>12)
					if(flg)
						if(v.indexOf("pm")>0)
							h+=12
				}else
					flg=false				
			}
			if(flg)
			{
				h=parseInt(h)
				flg=!(h<0||h>23)
				if(isNaN(m))
					flg=false
				else
					flg=!(m<0||m>59)
			}
		}		
	}			
	if(!flg)
	{
		alert("Invalid "+fnGetFieldName(theTimeField.name)+"\nExample of valid time entry - 1.20pm OR 13.20")	
		fnSetFocus(theTimeField)
		theTimeField.select
		return false		
	}		
	return true
}	
//----------------------------------------------------------------------------

function fnSwitch(theWin,obj,thing){
	eval("theWin.document."+obj+"["+thing+"].checked=true")
}
//----------------------------------------------------------------------------
function msg(txt){
	window.status=txt
	return true
}	
//----------------------------------------------------------------------------
function fnASPuploadProgress(theForm,flgReq,aspFile){
	var strAppVersion = navigator.appVersion;
	if(fnChkForm(theForm,flgReq)) 
    	if (strAppVersion.indexOf('MSIE') != -1 && strAppVersion.substr(strAppVersion.indexOf('MSIE')+5,1) > 4) {
			var winstyle = "dialogWidth=375px; dialogHeight:130px; center:yes"
			window.showModelessDialog(aspFile+'&b=IE',null,winstyle)
		}else 
			window.open(aspFile+'&b=NN','','width=370,height=115', true)
	else 
  		return false
	return true
}
//------------
function fnPopUp(url,n,w,h,p){
	if(!url)
		return
	if(!w) w=510
	if(!h) h=348;

	if(g_hPWin!=0&&!g_hPWin.closed){
		if(g_hPWin.name!=n)
			g_hPWin.close()
			
	}		
	if(!g_hPWin||g_hPWin.closed)
		g_hPWin=window.open(url,n,"width="+w+",height="+h+",scrollbars=1"+p)
	else 
		g_hPWin.location.replace(url);
	g_hPWin.focus()
}

function fnConvertDate(d){
	var o = d.indexOf("/")
	var cd = d.substring(0,o)//day
	d = d.substring( o+1, d.length )
	o = d.indexOf("/")
	cd = "/"+d.substring(0,o)+"/"+cd//month
	cd= d.substring(o+1, d.length)+cd//year
	o = cd.indexOf("/")//get length of year
	if(o==2)//only 2 dig in year??
		if(parseInt(cd.substring(0,2))<10)//<10 ??
			cd="20"+cd//add "20" to year string
	return cd
}

function fnChkMemoForm(theForm)		
{
	if(!fnChkForm(theForm,false))
		return false
	

	if(!fnChkWordCount(theForm.elements[0],1,1024))
		return false
		
	return true	
}		

function fnBoolean(theField,theFieldID){
	var fld=eval("theField.form.Field"+theFieldID)
	fld.value=(fld.value=="false")
	//alert(fld.name+" "+fld.id+" "+fld.value)
}			
