// setdatequick is to create a SQL server date from a single text box - to allow 01/04/04 entry
function setdatequick(frm, datefld, initial) {
	var datefield = document.getElementById(datefld); var datefield1 = document.getElementById(datefld + "1");
	var datefieldlast = document.getElementById(datefld+"last"); var datefieldlast1 = document.getElementById(datefld + "last1");
	var datestr = datefield1.value;
	if(datestr=="") { datefield.value=''; return; }
	if((datestr.length>5)&&(datestr.indexOf("/")==-1)&&(!isNaN(datestr))) { datestr = datestr.substr(0,2)+"/"+datestr.substr(2,2)+"/"+datestr.substr(4); }
	datestr = datestr.replace("-","/");
	datestr = datestr.replace("-","/");
	datefield1.value = datestr;
	if((datestr.indexOf("/")==-1)||(datestr.indexOf("/",5)==-1)||(datestr.indexOf("/")==datestr.indexOf("/",5))) {alert("Please enter dates in dd/mm/yyyy or ddmmyyyy format"); return;}
	var x = datestr.split("/"); var thisday = x[0]; var thismon = x[1]; var thisyea = x[2];
	// irrespective of the rest of the date values, update the year to a 4 figure year
	if ((thisyea<=100)&&(isNaN(parseFloat(thisyea))==false)) { if(thisyea>=31) thisyea=(1900 + parseFloat(thisyea)); else thisyea=(2000 + parseFloat(thisyea)); }
	if (isNaN(parseInt(thisday))||thismon==0||isNaN(parseFloat(thisyea))) { datefield.value=''; datefield1.value=''; }
	else{ if (thisday.length==1) thisday=("0" + thisday);
		if ((isDate(""+thisyea+thismon+thisday+"")==false)||thisyea<1900||thisyea>2050||thismon>12) {
			alert(" "+thisday+"/"+thismon+"/"+thisyea+" is not a valid date"); datefield.value = datefieldlast.value; datefield1.value = datefieldlast1.value;
			}
		else  {var thisDate = new Date(); 
			if((datefld=="empDob")&&((thisDate.getFullYear()-thisyea)<15)) alert("Sorry, but that would make the age less than 16 - please try again");
			else {
				if((new Date(thisyea,thismon-1,thisday) <= new Date(cutoffdate)) && typeof(initial)=="undefined" && cutoff) {
					alert("Sorry, but "+thisday+"/"+thismon+"/"+thisyea+" relates to a previous accounting period, the year end close down has already been processed.\n\nPlease contact us for further information."); 
					datefield.value=datefieldlast.value; datefield1.value=datefieldlast1.value;
					}
				else {
					if(typeof(cutoffchk)=="undefined") cutoffchk = false;
					if(new Date(thisyea,thismon-1,thisday) > new Date(cutoffdate) && typeof(initial)=="undefined" && cutoffchk) {
						alert("Sorry, but "+thisday+"/"+thismon+"/"+thisyea+" is a date in the future which cannot be entered here."); 
						datefield.value=datefieldlast.value; datefield1.value=datefieldlast1.value;
					}
					else {
						datefield.value = (""+thisyea+thismon+thisday+""); datefield1.value = (""+thisday+"/"+thismon+"/"+thisyea+""); 
						datefieldlast.value = datefield.value; datefieldlast1.value = datefield1.value; 
					}
					}
				}
			}
		}
}

