//Update:2012-01-09


function GetXmlHttp() {
  var xmlhttp = false;
  if (window.XMLHttpRequest)
  {
    xmlhttp = new XMLHttpRequest()
  }
  else if (window.ActiveXObject)// code for IE

  {
    try
    {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP")
    } catch (e) {
      try
      {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP")
      } catch (E) {
        xmlhttp=false
      }
    }
  }
  return xmlhttp;
}



function postalAddressSame(same) {
	$('mem_homeadd').disabled = same
	$('cty_num_home').disabled = same
	$('mem_homepostcode').disabled = same
	$('cou_num_home').disabled = same	
	if (same) {
		$('mem_homeadd').value = $('mem_postaladd').value
		$('cty_num_home').value = $('cty_num_postal').value
		$('mem_homepostcode').value = $('mem_postalpostcode').value
		$('cou_num_home').value = $('cou_num_postal').value
	}
	
}

var g_target, xmlHttp, xmlHttp2

function getSubBranches(brn_num,target) {
	g_target = target
	var url = '/ajax/getBranches.php?b=' + brn_num
	xmlHttp=GetXmlHttp()
	xmlHttp.onreadystatechange=getSubBranchesDone 
	xmlHttp.open("GET",url,true)
	xmlHttp.send(null)
}

function getSubBranchesDone() {
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
		var sel = $(g_target)
		var lbl = $('lbl_' + g_target)
		removeChildrenFromNode(sel)
		sel.options[0] = new Option("N/A","")
		var ret = xmlHttp.responseText.split("\n")
		var hasSub = false
		for(var i=0;i<ret.length;i++) {
			if (ret[i]!="") {
				var val = ret[i].split(",");
				sel.options[i+1] = new Option(val[1],val[0]);
				hasSub = true
			}
		}
		sel.style.display = (hasSub)?'inline':'none'
		lbl.style.display = (hasSub)?'inline':'none'
	}

}

function removeChildrenFromNode(node) {
	while (node.hasChildNodes()) {
		node.removeChild(node.firstChild);
	}
}

function checkCCD() {
	$('ccd').style.display=($('payby_1').checked?'block':'none')
	if($('payby_2')) $('ccdx').style.display=($('payby_2').checked?'block':'none')
	if($('paydatespan')) $('paydatespan').style.display = ((($('payby_1') &&$('payby_1').checked) || ($('payby_2') && $('payby_2').checked) || ($('payby_3') && $('payby_3').checked))?'none':'inline')
}

function uploadFile() {
	$('uploadbar').style.display = 'block'
	$('uploadfield').style.display = 'none'
}

function deleteFile(target,num,id) {
	if (confirm('Are you sure you want to delete this file?')) {
		g_target = target
		var url = '/membership/filedelete.php?f=' + id + '&num=' + num
		xmlHttp=GetXmlHttp()
		xmlHttp.onreadystatechange=deleteFileDone 
		xmlHttp.open("GET",url,true)
		xmlHttp.send(null)
	}
}

function deleteFileDone() {
	g_target.parentNode.parentNode.removeChild(g_target.parentNode)
}

function uploadDone(name,type, num, id) {
	var uploadfield = $('uploadfield')
	var limitfield = $('limitfield')
	var uploaded = $('uploaded')
	$('uploadbar').style.display = 'none'
	uploadfield.style.display = 'block'
	uploadfield.innerHTML = uploadfield.innerHTML //Resets file browse box
	if (name!=0) {
		var tag = document.createElement('P')
		tag.innerHTML = '<img style="vertical-align:middle" src="/images/fileicons/' + type + '.png" alt=".' + type + ' file" /> '+ name + ' <a class="hint" href="#" onclick="deleteFile(this,' + num + ',\'' + id + '\'); return false;\">Delete</a>'
		uploaded.appendChild(tag)
	}
}

function changeToProgress() {
	$('backnext').style.display = 'none'
	$('saveprogress').style.display = 'block'
}

function doCC(name,num,e) {
	if (!e) e = window.event
	var src = $(name + '_' + num)
	src.value = src.value.replace(/([^0-9*])/g,"")
	if (e.keyCode==8 & num>1) {
		//Backspace
		var targ = $(name + '_' + (num-1))
		if (src.value.length == 0) targ.focus()
	} else {
		if (num>3) {
			src.value = src.value.substring(0,4)
		} else {
			var targ = $(name + '_' + (num+1))
			var recur = false
			if(src.value.length>4) {
				targ.value = src.value.substring(4) + targ.value	
				src.value = src.value.substring(0,4)
				recur = true
				targ.focus()
			}
			if(e.keyCode>=48 && e.keyCode<59 && src.value.length==4) targ.focus()
			if (recur) doCC(name,num+1,e)
		}
	}
	checkCC(name,$('cc_tick'))
}







function isNotArrow(evt) {
	var keycode;
	evt = (evt) ? evt : ((event) ? event : null);
	keycode = evt.keyCode;
	if (keycode==40 || keycode==38) {
		return false
	}
	else return true;
}

function okToSubmit(evt) {
	var lines = document.getElementsByClassName('invline')
	var ready = false
	for(var i=0;i<lines.length;i++) {
		if(lines[i].value!='') ready = true
	}
	var now = new Date()
	now = now.valueOf()+1000
	var date = convertDate($('invdate').value).valueOf()
	if (date>now) if (!confirm('The Invoice Date is in the future. Are you sure you\'d like to proceed?')) return false
	if (date<now-30*24*60*60*1000) if (!confirm('The Invoice Date is set to more than 30 days ago. Are you sure this is correct?')) return false
	
	now = now.valueOf()+1000
	date = convertDate($('paydate').value).valueOf()
	if (date>now) if (!confirm('The Payment Date is in the future. Are you sure you\'d like to proceed?')) return false
	if (date<now-30*24*60*60*1000) if (!confirm('The Payment Date is set to more than 30 days ago. Are you sure this is correct?')) return false
	
	if (!ready) {
		alert('There are no items on this invoice. Please ensure a description is entered for each item')	
		return false
	}
	if (confirm('Are you sure you want to create this invoice?')) {
		changeToProgress();
		return true
	} else return false	
}

function okToSubmitCreditor(evt) {
	var lines = document.getElementsByClassName('pricetot')
	var ready = false
	var glcats = true
	for(var i=0;i<lines.length;i++) {
		num = lines[i].id.substr(6)
			//qty = parseFloat($('qty_'+num).value)
			//total+= parseFloat(sources[i].value.replace(/[^0-9\.-]/g,''))
		if($('desc_' + num).value!='' && $('desc_' + num).value!='Description') {
			ready = true
			if($('line[' + num + '][glc_num]').value<1) glcats = false
		}
	}
	var now = new Date()
	now = now.valueOf()+1000
	var date = convertDate($('crd_dateinvoice').value).valueOf()
	if (date>now) if (!confirm('The Invoice Date is in the future. Are you sure you\'d like to proceed?')) return false
	if($('cos_num').value<1) {
		alert('Please select a Cost Centre for this invoice')
		return false
	}
	if (!ready) {
		alert('There are no items on this invoice. Please ensure a description is entered for each item')	
		return false
	}
	if (!glcats) {
		alert('Please select a General Ledger Category for every item on this invoice')
		return false
	}
	if (confirm('Are you sure you want to save this invoice?')) {
		changeToProgress();
		return true
	} else return false	
}

function convertDate(date) {
	var y,m,d
	date = date.split('-')
	var n = new Date()
	n.setFullYear(date[0])
	n.setMonth(parseFloat(date[1])-1)
	n.setDate(date[2])
	return n
}

function doEnter(caller,evt) {
	if (!isNotEnter(evt)) {
		caller.onblur()
	}
}
var enterpushed = false
function isNotEnter(evt) {
	var keycode;
	evt = (evt) ? evt : ((event) ? event : null);
	keycode = evt.keyCode;
	if (keycode==13 || keycode==0) {
		return false
	}
	else return true
}

var start = new Array()
var eve_num
function moveUp(name,src,prefix,field) {
	var mem_num = $(src)
	field = $(field)
	if(mem_num.value=='' || $(name).children.length==1){
		var targ = $(name).lastChild
		targ.style.backgroundColor='#e1660b'
		mem_num.value = targ.id.substr(4)
		field.value = targ.innerHTML
	} else {
		var targ = $(prefix + mem_num.value)
		targ.style.backgroundColor = ''
		if (targ.previousSibling) {
			targ.previousSibling.style.backgroundColor = '#e1660b'
			mem_num.value = targ.previousSibling.id.substr(4);
			field.value = targ.previousSibling.innerHTML
		} else {
			mem_num.value = ''
			field.value = start[prefix]
		}
	}
	if(field.value.indexOf('</')) {
		field.value = field.value.substring(field.value.toUpperCase().indexOf('<STRONG>')+8,field.value.indexOf('</'))
	}
}
function moveDown(name,src,prefix,field) {
	var mem_num = $(src)
	field = $(field)
	if(mem_num.value=='' || $(name).children.length==1){
		var targ = $(name).firstChild
		targ.style.backgroundColor='#e1660b'
		mem_num.value = targ.id.substr(4)
		field.value = targ.innerHTML
	} else {
		var targ = $(prefix + mem_num.value)
		targ.style.backgroundColor = ''
		if (targ.nextSibling) {
			targ.nextSibling.style.backgroundColor = '#e1660b'
			mem_num.value = targ.nextSibling.id.substr(4);
			field.value = targ.nextSibling.innerHTML
		} else {
			mem_num.value = ''
			field.value = start[prefix]
		}
	}
	if(field.value.indexOf('</')>-1) {
		field.value = field.value.substring(field.value.toUpperCase().indexOf('<STRONG>')+8,field.value.indexOf('</'))
	}
}
var cpyBoxID = ''
var cpyNameID = ''
var memBoxID = ''
var memNameID = ''
var secBoxID = ''
var secNameID = ''

