window.addEvent('domready', function() {
	var div_section = $('div_section');

	$('add_colaboration').addEvent('click', function(e) {
		e.stop();
		var prev = this.getPrevious();

		// Clone fieldset with author inputs
		prev.clone().inject(this, 'before');

		if($$('.authors').length > 2) {
			removeOptions();injectOptions();
		} else {
			injectOptions();
		}
	});

	$('program').addEvent('change', function() {
		var val = this.getSelected().get('value');

		// If section is chosen for program, show sections selectbox
		if(val == 2) {
			div_section.addClass('show').removeClass('hide');
		} else {
			div_section.addClass('hide').removeClass('show');
			$('section').set('value', 0);
		}
	});

	if($$('.authors').length > 1) {
		injectOptions();
	}

	if($('program').getSelected().get('value') == 2) {
		div_section.toggleClass('show');
	} else {
		div_section.toggleClass('hide');
	}
});

function injectOptions() {
	$$('.authors').each(function(el) {

		var deleteImage = new Element('img', {
			'src': '/cms/themes/default/images/delete.png',
			'alt': '',
			'class': 'remove',
			'styles': {
				'cursor': 'pointer',
				'margin-top': '-10px'
			},
			'events':{
				'click': function() {
					var parent = this.getParent();
					// Remove fieldset
					parent.destroy();

					// Remove deleteImages if there is only one country/institution
					if($$('.authors').length == 1) {
						removeOptions();
					}
				}
			}
		});

		deleteImage.inject(el, 'top');
	});
}

function removeOptions() {
	$$('.authors').each(function(el) {el.getElement('img').destroy()});
}