function setdatequickold(frm,datefld,initial) {
	//if(typeof(initial=="undefined")) alert("undefined")
	//alert(typeof(initial=="undefined"))
	var thisobj = ("document." + frm);
	var datestr = "" + eval(thisobj + "." + datefld + "1.value");
	if(datestr=="") {eval(thisobj+"."+datefld+".value=''"); return;}
	if((datestr.length>5)&&(datestr.indexOf("/")==-1)&&(!isNaN(datestr))) {
		datestr = datestr.substr(0,2)+"/"+datestr.substr(2,2)+"/"+datestr.substr(4); }
	datestr = datestr.replace("-","/");
	datestr = datestr.replace("-","/");
	eval(thisobj + "." + datefld + "1.value='"+datestr+"'");
	if((datestr.indexOf("/")==-1)||(datestr.indexOf("/",5)==-1)||(datestr.indexOf("/")==datestr.indexOf("/",5))) {alert("Please enter dates in dd/mm/yyyy or ddmmyyyy format"); return;}
	var x = datestr.split("/"); var thisday = x[0]; var thismon = x[1]; var thisyea = x[2];
	// irrespective of the rest of the date values, update the year to a 4 figure year
	//alert(parseFloat("09"))//alert(thisyea)
  	if ((thisyea<=100)&&(isNaN(parseFloat(thisyea))==false)) { if(thisyea>=31) thisyea=(1900 + parseFloat(thisyea)); else thisyea=(2000 + parseFloat(thisyea)); }
	if (isNaN(parseInt(thisday))||thismon==0||isNaN(parseFloat(thisyea))) eval(thisobj+"."+datefld+".value='';" + thisobj+"."+datefld+"1.value='';")
	else{ if (thisday.length==1) thisday=("0" + thisday);
		  if ((isDate(""+thisyea+thismon+thisday+"")==false)||thisyea<1900||thisyea>2050||thismon>12) {
			alert(" "+thisday+"/"+thismon+"/"+thisyea+" is not a valid date"); eval(thisobj+"."+datefld+".value='';" + thisobj+"."+datefld+"1.value='';"); 
				eval(thisobj+"."+datefld+".value="+thisobj+"."+datefld+"last.value;")
				eval(thisobj+"."+datefld+"1.value="+thisobj+"."+datefld+"last1.value;"); 
				}
		  else  {var thisDate = new Date(); 
			if((datefld=="empDob")&&((thisDate.getFullYear()-thisyea)<15)) alert("Sorry, but that would make the age less than 16 - please try again");
			else {
				if((new Date(thisyea,thismon-1,thisday) <= new Date(cutoffdate)) && typeof(initial)=="undefined" && cutoff) {
					alert("Sorry, but "+thisday+"/"+thismon+"/"+thisyea+" relates to a previous accounting period, the year end close down has already been processed.\n\nPlease contact us for further information."); 
					//eval(thisobj+"."+datefld+".value='';" + thisobj+"."+datefld+"1.value='';"); 
					eval(thisobj+"."+datefld+".value="+thisobj+"."+datefld+"last.value;")
					eval(thisobj+"."+datefld+"1.value="+thisobj+"."+datefld+"last1.value;"); 
					}
				else {
					thisfld = eval(thisobj+"."+datefld);thisfld.value=(""+thisyea+thismon+thisday+"");
					eval(thisobj + "." + datefld + "1.value='"+thisday+"/"+thismon+"/"+thisyea+"'");
					eval(thisobj+"."+datefld+"last.value="+thisobj+"."+datefld+".value;")
					eval(thisobj+"."+datefld+"last1.value="+thisobj+"."+datefld+"1.value;"); 
					}
				}
			}
		}
}

// setdate is to create a SQL server date from a series of 2 text boxes and a select menu
// All fields use the same stem for naming to facilitate the generic nature of the function
function setdate(frm,datefld) {
	var thisobj = ("document." + frm);
	var thisday = eval(thisobj + "." + datefld + "1.value");
	var thismon = eval(thisobj+"."+datefld+"2.options["+thisobj+"."+datefld+"2.selectedIndex].value");
	var thisyea = eval(thisobj + "." + datefld + "3.value");
	// irrespective of the rest of the date values, update the year to a 4 figure year
  	if ((thisyea<=100)&&(isNaN(parseInt(thisyea))==false))
		{if(thisyea>=31)
			{thisyea=(1900 + parseInt(thisyea));}
		else
			{thisyea=(2000 + parseInt(thisyea));}
		 eval(thisobj + "." + datefld + "3.value="+thisyea);
		}

	if (isNaN(parseInt(thisday))||thismon==0||isNaN(parseInt(thisyea)))
		{ eval(thisobj+"."+datefld+".value=''");}
	else
		{ 
		  if (thisday.length==1) thisday=("0" + thisday);
		  if (isDate(""+thisyea+thismon+thisday+"")==false) { alert(" "+thisday+"/"+thismon+"/"+thisyea+" is not a valid date"); eval(thisobj+"."+datefld+".value=''"); }
		  else  {var thisDate = new Date();
			if((datefld=="empDob")&&((thisDate.getFullYear()-thisyea)<15))
				{alert("Sorry, but that would make the age less than 16 - please try again");}
			else {thisfld = eval(thisobj+"."+datefld);thisfld.value=(""+thisyea+thismon+thisday+"");}
			}
		}
}