function showCompanyLookup(object,evt,id) {
	cpyBoxID = id
	cpyNameID = object.id
	var keycode;
	evt = (evt) ? evt : ((event) ? event : null);
	keycode = evt.keyCode;
	if(keycode==40){	// Down arrow
		moveDown(id,'ser_cpy_num','cmpy',object.id)
		return false
	} else if(keycode==38){	// Up arrow
		moveUp(id,'ser_cpy_num','cmpy',object.id)
		return false
	} else if(keycode!=13) {
		if(object.value.length>2){
			xmlHttp=GetXmlHttp()
			xmlHttp.onreadystatechange=loadCompanyResults 
			xmlHttp.open("GET","/ajax/getCompanies.php?c=" + object.value,true)
			xmlHttp.send(null)
			start['cmpy'] = object.value
			if($('progressbar2')) $('progressbar2').style.display = 'inline'
			if($('noresults')) $('noresults').style.display = 'none'
			if($('selectButton2')) $('selectButton2').disabled = true
			loadingName = true
}
	}
	return true
}


function loadCompanyResults(){
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
		loadingName = false
		$(cpyBoxID).style.display = 'block';
		var ret = xmlHttp.responseText.split("\n")
		if($('progressbar2')) $('progressbar2').style.display = 'none'
		if($('selectButton2')) $('selectButton2').disabled = false
		var out = ''
		var val = ''
		var num = 0
		var thenumber = 0
		for (var i=0;i<ret.length;i++) {
			val = ret[i].split(',')
			if (val[0]>0) {
				out+= '<a href="" onclick="setCompanyValue(\'' + val[0] + '\'); return false"  id="cmpy' + val[0] + '" value="' + val[0] + '">' + val[1] + '</a>';
				num++
				thenumber = val[0]
			}
		}
		if (num>0) {
			$(cpyBoxID).style.display = 'block';	
			$('ser_cpy_num').value = ''
		} else {
			if($('noresults')) $('noresults').style.display = 'inline'
			$(cpyBoxID).style.display = 'none';	
		}
		if (num==1) {
			$('ser_cpy_num').value = thenumber
		}
		$(cpyBoxID).innerHTML = out
		
		
	} else {
		//hideNameLookup();
	}
}

function showSecLookup(object,evt,id,companies){
	if(companies==true) companies = 1
	if(companies==false) companies = 0
	secBoxID = id
	secNameID = object.id
	var keycode;
	evt = (evt) ? evt : ((event) ? event : null);
	keycode = evt.keyCode;
	var mem_num = $('mem_num')
	if(keycode==40){	// Down arrow
		moveDown(secBoxID,'sec_mem_num','secc','addname')
		return false
	} else if(keycode==38){	// Up arrow
		moveUp(secBoxID,'sec_mem_num','secc','addname')
		return false
	} else if(keycode!=13) {
		if(object.value.length>2){
			xmlHttp=GetXmlHttp()
			xmlHttp.onreadystatechange=loadSecResults 
			var cmp = '&cmp=' + companies
			xmlHttp.open("GET","/ajax/getNames.php?name=" + object.value + cmp,true)
			xmlHttp.send(null)
			start['sec'] = object.value
			if($('progressbar3')) $('progressbar3').style.display = 'inline'
			if($('noresults3')) $('noresults3').style.display = 'none'
			if($('selectButton3')) $('selectButton3').disabled = true
			loadingName = true
		}
	}
	return true
}

function showNameLookup(object,evt,id,companies){
	if(companies==true) companies = 1
	if(companies==false) companies = 0
	memBoxID = id
	memNameID = object.id
	var keycode;
	evt = (evt) ? evt : ((event) ? event : null);
	keycode = evt.keyCode;
	var mem_num = $('mem_num')
	if(keycode==40){	// Down arrow
		moveDown('suggest','mem_num','user','name')
		return false
	} else if(keycode==38){	// Up arrow
		moveUp('suggest','mem_num','user','name')
		return false
	} else if(keycode!=13) {
		if(object.value.length>2){
			xmlHttp=GetXmlHttp()
			xmlHttp.onreadystatechange=loadNameResults 
			var cmp = '&cmp=' + companies
			xmlHttp.open("GET","/ajax/getNames.php?name=" + object.value + cmp,true)
			xmlHttp.send(null)
			start['user'] = object.value
			if($('progressbar2')) $('progressbar2').style.display = 'inline'
			if($('noresults')) $('noresults').style.display = 'none'
			if($('selectButton')) $('selectButton').disabled = true
			loadingName = true
		}
	}
	return true
}

function hideSecLookup(){
	if(secBoxID)
		$(secBoxID).style.display = 'none';
}

function hideNameLookup(){
	if ($(memBoxID)) $(memBoxID).style.display = 'none';
}

function hideCpyLookup(){
	$(cpyBoxID).style.display = 'none';
}


var loadingName = false
function loadNameResults(){
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
		loadingName = false
		if($('progressbar2')) $('progressbar2').style.display = 'none'
		if($('selectButton')) $('selectButton').disabled = false
		var ret = xmlHttp.responseText.split("\n")
		var out = ''
		var val = ''
		var num = 0
		var thenumber = 0
		for (var i=0;i<ret.length;i++) {
			val = ret[i].split('~')
			if (val[0]>0) {
				out+= '<a href="" onclick="setSearchValue(\'' + val[0] + '\'); return false"  id="user' + val[0] + '" value="' + val[0] + '">' + val[1] + "\n" + '</a>';
				num++
				thenumber = val[0]
			}
		}
		if (num>0) {
			$(memBoxID).style.display = 'block';	
			$('mem_num').value = ''
		} else {
			if($('noresults')) $('noresults').style.display = 'inline'
			$(memBoxID).style.display = 'none';	
		}
		if (num==1) {
			$('mem_num').value = thenumber
		}
		$(memBoxID).innerHTML = out;
	} else {
		//hideNameLookup();
	}
}

function loadSecResults(){
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
		loadingName = false
		if($('progressbar3')) $('progressbar3').style.display = 'none'
		if($('selectButton3')) $('selectButton3').disabled = false
		var ret = xmlHttp.responseText.split("\n")
		var out = ''
		var val = ''
		var num = 0
		var thenumber = 0
		var thename = ''
		for (var i=0;i<ret.length;i++) {
			val = ret[i].split('~')
			if (val[0]>0) {
				out+= '<a href="" onclick="setSecValue(\'' + val[0] + '\'); return false"  id="secc' + val[0] + '" value="' + val[0] + '">' + val[1] + '</a>';
				num++
				thenumber = val[0]
				thename = val[1]
			}
		}
		if (num>0) {
			$(secBoxID).style.display = 'block';	
			$('sec_mem_num').value = ''
		} else {
			if($('noresults3')) $('noresults3').style.display = 'inline'
			$(secBoxID).style.display = 'none';	
		}
		if (num==1) {
			$('sec_mem_num').value = thenumber
			start['secc'] = thename
		}
		$(secBoxID).innerHTML = out;
	} else {
		//hideNameLookup();
	}
}


function setSecValue(val){
	hideSecLookup();
	var full = $('secc' + val).innerHTML
	full = full.substring(full.toUpperCase().indexOf('<STRONG>')+8,full.indexOf('</'))
	$('addname').value = full;
	$('sec_mem_num').value = val;
}

function setSearchValue(val){
	hideNameLookup();
	var full = $('user' + val).innerHTML
	full = full.substring(full.toUpperCase().indexOf('<STRONG>')+8,full.indexOf('</'))
	$('name').value = full;
	$('mem_num').value = val;
	if($('serMode')) setEmail($('serMode').value)
	if (!$('dontsubmit') && !$('setnamespan')) {
		$('name').form.submit()
	}
	else if ($('dontsubmit')) setEmail(1)
	else if ($('setnamespan')) {
		$('mem_name').innerHTML = full + '(' + val + ')'
		$('clearbutton').style.display = ''
		currentLB.deactivate()
	}
}

function setCompanyValue(val){
	$(cpyNameID).value = $('cmpy' + val).innerHTML;
	$('ser_cpy_num').value = val;
	if (!$('dontsubmit')) $(cpyNameID).form.submit()
	else setEmail(2)
}

function checkKeyDown(e) {
	var keycode;
	if (window.event){
		keycode = window.event.keyCode;
	} else if(e) {
		keycode = e.which;
	}
	if(keycode==40){	// Down arrow
		if(checkHighlighted()==-1){
			$('suggest').firstChild.style.backgroundColor='#e1660b';
		}
	}
}

function checkHighlighted(){
	var num = $('mem_num').value 
	if (num) {
		return 'user' + num
	} else return -1;

}

function goAdvanced(btn) {

	if (btn.value.substr(0,1)=='A') {
		btn.value="\u00AB Simple"
		$('advancedSearch').style.display = 'block'
//		$('simpleSearch').style.display = 'none'
		$('isAdvanced').value = 1
	} else {
		btn.value="Advanced \u00BB"
		$('advancedSearch').style.display = 'none'
//		$('simpleSearch').style.display = 'inline'
		$('isAdvanced').value = 0
	}
}
function chooseTaba(caller,num) {
	for (var i=1;i<=6;i++) {
		if ($('tab_' + i)) $('tab_' + i).style.display = 'none'
	}
	$('tab_' + num).style.display = 'block'
	var sources = document.getElementsByClassName('taba')
	sources[0].className = 'tabi'
	caller.className = 'taba'
	
}

var supress = false

function doSupress() {
	supress = true	
}

function chooseTab(num) {
	if (num==1) {
		$('membertab').className = 'taba'
		$('companytab').className = 'tabi'
		$('memberset').style.display = 'block'
		$('companyset').style.display = 'none'
	} else {
		$('membertab').className = 'tabi'
		$('companytab').className = 'taba'
		$('memberset').style.display = 'none'
		$('companyset').style.display = 'block'	
	}
	$('serMode').value = num
	supress = true
	setEmail(num)
}

function doQty(num) {
	if ($('price_'+num).style.color.toLowerCase() == '#aaaaaa') doEx(num)
	else doInc(num)
}

