function plswait(st) {
	document.getElementById('plswait').style.display='inline'
	if(!st) st = ''
	else st = st + ' '
	document.getElementById('msg').innerHTML='&nbsp;<i>' + st + 'Please wait...</i>'
	return true
}

function confirmmsg(msg,throbber) {
	if(!msg || msg && confirm(msg)) {
		if(throbber) plswait()
		return true
	} else return false
}

function promptYES(msg,throbber) {
	answer = prompt(msg + "\n\nType 'YES' to continue (all caps)",'')
	if(!answer) return false
	if(answer == 'YES') {
		if(throbber) plswait()
		return true
	} else {
		alert("Action canceled. You didn't type 'YES'")
		return false
	}
}

function getnewidnumber(oldid,count,max) {
	if(count) {
		newid = prompt('WARNING: Deleting this Master ID will affect '+count+' standard list records\n\nType a new Master ID for these records')
		if(!newid) return false
		if(!isNaN(newid) && newid > 0 && newid < max && newid != oldid) {
			document.getElementById('newmasterid').value = newid
			return true
		} else {
			alert('ERROR: '+newid+' is not a valid Master ID\n\nYou must supply an integer between 0 and '+max);
			return false
		}
	} else return confirm('Are you sure you want to delete this Master ID?')
}

function isempty(field,msg) {
	with (field) {
		if(value.length == 0 || value.length == null) {
			alert(msg)
			field.focus()
			return true
		}
		return false
	}
}

function enableupdate() {
	document.getElementById('update').disabled = 0
	document.getElementById('apply').style.display = 'inline'
}

function invalidemail(field,msg) {
	with (field) {
		if(value.length < 5 || value.indexOf("@") < 1 || value.indexOf(".") < 1 || value.length - value.indexOf("@") < 4) {
			alert(msg)
			field.focus()
			return true
		}
		return false
	}
}

function checklogin(form) {
	with (form) {
		if(isempty(loginusername,'Please type a username')) { return false; }
		if(isempty(tmppassword,'Please type a password')) { return false; }
		password.value = hex_hmac_md5(hex_hmac_md5(tmppassword.value, loginusername.value + '3jgf97c1m'),challenge.value) //Don't ever change 3jgf97c1m!!!
		loginbutton.disabled = 1
		challenge.disabled = 1
		tmppassword.disabled = 1
		return true
	}
}

function checkuser(form,usernamemin,passwordmin) {
	with (form) {

		if(isempty(username,'Please type a username')) { return false }
		if(username.value.length < usernamemin) {
			alert('The username must be at least '+usernamemin+' letters')
			return false;
		}
		if((id.value=='new' && username.value=='root') || (id.value=='new' && username.value=='admin') || (id.value=='new' && username.value=='administrator')) {
			alert('Invalid username')
			return false
		}
		if(isempty(realname,'Please type the person\'s name')) { return false }
		if(realname.value.length < 5) {
			alert('The name must be at least 5 letters') 
			return false
		}
		if(isempty(email,'Please type an email address')) { return false }
		if(invalidemail(email,'Please type a valid email address')) { return false }
		if(isempty(tmppassword1,'Please type a password')) { return false }
		if(tmppassword1.value.length < passwordmin) {
			alert('The password must be at least '+passwordmin+' letters')
			return false
		}
		if(isempty(tmppassword2,'Please repeat the password')) { return false }
		if(tmppassword1.value != tmppassword2.value) {
			alert('Passwords do not match')
			return false
		}
		if(tmppassword1.value.length==32 && tmppassword2.value.length==32) { //password probably hasn't changed, so don't re-hash it
			password1.value = tmppassword1.value
			password2.value = tmppassword2.value
		} else { //new password, hash it and send it 
			password1.value = hex_hmac_md5(tmppassword1.value, username.value + '3jgf97c1m')
			password2.value = hex_hmac_md5(tmppassword2.value, username.value + '3jgf97c1m')
		}
		tmppassword1.disabled = 1
		tmppassword2.disabled = 1
		return true;
	}
}