// Whereas this one allows the month to be a hidden or text field for year only choices
function setdateyr(frm,datefld) {
	var thisobj = ("document." + frm);
	var thisday = eval(thisobj + "." + datefld + "1.value");
	var thismon = eval(thisobj+"."+datefld+"2.value");
	if (thismon.length==1) thismon=("0" + thismon);
	var thisyea = eval(thisobj + "." + datefld + "3.value");
	// irrespective of the rest of the date values, update the year to a 4 figure year
  	if ((thisyea<=100)&&(isNaN(parseInt(thisyea))==false))
		{if(thisyea>=31)
			{thisyea=(1900 + parseInt(thisyea));}
		else
			{thisyea=(2000 + parseInt(thisyea));}
		 eval(thisobj + "." + datefld + "3.value="+thisyea);
		}

	if (isNaN(parseInt(thisday))||thismon==0||isNaN(parseInt(thisyea)))
		{ eval(thisobj+"."+datefld+".value=''");}
	else
		{ 
		  if (thisday.length==1) thisday=("0" + thisday);
		  if (isDate(""+thisyea+thismon+thisday+"")==false) {
			alert(" "+thisday+"/"+thismon+"/"+thisyea+" is not a valid date");
			eval(thisobj+"."+datefld+".value=''");
			}
		  else  {var thisDate = new Date();
			if((datefld=="empDob")&&((thisDate.getFullYear()-thisyea)<15))
				{alert("Sorry, but that would make the age less than 16 - please try again");}
			else {thisfld = eval(thisobj+"."+datefld);thisfld.value=(""+thisyea+thismon+thisday+"");}
			}
		}
}

// create a year from a number
function makeyear(thisyea) {
  	if ((thisyea<=100)&&(isNaN(parseInt(thisyea))==false))
		{if(thisyea>=31) thisyea=(1900 + parseInt(thisyea));
		else thisyea=(2000 + parseInt(thisyea));
		}
	return thisyea
}


function isDate(dateStr) {
    month = dateStr.substring(4,6);
    day = dateStr.substring(6,8);
    year = dateStr.substring(0,4);
    if (day < 1 || day > 31) { return false;}
    if ((month==4 || month==6 || month==9 || month==11) && day>=31) {return false;}
    if (month == 2) { // check for february 29th
        var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
        if (day > 29 || (day==29 && !isleap)) {return false;}
    }
    return true; // date is valid
}

// setzero is to turn a text string (which is a number) into a number with two padded decimal places
function setzero(sz_num) {
	if(sz_num=='') return "0.00"
	sz_num = "" + sz_num;
	sz_num = sz_num.replace(",","");
	sz_num = sz_num.replace(",","");
	sz_num = sz_num.replace(",","");
	if(isNaN(sz_num)) sz_num = "0" 
	sz_num = parseFloat(sz_num);
	sz_num = Math.round(sz_num*100)/100;
	sz_num = "" + sz_num;
	var sz_dotpos = sz_num.indexOf('.');
	if (sz_dotpos < 0) sz_num+=".00";
	if (sz_dotpos==(sz_num.length-1)) sz_num+="00";
	if (sz_dotpos==(sz_num.length-2)) sz_num+="0";
	return sz_num ;
}

function yoalogout(newurl) { if(confirm("This will log you out of the system. Is this OK?")) document.location.href=newurl; }