function doEx(num) {
	var source = $('inc_'+num)
	var targ = $('price_'+num)
	var total = $('total_'+num)?$('total_'+num):null
	var qty = $('qty_'+num)?$('qty_'+num).value:1
	source.value = source.value.replace(/[^0-9\.-]/g,'')
	if (!isNumeric(source.value)) source.value = 0
	targ.value = '$' + Math.round((source.value/(1+tax))*100)/100
	if(total) total.value = '$' + Math.round(source.value*qty*100)/100
	source.value = '$' + Math.round(source.value*100)/100
	doDecimals(targ)
	doDecimals(source)
	if(total) {
		doDecimals(total)
		$('dtotal_'+num).innerHTML = total.value
		doTotals()
		source.style.color = ''
		targ.style.color = '#aaaaaa'
	}
}

function doInc(num) {
	var targ = $('inc_'+num)
	var source = $('price_'+num)
	var total = $('total_'+num)?$('total_'+num):null
	var qty = $('qty_'+num)?$('qty_'+num).value:1
	source.value = source.value.replace(/[^0-9\.-]/g,'')
	if (!isNumeric(source.value)) source.value = 0
	targ.value = '$' + Math.round((source.value*(1+tax))*100)/100
	if(total) total.value = '$' + Math.round((source.value*(1+tax)*qty)*100)/100
	source.value = '$' + Math.round(source.value*100)/100
	doDecimals(targ)
	doDecimals(source)
	if(total) {
		doDecimals(total)
		$('dtotal_'+num).innerHTML = total.value
		doTotals()
		source.style.color = ''
		targ.style.color = '#aaaaaa'
	}
}

function doVoucher(num) {
	var text = $('voucher_'+num)
	var chk = $('vis_'+num)
	chk.disabled = text.value==''?false:true
}


function isNumeric(sText){
   var validChars = "0123456789.";
   var isNumber=true;
   var numDots = 0
   for (i = 0; i < sText.length && isNumber == true; i++) {
      if (validChars.indexOf(sText.charAt(i)) == -1) isNumber = false;
	  if (i==0 && sText.charAt(i)=='-') isNumber = true
	  if (sText.charAt(i)=='.') numDots++
   }
   if (numDots>1) isNumber = false
   return isNumber;
 }

function getDecimal(num) {
	newnum = num.replace(/[^0-9\.-]/g,'')
	var dollars = ''
	if (newnum!=num) dollars = '$'
	num = '' + Math.round(parseFloat(newnum)*100)/100
	var point = num.lastIndexOf('.')
	if (point==-1) num+='.00'
	else if (point+3>num.length) num+='0'
	return dollars + num
}

function doDecimals(targ) {
	var point = targ.value.lastIndexOf('.')
	if (point==-1) targ.value+='.00'
	else if (point+3>targ.value.length) targ.value+='0'
}

function loadEVC(num) {
	var table = $('invtable')
	if((table.childNodes.length<=2) || confirm('Are you sure want to load this template? This will overwrite any charges already entered below')) {
		while(table.firstChild.nextSibling.nextSibling) {
			table.removeChild(table.firstChild.nextSibling)	
		}
		xmlHttp=GetXmlHttp()
		xmlHttp.onreadystatechange=loadEVCResults
		xmlHttp.open("GET","/ajax/getEVC.php?e=" + num,true)
		xmlHttp.send(null)
		$('loadingEVC').style.display = 'block'
	}
}

function loadEVCResults() {
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
		var ret = xmlHttp.responseText.split("\n")
		$('show_cp').checked = false
		$('inc_cp').value = 0
		doEx('cp')
		for(var i=0;i<ret.length;i++) {
			var line = ret[i].split(',')
			if (line.length==3) {
				if(line[0]>0) addEvRow(line[0],line[1],line[2])
				else {
					$('show_cp').checked = line[2]?true:false
					$('inc_cp').value = line[1]
					doEx('cp')
				}
			}
		}
		$('loadingEVC').style.display = 'none'
	}
}

function addEvRowCheck(num,value) {
	if(num==(row-1) && value!=0) addEvRow(0,0,0)
}

function addRowCheck(num,value) {
	if(num==(row-1) && value) addRow()
}

function deleteEvRow(caller) {
	if(caller.parentNode.parentNode.nextSibling) {
		caller.parentNode.parentNode.parentNode.removeChild(caller.parentNode.parentNode)	
	}
}

function addExtRow() {
	highestExtraRow++
	extraRowClass = 1-extraRowClass
	var targ = $('extraTable')
	var tag = document.createElement('TR')
	tag.className = 'row' + extraRowClass
	var cell1 = document.createElement('TD')
	var cell2 = document.createElement('TD')
	var cell3 = document.createElement('TD')
	var cell4 = document.createElement('TD')
	var cell5 = document.createElement('TD')
	var cell6 = document.createElement('TD')
	cell1.innerHTML = '<input name="extra['+highestExtraRow+'][ext_name]" />'
	cell2.innerHTML = '<select name="extra['+highestExtraRow+'][ext_type]" onchange="checkExtNumber(this)"><option value="0" selected="selected">Labell Only</option><option value="1" selected="selected">Short Text</option><option value="2" >Long Text</option><option value="3" >Date</option><option value="4" >Checkbox</option><option value="5" >Number</option></select>'
	cell3.innerHTML = '<input name="extra['+highestExtraRow+'][ext_max]" value="10" style="width:20px; display:none" />'
	cell4.innerHTML = '<input name="extra['+highestExtraRow+'][ext_cost]" style="width:50px; display:none" />'
	cell5.innerHTML = '<input type="checkbox" name="extra['+highestExtraRow+'][ext_compulsory]" value="1"  />'
	cell6.innerHTML = '<input type="checkbox" name="extra['+highestExtraRow+'][ext_active]" value="1" checked="checked" />'
	tag.appendChild(cell1)
	tag.appendChild(cell2)
	tag.appendChild(cell3)
	tag.appendChild(cell4)
	tag.appendChild(cell5)
	tag.appendChild(cell6)
	targ.appendChild(tag)
}

function addTCORow() {
	highestTCORow++
	extraRowClass = 1-extraRowClass
	var targ = $('tcoTable')
	var tag = document.createElement('TR')
	tag.className = 'row' + extraRowClass
	var cell1 = document.createElement('TD')
	var cell2 = document.createElement('TD')
	var cell3 = document.createElement('TD')
	var cell4 = document.createElement('TD')
	cell1.innerHTML = '<input name="offerings['+highestTCORow+'][tco_name]" maxlength="50"/><br /><select name="offerings['+highestTCORow+'][tco_type]"><option value="1">Training</option><option value="2">Testing</option><option value="3">Training + Testing</option></select>'
	cell2.innerHTML = '<textarea name="offerings['+highestTCORow+'][tco_desc]" style="width:280px; height:70px" class="resizable"></textarea>'
	cell3.innerHTML = '<input name="offerings['+highestTCORow+'][tco_freq]" maxlength="50" style="width:100px" />'
	cell4.innerHTML = '<input name="offerings['+highestTCORow+'][tco_cost]" style="width:100px" maxlength="50" /><br /><a href="#" onclick="removeObject(this.parentNode.parentNode,\'Offering\'); return false" style="float:right"><img src="/images/cross.png" alt="Delete this Offering" /></a>'
	tag.appendChild(cell1)
	tag.appendChild(cell2)
	tag.appendChild(cell3)
	tag.appendChild(cell4)
	targ.appendChild(tag)
	initTextareas()
}

function checkExtNumber(field) {
	var targ = field.parentNode.nextSibling.firstChild
	targ.style.display = field.value==5?'':'none'
	
	targ = field.parentNode.nextSibling.nextSibling.firstChild
	targ.style.display = field.value>3?'':'none'
}

function addEvRow(ecc,price,vis) {
	var targ = $('invtable')
	var tag = document.createElement('TR')
	var cell1 = document.createElement('TD')
	var cell2 = document.createElement('TD')
	var cell3 = document.createElement('TD')
	var cell4 = document.createElement('TD')
	var cell5 = document.createElement('TD')
	cell1.innerHTML = '<select name="charges['+row+'][0]" id="charges['+row+'][0]" style="width:280px" onblur="addEvRowCheck('+row+',this.value)" >' + opts + '</select>'
	cell2.innerHTML = '<input name="charges['+row+'][4]" id="price_'+row+'" style="width:80px" value="$0.00" onblur="doInc('+row+')" class="priceex"/> '
	cell3.innerHTML = '<input name="charges['+row+'][1]" id="inc_'+row+'" style="width:80px" value="$0.00" onblur="doEx('+row+')" class="priceinc" /> '
	
	cell4.innerHTML = '<td><input name="charges['+row+'][3]" id="voucher_'+row+'" onchange="doVoucher('+row+')" onkeyup="doVoucher('+row+')" /></td>'
	
	cell5.innerHTML = '<input name="charges['+row+'][2]" type="checkbox" value="1" id="vis_'+row+'" checked="checked" /> <img src="/images/cross.png" style="vertical-align:middle" onclick="deleteEvRow(this)" alt="Delete this charge" />'
	tag.appendChild(cell1)
	tag.appendChild(cell2)
	tag.appendChild(cell3)
	tag.appendChild(cell4)
	tag.appendChild(cell5)
	if(ecc>0) {
		targ.insertBefore(tag,targ.lastChild)
		$('charges['+row+'][0]').value = ecc
		$('vis_'+row+'').checked = vis==1
		$('inc_'+row+'').value = price
		doEx(row)
	} else {
		targ.appendChild(tag)
	}
	
	row++
}

