/**
 * this is the book we browse by the ctrl
 * @param {Object} mapping
 */
Book = function (mapping, prev_element, next_element) {
	this.mapping = mapping
	this.texts = {}
	this.lineup = []
	for (i in this.mapping) {
		var id = this.mapping[i][0]
		var text = this.mapping[i][1]
		this.texts [id] = $('text_' + id)
		if (text.length) {
			for (j in text) {
				// connect all items and line them up
				var item = $('item_' + text[j])
				item.text_id = id
				this.lineup.push(item)
				if (this.current_item === null) this.show_item(this.lineup.length - 1) 
			}
		} 
	}
	
	// connect ctrl
	connect(prev_element, 'onclick', bind(function() {
		this.prev()
	}, this))
	connect(next_element, 'onclick', bind(function() {
		this.next()
	}, this))
}

Book.prototype = {
	mapping: {},
	lineup: [],
	texts: {},
	current_item_j: null,
	current_item: null,
	current_text: null,
	prev: function () {
		if (this.current_item_j > 0) this.show_item(this.current_item_j - 1)
	},
	next: function () {
		if (this.current_item_j < this.lineup.length - 1 ) this.show_item(this.current_item_j + 1)
	},
	show_text: function(i) {
		if (this.texts[i] == this.current_text) return
		if (this.current_text !== null) {
			fade(this.current_text)
		}
		this.current_text = this.texts[i]
		appear(this.current_text)
	},
	show_item: function (j) {
		if (this.lineup[j] == this.current_item) return
		if (this.current_item !== null) {
			fade(this.current_item)
		}
		this.current_item_j = j
		this.current_item = this.lineup[j]
		appear(this.current_item)
		this.show_text(this.current_item.text_id)
	}
}