function stripcrlf(thisval,in_out) {
	//if(in_out) { thisval = thisval.replace(/\r\n/g,'~~');thisval = thisval.replace(/\n\r/g,'~~');thisval = thisval.replace(/\'/g,'@#');}
	if(in_out) { thisval = thisval.replace(/\n/g,'~~');thisval = thisval.replace(/\r/g,'');thisval = thisval.replace(/\'/g,'@#');}
	else { thisval = thisval.replace(/~~/g,"\r\n"); thisval = thisval.replace(/@#/g,"'"); }
	return thisval;
}

function emptyList(box) { while (box.options.length) box.options[0] = null; }

function fillList(box,arr) {
	//	[0][x] is the visible value, [1][x] is the nomurn value, [2][x] is the vat flag 
	for ( i = 0; i < arr[0].length; i++ ) { option = new Option( arr[0][i], arr[1][i] ); box.options[box.length] = option; }
	box.selectedIndex=0;
}

//function changeList(box) { list = lists[whichlist()]; emptyList(box); fillList(box,list); nomchange(); }
function changeList(box) { list = lists[whichlist()]; fillList(box,list); nomchange();}

// this is for editing codes, where we want to select the code first, then fire the calculations
//	THIS SHOULD BE MAKE OBSOLETE WHEN THE NEW NOMCODES FLOODS THROUGH
function changeListSelected(box,ind,vat,vatind) { list = lists[whichlist()]; fillList(box,list); box.selectedIndex=ind; document.addemp.bkvatadj.disabled=(vatind==4); nomchange();}

function usevat() { return lists[whichlist()][2][document.addemp.nomurn.options.selectedIndex]; }

// used to check the type of invoice by returning document.addemp.bktype.value
function whichlist() { return 'p' ; }

function getvatrate(vatobj) {
	if(vatregistered()) return parseFloat(vatobj.options[vatobj.selectedIndex].value) - parseInt(vatobj.options[vatobj.selectedIndex].value)
	else return parseFloat(vatobj.value)
}
function vatregistered() {return (document.addemp.vatreg.value=='True')}

// Called when the nomurn list box is changed - adjusts VAT flags
// This forces the VAT to 17.5 if it goes to a vatable from a non vatable item
//		UPDATED to allow any VAT rate for any nominal code
function nomchange() {
	if(vatregistered()) calcgross(); else calcnet();
}

// Called when the item is edited for the first time - adjusts VAT flags
// This does not force the VAT to 17.5 
function nomchangenew() {
	if(vatregistered()) calcgross(); else calcnet()
}

function calcstock(direction) {
	unitprice = parseFloat(document.addemp.unitprice.value);
	qty = parseFloat(document.addemp.qty.value);
	stockvalue = parseFloat(document.addemp.stockvalue.value);
	if(qty==0) qty=1
	if(direction==0) {stockvalue = unitprice * qty}
	else {unitprice = stockvalue / qty}
	document.addemp.unitprice.value = setzero(unitprice)
	document.addemp.qty.value = setzero(qty)
	document.addemp.stockvalue.value = setzero(stockvalue)
}

function getSelectedRadio(buttonGroup) { // returns the array number of the selected radio button or -1 if no button is selected
	if (buttonGroup[0]) { for (var i=0; i<buttonGroup.length; i++) if (buttonGroup[i].checked) return i } 
	else {if (buttonGroup.checked) return 0;} return -1; }

function getSelectedRadioValue(buttonGroup) { // returns the value of the selected radio button or "" if no button is selected
	var i = getSelectedRadio(buttonGroup);
	if (i == -1) return ""; else {if (buttonGroup[i]) return buttonGroup[i].value; else return buttonGroup.value; }}

function authlevels(allornone) {
	for(i=0; i<55; i++) { thisradio = eval("document.addemp.a" + i + "")
	if(typeof(thisradio)=="object") { if(allornone) thisradio[thisradio.length - 1].checked=true; else thisradio[0].checked=true }
	}
}
// creates a proper, rounded two decimal point number
function twodps(thisval) { backval = Math.round(parseFloat(thisval)*100)/100; return backval}

// allow only numeric entry - includes full points though
function isNumberKey(evt) {
	var charCode = (evt.which) ? evt.which : event.keyCode
	if (charCode > 31 && ((charCode < 48 || charCode > 57) && charCode != 46)) return false;
	return true;
}

// pad a number or value to the left with trailing zeros
function padl(thisval, padchar, padnum) {
	if(thisval.length<padnum){
		for(i=0; i<padnum; i++) thisval = padchar + thisval
		thisval = thisval.substr(thisval.length-padnum, padnum)
	}
	return thisval
}

//================================================================
// Reconcile javascript
//================================================================
// update_all used to be called with the "set all checked boxes to" feature was there
function update_all() {
	for(i=1;i<document.tranform.cnt.value;i++) {
		if(eval("document.tranform.recthis"+i+".checked")) eval("document.tranform.statementno"+i+".value=document.setform.statementno.value")
	}
	calc()
}

function setpage(i) { 
	if(eval("document.tranform.recthis"+i+".checked")) eval("document.tranform.statementno"+i+".value=document.setform.statementno.value")
	calc();
	//else eval("document.tranform.statementno"+i+".value=0")
}

function clear_all() { for(i=1;i<document.tranform.cnt.value;i++) eval("document.tranform.recthis"+i+".checked=false"); calc(2) }
function tick_all()  { for(i=1;i<document.tranform.cnt.value;i++) eval("if(document.tranform.recthis"+i+".disabled==false) document.tranform.recthis"+i+".checked=true"); calc(3) }

function calc(calctype) {
	startbal = parseFloat(document.tranform.chkbal.value); targetbal = parseFloat(document.tranform.targetbal.value); 
	trantotal = parseFloat(document.tranform.trantotal.value); chkend = 0; differencebal = 0; chkdr = 0; chkcr = 0;
	switch(calctype){
	case 0: // adjust starting balance
		chkend = startbal + trantotal; differencebal = targetbal - chkend;
	break;
	case 1: // adjust target balance
		chkend = startbal + trantotal; differencebal = targetbal - chkend;
	break;
	case 2: // clear all ticks
		trantotal = 0
		for(i=1;i<document.tranform.cnt.value;i++) { eval("document.tranform.recthis"+i+".checked=false") }
		chkend = startbal + trantotal; differencebal = targetbal - chkend;
		document.tranform.checkcount.value = 0
	break;
	case 3: // select all
		trantotal = 0
		for(i=1;i<document.tranform.cnt.value;i++) {
			if(eval("document.tranform.recthis"+i+".checked")) { 
				chkdr = eval("parseFloat(document.tranform.dr"+i+".value)");
				chkcr = eval("parseFloat(document.tranform.cr"+i+".value)");
				//chkend += (chkcr-chkdr)
				trantotal += (chkcr-chkdr)
			}
		}
		chkend = startbal + trantotal; differencebal = targetbal - chkend;
		document.tranform.checkcount.value = parseInt(document.tranform.cnt.value)-1
	break;
	}
	document.tranform.chkend.value = setzero(chkend); document.tranform.differencebal.value = setzero(differencebal);
	document.tranform.trantotal.value = setzero(trantotal)
}

// to keep things efficient, calctick simply updates its own amounts, rather than looking through every record
function calctick(recno) {
	chkbal = parseFloat(document.tranform.chkbal.value); targetbal = parseFloat(document.tranform.targetbal.value); 
	chkend = parseFloat(document.tranform.chkend.value); trantotal = parseFloat(document.tranform.trantotal.value); 
	checkcount = parseInt(document.tranform.checkcount.value)
	chkdr = eval("parseFloat(document.tranform.dr"+recno+".value)");
	chkcr = eval("parseFloat(document.tranform.cr"+recno+".value)");
	if(eval("document.tranform.recthis"+recno+".checked")) {
		chkend += (chkcr-chkdr); document.tranform.checkcount.value = checkcount + 1; document.tranform.trantotal.value = parseFloat(trantotal + chkcr - chkdr)
		} 
	else {
		chkend += (chkdr-chkcr); document.tranform.checkcount.value = checkcount - 1; document.tranform.trantotal.value = parseFloat(trantotal + chkdr-chkcr)
		}
	document.tranform.chkend.value = setzero(chkend); document.tranform.differencebal.value = setzero(targetbal-chkend)
}

function leavecheckreconcile() { 
	chk_count = parseInt(document.tranform.checkcount.value);
	if(document.tranform.carryon.value==1) {chk_count = 0;}
	document.tranform.carryon.value=0;
	if(chk_count>0) event.returnValue = "You have entered statement page numbers for some transactions. If you leave this page they will be lost.";
}
// Validate form
function checkformreconcile(thisform) {
	var success = true; var msg = "";
	if(parseInt(thisform.chknum.value)==0) msg += "  - You have not entered a statement page number\n";
	chk_count = 0;
	for(i=1;i<thisform.cnt.value;i++) { if(eval("document.tranform.recthis"+i+".checked")) {chk_count ++;i=thisform.cnt.value} }
	if(typeof(document.getElementById("recupto"))=="object") { if(thisform.recupto.value=="") msg += "  - Please enter the date reconciled up to\n"; }
	if(chk_count==0) msg += "  - You have not selected any transactions to reconcile"
	if(!parseFloat(thisform.differencebal.value)==0 && parseInt(thisform.ulev.value)<2) msg += "  - Your target balance does not match"
	success=(msg=="");  
	if(success==false && thisform.submitted.value != "y") success = true
	if(success==false) alert("Sorry, but you have not yet filled in all of the required fields:\n\n"+msg); return success; 
}
function leavesafe(url) {
	document.tranform.carryon.value=1;
	window.open(url);
	//document.tranform.carryon.value=0;
}
//================================================================

//	FIXED ASSETS
// Validate form for a new FA
function checkformfa(thisform) {
	var success = true; var msg = "";
	if(thisform.bkdate.value=='') msg += "  - You have not entered the purchase date\n";
	if(parseFloat(thisform.bknet.value)==0) msg += "  - You have not entered the purchase price\n";
	if(thisform.bkref.value==''&&thisform.invnum.value=='') msg += "  - You have not entered your own reference\n";
	if(thisform.nomurn.options[thisform.nomurn.selectedIndex].value==0) msg += "  - Please select a " + nctxt1 + "\n";
	if(vatreg) { if(thisform.vat_type.selectedIndex==0) msg += "  - You have not chosen the VAT rate\n";}
	if((thisform.payamount.value>0)&&(thisform.bankurn.selectedIndex==0)) msg += "  - You have not chosen a bank account for this payment\n";
	if((thisform.payamount.value>0)&&(thisform.paydate1.value=='')) msg += "  - You have not entered a date this payment was paid\n";
	if((thisform.saleprice.value>0)&&(thisform.bankurnsale.selectedIndex==0)) msg += "  - You have not chosen a bank account for this sale\n";
	if((thisform.saleprice.value>0)&&(thisform.saledate1.value=='')) msg += "  - You have not entered a date this asset was sold\n";
	success = (msg==""); if(success==false) alert("Sorry, but you have not yet filled in all of the required fields:\n\n"+msg);
	return success; 
}

function showhide(id) { 
	obj = document.getElementById(id); 
	if (obj.style.display == "none") obj.style.display = "block"; else obj.style.display = "none"; 
} 
function toggleBox(szDivID, iState) { // 1 visible, 0 hidden
	if(document.layers){	   //NN4+
		if(document.layers[szDivID].visibility == "show" || iState==0) document.layers[szDivID].visibility = "hide"; else document.layers[szDivID].visibility = "show";
		showhide(szDivID)
	}
	else if(document.getElementById)	{  //gecko(NN6) + IE 5+
		var obj = document.getElementById(szDivID);
		if(obj.style.visibility == "visible" || iState==0) { obj.style.visibility = "hidden"; obj.style.display = "none"; } else { obj.style.visibility = "visible"; obj.style.display = "block"; }
	}
	else if(document.all) {	// IE 4
		if(document.all[szDivID].style.visibility=="visible" || iState==0) document.all[szDivID].style.visibility = "hidden"; else document.all[szDivID].style.visibility = "visible";
		showhide(szDivID)
	}
}
function showhidediv(szDivID, iState) {
    if(document.layers)	   //NN4+
       if(iState == 0) document.layers[szDivID].visibility = "hide"; else document.layers[szDivID].visibility = "show";
    else if(document.getElementById)	  //gecko(NN6) + IE 5+
    {
        var obj = document.getElementById(szDivID);
        if(iState == 0) obj.style.visibility = "hidden"; else obj.style.visibility = "visible";
    }
    else if(document.all)	// IE 4
        if(iState == 0) document.all[szDivID].style.visibility = "hidden"; else document.all[szDivID].style.visibility = "visible";
	if (iState == 1) document.getElementById(szDivID).style.display = ""; else document.getElementById(szDivID).style.display = "none"; 
		 //showhide(szDivID)
}
function layervisibility(layerid) {
	 if(document.layers)	return (document.layers[layerid].visibility == "show")
    else if(document.getElementById)	  //gecko(NN6) + IE 5+
    { return (document.getElementById(layerid).style.visibility == "visible" || document.getElementById(layerid).style.display != "none") }
    else if(document.all)	// IE 4
        return (document.all[layerid].style.visibility=="visible")
}


function swapfields(cnt, swp, thisform, fieldname, jsbufferval, fieldtype) {
	swapvalue = ".value"
	if(fieldtype=="checkbox") swapvalue = ".checked"
	jsbuffer = eval(thisform + jsbufferval); jsbufferval = thisform + jsbufferval + ".value"
	jsbuffer.value = eval(thisform + fieldname + swp + swapvalue);
	eval(thisform + fieldname + swp + swapvalue + "=" + thisform + fieldname + cnt + swapvalue);
	eval(thisform + fieldname + cnt + swapvalue + "=" + jsbufferval);
	if(fieldtype=="checkbox") eval(thisform + fieldname + cnt + swapvalue + "=" + eval(jsbufferval)+"");
}

//	Get the positions of an element on a page
function findPosX(obj) {
	var curleft = 0;
	if(obj.offsetParent)
	  while(1) {
		 curleft += obj.offsetLeft;
		 if(!obj.offsetParent) break;
		 obj = obj.offsetParent;
	  }
	else if(obj.x) curleft += obj.x;
	return curleft;
}

function findPosY(obj) {
	var curtop = 0;
	if(obj.offsetParent)
		while(1) {
			curtop += obj.offsetTop;
			if(!obj.offsetParent)
			break;
			obj = obj.offsetParent;
		}
    else if(obj.y) curtop += obj.y;
    return curtop;
}
// Ajax functions
function GetXmlHttpObject() {
	var xmlHttp=null;
	try { xmlHttp=new XMLHttpRequest(); } // Firefox, Opera 8.0+, Safari
	catch (e) { // Internet Explorer
		try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); }
	catch (e) { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); }
	}
	return xmlHttp;
}
// ajax parish look up
function ajaxplup(div,srch,curnfld,thispage) {
	xmlHttp=GetXmlHttpObject();
	srch = srch.replace('@',']').replace('+','@')
	if (xmlHttp==null) { alert ("Your browser does not support AJAX!"); return; } 
	xmlHttp.onreadystatechange=function() { if (xmlHttp.readyState==4) { document.getElementById(div).innerHTML=xmlHttp.responseText } }
	xmlHttp.open("GET",thispage+"?ajax=1|"+div+"|"+srch+"|"+curnfld+"|"+new Date().getTime(),true);
	xmlHttp.send(null);
} 

// ajax generic
function ajaxfunc(ajtype,div,srch,curnfld,thispage) {
	xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null) { alert ("Your browser does not support AJAX!"); return; } 
	xmlHttp.onreadystatechange=function() { if (xmlHttp.readyState==4) { document.getElementById(div).innerHTML=xmlHttp.responseText } }
	xmlHttp.open("GET",thispage+"?ajax="+ajtype+"|"+div+"|"+srch+"|"+curnfld+"|"+new Date().getTime(),true);
	xmlHttp.send(null);
} 