function addRow() {
	var targ = $('invtable')
	var credit = false
	var adjustment = false
	if (!targ) {
		targ = $('creditinvtable')
		credit = true
	}
	if (!targ) {
		targ = $('adjustmenttable')
		credit = false
		adjustment = true
	}
	var tag = document.createElement('TR')
	var tag2 = document.createElement('TR')
	var cell1 = document.createElement('TD')
	var cell2 = document.createElement('TD')
	var cell3 = document.createElement('TD')
	var cell4 = document.createElement('TD')
	var cell5 = document.createElement('TD')
	var cell6 = document.createElement('TD')
	if (!adjustment) cell1.innerHTML = '<input maxlength="255" name="line['+row+'][desc]" style="width:' + (credit?'458':'240') + 'px" onblur="addRowCheck('+row+',this.value)" class="fader" id="desc_'+row+'"/> '
	cell2.innerHTML = '<input name="line['+row+'][qty]" style="width:50px" value="1" id="qty_'+row+'" onblur="doQty('+row+'); doTotals()" /> '
	cell3.innerHTML = '<input name="line['+row+'][price]" id="price_'+row+'" style="width:70px" value="$0.00" onblur="if(tmp!=this.value) doInc('+row+')" onfocus="tmp=this.value; this.select()" class="priceex"/> '
	cell4.innerHTML = '<input name="line['+row+'][inc]" id="inc_'+row+'" style="width:70px" value="$0.00" onblur="if(tmp!=this.value) doEx('+row+')" onfocus="tmp=this.value; this.select()" class="priceinc" /> '
	cell5.innerHTML = '<input name="line['+row+'][total]" id="total_'+row+'" style="width:70px" value="$0.00" class="pricetot" type="hidden"/><span id="dtotal_'+row+'"></span> '
	cell5.style.paddingRight = '5px'
	cell5.style.textAlign = 'right'
	
	if (credit || adjustment) {
		if (adjustment) {
			//Generate cost centre drop-down
			cell1.innerHTML = '<strong>Cost Centre:</strong> ';
			var sel = document.createElement('SELECT')
			sel.name = "line[" + row + "][cos_num]"
			sel.onblur = 'addRowCheck(' + row + ',this.value)'
			for (var i = 0; i < costcentres.length; i++) {
				var line = document.createElement('OPTION')
				line.innerHTML = costcentres[i][1]
				line.value = costcentres[i][0]
				sel.appendChild(line)
			}
			cell1.appendChild(sel)
		}
		tag.appendChild(cell1)
		var sel = document.createElement('SELECT')
		sel.style.width = '232px'
		sel.name = "line[" + row + "][glc_num]"
		for (var i = 0; i < glcats.length; i++) {
			var line = document.createElement('OPTION')
			line.innerHTML = glcats[i][1]
			line.value = glcats[i][0]
			sel.appendChild(line)
		}
		cell6.innerHTML = '&nbsp;&nbsp;'
		cell6.appendChild(sel)
		tag2.appendChild(cell6)
		tag2.appendChild(cell2)
		tag2.appendChild(cell3)
		tag2.appendChild(cell4)
		tag2.appendChild(cell5)
		cell1.colSpan = 5
		cell1.className = 'topline'
		tag.className = tag2.className = 'row' + (row%2)
		targ.appendChild(tag)
		targ.appendChild(tag2)
	} else {
		tag.appendChild(cell1)
		tag.appendChild(cell2)
		tag.appendChild(cell3)
		tag.appendChild(cell4)
		tag.appendChild(cell5)
		targ.appendChild(tag)
	}
	row++
}

function doTotals() {
	if($('totalinc')) {
		var sources = document.getElementsByClassName('pricetot');
		var total = 0
		var num, qty
		for(i = 0; i < sources.length; i++) {
			num = sources[i].id.substr(4)
			//qty = parseFloat($('qty_'+num).value)
			total+= parseFloat(sources[i].value.replace(/[^0-9\.-]/g,''))
		}
		$('totalex').innerHTML = '<strong>Total:</strong> (' + getDecimal('$' + (total/(1+tax))) + ' ex GST) '
		$('totalinc').innerHTML = getDecimal('$' + total)
		
	/*	sources = document.getElementsByClassName('priceex');
		total = 0
		for(i = 0; i < sources.length; i++) {
			num = sources[i].id.substr(6)
			qty = parseFloat($('qty_'+num).value)
			total+= qty*parseFloat(sources[i].value.replace(/[^0-9\.-]/g,''))
		}
		targ = $('totalex')
		$('totalex').innerHTML = getDecimal('$' + total)*/
		return total
		//doDecimals(targ)
	}else return 0
}

var curnum = 0
var numloaded = false
var ser_modeg

function setEmail(ser_mode) {
	var newnum
	ser_modeg = ser_mode
	var oktogo = false
	if (ser_mode==1) {
		var mem_num = $('mem_num').value
		if (mem_num) {
			newnum = mem_num
			if (newnum!=curnum || !numloaded) {
				xmlHttp=GetXmlHttp()
				xmlHttp2 = GetXmlHttp()
				xmlHttp.onreadystatechange = setDetailReturn
				xmlHttp2.onreadystatechange = setEmailReturn
				xmlHttp.open("GET","/ajax/getMemDetails.php?cc=1&m=" + mem_num,true)
				xmlHttp2.open("GET","/ajax/getMemEmail.php?m=" + mem_num,true)
				oktogo = true
			}
		} else {
			//alert("Please select a member")
		}
	} else {
		if ($('ser_cpy_num')) var cpy_num = $('ser_cpy_num').value
		if (cpy_num) {
			newnum = cpy_num
			if (newnum!=curnum || !numloaded) {
				xmlHttp=GetXmlHttp()
				xmlHttp2 = GetXmlHttp()
				xmlHttp.onreadystatechange = setDetailReturn
				xmlHttp2.onreadystatechange = setEmailReturn
				xmlHttp.open("GET","/ajax/getCpyDetails.php?cc=1&c=" + cpy_num,true)
				xmlHttp2.open("GET","/ajax/getCpyEmail.php?c=" + cpy_num,true)
				oktogo = true
			}
		} else {
			//alert("Please select a member")
		}
	}
	if (newnum==curnum && numloaded) {
		
	} else {	
		$('invDetail').style.display = 'none'
		if (oktogo) {
			if($('savedCC')) {
				$('savedCC').innerHTML = ''
				$('payby_2').disabled = true
				$('payby_2').nextSibling.style.color = '#999'
			}
			$('invLoading').style.display = 'block'
			xmlHttp.send(null)
			xmlHttp2.send(null)
		}
		
		
	}
	curnum = newnum
}

function setDetailReturn() {
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
		$('invLoading').style.display = 'none'
		if(xmlHttp.responseText) {
			res = xmlHttp.responseText.split('~')
			if (res.length==2) {
				if($('savedCC')) $('savedCC').innerHTML = res[1]
				if($('payby_2')) {
						$('payby_2').disabled = false
						$('payby_2').nextSibling.style.color = ''
				}
			}
			$('details').innerHTML = res[0]
			$('invDetail').style.display = 'block'
			if ($('cos_num')) $('cos_num').focus()
			if ($('sec_mem_num') && eve_num) {
				addAttendee($('mem_num').value,eve_num)
			}
			if ($('editlink')) {
				if(ser_modeg==1) {
					$('editlink').href = '/system/details/update=' + $('mem_num').value
					$('editlink').innerHTML = 'Edit Member Details'
				} else {
					$('editlink').innerHTML = ''
				}
			} 
		} else {
			alert("Please select a member")	
		}
	}
	numloaded = true
}

function setEmailReturn() {
	if (xmlHttp2.readyState==4 || xmlHttp2.readyState=="complete") {
		if(xmlHttp2.responseText) {
			if($('email')) $('email').value = xmlHttp2.responseText
		} else {
			//alert("The selected user ")	
		}
	}
}

function isNumber(evt) {
	var keycode;
	evt = (evt) ? evt : ((event) ? event : null);
	keycode = evt.keyCode;
	if ((keycode>57 && keycode<127)) {
		return false	
	} else {
		return true
	}
}

function deleteNotice(targ) {
	targ.parentNode.parentNode.removeChild(targ.parentNode)	
}

var emailBox
function checkEmail(src,mem_num) {
	emailBox = src
	xmlHttp=GetXmlHttp()
	xmlHttp.onreadystatechange = checkEmailReturn
	xmlHttp.open("GET","/ajax/checkEmail.php?e=" + src.value + '&m=' + mem_num,true)
	xmlHttp.send(null)	
	$(emailBox.id + '_after').innerHTML = '<div style="text-align:center"><img src="/images/progress.gif" /></div>'
	emailBox.parentNode.style.border = '0'
}

function checkEmailReturn() {
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
		var ret = xmlHttp.responseText
		if(ret==0) {	
			$(emailBox.id + '_after').innerHTML = '<img src=\"/images/tick.png\" />'
		} else if (ret==1) {
			$(emailBox.id + '_after').innerHTML = '<img src=\"/images/cross.png\" /><div style="font-size:10px; padding:0 3px">This email address is already in use. If you have forgotten your password, please <a href="/members/forgot">reset it here</a>.</div>'
			emailBox.parentNode.style.border = '2px solid #FF0000'
		} else {
			$(emailBox.id + '_after').innerHTML = '<img src=\"/images/cross.png\" /><br/>Please enter a valid email address'
			emailBox.parentNode.style.border = '2px solid #FF0000'
		}
	}
}

var editing
var today, todayf

function changeNotice(caller) {
	editing = caller
	var i = caller.getElementsByTagName('INPUT')
	var d = convertDate(i[1].value)
	var mo = new Array('January','February','March','April','May','June','July','August','September','October','November','December')
	$('newNotices').value = i[0].value
	$('newNoticed_disp').innerHTML = d.getDate() + ' ' + mo[d.getMonth()] + ' ' + d.getFullYear()
	$('newNoticed').value = i[1].value
	$('addnotice').style.display = 'block'
}

