var idStack = new Array;   // use as a queue to reuse IDs

$(function() {
	// code for adding and taking away transportation permits dynamically

	for (i=$('#tpns .permitstateprov').size(); i<5; i++) idStack.push(i);
	
	$('#addpermit').click(function(e){			
		// copy the first permitstateprov div of the 'tpns' div and append them back on to the div
		s = $('#tpns .permitstateprov:first').clone().appendTo('#tpns');
		// clear out the permit fields
		s.find(':input').val('');
		// get the lowest ID
		id = idStack.sort(function(a,b){return a - b}).shift();
		// set this ID on the newly cloned div so that it can be easily erased later
		s.attr("id", "permitstateprov_"+id)
		// append a 'Remove' link after the text field
		$('&nbsp;<a href="#" class="removepermit">Remove permit</a>').
			filter(".removepermit").bind('click',id,function(evt) {
				$('#permitstateprov_'+evt.data).remove();
				// recycle the id
				idStack.push(evt.data);
				// re-show the add permit link
				if (idStack.length > 0) $('#addpermit').show();
				return false;
			}).appendTo($('.formElement:nth-child(2) .formField', s.get(0)));
			
		// replace the id and name with an incremented number for each input
		s.find(':input').each(function(n){
			this.id = this.id.replace(/\d/, id);
			this.name = this.name.replace(/\d/, id);
		});
		// hide the add permit link if user has already entered 5
		if (idStack.length == 0) $('#addpermit').hide();
		
		return false; 
	});

	// clear out the instructional text
	$('#operator_signup_comments').one('focus', function(){ $(this).val(''); });
	
	$('#new_operator').submit(function() {
	  shield('operator_submit', null, 'Working    ', 'Working ');
	});
});