function checktracker(form) {
	with (form) {
		if(isempty(title,'Please fill the title field')) { return false }
		if(isempty(description,'Please fill the description field')) { return false }
		if(isempty(object,'Please fill in the object field')) { return false }
	}
}

function checkcomment(form) {
	with (form) {
		if(isempty(text,'Please type a comment')) { return false }
	}
}

function clicktab(tabnum) {
	document.getElementById('tab1').style.display = (tabnum==1) ? 'block' : 'none';
	document.getElementById('tab2').style.display = (tabnum==2) ? 'block' : 'none';
	document.getElementById('tab3').style.display = (tabnum==3) ? 'block' : 'none';
	document.getElementById('tab4').style.display = (tabnum==4) ? 'block' : 'none';
}

function columnselect(v) {
	for(var i=0; i<document.forms['qform']['col[]'].length; i++) {
		document.forms['qform']['col[]'].options[i].selected=v;
	}
}

function showhideadv(el) {
	var adv1 = document.getElementById('adv1').style
	var adv2 = document.getElementById('adv2').style
	var adv3 = document.getElementById('adv3').style
	if(adv1.display=='none') {
		adv1.display = 'block'
		adv2.display = 'block'
		adv3.display = 'block'
		el.innerHTML = 'Advanced &lt;'
		document.forms['qform']['wdl[]'].ondblclick = function ondblclick(event) { addwdl(0); }
	} else {
		adv1.display = 'none'
		adv2.display = 'none'
		adv3.display = 'none'
		el.innerHTML = 'Advanced &gt;'
		document.forms['qform']['wdl[]'].ondblclick = function ondblclick(event) { quickview(this); }
	}
}

function addwdl(all) {
	var wdl1 = document.forms['qform']['wdl[]']
	var wdl2 = document.forms['qform']['wdl2[]']

	for(var i=0; i<wdl1.length; i++) {
		if(all || (!all && wdl1.options[i].selected == true)) {
			var newoption = document.createElement('option');
			newoption.text = wdl1.options[i].innerHTML;
			newoption.value = wdl1.options[i].value;
			
			try {
				wdl2.add(newoption,null); // standards compliant; doesn't work in IE
			}
			catch(ex) {
				wdl2.add(newoption); // works in IE
			}
		}
	}
}

function delwdl(all) {
	var wdl2 = document.forms['qform']['wdl2[]']
  for(i = wdl2.length - 1; i>=0; i--) {
    if(all || (!all && wdl2.options[i].selected)) {
      wdl2.remove(i);
    }
  }
}

function resetquery() {
	document.getElementById('qoptions').style.display = 'block'
	columnselect(0)
	clicktab(1)
	with (document.forms['qform']) {
		for(var i=0; i<document.forms['qform']['wdl[]'].length; i++) {
			document.forms['qform']['wdl[]'].options[i].selected=false
		}
		document.forms['qform']['col[]'].options[0].selected=true
		document.forms['qform']['col[]'].options[1].selected=true
		document.forms['qform']['col[]'].options[2].selected=true
		document.forms['qform']['col[]'].options[3].selected=true
		flt[0].checked=true
		lst.options[0].selected=true
		fln.value="- filter by id(s) -"
		egl.checked=true
		fgl.checked=false
		blk.checked=false
		dmn.options[0].selected=true
		stx.value='- search text -'
		sfd[0].selected=true
		stp[0].checked=true
		stp[3].checked=false
		stp[0].disabled = 0
		stp[1].disabled = 0
		stp[2].disabled = 0
		fln.disabled = 0
		lst.disabled = 0
		blk.disabled = 0
		egl.disabled = 0
		fgl.disabled = 0
		dmn.disabled = 0
		stp[0].disabled = 0
		stp[1].disabled = 0
		stp[2].disabled = 0
		stp[3].disabled = 0
		sfd.disabled = 0
		stx.disabled = 0
	}
}

function quickview(el) {
	document.forms['qform'].flt[3].checked = true
	clicktab(5)
	for(var i=0; i<document.forms['qform']['col[]'].length; i++) {
		document.forms['qform']['col[]'].options[i].selected=true
	}
	document.forms['qform'].suh.value=1
	document.forms['qform'].submit()
}