function addNotice() {
	numNotices++
	var out = ''
	var newObject = document.createElement('TR')
	var sel = $('newNotices').value
	var types = new Array(4)
	types[1]= 'New Event'
	types[2]= 'Reminder'
	types[3]= 'Final Reminder'
	types[4]= 'Attendance Reminder'
	var weekday=new Array(7)
	weekday[0]="Sunday"
	weekday[1]="Monday"
	weekday[2]="Tuesday"
	weekday[3]="Wednesday"
	weekday[4]="Thursday"
	weekday[5]="Friday"
	weekday[6]="Saturday"
	var month = new Array(12)
	month[0] = 'Jan'
	month[1] = 'Feb'
	month[2] = 'Mar'
	month[3] = 'Apr'
	month[4] = 'May'
	month[5] = 'Jun'
	month[6] = 'Jul'
	month[7] = 'Aug'
	month[8] = 'Sept'
	month[9] = 'Oct'
	month[10] = 'Nov'
	month[11] = 'Dec'
	if ($('newNoticed_disp').innerHTML!='') {	
		var date = $('newNoticed').value.split('-')
		var d = new Date(date[0],parseFloat(date[1])-1,date[2])
		var td1 = document.createElement('TD')
		var td2 = document.createElement('TD')
		var td3 = document.createElement('TD')
		var td4 = document.createElement('TD')
		td1.innerHTML = '<strong>' + d.getDate() + ' ' + month[d.getMonth()] + ' ' + d.getFullYear() + '</strong>'
		td2.innerHTML = ' ' + weekday[d.getDay()]
		td3.innerHTML = types[$('newNotices').value]
		td4.innerHTML = '<span class="hint">(<a class="editlink2" onclick="changeNotice(this.parentNode.parentNode.parentNode)">Change</a> or <a class="editlink2" onclick="deleteNotice(this.parentNode.parentNode)">Delete</a>)</span>'
		td4.innerHTML+= '<input type="hidden" name="notices['+numNotices+'][0]" value="'+$('newNotices').value+'" id="notices['+numNotices+'][0]" />'
		td4.innerHTML+= '<input type="hidden" name="notices['+numNotices+'][1]" value="'+$('newNoticed').value+'" id="notices['+numNotices+'][1]" />'
		td4.innerHTML+= '<input type="hidden" name="notices['+numNotices+'][2]" value="0" id="notices['+numNotices+'][2]" />'
		
		if (editing) {
			//alert(editing)
			//editing.innerHTML = out	
			removeChildrenFromNode(editing)
			editing.appendChild(td1)
			editing.appendChild(td2)
			editing.appendChild(td3)
			editing.appendChild(td4)
		} else {
			newObject.appendChild(td1)
			newObject.appendChild(td2)
			newObject.appendChild(td3)
			newObject.appendChild(td4)
			//alert($('notifications1').firstChild.firstChild.innerHTML)
			if($('newNotices').value=='4') {
				if($('notifications2').firstChild.tagName == 'TBODY')
					$('notifications2').firstChild.appendChild(newObject)
				else 
					$('notifications2').appendChild(newObject)
			} else {
				if($('notifications1').firstChild.tagName == 'TBODY')
					$('notifications1').firstChild.appendChild(newObject)
				else
					$('notifications1').appendChild(newObject)
			}
		}
		$('newNotices').value = '2'
		$('newNoticed').value = today
		$('newNoticed_disp').innerHTML = todayf
		editing = null
		$('addnotice').style.display = 'none'
	} else {
		alert('Please select a date')	
	}
}

function checkEmailDateLabel() {
	$('datelabel').innerHTML = (!$('anydate').checked && $('isdrange').checked)?'Start Date:':'Date:';
}

function checkDateLabel() {
	$('datelabel').innerHTML = (!$('anydate').checked && $('isdrange').checked)?'Invoice Start Date:':'Invoice Date:';
	if($('pdatelabel')) 
		$('pdatelabel').innerHTML = (!$('anypdate').checked && $('isprange').checked)?'Start Paid Date:':'Paid Date:';
}

function sendStatement(num,type) {
	var add = $('snd_email').value
	var mess = $('snd_message').value	
	$('lightbox').className = "loading";
	xmlHttp=GetXmlHttp()
	xmlHttp.onreadystatechange = lbResponse
	xmlHttp.open("GET","/ajax/sendStatement.php?t=' + type + '&i=" + num + '&e=' + escape(add) + '&m=' + escape(mess),true)
	xmlHttp.send(null)	
}

function sendReport(data) {
	var add = $('snd_email').value
	var mess = $('snd_message').value	
	$('lightbox').className = "loading";
	var url = "/ajax/sendReport.php?"
	if (data.sur_num){url += "s=" + data.sur_num + "&"}
	if (data.sur_show) {url += "showall=" + data.sur_show + "&"}
	if (data.sur_numbers) {url += "nonumbers=" + data.sur_numbers + "&"}
	if (data.sur_privacy) {url += "privacy=" + data.sur_privacy + "&"}
	if (data.qst_num) {url += "q=" + data.qst_num + "&"}
	if (data.go) {url += "go=" + data.go + "&"}
	if (data.k) {url += "k=" + data.k + "&"}
	url += 'e=' + escape(add) + '&m=' + escape(mess)
	xmlHttp=GetXmlHttp()
	xmlHttp.onreadystatechange = lbResponse
	xmlHttp.open("GET",url,true)
	xmlHttp.send(null)	
}

function sendInvoice(num) {
	var add = $('snd_email').value
	var mess = $('snd_message').value	
	$('lightbox').className = "loading";
	xmlHttp=GetXmlHttp()
	xmlHttp.onreadystatechange = lbResponse
	xmlHttp.open("GET","/ajax/sendInvoice.php?i=" + num + '&e=' + escape(add) + '&m=' + escape(mess),true)
	xmlHttp.send(null)	
}

function lbResponse() {
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
		var ret = xmlHttp.responseText
		$('lightbox').className = "done";
		$('lbContent').innerHTML = ret
		currentLB.actions()
	}
}

var tmpLoadTarg

function loadTemplate(num, targ) {
	tmpLoadTarg = targ
	if (tinyMCE.get(targ).getContent()=='' || confirm('Are you sure? This will overwrite all details below.')) {
		xmlHttp=GetXmlHttp()
		xmlHttp.onreadystatechange = loadTemplateDone
		xmlHttp.open("GET","/ajax/getTemplate.php?e=" + num,true)
		xmlHttp.send(null)		
	}
}

function loadTemplateDone() {
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
		tinyMCE.get(tmpLoadTarg).setContent(xmlHttp.responseText)
	}
}

function addAttendee(mem_num, eve_num) {
	var voucher = ''
	if ($('voucher')) voucher = $('voucher').value
	if (mem_num>0) {
		if (findInArray(mem_num,signedup)==-1) {
			xmlHttp=GetXmlHttp()
			xmlHttp.onreadystatechange = doAddAttendee
			xmlHttp.open("GET","/ajax/getEventPrice.php?m=" + mem_num + '&e=' + eve_num + '&v=' + voucher,true)
			xmlHttp.send(null)
			$('progressbar3').style.display = 'block'
			$('addbutton').disabled = true
		} else {
			if (!supress)alert('You can not register the same person twice.')
			supress = false
			$('sec_mem_num').value = ''
			$('addname').value = ''
		}
	}
}
var count = 0
function doAddAttendee() {
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
		var rep = xmlHttp.responseText.split('~')
		if(rep[0]==-3) {
			//Is a company hopefully!
			$('clickToAdd').onclick()
		} else if(rep[0]==-2) {
			alert('The selected person has already registered for this event. Please contact NZCS if you don\'t believe this is correct')
		} else if(rep[0]==-1 && !isAdmin) {
			alert('The selected person is not eligible for this event. Please contact NZCS if you don\'t believe this is correct')
		} else {
			var allowed = true
			var ineligible = false
			if(rep[0]==-1 && isAdmin) {
				allowed = confirm('The selected person is NOT eligible for this event.\n\nAre you sure you wish to proceed?')
				ineligible = true
			}
			if(allowed) {
				var ok = rep[3].split(',')
				signedup.push(rep[1])
				count++
				var newrow = document.createElement('TR')
				var td1 = document.createElement('TD')
				var td2 = document.createElement('TD')
				var td3 = document.createElement('TD')
				var td4 = document.createElement('SPAN')
				var td5 = document.createElement('TD')
				var sel = document.createElement('SELECT')
				for (var i in types) if(i>=0 && i<999) {
					var opt = document.createElement('OPTION')
					opt.innerHTML = names[i] + ': $' + getDecimal('' + types[i])
					opt.value = i
					if (i==rep[0]) opt.selected = true
					if(findInArray(i,ok)==-1) {
						opt.className = 'ineligible'
						if(isAdmin) sel.appendChild(opt)
					} else {
						sel.appendChild(opt)
					}
					if(ineligible) {
						rep[0] = i
						ineligible = false
					}
				}
				sel.name = "type[" + count + "]"
				sel.value = rep[0]
				td1.innerHTML = '<input type="hidden" name="attendee[' + count + ']" value="' + rep[1] + '" />' + rep[1]
				td1.className = 'hint'
				td2.innerHTML = rep[2]
				td3.appendChild(sel)
				td4.className = 'price'
				td4.innerHTML = getDecimal('' + types[rep[0]])
				td4.style.display = 'none'
				td5.innerHTML = '<a href="" onclick="deleteAttendee(this.parentNode,\'' + rep[1] + '\'); regTotal(); return false;"><img src="/images/cross.png" /></a>'
				newrow.appendChild(td1)
				newrow.appendChild(td2)
				newrow.appendChild(td3)
				td3.appendChild(td4)
				newrow.appendChild(td5)
				$('invtable').appendChild(newrow)
				sel.onchange = function() {
					this.nextSibling.innerHTML = getDecimal('' + types[this.value])
					regTotal()
				}
				sel.onclick = "this.onchange()"
			}
		}
		$('progressbar3').style.display = 'none'
		$('sec_mem_num').value = ''
		$('addname').value = ''
		$('addbutton').disabled = false
		regTotal()
	}
}


function deleteAttendee(targ,num) {
	targ.parentNode.parentNode.removeChild(targ.parentNode)
	signedup[findInArray(num,signedup)] = 0
}


