/* jslint verified 2008.11.19 */
/*jslint browser: true, onevar: false, undef: true, white: false, eqeqeq: true */
/*globals $, $$, Constants, Ajax, Song, User,
	bestUsers, bestStems, bestSongs, buildTopSection */
var Index = function () {

	var ids = {
		top: 'panelHolder', bestSongs: 'bestSongs', bestStems: 'bestStems', bestUsers: 'bestUsers',
		whatToDo: 'whatToDo'
	}, classes = {
		section: 'topSection', expander: 'topSectionExpand', content: 'topSectionContent',
		expanded: 'topSectionContract', header: 'topSectionHeader', moreLink: 'moreLink',
		hover: 'hover'
	};
	
	function doSection(section) {
		var header = section.getElementsByClassName(classes.header, 'div')[0],
			expander = section.getElementsByClassName(classes.expander, 'div')[0],
			content = section.getElementsByClassName(classes.content, 'div')[0];
		header.showing = false;
		
		function doClick() {
			if (header.showing) {
				content.hide();
				expander.removeClassName(classes.expanded);
			} else {
				content.show();
				expander.addClassName(classes.expanded);
			}
			header.showing = !header.showing;
		}
		//header.addClick(doClick);
		doClick();
		
		if (content.id === ids.bestSongs) {
			buildTopSection(bestSongs, content, 'song');
		} else if (content.id === ids.bestStems) {
			buildTopSection(bestStems, content, 'stem');
		} else if (content.id === ids.bestUsers) {
			buildTopSection(bestUsers, content, 'user');
		}
	}

	function setup() {
		var top = $(ids.top), i,
			sections = top.getElementsByClassName(classes.section, 'div');
		for (i=0; i<sections.length; ++i) { doSection(sections[i]); }

		var whatToDo = $('whatToDo');
		for (var i = 0; i < whatToDo.rows[0].cells.length; i++) {
			var cell = $$(whatToDo.rows[0].cells[i]);
			var a = cell.getChild('a');
			cell.addClick(function() { window.location = a.href; });
			cell.addEvent('mouseover', function() { this.addClassName(classes.hover); });
			cell.addEvent('mouseout', function() { this.removeClassName(classes.hover); });
		}
	}

	function buildTopSection(arr, holder, type) {
		var id, moreLinkHolder, moreLink;
		for (id in arr) {
			if (arr.hasOwnProperty(id)) {
				var obj = (type === 'song' || type === 'stem') ?
					new Song(id, arr[id], type === 'stem') : new User(id, arr[id]);
				if (typeof(obj) === 'object') {
					holder.appendChild(obj);
				}
			}
		}
		moreLinkHolder = document.create('div').classify(classes.moreLink);
		moreLink = moreLinkHolder.create('a').textify('more ' + type + 's').attrib('href', 'discover?t=' + type);
		holder.appendChild(moreLinkHolder);
	}

	window.addLoad(setup);
}();
