$(function() {
	$('#link-insert-cancel').click(function() {
		window.close();
	});

	$('#form-entries tr>td.maximal>a').click(function() {
		var query_string = document.location.search,
		editor_name = query_string.replace(/\?editor=([^&]*)(&|$)/, "$1"),
		editor = window.opener.CKEDITOR.instances[editor_name],
		link = '',
		selected_text = editor.getSelection().getNative().toString();

		if (editor.mode=='wysiwyg') {
			link = '<a href="'+stripBaseURL($(this).attr('title'))+'">'+selected_text+'</a>';
			var element = window.opener.CKEDITOR.dom.element.createFromHtml(link);
			editor.insertElement(element);
		}
		window.close();
	});

	function stripBaseURL(url) {
		if (dotclear.base_url != '') {
			var pos = url.indexOf(dotclear.base_url);
			if (pos == 0) {
				url = url.substr(dotclear.base_url.length);
			}
		}
		
		return url;
	}
});
