/**
 *	Cleanup functions
 *
 *	Developed for Greenflame
 *	November 2011
 *
 *	Version 1.0
 */
 
//-------------------------------------------------------------------

/**
 *	Cleanup styles and classes
 */
$(document).ready(function() {
	$('.cleanup').find('*').each(function() {
		// CSS
		$(this).removeAttr('style');
		$(this).removeAttr('class');
		
		// Language
		$(this).removeAttr('lang');
		
		// Tables
		$(this).removeAttr('align');
		$(this).removeAttr('valign');
		$(this).removeAttr('bgcolor');
		$(this).removeAttr('border');
		$(this).removeAttr('cellpadding');
		$(this).removeAttr('cellspacing');
		$(this).removeAttr('frame');
		$(this).removeAttr('rules');
		$(this).removeAttr('summary');
		$(this).removeAttr('width');
		
		// Headings
		if($(this).is('h1')) {
			$(this).replaceWith('<h2>'+$(this).html()+'</h2>');
		} else if($(this).is("h2")) {
			$(this).replaceWith('<h3>'+$(this).html()+'</h3>');
		} else if($(this).is("h3")) {
			$(this).replaceWith('<h4>'+$(this).html()+'</h4>');
		} else if($(this).is("h4")) {
			$(this).replaceWith('<h5>'+$(this).html()+'</h5>');
		} else if($(this).is("h5")) {
			$(this).replaceWith('<h6>'+$(this).html()+'</h6>');
		};
	});
	
	// More reset to TABLES
	$('.cleanup').find('table').each(function() {
		$(this).attr('border','0');
		$(this).attr('cellpadding','0');
		$(this).attr('cellspacing','0');
		
		$(this).find('td').each(function() {
			if($(this).is(':empty')) {
				$(this).parent().remove();
			} else if($(this).html() == '<br>') {
				$(this).parent().remove();
			} else if($(this).html() == '&nbsp;') {
				$(this).parent().remove();
			} else {
				var theTD = $(this).text();
				var trimedTD = theTD.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
				//var trimedTD = $.trim(theTD);
				$(this).text(trimedTD);
			};
		});
	});
	
	// Remove br in UL and OL
	$('.cleanup ul').find('br').remove();
	$('.cleanup ol').find('br').remove();	
});


/**
 *	Add design to tables
 */
$(document).ready(function() {
	// Wrap div.table arround table if not done yet
	$(".cleanup table").each(function() {
		$(this).wrap('<div class="table" />');
	});
	
	// th wrap content with span
	// If no content in th add a numbspace
	$(".cleanup table").find('th').each(function() {
		if($(this).html() == "") {
			$(this).html("&nbsp;");
		};
		if(!$(this).children().is("span")) {
			$(this).wrapInner('<span />');
		};
	});
});
