/* You pretty much have to subclass this in order to define the units to initialize on each tab. */

BLIP.Class.create("BLIP.Unit.TabbedContent.AjaxTabbedContent", BLIP.Unit.TabbedContent,
	function(config) {
		BLIP.Unit.TabbedContent.call(this, config);
	},
	{
		tabCache : {},

		/* tablinks have classnames, e.g., "StaffPicks". That corresponds to an index in this
		 * property. This property is a hash of tablink classnames that reference arrays of units:
		 *  { StaffPicks : [BLIP.Unit.Flipper.ShowPosterFlipper] }
		 */
		tabSubUnitsReference : {},

		init : function() {
			BLIP.Unit.TabbedContent.prototype.init.call(this);
			this.initTabContent(0);
		},

		onTabClick : function(tabIndex) {
			if(this.tabCache[tabIndex]) {
				this.fillTabContent(this.tabCache[tabIndex], tabIndex);
			}
			else {
				this.loadTab(tabIndex);
			}
		},

		loadTab : function(tabIndex) {
			var thisContext = this;
			$.get(this.domRoot.find(".TabLinks li").eq(tabIndex).attr("data-source-uri"), function(content) {
				thisContext.tabCache[tabIndex] = content;
				thisContext.fillTabContent(content, tabIndex);
			});
		},

		fillTabContent : function(content, tabIndex) {
			if(this.domRoot.find(".TabContent > li[data-tab-n="+tabIndex+"]").length) {
				this.setCurrentTab(tabIndex);
			}
			else {
				var tab = $("<li data-tab-n="+tabIndex+">").append($(content).find(".ShowEpisodeList"));
				this.domRoot.find(".TabContent").append(tab);
				this.setCurrentTab(tabIndex, tab);
				this.initTabContent(tabIndex, tab);
			}
		},

		initTabContent : function(tabIndex) {
			var tabUnits = this.tabSubUnitsReference[this.domRoot.find(".TabLinks li").eq(tabIndex).attr("data-unit")],
					i;

			if (tabUnits && tabUnits.length) {
				for (i = 0; i < tabUnits.length; i++) {
					this.initSubUnit(tabUnits[i]);
				}
			}
		},

		setCurrentTab : function(tabIndex, tab) {
			this.domRoot.find(".Current")
				.removeClass("Current");
			this.domRoot.find(".TabLinks > li").eq(tabIndex).addClass("Current");

			if(tab) {
				tab.addClass("Current");
			}
			else {
				this.domRoot.find(".TabContent > li[data-tab-n="+tabIndex+"]").addClass("Current");
			}
		}
	}
);

