(function($)
{
	jQuery.fn.tableFlip = function ()
	{
		return this.each(function ()
		{
			var table = this;
			
			// clone the source table
			$(table).clone().insertAfter(table);
			
			// hide the source table
			$(table).css('display', 'none');
			
			// clear the new table (we cloned it for the attributes, events etc..)
			$(table).next().html('');
		
			// find the rows we want to read
			var rows;
			if($(table).children('tr').length != 0)
			{
				rows = $(table).children('tr');
			} else {
				rows = $(table).children('thead, tbody, tfoot').children('tr');
			}
			
			// go through the elements and copy the source cells into each new row.
			// but only create new rows for every cell on the first source row.
			rows.each(function (row, rowElement)
			{
				var columnCount = 0;
				$(rowElement).children('th, td').each(function (column, columnElement)
				{
					oriColspan = $(columnElement).attr('colspan');
					
					if(row == 0)
					{
						for(var colspan = 1; colspan <= oriColspan; colspan++)
						{
							$(table).next().append('<tr></tr>');
						}
					}
					
					if(oriColspan > 1)
					{
						$(columnElement).attr('rowspan', oriColspan);
						$(columnElement).attr('colspan', '1')
					}
					
					if($(table).next().children('tr').length != 0)
					{
						$($(table).next().children('tr')[columnCount]).append();
					} else {
						$($(table).next().children('thead, tbody, tfoot').children('tr')[columnCount]).append(columnElement);
					}
					
					columnCount += oriColspan;
				});
			});
			
			// remove the source table
			$(table).remove();
		});
	}
})(jQuery);