var richtextarea;

document.observe('dom:loaded', function() { initRichTextArea(); });

function initRichTextArea(){
	if ($('rich_text_area') != undefined) {
		richtextarea = new Control.TextArea('rich_text_area');
		
		if ($('rich_text_event_link') != undefined) {
			$('rich_text_event_link').observe('change', function() {
				addRichLink(this, 'event');
			});
		}
		
		if ($('rich_text_artist_link') != undefined) {
			$('rich_text_artist_link').observe('change', function() {
				addRichLink(this, 'artist');
			});
		}
	}
}

function addRichLink(e, type) {
	selected = e.options[e.selectedIndex];
	text = selected.text;
	id = selected.value;
	
	var selection = richtextarea.getSelection();  	
	richtextarea.replaceSelection(
		'[' + type + '=' + id + ']' +
		(selection == '' ? text : selection) +
		'[/' + type + ']'
	);  
	
	e.selectedIndex = 0;
}