$(function() {      

    $.fn.tabWebpart = function(options) {

            var defaults = {"cssPrefix" : "qr-"},
                        o = $.extend({}, defaults, options),
                        currWebpart = this;
        
        var currWebpartTitle = this.find(".ms-WPTitle span[id='']");   
        var webPartZone = this.parent().parent().parent();  
        webPartZone.find(".ms-PartSpacingVertical").hide();

        var webparts = webPartZone.find("td[id^='MSOZoneCell_WebPart']").addClass(o.cssPrefix + "wpzMiddle")				
        .each(function(i, elem)
        {
            if (elem != currWebpart[0])
            {
	            var header = $(this).find("tr:first").hide().find(".ms-WPTitle span[id='']");
	            var title = "Untitled " + i;
	            if (header.length)
		            title = header.text();
	            webPartZone.before("<div class='" + o.cssPrefix + "tabHeader' id='localTabHeader" + i +"' ><span>" + title + "</span></div>");
            }
        });	

        var tabHeaders = webPartZone.siblings("." + o.cssPrefix + "tabHeader").click(function() 
        {
            $(this).addClass(o.cssPrefix + "tabHeaderSelected").siblings().removeClass(o.cssPrefix + "tabHeaderSelected");				
            webparts.parent().hide();
            webparts.eq(parseInt($(this).attr("id").substr(14))).parent().show();	
        });

        //hide all  webpart rows other than the one related the first tab header
        webparts.filter(":not(:eq(" + $(tabHeaders[0]).addClass(o.cssPrefix + "tabHeaderSelected").attr("id").substr(14) + "))").parent().hide();

        //add rows above and below and cells left and right to enclose the webparts in a structure which can be styled separately
        webPartZone.find(">tbody>tr")
            .append("<td class='" + o.cssPrefix + "wpzRight'></td>")
            .prepend("<td class='" + o.cssPrefix + "wpzLeft'></td>")	
            .filter(":first").before("<tr><td class='" + o.cssPrefix + "wpzTopLeft'>&nbsp;</td><td class='" + o.cssPrefix + "wpzTop'></td><td class='" + o.cssPrefix + "wpzTopRight'>&nbsp;</td></tr>")
            .siblings(":last").after("<tr><td class='" + o.cssPrefix + "wpzBottomLeft'>&nbsp;</td><td class='" + o.cssPrefix + "wpzBottom'></td><td class='" + o.cssPrefix + "wpzBottomRight'>&nbsp;</td></tr>");
        
        // hide the title row 
        return this;
    }; 
});