// Selects and colours a table row
function ChangeColor(tableRow, highLight) { if(highLight) tableRow.style.backgroundColor = '#Ffff99'; else tableRow.style.backgroundColor = 'white'; }
function DoNav(theUrl) { document.location.href = theUrl; }

function tickall(chkval, chkname, chknum, reconcile) { // if(typeof document.getElementById(chkname+i)!="undefined")
	var items = parseInt(document.getElementById(chknum).value); if(reconcile=="y") items=items-1; 
	for(i=1; i<=items; i++) {document.getElementById(chkname+i).checked=chkval; if(reconcile=="y") calctick(i) } 
}


//Postcode anywhere
var account_code='AAAAA11111';
var license_code='FX14-JB39-MJ18-BA12';
var machine_id='';
function pcaByPostcodeBegin(thisform, searchfield) {
	var postcode  = searchfield.value;
	var scriptTag = document.getElementById("pcaScriptTag");
	var headTag   = document.getElementsByTagName("head").item(0);
	var strUrl    = "";
	document.getElementById("divLoading").style.display = '';
	strUrl = "https://services.postcodeanywhere.co.uk/inline.aspx?action=lookup&type=by_postcode&postcode=" + escape(postcode) + "&account_code=" + escape(account_code) + "&license_code=" + escape(license_code) + "&machine_id=" + escape(machine_id) + "&callback=pcaByPostcodeEnd";
	//Make the request
	if (scriptTag) { // The following 2 lines perform the same function and should be interchangeable
			headTag.removeChild(scriptTag); //scriptTag.parentNode.removeChild(scriptTag);
	}
	scriptTag = document.createElement("script");
	scriptTag.src = strUrl
	scriptTag.type = "text/javascript";
	scriptTag.id = "pcaScriptTag";
	headTag.appendChild(scriptTag);
}

