/**
 * @author Sjors
 */
var CardStack = new Class({
	Implements: [Options],
	cards: {},
	selection: new Array(),
	pagesForSelection: 0,

	initialize: function (options) {
		this.setOptions(options);

		var cardStack = this;
		this.request = new Request({
			async: false,
			evalScripts: true,
			onSuccess: function (responseText) {
				var response     = JSON.decode(responseText);
				var newCardsHTML = '';

				cardStack.pagesForSelection = Math.ceil(response.total / Denham.config.pageSize); 

				if ($type(response.cards) == 'object') {
					for (var cardId in response.cards) {
						if (!cardStack.cards[cardId])
							newCardsHTML += response.cards[cardId];
						cardStack.selection.push(cardId);
					}

					Denham.createCardsFromHTML(newCardsHTML);
				}
			}
		});
	},


	/**
	 * Places an array with card objects on to the stack
	 * @param {Array} cards
	 */
	add: function (cards) {
		if (!(cards instanceof Array)) throw new Error('CardWarehouse::add - \'cards\' not an array');

		cards.each(function (card) {
			this.cards[card.id] = card;
		}, this);
	},


	/**
	 * Fetches and returns a selection of cards based on the section, category, filter and page 
	 * @param {Object} options
	 */
	getSelection: function (params) {
		if (!params) throw new Error('CardWarehouse::getSelection - \'options\' not an object');

		this.selection.empty();

		//set the filtering options
		var url;
		var page     = parseInt(params.page) || 1;
		var pageSize = params.pageSize || Denham.config.pageSize;
		var offset   = (page-1) * pageSize;

		if (params.query) {
			url = '/cards/' + offset + '-' + pageSize + '/search.json?q=' + params.query;
		} else {
			var section  = params.section || 'all';
			var category = params.category || 'all';
			var filter   = params.filter || 'all';

			url = '/cards/' + section + '/' + category + '/' + filter + '/' + offset + '-' + pageSize + '/list.json'
		}

		this.request.get(url);

		var selectionCards = new Array();
		this.selection.each(function (cardId) {
			selectionCards.push(this.cards[cardId]);
		}, this);

		return selectionCards;
	}
});