// TODO Make the differences between this and the copy in mod_bonsailatestpopular configurable so we don't need 2 copies
var AskQuestionLatestBox = new Class({
	initialize: function(container) {
		this.container = $(container);
		this.container.addClass('has-javascript');
		this._setupSections();
		this._setupTabs();
		this.showSection(0);
	},
	
	_setupSections: function() {
		this.sections = [];
		this.currentSection = -1;
		
		var tempSections = this.container.getElements('.ask-question-latest-section');
		tempSections.each(function(section, i) {
			var title = section.getElement('h4');
			this.sections[i] = {
				'id': section.getProperty('rel'),
				'title': title.getText(),
				'container': section
			};
			section.setStyle('display', 'none');
			title.remove();
		}, this);
	},
	
	_setupTabs: function() {
		this.tabContainer = new Element('div', { 'class': 'green-box-tabs-right' });

		this.sections.each(function(section, t) {
			section.tab = new Element('div', { 'class': 'green-box-tab green-box-tab-' + section.id + (t == 0 ? ' green-box-tab-first' : '') }).adopt(
				new Element('div', { 'class': 'green-box-tab-left' }).adopt(
					new Element('div', { 'class': 'green-box-tab-right' }).adopt(
						new Element('div', { 'class': 'green-box-tab-text' }).setText(section.title)
					)
				)
			);
			
			section.tab.addEvent('click', function(event) {
				event = new Event(event).stop();
				this.showSection(t);
			}.bindAsEventListener(this));

			this.tabContainer.adopt(section.tab);
		}, this);

		var temp = new Element('div', {
			'class': 'green-box-tabs' 
		}).adopt(
			new Element('div', { 'class': 'green-box-tabs-left' }).adopt(this.tabContainer)
		).injectTop(this.container);
		//this.tabContainer.injectTop(this.container);
	},
	
	_isValid: function(section) {
		return ($type(section) == 'number' && section > -1 && section < this.sections.length);
	},
	
	showSection: function(section) {
		if (this.currentSection == section || !this._isValid(section)) {
			return;
		}
		this.hideSection(this.currentSection);
		this.sections[section].container.setStyle('display', 'block');
		this.sections[section].tab.addClass('green-box-tab-selected');
		this.currentSection = section;
	},
	
	hideSection: function(section) {
		if (!this._isValid(section)) {
			return;
		}
		this.sections[section].container.setStyle('display', 'none');
		this.sections[section].tab.removeClass('green-box-tab-selected');
	}
});

window.addEvent('domready', function() {
	$$('.ask-question-latest-sections').each(function(el) {
		new AskQuestionLatestBox(el);
	});
});