function play(mp3file) {
	o = '<object type="application/x-shockwave-flash" data="includes/musicplayer.swf" width="0" height="0">'
	o = o + '<param name="movie" value="includes/musicplayer.swf" />'
	o = o + '<param name="FlashVars" value="autoload=true&autoplay=true&song_url='
	o = o + mp3file
	o = o + '"/></object>'
	document.getElementById('flash').innerHTML = o
}

function regexsearch() {
	if(document.forms['qform']['stp'][3].checked) {
		document.forms['qform']['stp'][0].disabled = 1
		document.forms['qform']['stp'][1].disabled = 1
		document.forms['qform']['stp'][2].disabled = 1
	} else {
		document.forms['qform']['stp'][0].disabled = 0
		document.forms['qform']['stp'][1].disabled = 0
		document.forms['qform']['stp'][2].disabled = 0
	}
}

function hidepartialblanks() {
	if(document.forms['qform']['plk'].checked) {
		document.forms['qform']['blk'].checked = true
		document.forms['qform']['blk'].disabled = 'disabled'
	} else {
		document.forms['qform']['blk'].checked = false
		document.forms['qform']['blk'].disabled = false
	}
}

function checkqueryform(form) {
	//check that a wordlist is selected
	l = document.forms['qform']['wdl[]']
	noneselected = 1
	for(var i=0; i<l.length; i++) {
		if(l.options[i].selected) {
			noneselected = 0;
		}
	}
	if(noneselected) {
		alert('Please select at least one word list')
		document.forms['qform']['wdl[]'].focus()
		return false
	}

	//check that some columns are selected
	l = document.forms['qform']['col[]']
	noneselected = 1
	for(var i=0; i<l.length; i++) {
		if(l.options[i].selected) {
			noneselected = 0;
		}
	}
	if(noneselected) {
		alert('Please select at least one column to display')
		document.forms['qform']['col[]'].focus()
		return false
	}

	//stdlist filter
	if(document.forms['qform'].flt[0].checked && !document.forms['qform']['lst'].value) {
		alert('Please select a standard list to filter results') 
		document.forms['qform'].dmn.focus()
		return false
	}

	//domain filter
	if(document.forms['qform'].flt[1].checked && !document.forms['qform']['dmn'].value) {
		alert('Please select a semantic domain to filter results') 
		document.forms['qform'].dmn.focus()
		return false
	}

	//search filter, check searchtext
	if(document.forms['qform'].flt[2].checked && document.forms['qform'].stx.value=='- search text -') {
		alert('Please type something to search for') 
		document.forms['qform'].stx.focus()
		return false
	}
	return true
}

function checkwlist(el) {
	with(el) {
		if(!listname.value) { alert('You must specify a name in #1'); listname.focus(); return false }
		if(!stdlist.value) { alert('You must specify a standard word list in #6'); stdlist.focus(); return false }
		if(consent[1].checked) {
			if(isempty(country,'You must specify a country name in #2')) { return false }
			if(isempty(region,'You must specify a region name in #3')) { return false }
			if(isempty(family,'You must specify a language family in #5')) { return false }
			if(isempty(datecollected,'You must specify the date elicited in #7')) { return false }
			if(isempty(author,'You must specify the contributing researcher in #11')) { return false }
			if(isempty(copyrightholder,'You must specify the copyright holder of the word list in #12')) { return false }
			if(!authorpublish[0].checked && !authorpublish[1].checked) { alert("You must answer question #13"); authorpublish[0].focus(); return false }
			if(!audiopublish[0].checked && !audiopublish[1].checked) { alert("You must answer question #14"); audiopublish[0].focus(); return false }
			if(!copyrightpermission[0].checked && !copyrightpermission[1].checked) { alert("You must answer question #15"); copyrightpermission[1].focus(); return false }
			if(copyrightpermission[0].checked && !assurance.value) { alert("You answered 'No' to question 15. Please fill in #17"); assurance.focus(); return false }

			if(!permission[0].checked && !permission[1].checked) { alert("You must answer question #16"); permission[1].focus(); return false }
			if(permission[0].checked && !assurance.value) { alert("You answered 'No' to question 16. Please fill in #17"); assurance.focus(); return false }

			if(!finished[1].checked) { alert("You must answer 'Yes' to #18"); finished[1].focus(); return false }
		}
	}
}

