(function($) {
	$(function() {

		var textarea = $('textarea[name="comment"]');
		var showText = 'Preview';
		var hideText = 'Hide preview';
		var comment = '';

		textarea.wrap('<div id="jcpWrap"></div>');
		textarea.before('<div id="jcpToolbar"></div>');
		$('#jcpToolbar').prepend('<div id="previewTab">'+ showText +'</div>');
		var toggled = false;

		$('#previewTab').click(function() {
			if (!toggled) {
				comment = textarea.val();
				if (comment != '') comment = comment + '\n\n';
				previewText = comment.replace(/(<\/?)script/g,'$1noscript')
				.replace(/ (http:\/\/\S+)/gi, ' <a href="$1">$1</a>')
				.replace(/\n(http:\/\/\S+)/gi, '\n<a href="$1">$1</a>')
				.replace(/(<blockquote[^>]*>)/g, '\n$1')
				.replace(/(<\/blockquote[^>]*>)/g, '$1\n')
				.replace(/\r\n/g, '\n')
				.replace(/\r/g, '\n')
				.replace(/\n\n+/g, '\n\n')
				.replace(/\n?(.+?)(?:\n\s*\n)/g, '<p>$1</p>')
				.replace(/<p>\s*?<\/p>/g, '')
				.replace(/<p>\s*(<\/?blockquote[^>]*>)\s*<\/p>/g, '$1')
				.replace(/<p><blockquote([^>]*)>/ig, '<blockquote$1><p>')
				.replace(/<\/blockquote><\/p>/ig, '</p></blockquote>')
				.replace(/<p>\s*<blockquote([^>]*)>/ig, '<blockquote$1>')
				.replace(/<\/blockquote>\s*<\/p>/ig, '</blockquote>')
				.replace(/\s*\n\s*/g, '<br />');

				var email = $('#email').val();
				if(!email) email = '';
				var md5 = MD5(email);
				var avatar = '<img src="http://www.gravatar.com/avatar/' + md5 + '?s=40" alt="" class="avatar" />';
				var author = $('#author').val();
				var url = $('#url').val();
				if(!$('#url').length) url = '';
				if(!$('#author').length) author = '';
				if(url != '') author = '<a href="'+ url +'">'+ author +'</a>';
				var date = 'April 2, 2021 2:34 am at 2:34 am';
				var previewHTML = ''+ avatar +'<div class="comment-author vcard"><cite class="fn">'+ author +'</cite> says:</div><div class="comment-meta commentmetadata">'+ date +'</div>'+ previewText +'';
				var preview = $('<div id="jQueryCommentPreview"></div>');
				preview.html(previewHTML);
				textarea.after(preview).hide();
				$(this).text(hideText);
				$('#htmlEditor a').hide();
				toggled = true;
			} else {
				$('#jQueryCommentPreview').remove();
				$('#htmlEditor a').show();
				$(this).text(showText);
				textarea.show().focus();
				toggled = false;
			}
		})

		$('#htmlEditor').append('<a href="http://dimox.net/jquery-comment-preview-wordpress-plugin/" target="_blank" title="About the plugin">?</a>');

	}) 
})(jQuery)
