/**
 * Launch a mailto link based on an element's content.
 *
 * 
 */
(function($) {
	$.fn.mailElement = function(options) {
		// extends defaults with options provided
		var o = $.fn.mailElement.defaults;
		if (options) {
			o = $.extend(o, options);
		}
		// iterate over matched elements
		return this.each(function() {
			var url = 'mailto:?subject=';
			var subject = o.subjectPrefix + document.title + o.subjectPostfix;
			url += encodeURIComponent(subject);
			url += '&body=';

			var body = window.location.href + "\n";
			var metaDesc = $('meta[name=description]').attr('content');
			if(metaDesc) {
				body += metaDesc + "\n";
			}
			body += "\n";

			var content = $(this).html();

			//Turn the end of any block element into a linebreak.
			//MSIE needs the i qualifier because its tags are uppercase.
			content = content.replace(/<\/div>/gi, "\n");
			content = content.replace(/<\/p>/gi, "\n");
			content = content.replace(/<\/tr>/gi, "\n");
			content = content.replace(/<br ?>/gi, "\n");
			content = content.replace(/<\/h[1-7]>/gi, "\n");

			//Strip tags
			content = content.replace(/<[^>]+>/g, "\n");

			//Collapse spaces
			content = content.replace(/\t/g, " ");
			content = content.replace(/ {2,}/g, " ");
			content = content.replace(/\n /g, "\n");

			//Collapse long runs of linebreaks, and remove CRs for windows.
			content = content.replace(/\r/g, "\n");
			content = content.replace(/\n{3,}/g, "\n\n");

			//Get rid of highbit characters
			content = content.replace(/\xAE/g, "(R)");
			content = content.replace(/[\xC0-\xFF]/g, " ");

			//Truncate really long content
			if(content.length > 500) {
				content = content.substr(0,500);
				content += "\n...\nPlease visit the URL to view the complete content.\n";
			}
		
			body += content;

			url += encodeURIComponent(body);
			window.location.href = url;
		});
	};

	// plugin default options
	$.fn.mailElement.defaults = {
		subjectPrefix: "",
		subjectPostfix: ""
	};

})(jQuery);

