// Copyright 2011-3011 MrSupplement.com.au. All rights reserved.

function IE_WrapDivTables (maxversion, parent, firstdetails)
{
	if ($.browser.msie && $.browser.version <= maxversion)
	{
		// Find the number of maximum number of columns that exist in a row
		var colspan = 1;
		if (parent.length <= 0) { parent = $("*"); }
		parent.find (".istablerow").each (function ()
		{
			var cols = $(this).find (".istablecell").length;
			if (cols > colspan) { colspan = cols; }
		});

		// Replace all cells with <td>
		$(".istablecell").replaceWith (function ()
		{
			var id = $(this).attr ("id");
			if (id != "") { id = 'id="' + id + '"'; }
			var cls = $(this).removeClass ("istablecell");
			cls = $(this).attr ("class");
			if (cls != "") { cls = 'class="' + cls + '"'; }

			return "<td " + id + " " + cls + ">" + $(this).html () + "</td>";
		});

		// Replace all rows with <tr>
		$(".istablerow").replaceWith (function ()
		{
			// Check if any <td>'s exist in the current row
			var td = $(this).find ("td");
			if (td.length > 0 && (td.length < colspan))
			{
				// Place a "colspan" attribute onto the last <td>
				td.last ().attr ('colspan', (colspan - td.length + 1));
			}

			// Check if the first element should be replaced with the <tr> instead of the row that has the .istablerow class
			var element = $(this);
			if (firstdetails == true)
			{
				var firstel = $(this).find (":first-child").not ("td, th");
				if (firstel.length > 0) { element = firstel; }
			}

			var id = element.attr ("id");
			if (id != "") { id = 'id="' + id + '"'; }
			var cls = element.removeClass ("istablerow");
			cls = element.attr ("class");
			if (cls != "") { cls = 'class="' + cls + '"'; }

			// Retrieve the HTML for the current row and remove any elements that are not <td> or <th>
			var html = element.html ();
			$(this).find (":not(td, th)").remove ();

			// If no HTML exists, add a <td></td> around the content
			if ($(this).html () == "" && html.search (new RegExp ("\<t[dh]", "i"))) { html = "<td colspan=\"" + colspan + "\">" + html + "</td>"; }

			return "<tr " + id + " " + cls + ">" + html + "</tr>";
		});

		$(".istable").replaceWith (function ()
		{
			var id = $(this).attr ("id");
			if (id != "") { id = 'id="' + id + '"'; }
			var cls = $(this).removeClass ("istable");
			cls = $(this).attr ("class");
			if (cls != "") { cls = 'class="' + cls + '"'; }

			return "<table " + id + " " + cls + " style=\"border-collapse:collapse;\">" + $(this).html () + "</table>";
		});
	}
}

