;
String.prototype.format = function() {
	var s = this;
	for (i = 0; i < arguments.length; i++)
		s = s.replace(new RegExp('\\{' + i + '\\}','gi'), arguments[i]);
	return s;
}

jQuery(document).ready(function() {
	var ws = WidgetVoodooSelectors.widget;
	var ts = WidgetVoodooSelectors.title;
	var cs = WidgetVoodooSelectors.autocollapse;
	var widgets = jQuery(ws);
	widgets.each( function(index, elem) {
		//if (elem.id == 'tag_cloud') return;
		var self = jQuery(this);
		var title = jQuery(ts, self);
		if ( !title.length || !title.html().replace('&nbsp;','') ) return true;
		//var body = self.children(':not(' + ts + ')');
		var body = jQuery(':not(' + ts + ')', self);
		var wid = 'widgetbody-' + index;

		if (body.length > 1) {
			// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
			// !!! wrapAll does not work as expected                  !!!
			// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
			//body = body.wrapAll( '<div class="widgetbody {0}"></div>'.format(wid) );
			//
			// Instead, we will do this:
			var wrap = jQuery( '<DIV class="widgetbody {0}">{1}</DIV>'.format(wid, self.html()) );
			title = jQuery(ts, wrap);
			self.html(wrap);
			title.insertBefore(wrap);
			//alert(self.html());
		}
		else
			body.addClass('widgetbody ' + wid);

		title.addClass('collapsible');
		self.addClass('collapsible');
		title.click(function() {
			//alert(ws + ' .' + wid);
			jQuery(ws + ' .' + wid).slideToggle('fast');
			jQuery(this).toggleClass('collapsed');
		});
	});
	if (cs) {
		jQuery.each(cs.split(/\s*,\s*/), function(i, it) {
			//jQuery(it + ' ' + ts).click();
			jQuery(it + ' .widgetbody').hide();
			jQuery(it + ' ' + ts).addClass('collapsed');
		});
	}
});