/*
	Javascript Mac-esque Multi-Select
	Lech M. Boron

	Given a Select, replaces with multi-select table		
*/

function MultiInput(instance,el,tableClass){
	this.instanceName = instance;
	tbl = document.createElement("table");
	tbl.className = tableClass;
	this.tBody = document.createElement("tbody");
	tbl.appendChild(this.tBody);
	
	this.input = document.createElement("input");
	this.input.type = "text";
	this.input.name = el.name;
//	values = el.value.split(/\s+/); // by word
	values = el.value.split("\n"); // by line
	
	this.addLink = document.createElement("a");
	this.addLink.className = "add";
	this.addLink.innerHTML = "<img src='/static/images/buttons/plus.png' width='12' alt='+' />";
	this.addLink.href = "#";
	this.removeLink = document.createElement("a");
	this.removeLink.className = "remove";
	this.removeLink.innerHTML = "<img src='/static/images/buttons/minus.png' width='12' alt='-' />";
	this.removeLink.href = "#";
	this.tr = document.createElement("tr");
	this.tr.appendChild(document.createElement("td"));
	this.tr.appendChild(document.createElement("td"));
	this.tr.appendChild(document.createElement("td"));
	this.tr.childNodes[0].appendChild(this.input);
	this.tr.childNodes[1].appendChild(this.addLink);
	this.tr.childNodes[2].appendChild(this.removeLink);
	
	if(values.length > 0){
		for(var i = 0; i < values.length; i++){
			this.addRow(false,values[i]);
		}		
	}
	else {
		this.addRow(false,false);
	}
	
	el.parentNode.replaceChild(tbl,el);
}
MultiInput.prototype.tBody;
MultiInput.prototype.input;

MultiInput.prototype.removeRow = function(rowIndex){
	if(this.tBody.childNodes.length > 1){
		this.tBody.removeChild(this.tBody.childNodes[rowIndex]);
	}
	this.refreshNames();
}
MultiInput.prototype.addRow = function(insertAfter,value){
	tr = this.tr.cloneNode(true);
	if(value != false){
		tr.childNodes[0].childNodes[0].value = value;
	}
	if(insertAfter === false || this.tBody.childNodes.length==0 || insertAfter==(this.tBody.childNodes.length-1)){
		this.tBody.appendChild(tr);
	}
	else{
		this.tBody.insertBefore(tr,this.tBody.childNodes[insertAfter+1]);
	}
	this.refreshNames();
}
MultiInput.prototype.refreshNames = function(){
	for(var i = 0; i < this.tBody.childNodes.length; i++){
		this.tBody.childNodes[i].childNodes[0].childNodes[0].name = this.input.name+"["+i+"]";
		this.tBody.childNodes[i].childNodes[1].childNodes[0].onclick = new Function(this.instanceName+".addRow("+i+",false);return false;");
		this.tBody.childNodes[i].childNodes[2].childNodes[0].onclick = new Function(this.instanceName+".removeRow("+i+");return false;");
	}
}