function regTotal() {
	if($('totalprice')) {
		var sources = document.getElementsByClassName('price');
		var total = 0
		for(var i = 0; i < sources.length; i++) {
			total+= parseFloat(sources[i].innerHTML.replace(/[^0-9\.-]/g,''))
		}
		var targ = $('totalprice')
		targ.innerHTML = '$' + getDecimal('' + total)
		if ($('pay0')) {
			if (total>0) {
				$('pay1').style.display = 'block'
				$('pay0').style.display = 'none'	
			} else {
				$('pay0').style.display = 'block'
				$('pay1').style.display = 'none'	
			}
			$('summary').style.display = (sources.length==0)?'none':'block'
		}
	}
	if($('invtable')) {
		var row = $('invtable').firstChild
		var num = 1
		while (row) {
			num = 1-num
			row.className = 'row' + num
			row = row.nextSibling	
		}
	}
}

function findInArray(needle, haystack) {
    var found = -1, key;
 
    for (key in haystack) {
        if (haystack[key] == needle) {
            found = key;
            break;
        }
    }
 
    return found;
}

function urlencode(str) {
	return escape(str).replace(/\+/g,'%2B').replace(/%20/g, '+').replace(/\*/g, '%2A').replace(/\//g, '%2F').replace(/@/g, '%40');
}
   	
	
function addMember() {
	var fields = new Array('mem_fname','mem_mname','mem_lname','mem_prefname','mem_gender','mem_email','mem_postaladd','cty_num_postal','mem_postalpostcode','cou_num_postal','cpy_num','mem_companyother','bra_num','sub_num','typ_num','formID','invite')
	var url = '/ajax/addMember.php'
	var params = ''
	for(var i=0;i<fields.length;i++) {
		if ($(fields[i])) params+= fields[i] + '=' + urlencode($(fields[i]).value) + '&'
	}
	if($('mem_gender_1') && $('mem_gender_1').checked) params+= 'mem_gender=1&'
	else if($('mem_gender_2') && $('mem_gender_2').checked) params+= 'mem_gender=2&'
	xmlHttp=GetXmlHttp()
	xmlHttp.onreadystatechange = doAddMember
	xmlHttp.open("POST",url,true)
	xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlHttp.setRequestHeader("Content-length", params.length);
	xmlHttp.setRequestHeader("Connection", "close");
	xmlHttp.send(params)
	$('backnext').style.display = 'none'
	$('saveprogress').style.display = 'block'
	$('errorSection').style.display = 'none'
	$('errorMessages').innerHTML = ''
	var err = document.getElementsByClassName('error')
	for(var i=0;i<err.length;i++) {
		if(err[i].id != 'errorSection') err[i].className = ''
	}
	
}

function doAddMember() {
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
		$('backnext').style.display = 'block'
		$('saveprogress').style.display = 'none'
		var res = xmlHttp.responseText.split('~')
		if (res[0]=='0') {
			$('errorSection').style.display = 'block'
			$('errorMessages').innerHTML = res[2] + '<br/>'
			var err = res[1].split(',')
			for(var i=0;i<err.length;i++) {
				$(err[i]).className = 'error'
			}
			$('lightbox').scrollTop = 0
		} else {
			addAttendee(res[1],eve_num)
			currentLB.deactivate()
		}
	}	
}
	
function addCompany() {
	var fields = new Array('ctt_num','cpy_name','cpy_contactemail','cpy_accountemail','cpy_postaladd','cty_num','cpy_postcode','cou_num','cpy_url','bra_num','sub_num','cpy_invoicemonth', 'img_num', 'cpy_status', 'cpy_visible', 'cpy_algim', 'cpy_description','formID')
	var url = '/ajax/addCompany.php'
	var params = ''
	for(var i=0;i<fields.length;i++) {
		if ($(fields[i])) params+= fields[i] + '=' + urlencode($(fields[i]).value) + '&'
	}
	if($('cpy_visible') && $('cpy_visible').checked) params+= 'cpy_visible=1&'
	if($('cpy_algim') && $('cpy_algim').checked) params+= 'cpy_algim=1&'
	xmlHttp=GetXmlHttp()
	xmlHttp.onreadystatechange = doAddCompany
	xmlHttp.open("POST",url,true)
	xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlHttp.setRequestHeader("Content-length", params.length);
	xmlHttp.setRequestHeader("Connection", "close");
	xmlHttp.send(params)
	$('backnext').style.display = 'none'
	$('saveprogress').style.display = 'block'
	$('errorSection').style.display = 'none'
	$('errorMessages').innerHTML = ''
	var err = document.getElementsByClassName('error')
	for(var i=0;i<err.length;i++) {
		if(err[i].id != 'errorSection') err[i].className = ''
	}
	
}

function doAddCompany() {
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
		$('backnext').style.display = 'block'
		$('saveprogress').style.display = 'none'
		var res = xmlHttp.responseText.split('~')
		if (res[0]=='0') {
			$('errorSection').style.display = 'block'
			$('errorMessages').innerHTML = res[2] + '<br/>'
			var err = res[1].split(',')
			for(var i=0;i<err.length;i++) {
				$(err[i]).className = 'error'
			}
			$('lightbox').scrollTop = 0
		} else {
			if($('mem_num')) $('mem_num').value = res[1]
			if($('cpy_num')) $('cpy_num').value = res[1]
			if($('name')) $('name').value = res[2]
			currentLB.deactivate()
			setEmail(1)
		}
	}	
}

function sendReminder(num,key) {
		xmlHttp=GetXmlHttp()
		$('maincontent').innerHTML = '<img src="/images/progress.gif" alt="Sending"><br/>Sending... Please Wait'
		xmlHttp.onreadystatechange = function() {
			if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
				if(xmlHttp.responseText=='1') {
					$('doSend').style.display = 'none'
					$('deactivate').value = 'Close'
					$('maincontent').innerHTML = 'This reminder was successfully sent'
				} else {
					$('maincontent').innerHTML = 'Are you are you want to send a reminder to all selected members about this event?'
					alert("There was an error and this reminder could NOT be sent")	
				}
			}
		}
		xmlHttp.open("GET","/ajax/sendReminder.php?e=" + num + '&k=' + key,true)
		xmlHttp.send(null)			
}

var FAQIsEdit = false

function FAQClick(obj) {
	if(obj && obj.nextSibling.style.display == 'block') obj.nextSibling.style.display = 'none'
	else {
		var a = document.getElementsByClassName('faq_answer')
		for (var i=0; i<a.length; i++) {
			a[i].style.display = 'none'
			/*if (FAQIsEdit) {
				var newTitle = a[i].getElementsByTagName('INPUT')[0].value
				if (newTitle=='') newTitle = '[[NO QUESTION ENTERED]]'
				a[i].previousSibling.lastChild.innerHTML = newTitle
			}*/
		}
		var a = document.getElementsByClassName('faq_question')
		for (var i=0; i<a.length; i++) a[i].style.display = 'inline'
		if (obj) {
			obj.nextSibling.style.display = 'block'
			//if (FAQIsEdit) obj.style.display = 'none'
		}
	}
}

function keepAlive(sid) {
	if ($('debug')) $('debug').innerHTML +=	"Starting<br/>"
	xmlHttp=GetXmlHttp()
	xmlHttp.onreadystatechange = keepAliveReturn
	xmlHttp.open("GET",'/ajax/keepalive.php?sid=' + sid,true)
	xmlHttp.send(null)
	if ($('debug')) $('debug').innerHTML +=	"Sent<br/>"
}

function keepAliveReturn() {
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
		if ($('debug')) $('debug').innerHTML +=	xmlHttp.responseText + "<br/>"
	}
}

function moveObjectUp(targ,colour) {
	var prev = targ.previousSibling
	if (prev) targ.parentNode.insertBefore(targ,prev)
	if (colour) recolour(targ.parentNode)
}

function moveObjectDown(targ,colour) {
	var next = targ.nextSibling
	if (next) targ.parentNode.insertBefore(next,targ)
	if (colour) recolour(targ.parentNode)
}

function recolour(obj) {
	var row = 1
	obj = obj.firstChild
	while (obj) {
		if(obj.tagName) {
			row = 1-row
			obj.className = obj.className.replace('row1','').replace('row0','') + ' row' + row
		}
		obj = obj.nextSibling
	}
}




function insertAfter(newObject,target) {
	if (target.nextSibling) {
		target.parentNode.insertBefore(newObject,target.nextSibling)
	} else {
		target.parentNode.appendChild(newObject)
	}
}

function removeObject(target,confirmType) {
	var ok = false
	if (confirmType && confirmType!='') {
		ok = confirm('Are you sure you want to remove this ' + confirmType + '?')
	} else ok = true
	if (ok) target.parentNode.removeChild(target)
	return ok
}

function totalToPay() {
	var a = document.getElementsByClassName('topay')
	var total = 0
	for (var i=0; i<a.length;i++) {
		total+=parseFloat(getDecimal(a[i].value.replace(/[^0-9\.-]/g,'')))
	}
	$('totalToPay').innerHTML = '$' + getDecimal('' + total)
	
	a = document.getElementsByClassName('outstanding')
	total = 0
	for (var i=0; i<a.length;i++) {
		total+=parseFloat(getDecimal(a[i].innerHTML.replace(/[^0-9\.-]/g,'').replace('*','').replace(',','')))
	}
	$('totalOutstanding').innerHTML = '$' + getDecimal('' + total)
}

function checkAmount(caller,maxAmount) {
	caller.value = caller.value.replace(/[^\d\.]/g,'')
	if (caller.value=='') caller.value = maxAmount
	//caller.value = caller.value.replace(',','')
	if (parseFloat(caller.value)>maxAmount && maxAmount>=0) {
		//alert('You may not pay more than the value of an invoice')
		caller.value = maxAmount
	} else if (parseFloat(caller.value)>0 && maxAmount<0) {
		//alert('You may not pay more than the value of an invoice')
		caller.value = maxAmount
	} else if (maxAmount>=0 && parseFloat(caller.value)<0) {
		//alert('You may not pay a negative amount')
		caller.value = '0'
	} else if (parseFloat(caller.value)<0 && parseFloat(caller.value)<maxAmount) {
		//alert('You may not pay a negative amount lower than the balance of a negative invoice')
		caller.value = maxAmount
	}
	caller.value = '$' + getDecimal(caller.value)
}

