// function to strip html and special characters (unicode) from a passed string
function stripHTML(txt) {
	var stripall = /<(?:.|\s)*?>/g;
	
	// replace funky chars
	var replacements = {
		"\xa0": " ",
		"\xa9": "(c)",
		"\xae": "(r)",
		"\xb7": "*",
		"\u2018": "'",
		"\u2019": "'",
		"\u201c": '"',
		"\u201d": '"',
		"\u2026": "...",
		"\u2002": " ",
		"\u2003": " ",
		"\u2009": " ",
		"\u2012": "-",
		"\u2013": "-",
		"\u2014": "--",
		"\u2015": "--",
		"\u2122": "(tm)"
	};
	var regex = {};
	for (key in replacements) {
		regex[key] = new RegExp(key, 'g');
	}
	for (key in replacements) {
		txt = txt.replace(regex[key],replacements[key]);
	}
	
	// convert par breaks to double car returns 
	txt = txt.replace("<br />","\n\n");
	txt = txt.replace("<br>","\n\n");
	txt = txt.replace("</p>","\n\n");
	
	// strip out all html tags
	txt = txt.replace(stripall,"");
	
	// convert double car returns back to br's
	txt = txt.replace("\n\n","<br /><br />");
	
	return(txt);
}

// attach a cleaner to any wysiwyg editors on the current page
$(document).ready(function() {

	var isIE = (document.compatMode && document.all) ? true : false; // IE 6+
	
	$('iframe.wysiwyg_iframe').each(function() {
		edit_doc = $("#"+$(this).attr("id")).contents().find("body");
		edit_doc.bind("input paste",function() {
			box = $(this).attr("id");
			headline_interval = setTimeout(function() {
				//var base_id = "#" + this.box.split("_",1);
				var base_id = "#" + this.box.replace("_editor_body","");  // _editor_body is the id of the editable content, as defined on line 499 of jquery wysiwyg plugin. Ugly way to do it, but at least it works cross-platform
				var html_cleaned = stripHTML($(base_id + "IFrame").contents().find("body").html());
				if(isIE) { alert("HTML formatting and special characters removed from pasted text."); }
				$(base_id).wysiwyg('setContent',html_cleaned);
			},250);
		});
	});
});