var filesPrefix = 'data/mediapool/';

function insertLink(id, fullName, name, link) {
	link = shortenFilename(link);
	$('.wym_dialog_file '+wym._options.hrefSelector).val(link);
	return true; // close the popup
}

function shortenFilename(filename) {
	if (typeof(filename) === 'string' && filename.length > filesPrefix.length && filename.substr(0, filesPrefix.length) === filesPrefix) {
		filename = filename.substr(filesPrefix.length);
	}

	return filename;
}

jQuery(function($) {
	$('.mediapoolLink').click(function() {
		var curFile = $('.wym_href').val().split('/');
		sly.openMediapool('detail', curFile.length ? curFile[curFile.length-1] : '', 'insertLink');
		return false;
	});

	var selected = wym.selected();
	var href     = $(wym.selected()).attr(WYMeditor.HREF);

	href = shortenFilename(href);

	$('.wym_dialog_file '+wym._options.hrefSelector).val(href);
	$('.wym_dialog_file '+wym._options.titleSelector).val($(wym.selected()).attr(WYMeditor.TITLE));

	$('form').submit(function() {
		var sUrl = $(wym._options.hrefSelector).val(), link, title, sStamp;

		if (sUrl.length > 0) {
			title = $(wym._options.titleSelector).val();
			if (title === '') title = sUrl;
			sUrl = filesPrefix+sUrl;

			if (selected[0] && selected[0].tagName.toLowerCase() === WYMeditor.A) {
				link = selected;
			}
			else {
				sStamp = wym.uniqueStamp();
				wym._exec(WYMeditor.CREATE_LINK, sStamp);

				link = $('a[href="'+sStamp+'"]', wym._doc.body);
			}

			link.attr(WYMeditor.HREF, sUrl).attr(WYMeditor.TITLE, title);
		}

		window.close();
	});

	$(wym._options.cancelSelector).mousedown(function() { window.close(); });
});
