// vim: set ft=javascript noet ts=2:
// ----------------------------------
// Tab Class
// ----------------------------------
// all tabs subclass the tab class so they can be
// notified when they are coming in to view.
var TAB_TEMPLATE = new Template("<img src='#{icon}'><p class='emboss'>#{tabName}</p><p>#{tabName}</p><p class='counter' style='display: none;'></p>");
var Tab = Class.create({
	initialize: function(tab, notifyURL, notifyPeriod) {
		this.tabName = tab.name;
		this.reference = tab.reference;
		this.icon = tab.icon;
		this.hasBeenShown = false;
		
		this.cleanID = tab.name.toLowerCase().replace(/[^a-z]/g, '_');
		this.tabID = this.cleanID + '_button';
		this.contentID = this.cleanID;

		this.notifyURL = notifyURL;
		if (notifyURL)
			new PeriodicalExecuter(this.doNotify.bind(this), notifyPeriod);
	},

	display: function() {
		if (!this.hasBeenShown) {
			this.firstDisplay();
			this.hasBeenShown = true;
		}
		this.willDisplay();
	},
	
	toHTML: function() {
		var me = this;
		var e = new Element('li', {id: this.tabID});
		e.insert(TAB_TEMPLATE.evaluate(this));
		e.observe('click', function(event) {
			switchToTab(me.tabID);
		});
		return e;
	},

	doNotify: function() {
		ajaxWrapper(this.notifyURL, {course: courseID}, null, this.uponNotify.bind(this), function(transport, msg) { console.log(msg); });
	},

	setNotification: function(value) {
		var counter = $$('#' + this.tabID + ' .counter').first();
		counter.update(value);
		counter.show();
	},

	clearNotification: function() {
		var counter = $$('#' + this.tabID + ' .counter').first();
		counter.hide();
	}
});



// ----------------------------------
// Tab Subclasses
// ----------------------------------
// Page Tab
var PageTab = Class.create(Tab, {
	initialize: function($super, tab) {
		$super(tab);
		this.contentID = this.cleanID + '_page';
	},

	firstDisplay: function() {
		var tab = new Element('div', {id: this.contentID, dispay: 'none'});
		tab.addClassName('tab');
		var slider = new Element('div');
		slider.addClassName('slider');
		var page = new Element('div');
		page.addClassName('container container1');
		var heading = new Element('h1');
		page.appendChild(heading);
		var content = new Element('div', {id: this.contentID + '_content'});
		content.addClassName('confluence');
		page.appendChild(content);
		slider.appendChild(page);
		tab.appendChild(slider);
		$('content').insert(tab);

		loadFlatpage(this.reference, this.contentID);
	},
	
	willDisplay: function() {}
});


// Questions Tab
var QuestionsTab = Class.create(Tab, {
	initialize: function($super, tab) {
		$super(tab);
		this.contentID = 'questions';
	},
	
	firstDisplay: function() {
		loadQuestionSets({prefix: '', user: null});
	},
	
	willDisplay: function() {}
});


// Exam Tab
var ExamTab = Class.create(Tab, {
	initialize: function($super, tab) {
		$super(tab);
		this.contentID = 'exams';
	},
	
	firstDisplay: function() {
		loadExams();
	},
	
	willDisplay: function() {}
});


// Leader Tab
var LeadersTab = Class.create(Tab, {
	initialize: function($super, tab) {
		$super(tab);
		this.contentID = 'leaders';
	},
	
	firstDisplay: function() {},
	
	willDisplay: function() {
		loadLeaderBoard();
	}
});


// Forums Tab
var ForumsTab = Class.create(Tab, {
	initialize: function($super, tab) {
		$super(tab);
		this.contentID = 'forums';
	},
	
	firstDisplay: function() {
		loadForums();
	},
	
	willDisplay: function() {}
});


// Profile Tab
var ProfileTab = Class.create(Tab, {
	initialize: function($super, tab) {
		$super(tab);
		this.contentID = 'profile';
	},
	
	firstDisplay: function() {},
	
	willDisplay: function() {
		loadUserProfile();
	}
});


// Logout Tab
var LogoutTab = Class.create(Tab, {
	initialize: function($super, tab) {
		$super(tab);
	},

	firstDisplay: function() {},
	
	willDisplay: function() {
		logout();
	}
});


// User Groups Tab
var UserGroupsTab = Class.create(Tab, {
	initialize: function($super, tab) {
		$super(tab);
		this.contentID = 'groups';
	},
	
	firstDisplay: function() {},
	
	willDisplay: function() {
		loadUserGroups();
	}
});


// Conversations Tab
var ConversationsTab = Class.create(Tab, {
	initialize: function($super, tab) {
		$super(tab, 'api/messages/notify', 60);
		this.contentID = 'conversations';
	},
	
	firstDisplay: function() {},
	
	willDisplay: function() {
		loadConversations(true);
	},

	uponNotify: function(json) {
		if (json.notification.unread)
			this.setNotification(json.notification.unread);
		else
			this.clearNotification();
	}
});


// Problems Tab
var ProblemsTab = Class.create(Tab, {
	initialize: function($super, tab) {
		$super(tab);
		this.contentID = 'problems';
		
		// load associated records
		languageStore.load();
		tagStore.load();
		fileStore.load();
		testCodeStore.load();
		problemStore.load();
	},
	
	firstDisplay: function() {},
	
	willDisplay: function(){
		// make sure we've got updated problems each time (to minimise edit race conditions)
	}
});

