var OrderList = Class.create({
	
    initialize: function(args) {
    	
		// We'll create two lists, one for pending orders and one for shipped orders.
    	this.pendingOrderList = [];
		this.shippedOrderList = [];
		this.callback = null;	
    	
		// Load up passed params
        Object.extend(this, args || {});
		
		var id = jsonrpc.fetch( 'user.orders', 
			[],
			{ 
				onSuccess: this._load_data.bind(this),
				onFailure: function () { console.log( 'OrderList JSON failed to load ' ) }
			}
		);
		return id;
	},
	
	_load_data: function (t) {
		var o = t.responseText.evalJSON()[0];
		if (o.error == null) {
			var data = $H(o.result);
			var shipped = $H(data.get('shipped'));
			var pending = $H(data.get('pending'));
			
			shipped.each ( function(pair) {
				var i = pair.key.toInt();
				this.shippedOrderList[i] = $H(pair.value);
			}, this );
			
			pending.each ( function(pair) {
				var i = pair.key.toInt();
				this.pendingOrderList[i] = $H(pair.value);
			}, this );
		}
		if ( this.callback ) {
			this.callback();
		}
		document.fire("orders:loaded");
	},
	
	hasOrders: function() {
		return ( this.pendingOrderList.length > 0 || this.shippedOrderList.length > 0 );
	},
	
	// Return an order by index, starting with pending orders
	getByIndex: function(i) {
		// If the requested index is within the pending list, return it
		if ( i < this.pendingOrderList.length ) {
			return this.pendingOrderList[i];
		} else {
			// Subtract off the length of the pending list and check the shipping list.
			i -= this.pendingOrderList.length;
			if ( i < this.shippedOrderList.length ) {
				return this.shippedOrderList[i];
			}
		}
		// Didn't find nuthin.
		return null;
	}
	
	
});

