(function($) {
	$(function() {

		var textarea = $('textarea[name="comment"]');
		var show_text = 'Preview';
		var hide_text = 'Hide preview';
		var comment = '';

		$(textarea).wrap('<div id="jquery-comment-wrap"></div>');
		$(textarea).before('<div id="jquery-comment-preview"></div>');
		$('#jquery-comment-preview').prepend('<div id="preview-tab">'+ show_text +'</div>');

		$('#preview-tab').toggle(
			function() {
				comment = $(textarea).val();
				if ($(textarea).val() != '') comment = comment + '\n\n';
				comment_preview = 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=32" 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 = 'March 26, 2021 at 9:26 pm';
				var preview_html = '<ol id="comment-preview"><li>'+ avatar +'<p><strong>'+ author +'</strong> says ('+ date +'):</p>'+ comment_preview +'</li></ol>';

				$(textarea).after('<div id="textarea_clone"></div>');
				$(textarea).clone().appendTo($('#textarea_clone'));
				$('#textarea_clone textarea').text(comment);
				$('#textarea_clone').hide();
				$(textarea).replaceWith('<div id="comment_preview"></div>');
				$('#comment_preview').html(preview_html);
				$(this).text(hide_text);
				$('#html-editor a').hide();
			},
			function() {
				$('#textarea_clone').remove();
				$('#comment_preview').replaceWith(textarea);
				comment = comment.replace(/\n\n+/g, '\n\n');
				$(textarea).text(comment);
				$(this).text(show_text);
				$('#html-editor a').show();
				$(textarea).focus();
			}
		)

		$('#html-editor').append('<a href="http://dimox.net/jquery-comment-preview-wordpress-plugin/" target="_blank" title="About the plugin">?</a>');

	}) 
})(jQuery)
