function updateDivs(tdname, maxdivs) {
	//alert(maxdivs);
	removeEmptyDivs(tdname);
	newEmptyDiv(tdname, maxdivs);
}

function newEmptyDiv(tdname, maxdivs) {
	tdi = document.getElementById(tdname);
	tdidivs = tdi.getElementsByTagName("div");
	cni = tdidivs[0].getElementsByTagName("select");
	if (cni[0].options[cni[0].selectedIndex].value != "" && tdidivs.length<maxdivs) { //only add new div when first div is not empty and there's less than maxdivs divs
		cloneDiv = tdidivs[(tdidivs.length-1)];
		var newDiv = cloneDiv.cloneNode(true);
		var insertHere = tdi.appendChild(newDiv);
		newSelect = newDiv.getElementsByTagName("select");
		addOnClick(newSelect[0], tdname, maxdivs);
		newSelect[0].className = "defaultWidth"; //restore original class because we cannot restore multiple error classes with ajax formfeedback
		newSelect[0].id = tdname.replace("td_","fc_") + (tdidivs.length-1); //prevent identical ids
		newSelect[0].options[0].selected = true; //select first (empty) option
	}
}

function removeEmptyDivs(tdname) {
	tdi = document.getElementById(tdname);
	tdidivs = tdi.getElementsByTagName("div");
	//alert(tdidivs.length);
	for (var i = 0; i < tdidivs.length; i++) { //loop all divs
		cni = tdidivs[i].getElementsByTagName("select"); //loop all selects, fetch first select
		tdidivs[i].className = "clone";
		cni[0].id = tdname.replace("td_","fc_") + i; //make sure id is correct
		if (cni[0].options[cni[0].selectedIndex].value == "" && (i>0 || tdidivs.length>1)) { //remove div when div is empty, and (there's more than 1 div or this isn't the first div) 
			tdi.removeChild(tdidivs[i]);
			i--;
		}
	}
}

function addOnClick(selobj, c, maxdivs) {
	if(window.addEventListener){ // Mozilla, Netscape, Firefox
		selobj.addEventListener("change", function() { updateDivs(c, maxdivs); }, false);
	} else { // IE
		selobj.attachEvent("onchange", function() { updateDivs(c, maxdivs); } );
	}
}