var curCat = null;

function removeSpecies(evt) {
	var tbl = document.getElementById('species-table').getElementsByTagName('tbody')[0];
	if (evt) var node = evt.target;
	else var node = window.event.srcElement;
	while (node) {
		if (node.nodeName.toLowerCase() == "tr") break;
		node = node.parentNode;
	}
	tbl.removeChild(node);
	var none = document.getElementById('species-none');
	if (tbl.getElementsByTagName('tr').length == 1) none.style['display'] = '';
}

function insertSpecies(species) {
		
	var tbl = document.getElementById('species-table').getElementsByTagName('tbody')[0];
	var row = document.createElement('tr');
	
	var td1 = document.createElement('td');
	td1.setAttribute('class','chem1');
	td1.innerHTML = '<input type="text" />';
	row.appendChild(td1);
	
	var td2 = document.createElement('td');
	td2.setAttribute('class','chem2');
	td2.innerHTML = species;
	row.appendChild(td2);
	
	var td3 = document.createElement('td');
	td3.setAttribute('class','chem3');
	td3.innerHTML = '<input type="text" />';
	row.appendChild(td3);
	
	var td4 = document.createElement('td');
	td4.setAttribute('class','chem4');
	td4.innerHTML = '<select><option>Abs</option><option>Rel</option></select>';
	row.appendChild(td4);
	
	var td5 = document.createElement('td');
	td5.setAttribute('class','chem5');
	var rem = document.createElement('img');
	rem.setAttribute('src','images/icon-remove.gif');
	rem.style['cursor'] = 'pointer';
	rem.onclick = removeSpecies;
	td5.appendChild(rem);
	row.appendChild(td5);
	
	tbl.insertBefore(row, tbl.firstChild);
	td1.getElementsByTagName('input')[0].focus();
}

function insertSpeciesRow(evt) {
	if (curCat) {
		document.getElementById('species-none').style['display'] = 'none';
		var selects = document.getElementsByTagName('select');
		var sp = document.getElementById('species-input').value;
		var type = document.getElementById('species-type').value;
		var species = document.getElementById(sp + "-" + type).value;
		insertSpecies(species);
	}
}

function changeCat(evt) {
	var selects = document.getElementById('species-list').getElementsByTagName('select');
	var sp = document.getElementById('species-input').value;
	var type = document.getElementById('species-type').value;
	if (sp != 0 && type != 0) {
		var newCat = sp + "-" + type;
		if (curCat && curCat != newCat ) {
			document.getElementById(curCat).style['display'] = 'none';
			document.getElementById(curCat).style['zIndex'] = '0';
		}
		document.getElementById(newCat).style['display'] = 'inline';
		document.getElementById(newCat).style['zIndex'] = '100';
		curCat = newCat;
	}
}

setup = function() {
	document.getElementById('species-button').onclick = insertSpeciesRow;
	document.getElementById('species-input').onchange = changeCat;
	document.getElementById('species-type').onchange = changeCat;
}
window.onload = setup;