function showSection(sect) {
	var old = sect.nextSibling.style.display
	var a = document.getElementsByClassName('menuset')
	for (var i=0; i<a.length; i++) {
		a[i].style.display = 'none'	
	}
	a = document.getElementsByClassName('sectheadingon')
	for (var i=0; i<a.length; i++) {
		a[i].className = 'sectheading'
	}
	sect.nextSibling.style.display = old=='block'?'none':'block'
	sect.className = old=='block'?'sectheading':'sectheadingon'
}

function login(username, password) {
	url = '/ajax/login.php?username=' + urlencode(username) + '&password=' + urlencode(password)
	xmlHttp=GetXmlHttp()
	xmlHttp.onreadystatechange = doLogin
	xmlHttp.open("GET",url,true)
	xmlHttp.send(null)
	$('backnext1').style.display = 'block'
	$('saveprogress1').style.display = 'none'
	
}

function doLogin() {
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
		$('backnext1').style.display = 'block'
		$('saveprogress1').style.display = 'none'
		var res = xmlHttp.responseText
		if (res=='0') {
			alert('Your username and password were not accepted. Please try again')
			$('lightbox').scrollTop = 0
		} else {
			//addAttendee(res[1],eve_num)
			currentLB.deactivate()
			document.invoiceform.submit()
		}
	}		
}

function checkAll(classname, status) {
	var a = document.getElementsByClassName(classname)
	for (var i=0; i<a.length; i++) {
		a[i].checked = status
	}
}

function checkChecks() {
	var status = true
	var a = document.getElementsByClassName('type_mem')
	for (var i=0; i<a.length; i++) {
		if(!a[i].checked) status = false
	}
	$('typ_num_mem').checked = status
	status = true
	a = document.getElementsByClassName('type_non')
	for (var i=0; i<a.length; i++) {
		if(!a[i].checked) status = false
	}
	$('typ_num_non').checked = status
}

function setDueDate() {
	var invDate = $('crd_dateinvoice').value
	invDate = invDate.split('-')
	invDate[1]++
	if(invDate[1]==13) {
		invDate[0]++
		invDate[1] = 1
	}
	invDate[1] = '' + '00'.substr((''+invDate[1]).length) + invDate[1]
	invDate[2] = '20'
	yy = $('crd_datedue')
	yy.value = invDate.join('-')
	zz = $('crd_datedue_disp')
	onCalendarSet = ''
	setZZ()
	
}

var scanCaller
function deleteScan(caller,crd_num) {
	scanCaller = caller
	xmlHttp=GetXmlHttp()
	xmlHttp.onreadystatechange = doDeleteScan
	xmlHttp.open("GET",'/ajax/deleteScan.php?c=' + crd_num,true)
	xmlHttp.send(null)
}

function doDeleteScan() {
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
		var res = xmlHttp.responseText
		if (res=='1') {
			scanCaller.parentNode.parentNode.removeChild(scanCaller.parentNode)	
			$('lbl_crd_data').innerHTML = 'Attach Invoice Scan:'
		} else {
			alert('Error: Could not delete scan');	
		}
	}
}

function showEventsSelect(cos_num) {
	xmlHttp=GetXmlHttp()
	xmlHttp.onreadystatechange = doShowEventsSelect
	xmlHttp.open("GET",'/ajax/getEvents.php?c=' + cos_num,true)
	xmlHttp.send(null)	
}

function doShowEventsSelect() {
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
		var ret = xmlHttp.responseText.split("\n")
		var sel = document.createElement('SELECT')
		sel.name = 'ev_num'
		sel.options[0] = new Option("N/A","")
		for(var i=0;i<ret.length;i++) {
			if (ret[i]!="") {
				var val = ret[i].split(",");
				sel.options[i+1] = new Option(val[1],val[0]);
			}
		}
		sel.style.width = '300px'
		$('eventarea').innerHTML = '<label>Event:</label>'
		$('eventarea').appendChild(sel)
		$('eventarea').appendChild(document.createElement('BR'))
	}
}

function round2dp(total) {
	total = Math.round(total*100)/100
	total = total.toString()
	var point = total.lastIndexOf('.')
	if (point==-1) total+='.00'
	else if (point+3>total.length) total+='0'	
	return total
}

function extraTotals() {
	var total = attTotal
	var targ
	for (k=0; k<attKeys.length; k++) {
		for ( var i in extraCosts ) if(!isNaN(i)) {
			targ = $('extra[' + attKeys[k] + '][' + i + ']')
			disp = $('extcost[' + attKeys[k] + '][' + i + ']')
			if(targ.type.toLowerCase()=='checkbox') {
				if(targ.checked) {
					total+= extraCosts[i]
					disp.innerHTML = '$' + round2dp(extraCosts[i])
				} else {
					disp.innerHTML = '$0.00'
				}
			} else {
				total+= targ.value*extraCosts[i]
				disp.innerHTML = '$' + round2dp(targ.value*extraCosts[i])
			}
		}
	}
	targ = $('extratotal')
	targ.innerHTML = 'Total Cost: $' + round2dp(total)
	
}

function mapAdd(fields) {
	var add = ''
	fields = fields.split(',')
	for(var i=0; i<fields.length; i++) {
		var targ = $(fields[i])
		if(targ.tagName=='SELECT') {
			add+= targ.options[targ.selectedIndex].text + ', '
		} else {
			add+= targ.value.replace("\n",", ")	 + ', '
		}
	}
	window.open('/map.php?add=' + add,'map','width=800,height=600')
}

function mlOptIn(ml_num,optin) {
	xmlHttp=GetXmlHttp()
	xmlHttp.open("GET",'/ajax/optIn.php?m=' + ml_num + '&in=' + (optin?1:0),true)
	xmlHttp.onreadystatechange = function() {
		if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
			var ret = xmlHttp.responseText
			currentLB.deactivate()
		}
	}
	xmlHttp.send(null)
}
function convertSQLDate(value) {
	var invDate = value.split('-')
	invDate[1]--
	if(invDate[1]<0) {
		invDate[0]--
		invDate[1] = 11
	}
	return new Date(invDate[0],invDate[1],invDate[2])
	
}

function setBlastSite(status) {
	if(status) {
		$('showSite').show()
	} else {
		$('showSite').hide()
		$('bla_site').value = 0
	}
	setBlastButton()
}

function setBlastEmail(status) {
	if(status) {
		$('showEmail').show()
	} else {
		$('showEmail').hide()
	}
	setBlastButton()
}

function setBlastTemplate(status) {
	if(status) {
		$('showTemplate').show()
		$('emt_num').value = $('emt_num2').value
	} else {
		$('showTemplate').hide()
		$('emt_num').value = 0
	}
}

function setBlastSiteDate(status) {
	if(status) {
		$('showSiteDate').hide()
	} else {
		$('showSiteDate').show()
	}
}

function setBlastSendDate(status) {
	if(status) {
		$('showSendDate').hide()
	} else {
		$('showSendDate').show()
	}
}

function setBlastLists(status) {
	if(status) {
		$('showEmailLists').show()
	} else {
		$('showEmailLists').hide()
		var arr = $$('.mlcheck')
		for(var i=0; i<arr.length; i++) arr[i].checked = false
	}
	
}

function setBlastEvents(status) {
	if(status) {
		$('showEmailEvents').show()
	} else {
		$('showEmailEvents').hide()
		var arr = $$('.evcheck')
		for(var i=0; i<arr.length; i++) arr[i].checked = false
	}
	
}

function setBlastButton() {
	var e = $('showEmailCheck')?($('showEmailCheck').checked && !$('showEmailCheck').disabled):false
	var s = $('showSiteCheck').checked
	var button = ''
	if(e && s) {
		button = 'Send and Publish'
	} else if (e) {
		button = 'Send'	
	} else if (s) {
		button = 'Publish'	
	} else {
		button = 'Save'	
	}
	$('sendButton').value = button
}

function applyDiscount(apply, invoice, total, discount,valid) {
	if (apply) total-=discount
	$('topay_' + invoice).value = '$' + getDecimal('' + total)
	$('topay_' + invoice).onchange = 'checkAmount(this,' + total + '); totalToPay()'
	$('outstanding_' + invoice).innerHTML = (valid?'*':'') + '$' + getDecimal('' + total)
	totalToPay()
	
}

function applyCode() {
	$('voucher').value = $('lbvoucher').value
	$('addvoucher').value = '1'
	$('voucher').form.submit()
}

function addLinkRow() {
	var d = document.createElement('DIV')
	d.innerHTML = '<strong>Name:</strong> <input name="exl_name[]" />' + "\n" + '<strong>Link:</strong> <input name="exl_url[]" value="http://" /><a href="#" onclick="window.open(this.previousSibling.href)"> Test</a>' + "\n" + '<a href="#" onclick="this.parentNode.parentNode.removeChild(this.parentNode); return false" style="vertical-align:middle"><img src="/images/cross.png" alt="Delete Link" /></a>'
	$('linklist').appendChild(d)
	Sortable.create('linklist',{elements:$$('#linklist div')})
}

function checkLength(obj,len) {
	if (obj.value.length > len) {
		obj.value = obj.value.substring(0,len)	
	}
	if($(obj.id + '_count')) {
		$(obj.id + '_count').innerHTML = '' + (len-obj.value.length) + ' chars left'
	}
}

function venueLoad(ven_num) {
	xmlHttp=GetXmlHttp()
	xmlHttp.open("GET",'/ajax/venueLoad.php?v=' + ven_num)
	xmlHttp.onreadystatechange = function() {
		if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
			var ret = xmlHttp.responseText
			currentLB.deactivate()
			ret = ret.split('~~')
			$('ev_venue').value = ret[0]
			$('ev_map').value = ret[1]
			$('ev_maxattendees').value = ret[2]
			$('venuebox').show()
			$('venuechoose').hide()
		}
	}
	xmlHttp.send(null)
}

function venueDel(ven_num,caller) {
	xmlHttp=GetXmlHttp()
	xmlHttp.open("GET",'/ajax/venueDel.php?v=' + ven_num)
	xmlHttp.onreadystatechange = function() {
		if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
			var row = caller
			var x, y
			while(row) {
				x = row.className
				row.className = y
				y = x
				row = row.nextSibling
			}
			caller.parentNode.removeChild(caller)
		}
	}
	xmlHttp.send(null)
}

