var Sm = Sm || {}

Sm.BookChooser = Class.create({

	initialize: function(options) {
		this.disciplineDivs = $$('input[type=radio][name=' + options.disciplineRadioName + ']');
		this.sort = $(options.sort);
		this.chooser = $(options.chooser);
		this.books = new Hash();
		options.data.each(function(book) {
			this.books.set(book.textbook.id, book.textbook);
		}.bind(this));
		this.bookField = $(options.field);
		this.numColumns = options.numColumns;
		this.onChoice = options.onChoice || Prototype.emptyFunction;
		this.bookDivs = new Hash();
		this.detail = $(options.detail);
		this.chooser.select('div.book').each(function(book) {
			this.bookDivs.set(book.id, book);
			book.hide();
			book.observe('click', this.selectBook.bindAsEventListener(this, book, true));
		}.bind(this));
		this.sort.observe('change', this.filter.bind(this));
		this.disciplineDivs.each(function(radio) {
			radio.observe('click', this.filter.bind(this));
		}.bind(this));
		if ($F(this.bookField) != null && $F(this.bookField) != '') {
			this.selectBook(null, this.bookDivs.get('book_' + $F(this.bookField)));
		}
		this.filter();
	},

	getDiscipline: function() {
		var checked = this.disciplineDivs.find(function(d) {
			return d.getValue();
		});
		return checked.getValue();
	},

	getSort: function() {
		return $F(this.sort);
	},

	filter: function() {
		// Filter by discipline
		var discipline = this.getDiscipline();
		var filteredBooks = this.books.values().findAll(function(book) {
			return book.title_id == discipline;
		});

		// Sort the books
		var sortOptions = this.getSort().split(':');
		var sortAttribute = sortOptions.first();
		var reverse = false;
		if (sortOptions.length > 1) reverse = (sortOptions[1] == 'reverse');

		filteredBooks = filteredBooks.sortBy(function(book) { return book[sortAttribute]; });
		if (reverse) filteredBooks = filteredBooks.reverse();

		// Hide all the displayed books and reset 'clear' values
		this.books.values().each(function(book) {
			this.bookDivs.get('book_'+book.id).hide().setStyle({ clear: 'none' });
		}.bind(this));

		// Display them in order
		var currentIndex = 0;
		filteredBooks.each(function(book) {
			var bookDiv = this.bookDivs.get('book_'+book.id);
			this.chooser.appendChild(bookDiv);
			bookDiv.setStyle({ clear: (currentIndex++ % this.numColumns) == 0 ? 'both' : 'none' });
			bookDiv.show();
		}.bind(this));
	},

	selectBook: function(e, book, realClick) {
		var id = book.id.split('_').last();
		this.bookField.setValue(id);
		this.chooser.select('.selected').each(function(book) { book.removeClassName('selected'); });
		book.addClassName('selected');
		this.detail.select('div.book_detail').each(function(div) { div.hide(); });
		this.detail.select('div.book_detail').detect(function(div) { return div.id.split('_').last() == id }).show();
		if (realClick) this.onChoice.bind(book).call();
	}

});

Sm.BookChooser.activate = function(options) {
	document.observe("dom:loaded", function() {
		new Sm.BookChooser(options);
	});
};