$(function() {
	var editor_name = document.location.search.replace(/.*editor=(.*)/,'$1');
	
	$('#media-insert-cancel').click(function() {
		window.close();
	});
	
	$('#media-insert-ok').click(function() {
		var insert_form = $('#media-insert-form').get(0);
		if (insert_form === undefined) { 
			return; 
		}

		var editor = window.opener.CKEDITOR.instances[editor_name],
		type = insert_form.elements.type.value,
		img = '',
		media_align_grid = {
			left: 'float: left; margin: 0 1em 1em 0;',
			right: 'float: right; margin: 0 0 1em 1em;',
			center: 'text-align: center;'
		};

		if (type == 'image') {
			if (editor.mode=='wysiwyg') {
				img = '<img src="'+stripBaseURL($('input[name="src"]:checked',insert_form).val())+'"';
				img += ' alt=""/>';
				var element = window.opener.CKEDITOR.dom.element.createFromHtml(img);
				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;
	}
});
