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

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

function MultiSelect(instance,el,tableClass,noneText){
	if(!noneText)noneText = "None";
	this.instanceName = instance;
	var tbl = document.createElement("table");
	tbl.className = tableClass;
	this.tBody = document.createElement("tbody");
	tbl.appendChild(this.tBody);
	
	this.select = document.createElement("select");
	this.select.name = el.name;
	selected = new Array();
	opt = document.createElement("option");
	opt.value = "";
	opt.innerHTML = noneText;
	this.select.appendChild(opt);
	for(i = 0; i < el.options.length; i++){
		if(el.options[i].selected)selected[selected.length] = i+1;
		opt = document.createElement("option");
		opt.value = el.options[i].value;
		opt.innerHTML = el.options[i].innerHTML;
		this.select.appendChild(opt);
	}
	this.addLink = document.createElement("a");
	this.addLink.className = "add";
	this.addLink.innerHTML = "<span>+</span>";
	this.addLink.href = "#";
	this.removeLink = document.createElement("a");
	this.removeLink.className = "remove";
	this.removeLink.innerHTML = "<span>&minus;</span>";
	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.select);
	this.tr.childNodes[1].appendChild(this.addLink);
	this.tr.childNodes[2].appendChild(this.removeLink);
	
	if(selected.length > 0){
		for(var i = 0; i < selected.length; i++){
			this.addRow(false,selected[i]);
		}		
	}else this.addRow(false,false);
	
	el.parentNode.replaceChild(tbl,el);
}
MultiSelect.prototype.tBody;
MultiSelect.prototype.select;

MultiSelect.prototype.removeRow = function(rowIndex){
	if(this.tBody.childNodes.length > 1){
		this.tBody.removeChild(this.tBody.childNodes[rowIndex]);
	}
	this.refreshNames();
}
MultiSelect.prototype.addRow = function(insertAfter,selectedIndex){
	tr = this.tr.cloneNode(true);
	if(selectedIndex != false){
		tr.childNodes[0].childNodes[0].selectedIndex = selectedIndex;
	}
	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();
}
MultiSelect.prototype.refreshNames = function(){
	for(var i = 0; i < this.tBody.childNodes.length; i++){
		this.tBody.childNodes[i].childNodes[0].childNodes[0].name = this.select.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;");
	}
}