function venueSave(ven_num) {
	xmlHttp=GetXmlHttp()
	xmlHttp.open("GET",'/ajax/venueSave.php?v=' + ven_num + '&n=' + escape($('ven_name').value) + '&a=' + $('ev_maxattendees').value + '&b=' + $('bra_num').value + '&m=' + escape($('ev_map').value) + '&l=' + escape($('ev_venue').value))
	xmlHttp.onreadystatechange = function() {
		if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
			currentLB.deactivate()
		}
	}
	xmlHttp.send(null)
}

function checkTPEs() {
	var status = true
	if($('mem_eventreminders').checked || $('mem_eventsummary').checked) {
		status = false
	}
	var list = $$('.tpe.mlcheck input')
	for(var i=0; i<list.length; i++) {
		list[i].disabled = status
		list[i].parentNode.className = list[i].parentNode.className.replace(' disabled','')
		if(status) list[i].parentNode.className = list[i].parentNode.className + " disabled"
	}
}

var orgToSelect = 0
		
function loadOrgs(ml_num) {
	var targ = $('oo_num')
	$('oo_num_area').hide()
	removeChildrenFromNode(targ)
	if(ml_num>0) {
		xmlHttp=GetXmlHttp()
		xmlHttp.open("GET",'/ajax/otherOrgs.php?m=' + ml_num)
		xmlHttp.onreadystatechange = function() {
			if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
				var ret = xmlHttp.responseText.split("\n")
				var hasSub = false
				targ.options[0] = new Option('Please Select',0)
				for(var i=0;i<ret.length;i++) {
					if (ret[i]!="") {
						var val = ret[i].split(",");
						targ.options[i+1] = new Option(val[1],val[0]);
						if(orgToSelect==val[0]) {
							targ.options[i+1].selected = true
						}
					}
				}
				targ.options[i+2] = new Option('Other...',-1)
				$('oo_num_area').show()
				$('tpe_otherorg_area').hide()
			}
		}
		xmlHttp.send(null)
	}	
}

function updateNewsletter(news_num) {
	$('updateButton').hide()
	$('updateTick').hide()
	$('updateProgress').show()
	xmlHttp=GetXmlHttp()
	xmlHttp.open("GET",'/ajax/updateNewsletter.php?n=' + news_num)
	xmlHttp.onreadystatechange = function() {
		if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
			$('updateButton').show()
			$('updateButton').style.width = '135px'
			$('updateProgress').hide()
			$('updateTick').show()
			window.setTimeout(function() {
				$('updateButton').style.width = '150px'
				$('updateTick').hide()
			},5000)
		}
	}
	xmlHttp.send(null)
}
function showTitle(targ) {
	var title = targ.title
	targ.title = ''
	targ.onmouseout = function() {
		hideddrivetip()
		targ.title = title
	}
	ddrivetip(title,200,'#333333');
}

function nextMonth() {
	if ($('calmonth').value==12) {
		$('calmonth').value = 1
		$('calyear').value++
	} else {
		$('calmonth').value++
	}
	getCal()
}

function lastMonth() {
	if ($('calmonth').value==1) {
		$('calmonth').value = 12
		$('calyear').value--
	} else {
		$('calmonth').value--
	}
	getCal()
}

function getCal() {
	var year, month, reg
	var date = new Date()
	if ($('calreg')) reg = $('calreg').value
	else reg = ''
	if ($('calyear')) year = $('calyear').value
	else year = date.getFullYear()
	if ($('calmonth')) month = $('calmonth').value
	else month = date.getMonth()+1
	var url = '/events/getcal.php?reg=' + reg + '&y=' + year + '&m=' + month
	var xmlhttp = new GetXmlHttp();
	if (xmlhttp) {
		$('calendar').innerHTML = '<div style="text-align:center; padding:150px 0"><img src="/images/progress.gif" alt="Now Loading"><br/>Loading Calendar</div>'
		xmlhttp.onreadystatechange = 
			function () {
				if (xmlhttp && xmlhttp.readyState==4) {
					var response = xmlhttp.responseText;
					$('calendar').innerHTML = response
				}
			}
		xmlhttp.open("GET",url,true);
		xmlhttp.send(null);
	}

}

function setEvShortDesc(caller) {
	if(caller.value=='') {
		var text = tinyMCE.get('ev_desc').getContent()
		
		var tmp = document.createElement("DIV");
		text = text.replace(/&[rl]dquo;/g,"&quot;")
		text = text.replace(/&hellip;/g,"...")
		text = text.replace(/&emdash;/g,"-")
		text = text.replace(/&[rl]squo;/g,"'")
		tmp.innerHTML = text.replace(/<\/p>/g,"~~N~~").replace(/\n/g,"")
		text = tmp.textContent||tmp.innerText;
		
		text = text.substring(0,200)
		text = text.replace(/~~N~~/g,"\n\n")
		caller.value = text
		caller.select()
		caller.focus()
	}
}

function showCttPrice(caller) {
	if(!caller.value || caller.value=='0')  $('cttPrice').innerHTML = '';
	else $('cttPrice').innerHTML = '$' + cttPrices[caller.value] + ' + GST'
}

function deleteCreditorInvoice(caller,inv) {
	var xmlhttp = new GetXmlHttp();
	if (xmlhttp && confirm('Are you sure you want to delete this invoice? This process can not be undone.')) {
		//$('calendar').innerHTML = '<div style="text-align:center; padding:150px 0"><img src="/images/progress.gif" alt="Now Loading"><br/>Loading Calendar</div>'
		$('overlay').style.display = 'block'
		xmlhttp.onreadystatechange = 
			function () {
				if (xmlhttp && xmlhttp.readyState==4) {
					var response = xmlhttp.responseText;
					$('overlay').style.display = ''
					var targ = caller
					do{
						targ = targ.parentNode
					} while (!targ.tagName || targ.tagName.toLowerCase()!='tr')
					p = targ.parentNode
					p.removeChild(targ)
					recolour(p)
				}
			}
		xmlhttp.open("GET",'/ajax/deleteCreditorInvoice.php?i=' + inv,true);
		xmlhttp.send(null);
	}
}

function updateCreditorInvoice(inv,status) {
	var xmlhttp = new GetXmlHttp();
	if (xmlhttp) {
		$('overlay').style.display = 'block'
		xmlhttp.onreadystatechange = 
			function () {
				if (xmlhttp && xmlhttp.readyState==4) {
					var response = xmlhttp.responseText;
					$('overlay').style.display = ''
					$('cistatus_' + inv).innerHTML = response
					currentLB.deactivate()
				}
			}
		xmlhttp.open("GET",'/ajax/updateCreditorInvoice.php?i=' + inv + '&s=' + status,true);
		xmlhttp.send(null);
	}
	
}

Event.observe(window, 'load', function() { 
	initTextareas()
	var parentList = $$('#leftbar ul ul')
	for (var i=0; i<parentList.length; i++) {
		var parent = parentList[i].parentNode
		var child=parent.firstChild
		while(!child.tagName || child.tagName.toLowerCase() != "a") {
			child = child.nextSibling
		}
		child.onclick = function() {
			var parent = this.parentNode
			var child = parent.firstChild
			while(!child.tagName || child.tagName.toLowerCase() != "ul") {
				child = child.nextSibling
			}
			if (child.parentNode.className.indexOf("subactive")!=-1) {
				hideall()
			} else {
				hideall()
				child.parentNode.className += " subactive"
				child.style.height = child.select('li').length*33 + 'px'
			}
			return false
		}
	}
	var active = $$('#leftbar li li.active')
	for (var i=0; i<active.length; i++) {
		active[i].parentNode.parentNode.className += " subactive"
		active[i].parentNode.style.height = active[i].parentNode.select('li').length*33 + 'px'
	}
})

function hideall() {
	//alert('gone')
	var parentList = $$('#leftbar li.subactive')
	
	for (var i=0; i<parentList.length; i++) {
		parentList[i].className = parentList[i].className.replace(" subactive","")
		parentList[i].select('ul')[0].style.height = '0'
	}
}


function toggleFlag(caller, flag, mem_num) {
	if(caller.className.indexOf('active')>-1) setFlag(caller, flag, mem_num, 0)
	else setFlag(caller, flag, mem_num, 1)
}

function setFlag(caller, flag, mem_num, status) {
	var url = '/ajax/setFlag.php?mem_num=' + mem_num + '&flag='  +flag + '&status=' + status
	var xmlhttp = new GetXmlHttp();
	$('overlay').style.display = 'block'
	xmlhttp.onreadystatechange = function () {
		if (xmlhttp && xmlhttp.readyState==4) {
			var response = xmlhttp.responseText;
			$('overlay').style.display = ''
			if(status) {
				caller.className+=' active'
			} else {
				caller.className = caller.className.replace('active','')
			}
		}
	}
	xmlhttp.open("GET",url,true);
	xmlhttp.send(null);	
}

function checkInvoicePayDate() {
	if($('payby_1').checked) return true
	var rawdate = $('paydate').value.split('-')
	var paydate = new Date(rawdate[0],rawdate[1]-1,rawdate[2])
	var today = new Date()
	if(paydate.getTime()>today.getTime()) {
		return confirm('The pay date is set to a date in the future. Are you sure you want to continue?')
	} else {
		return true
	}
}

function sendPassRequest(mem_num) {
	if (confirm('Are you sure you want to send this member a Password Change Request?')) {
		var url = '/ajax/passRequest.php?mem_num=' + mem_num
		var xmlhttp = new GetXmlHttp();
		$('overlay').style.display = 'block'
		xmlhttp.onreadystatechange = function () {
			if (xmlhttp && xmlhttp.readyState==4) {
				var response = xmlhttp.responseText;
				$('overlay').style.display = ''
				alert('The Password Change Request has been sent successfully')
			}
		}
		xmlhttp.open("GET",url,true);
		xmlhttp.send(null);	
	}
}
