﻿var BookBrowser = Class.create();
BookBrowser.prototype = {
	initialize: function (xml_file_name) {
		this.rowSize = 5;
		this.browserContainer = 'browseCharacterWrapper';
		this.rowClass = 'browseCharacterRow';
		this.rowItemClass = 'browseCharacterItem';
		this.itemElements = new Array();
		this.loadXmlFile(xml_file_name);
	},
	
	loadXmlFile: function (xml_file) {	
		if (!xml_file) 
			throw("Browser: XML file attribute is blank");
		
		new Ajax.Request(xml_file, {
			onSuccess: this.xmlReady.bind(this),
			onException: this.xmlReadyWrapper.bind(this),
			method: 'get'
		});
		
	},
	
	xmlReadyWrapper: function (request, e) {
		this.xmlReady(request.transport);
	},
	
	xmlReady: function (transport) {
		var rootElement = transport.responseXML.getElementsByTagName('favorites').item(0);
		this.items = rootElement.getElementsByTagName('item');
		this.showBooks();
	},
	
	showBooks: function () {
		this.items.length.times(this.showBooksIterator.bind(this));
		this.items.length.times(this.itemsIntoRowsIterator.bind(this));
		this.appendCurrentRow();
		if (!this.appended) this.appendCurrentRow();
	},
	
	showBooksIterator: function (index) {
		var item = this.items.item(index);
		
		var div = new Element('div', {'class': this.rowItemClass});
		var a = new Element('a', {
			href: this.getUrl(item),
			title: this.getTitle(item)
		}).update(this.getTitle(item));
		
	
		var img = new Element('img', {
			src: this.getImage(item),
			alt: this.getTitle(item),
			width: '84',
			height: '113'
		});
		
		a.insert({top: img});
		div.insert(a);
		this.itemElements[index] = div;
	},
	
	itemsIntoRowsIterator: function (index) {
		if ((index != 0) && (index%this.rowSize == 0)) {
			this.appendCurrentRow();
			this.createNewRow();
		} else if (index == 0) {
			this.createNewRow();
		}
		this.appended = false;
		this.currentRow.insert(this.itemElements[index]);
	},
	
	addClear: function () {
		return new Element('br', {'style': 'clear: both;'});
	},
	
	createNewRow: function () {
		this.currentRow = new Element('div', {'class': this.rowClass});
	},
	
	appendCurrentRow: function () {
		this.currentRow.insert(this.addClear());
		$(this.browserContainer).insert(this.currentRow);
		this.appended = true;
	},
	
	getNodeValue: function (item, value) {
		return item.getElementsByTagName(value)[0].firstChild.nodeValue;
	},
	
	getUrl: function (item) {
		return this.getNodeValue(item, 'url');
	},
	
	getTitle: function (item) {
		return this.getNodeValue(item, 'title');
	},
	
	getImage: function (item) {
		return this.getNodeValue(item, 'image');
	}
}