jQuery(function($) {
	var selected     = wym.selected();
	var selectedhref = $(selected).attr(WYMeditor.HREF);
	var mailPrefix   = 'mailto:';

	if (typeof(selectedhref) === 'string' && selectedhref.length > mailPrefix.length && selectedhref.substr(0, mailPrefix.length) === mailPrefix) {
		selectedhref = selectedhref.substr(mailPrefix.length).split('?');

		$(wym._options.hrefSelector).val(selectedhref[0]);

		if (selectedhref[1]) {
			$(wym._options.subjectSelector).val(selectedhref[1].substr(8, selectedhref[1].length));
		}
	}

	$(wym._options.titleSelector).val($(selected).attr(WYMeditor.TITLE));

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

		if (sUrl.length > 0) {
			title   = $(wym._options.titleSelector).val() || sUrl;
			subject = $(wym._options.subjectSelector).val();

			if (subject !== '') {
				sUrl = sUrl + '?subject=' + subject;
			}

			sUrl = mailPrefix + 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();
	});
});