function drawtonebar(tone,nexttone) {
	diff = parseInt(nexttone) - parseInt(tone)
	if(diff < 0) {       //down tone
		return "<img src='0.gif' class='d"+(diff*-1)+" l"+nexttone+"'>"
	} else if(diff > 0) { //up tone
		return "<img src='0.gif' class='u"+diff+" l"+tone+"'>"
	} else {             //flat tone
		return "<img src='0.gif' class='f l"+tone+"'>"
	}
}

function gettone(cell,i) {
	var t = cell.charAt(i)
	if(t > 0 && t < 8) return t
	else return false
}

function drawtone(cell) {

	if(!cell) return "<div title=''></div>"
	var cont = 0
	var length = cell.length //Get the length of the string (multibyte)
	var str = "<div title='"+cell+"'>[";

	for(var k=0; k<length; k++) {
		var tone = gettone(cell,k); //extract one character from the string
		var nexttone = null
		if((k+1) < length) nexttone = gettone(cell,(k+1)) //get the next character from the string
		if(tone) { //Current char is a valid tone
			if(nexttone) { //next char is also a valid tone
				str += drawtonebar(tone,nexttone)
				cont = 1
			} else { //following char is not a tone
				if(!cont) {//if it's a continuation, skip it - otherwise output a flat tone
					str += drawtonebar(tone,tone)
					str += ' ' //thin space U+2009
				}
				cont = 0
			}
		} else str += cell.charAt(k)
	}
	str += "]</div>"
	return str
}

function ajax(str,ignoreresponse) {

	if(window.XMLHttpRequest) ajaxrequest = new XMLHttpRequest()
	else if(window.ActiveXObject) ajaxrequest = new ActiveXObject("Microsoft.XMLHTTP")
	ajaxrequest.open("POST", "ajax.php", true); //send this via form POST method to the ajax.php script, true=synchronous (wait for response)
	if(!ignoreresponse) ajaxrequest.onreadystatechange = ajaxresponse;
	ajaxrequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
	ajaxrequest.send(str + '&token='+token) //add the token to validate it for the php script
	if(ignoreresponse) setTimeout("ajaxrequest.abort();",100); //if we're ignoring response, abort after 1/10 second
}

function ajaxresponse() {
//readyState: 0 uninitialized, 1 loading, 2 loaded, 3 interactive, 4 complete

	//alert('readyState='+ajaxrequest.readyState);
	if(ajaxrequest.readyState == 4) {
		//alert('status='+ajaxrequest.status);
		if(ajaxrequest.status == 200) {
			if(ajaxrequest.responseText == '1') { //everything went fine
				tablecell2.innerHTML = newvalue2 //put the new value in
			} else if(ajaxrequest.responseText.substring(0,1) == '^') { //page load time. put remainder in the footer
				document.getElementById('pgloadtime').innerHTML = ajaxrequest.responseText.substr(1)
			} else if(ajaxrequest.responseText) { //ajax.php reports a problem :)
				alert('PHP SAYS'+ajaxrequest.responseText)
				if(window.tablecell2 !== undefined) tablecell2.innerHTML = oldvalue2
			}
		} else { //there was a different problem
			tablecell.innerHTML = oldvalue2
		}
		clearedit()
	}
}

