jQuery(document).ready(function($){

	var widgetID = "resource-center-widget";
	var tabList;

	tabList = $('#secondary-content dl#' + widgetID);
	if ( tabList.length > 0 ) {
    		tabList.accordion( { collapsible: true, active: false });
	}

	tabList = $('#main-content dl#' + widgetID);
	if ( tabList.length > 0 ) {
		var newDiv  = $("<div>").attr("id", tabList.attr("id"));

		tabList.find('dd').each(function(i) {
			newDiv.append(
				$("<div>").append(
					$(this).clone().contents()
				).attr("id", $(this).attr("id"))
			 	.attr("class", $(this).attr("class"))
			);

			var tab      = $(this).attr("id")
			var tab_name = $(this).attr("id").match(/^TAB__(.*)/)[1];
			$('#extra-nav #resource-center li#' + tab_name + " a").click(function(e){
				$(newDiv).tabs('select', tab);
				e.preventDefault();
			});
		});

		var newUl = $("<ul>");
		tabList.find('dt').each(function(i) {
			newUl.append(
				$("<li>").append(
					$(this).clone().contents()
				)
			);
		});

		newDiv.append(newUl);
		$('#main-content dl#' + widgetID).replaceWith(newDiv);

		newDiv.tabs({
			cookie: {expires: (1 / 12)},
			select: function(e, ui) {
					var old_num = $(newDiv).tabs('option', 'selected');
					var old_panel = $(e.target).data().tabs.panels[old_num];
					var old_id = $(old_panel).attr('id');
					var old_name = old_id.match(/^TAB__(.*)/)[1];

					// console.log('Leaving ' + old_name);
					$('body').removeClass(old_name);

					var tab_name = ui.panel.id.match(/^TAB__(.*)/)[1];
					// console.log('Selecting ' + tab_name);
					$('body').addClass(tab_name);

					return true;
				}
		});

		// console.log('location.hash=' + location.hash);
		if ( location.hash.length > 0 ) {
			var hash = location.hash.match(/^#(.+)/)[1];
			if ( hash.length > 0 ) {
				// console.log('selecting #TAB__' + hash);
				newDiv.tabs( 'select', '#TAB__' + hash );
			}
		}
	}
});