function pcaByPostcodeEnd() {
	document.getElementById("divLoading").style.display = 'none';
	selectfield = document.getElementById("selectaddress")
	//Test for an error
	if (pcaIsError) { selectfield.style.display = 'none'; document.getElementById("btnFetch").style.display = 'none'; alert(pcaErrorMessage); }
	else { //Check if there were any items found
		if (pcaRecordCount==0) {
			selectfield.style.display = 'none';
			document.getElementById("btnFetch").style.display = 'none';
			alert("Sorry, no matching items found. Please try another postcode.");
		}
		else {
			selectfield.style.display = '';
			document.getElementById("btnFetch").style.display = '';
			for (i=selectfield.options.length-1; i>=0; i--){ selectfield.options[i] = null; }
			for (i=0; i<pca_id.length; i++){ selectfield.options[selectfield.length] = new Option(pca_description[i], pca_id[i]); }
		}
	}
}

function pcaFetchBegin() {
	var address_id = document.getElementById("selectaddress").value;
	var scriptTag = document.getElementById("pcaScriptTag");
	var headTag = document.getElementsByTagName("head").item(0);
	var strUrl = "";
	
	//Build the url
	strUrl = "https://services.postcodeanywhere.co.uk/inline.aspx?action=fetch&id=" + escape(address_id) + "&account_code=" + escape(account_code) + "&license_code=" + escape(license_code);
	strUrl += "&machine_id=" + escape(machine_id) + "&callback=pcaFetchEnd";
	
	//Make the request
	if (scriptTag) {
		//The following 2 lines perform the same function and should be interchangeable
		headTag.removeChild(scriptTag);
		//scriptTag.parentNode.removeChild(scriptTag);
	}
	scriptTag = document.createElement("script");
	scriptTag.src = strUrl
	scriptTag.type = "text/javascript";
	scriptTag.id = "pcaScriptTag";
	headTag.appendChild(scriptTag);
	document.getElementById("selectaddress").style.display = 'none';
	document.getElementById("btnFetch").style.display = 'none';
}

function pcaFetchEnd() {
	//Test for an error
	if (pcaIsError) { alert(pcaErrorMessage); }
	else { //Check if there were any items found
		if (pcaRecordCount==0) { alert("Sorry, no matching items found"); }
		else {
			//document.forms[0]["company"].value = '' + pca_organisation_name[0];
			document.getElementById("ad1").value=pca_line1[0];
			document.getElementById("ad2").value=pca_line2[0];
			document.getElementById("ad3").value=pca_line3[0];
			document.getElementById("town").value=pca_post_town[0];
			document.getElementById("county").value=pca_county[0];
			document.getElementById("postcode").value=pca_postcode[0];
		}
	}
}