function edit(el) {
//convert the tabel cell into a form field

	if(tablecell) { //are we already editing something else?
		tablecell.innerHTML = oldvalue
		clearedit()
	}
	var cell = el.innerHTML.replace("\n", '') //take out newlines
	var arr = el.className.split(' ') //get the word id from the td class
	var str = arr[0]
	var arr = str.split('-')
	id = arr[0] //wordid - store values in global variables
	field = arr[1] //field
	oldvalue = cell //original value
	tablecell = el //link to table cell (td)
	var st = ''
	
	//this is an audio/mp3 column, needs to be treated differently
	if(window.field == 'audio') {	
		st += "<input type='file' title='Audio file name' name='audio' id='imp3' size='10' onkeydown='event.cancelBubble=true; checkkey(event.keyCode,event)' onkeypress='event.cancelBubble=true; if(event.keyCode==13) return false;'  />"
		st += "<input type='hidden' name='id' value='"+id+"' />"
		st += "<input type='hidden' name='field' value='"+field+"' />"
		st += "<input type='hidden' name='token' value='"+token+"' />"
		st += " <img src='0.gif' class='sbutton ssave' id='isave' title='Upload file and save changes' onclick='doupload()' />"
		st += " <img src='0.gif' class='sbutton sundo' id='icancel' title='Cancel' onclick='cancel()' />"
		st += "<img src='images/wait.gif' width='16' height='16' id='iwait' style='display: none; margin: 0 0 -2px 5px;'>"
		st += "<iframe id='upload_target' name='upload_target' src='' style='width:0;height:0;border:0;float:left;'></iframe>"
		el.innerHTML = st
		el.firstChild.focus()
		
	//this is the wordlist stdlistid, stdlist masterlistid, or masterlist domainid column
	} else if((window.field.substring(0,9) == 'stdlistid' || window.field == 'Smasterid' || window.field == 'Mdomainid') && window.list !== undefined) { 
		var listnum = window.field.substring(9,10)
		if(listnum) {
			field = window.field.substring(0,9)
			listlines = list[listnum].split('value="')
		} else {
			listlines = list.split('value="')
		}
		str = oldvalue.split(':')[0]
		nonnumber = isNaN(str)
		for(var i=0; i < listlines.length; i++) {
			if(nonnumber) {
				if(str == listlines[i].split('"')[0]) {
					listlines[(i-1)] += ' selected '
					break
				}
			} else {
				if(parseFloat(str) == parseFloat(listlines[i].split('"')[0])) {
					listlines[(i-1)] += ' selected '
					break
				}
			}
		}
		var newlist = listlines.join('value="')
		st += newlist
		st += " <img src='0.gif' id='isave' title='Save changes' class='sbutton ssave' onclick='save()' />"
		st += " <img src='0.gif' id='icancel' title='Cancel' class='sbutton sundo' onclick='cancel()' />"
		st += "<img src='images/wait.gif' width='16' height='16' id='iwait' style='display: none; margin: 0 0 -2px 5px;'>"
		el.innerHTML = st
		el.firstChild.focus()
		
	//phonetic pitch field
	} else if(window.field == 'pitch' || window.field == 'pitchpl') {
		if(el.firstChild) cell = el.firstChild.title
		if(!cell) cell = ''
		len = cell.length
		if(len < 1) len = 1
		if(len > 50) len = 50
		cell = cell.replace(/"/g, '&quot;')
		cell = cell.replace(/'/g, '&#039;')
		st += "<input size='"+ len +"' type='text' title='Type pitch in numbers 1 (low) to 7 (high)' maxlength='255' value='" + cell + "' onkeydown='event.cancelBubble=true; checkkey(event.keyCode,event)' onkeypress='event.cancelBubble=true; if(event.keyCode==13) return false;'  />"
		st += " <img src='0.gif' id='isave' title='Save changes' class='sbutton ssave' onclick='save()' />"
		st += " <img src='0.gif' id='icancel' title='Cancel' class='sbutton sundo' onclick='cancel()' />"
		st += "<img src='images/wait.gif' width='16' height='16' id='iwait' style='display: none; margin: 0 0 -2px 5px;'>"
		el.innerHTML = st
		el.firstChild.focus()
		
	//all other columns
	} else {
		len = cell.length
		if(len < 1) len = 1
		if(len > 50) len = 50
		cell = cell.replace(/"/g, '&quot;')
		cell = cell.replace(/'/g, '&#039;')
		cell = cell.replace(/^0+/g,'')
		st += "<input size='"+ len +"' type='text' maxlength='255' value='" + cell + "' onkeydown='event.cancelBubble=true; checkkey(event.keyCode,event)' onkeypress='event.cancelBubble=true; if(event.keyCode==13) return false;' />"
		st += " <img src='0.gif' id='isave' title='Save changes' class='sbutton ssave' onclick='save()' />"
		st += " <img src='0.gif' id='icancel' title='Cancel' class='sbutton sundo' onclick='cancel()' />"
		st += "<img src='images/wait.gif' width='16' height='16' id='iwait' style='display: none; margin: 0 0 -2px 5px;'>"
		el.innerHTML = st
		el.firstChild.focus()	
	}
}

function doupload() {
	document.getElementById('isave').style.display = 'none'
	document.getElementById('icancel').style.display = 'none'
	document.getElementById('iwait').style.display = 'inline'

	htmltxt = tablecell.firstChild.value.replace(/^\s+|\s+$/g, "") //trim white space
	htmltxt = htmltxt.replace(/&/g, "&amp;") //convert amp
	htmltxt = htmltxt.replace(/</g, "&lt;") //convert wedges
	htmltxt = htmltxt.replace(/>/g, "&gt;")
	
	lform = document.getElementById('listform')
	lform.target = 'upload_target'
	lform.action = 'ajax.php'
	document.getElementById('listform').submit()
	document.getElementById('imp3').disabled = 1

	lform.target = ''
	lform.action = ''
}

function finishupload(st) {
	if(!st) st = '&nbsp;'
	tablecell.innerHTML = st
	clearedit()
}

function clearedit() {
	tablecell = null
	tablecell2 = null
	oldvalue = null
	oldvalue2 = null
	newvalue = null
	newvalue2 = null
	field = null
	id = null
}

function cancel(st) {
	if(st) alert(st)
	tablecell.innerHTML = oldvalue
	clearedit()
}

function save() {

	document.getElementById('isave').style.display = 'none'
	document.getElementById('icancel').style.display = 'none'
	document.getElementById('iwait').style.display = 'inline'

	var txt = tablecell.firstChild.value
	txt = txt.replace(/^\s+|\s+$/g, "") //trim white space

	if(field == 'stdlistid') {
		htmltxt = txt
		txt = txt.replace(/^0+/g, "") //trim leading zeros
	} else {
		if(field == 'Smasterid' || field == 'Mdomainid') {
			for(var i=0; i < tablecell.firstChild.length; i++) { //go through all the items in the list and find the right one
				if(tablecell.firstChild.options[i].value == tablecell.firstChild.value) break
			}
			txt = txt.replace(/^0+/g, "") //trim leading zeros
			htmltxt = tablecell.firstChild.options[i].innerHTML
			htmltxt = htmltxt.replace(/&/g, "&amp;") //convert wedges & &
			htmltxt = htmltxt.replace(/</g, "&lt;")
			htmltxt = htmltxt.replace(/>/g, "&gt;")
		} else {
			if(window.field == 'pitch' || window.field == 'pitchpl') {
				txt = txt.replace(/^\[+|\]+$/g, "") //trim square brackets
				htmltxt = drawtone(txt)
			} else {
				htmltxt = txt
				htmltxt = htmltxt.replace(/&/g, "&amp;") //convert wedges & &
				htmltxt = htmltxt.replace(/</g, "&lt;")
				htmltxt = htmltxt.replace(/>/g, "&gt;")
				if(txt== '') htmltxt = '&nbsp;'
			}
		}
	}

	newvalue = htmltxt
	newvalue2 = newvalue //I don't know why but this needs to be done
	tablecell2 = tablecell
	oldvalue2 = oldvalue

	if(htmltxt != oldvalue) { //check if the value changed
		txt = encodeURIComponent(txt)
		ajax("id=" + id + "&field=" + field + "&value=" + txt)
	} else {
		tablecell.innerHTML = oldvalue
		clearedit()
	}
}

function checkkey(code) {

	if(tablecell) { //is there a cell being edited?
		if(code == 13) { //ENTER key
			if(field == 'audio') doupload()
			else save()
			return false
		} else {
			if(code == 27) { //ESC key
				cancel()
				return false
			}
		}
	}
	return true
}

var tablecell = null
var oldvalue = null
var newvalue = null
var field = null
var id = null