// Switch Course Tab
var SwitchCoursesTab = Class.create(Tab, {
	initialize: function($super, tab) {
		$super(tab);
		this.contentID = 'switch_courses';
	},
	
	firstDisplay: function() {
	},
	
	willDisplay: function() {
		loadSwitchCourses();
	}
});


// Edit Files Tab
var EditFilesTab = Class.create(Tab, {
	initialize: function($super, tab) {
		$super(tab);
		this.contentID = 'edit_files';
	},
	
	firstDisplay: function() {
	},
	
	willDisplay: function() {}
});


// Edit Code Tab
var EditCodeTab = Class.create(Tab, {
	initialize: function($super, tab) {
		$super(tab);
		this.contentID = 'edit_code';
	},
	
	firstDisplay: function() {},
	
	willDisplay: function() {}
});


// Survey Tab
var SurveyTab = Class.create(Tab, {
	initialize: function($super, tab) {
		$super(tab);
		this.contentID = 'surveys';
	},
	
	firstDisplay: function() {},
	
	willDisplay: function() {
		loadSurveys(true);
	}
});

// Registration Tab
var RegistrationTab = Class.create(Tab, {
	initialize: function($super, tab) {
		$super(tab);
		this.contentID = 'registration';
	},
	
	firstDisplay: function() {},
	
	willDisplay: function() {}
});

// Enrol Tab
var EnrolTab = Class.create(Tab, {
	initialize: function($super, tab) {
		$super(tab);
		this.contentID = 'enrol';
	},
	
	firstDisplay: function() {
		loadEnrolTab();
	},
	
	willDisplay: function() {}
});

// Login Tab
var LoginTab = Class.create(Tab, {
	initialize: function($super, tab) {
		$super(tab);
	},

	firstDisplay: function() {},
	
	willDisplay: function() {
		document.location = '/account/';
	}
});

// Reset Password Tab
var ResetPasswordTab = Class.create(Tab, {
	initialize: function($super, tab) {
		$super(tab);
		this.contentID = 'reset_password';
	},
	firstDisplay: function() {},
	willDisplay: function() {}
});

// Documents Tab
var DocumentsTab = Class.create(Tab, {
	initialize: function($super, tab) {
		$super(tab);
		this.contentID = 'documents';
	},
	firstDisplay: function() { },
	willDisplay: function() {
		loadDocuments(true);
	}
});


// store a reference to each of the tab classes indexed by type id
var tabConstructors = [];
tabConstructors[0]  = PageTab;
tabConstructors[1]  = QuestionsTab;
tabConstructors[2]  = LeadersTab;
tabConstructors[3]  = ForumsTab;
tabConstructors[4]  = ProfileTab;
tabConstructors[5]  = EditFilesTab;
tabConstructors[6]  = UserGroupsTab;
tabConstructors[7]  = ConversationsTab;
tabConstructors[8]  = ProblemsTab;
tabConstructors[9]  = SwitchCoursesTab;
tabConstructors[10] = EditCodeTab;
tabConstructors[11] = ExamTab;
tabConstructors[12] = SurveyTab;
tabConstructors[13] = RegistrationTab;
tabConstructors[14] = EnrolTab;
tabConstructors[15] = LoginTab;
tabConstructors[16] = ResetPasswordTab;
tabConstructors[17] = LogoutTab;
tabConstructors[18] = DocumentsTab;
var SWITCH_COURSES_TAB_TYPE = 9;
var LOGOUT_TAB_TYPE = 17;

// store the tabs
var tabs = {};
var currentTab = null;


// ----------------------------------
// Tab UI
// ----------------------------------
function loadTabs(tabList, is_index, ncourses, series_name) {
	// re-initialise the list of tabs
	tabs = {};
	currentTab = null;
	firstTab = null;
	var sidebar = $('sidebar_tabs');
	sidebar.update();
	
	// add account management tags if not the index page
	if (!is_index) {
		if (ncourses > 1 || series_name == 'account')
			tabList.push({type: SWITCH_COURSES_TAB_TYPE, name: 'Courses', reference: '', icon: 'images/icons/switch_course.png'});
		tabList.push({type: LOGOUT_TAB_TYPE, name: 'Logout', reference: '', icon: 'images/icons/logout.png'});
	}
	
	// generate each tab
	tabList.each(function(tabInfo) {
		tab = new tabConstructors[tabInfo.type](tabInfo);
		if(!firstTab)
			firstTab = tab;
		tabs[tab.tabID] = tab;
		sidebar.insert(tab.toHTML());
	});
	
	switchToTab(firstTab.tabID);
}

function switchToTab(newTab) {
	// quick check to see if we're already displaying the tab
	var tab = tabs[newTab];
	if(tab == currentTab)
		return;
	
	// switch the tabs
	tab.clearNotification();
	tab.display();
	if (currentTab)
		$(currentTab.contentID).fade({duration: 0.3});
	if ($(tab.contentID)) // need this check in the case of logout, which doesn't have anything to switch to
		$(tab.contentID).appear({duration: 0.3});
	
	// swap the selected button
	if(currentTab)
		$(currentTab.tabID).toggleClassName('selected');
	$(tab.tabID).toggleClassName('selected');
	currentTab = tab;
}
