//multicamper.js
multicamper = {

	//first we want to identify the campers we have
	maxcampers:15,
	getCamperNodes:function(){
		var i=-1, nodes = new Array(), node;
		do{
			i++;
			node = document.getElementById('camper'+i);
			if(node) nodes[i] = node;
		}
		while(nodes[i]);
		this.campers = nodes;
	},
	appendCamperAdder:function(){
		var lastcamper = this.campers[this.campers.length-1];
		nextnode = lastcamper.nextSibling;
		var addLink = document.createElement('a');
		addLink.appendChild(document.createTextNode('Add another camper'));
		addLink.onclick = function(e){
			e = (e) ? e : window.event;
			if(e.preventDefault) e.preventDefault();
			multicamper.addCamper();
			return false;
		}
		addLink.className = "camperadder";
		addLink.href = "#";
		if(lastcamper && nextnode){
			lastcamper.parentNode.insertBefore(addLink,nextnode);
		}
	},
	addCamper:function(){
		if(this.campers.length < this.maxcampers){
			var lastcamper = this.campers[this.campers.length-1], n = this.campers.length;
			var newcamper = document.createElement('fieldset');
			newcamper.id = 'camper'+n;
			newcamper.className = this.campers[n-2].className;
			newcamper.innerHTML = lastcamper.innerHTML.replace('Camper '+(n), 'Camper '+(n+1));
			this.campers[n] = lastcamper.parentNode.insertBefore(newcamper, lastcamper.nextSibling);
			newcamper.style.height = 0;
			newcamper.style.overflow = 'hidden';
			var inputs = newcamper.getElementsByTagName('input');
			for(var i=0;i<inputs.length;i++){
				//inputs[i].name = inputs[i].name.replace('['+(n-1)+']','['+n+']');
				inputs[i].name = inputs[i].name.replace((/[\d]{1,}/),n);
				inputs[i].value = '';
			}
			var selects = newcamper.getElementsByTagName('select');
			for(var i=0;i<selects.length;i++){
				selects[i].name = selects[i].name.replace((/[\d]{1,}/),n);
				selects[i].selectedIndex = 0;
			}
			var target_h = newcamper.offsetHeight;
			this.displayCamper(n, target_h - 20);
		}
	},
	displayCamper:function(n, target_h){
		current_h = this.campers[n].offsetHeight;
		var distance = target_h - current_h;
		var movement = (distance/100) + 1;
		var next_h = current_h + movement;
		if(next_h < target_h){
			this.campers[n].style.height = next_h + 'px';
			setTimeout('multicamper.displayCamper('+n+','+target_h+')',20);
		}else{
			this.campers[n].style.overflow = 'visible';
			this.campers[n].style.height = null;
		}
	},
	init:function(){
		this.getCamperNodes();
		this.appendCamperAdder();
	}

}

multicamper.init();

