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 = jsonRpcWrapper.fetch({
		    method: 'user.transactionsorders', 
			params: [],
			onSuccess: this._load_data.bind(this),
			onError: function () { console.log( 'OrderList JSON failed to load ' ) }
		});
		return id;
	},
	
	_load_data: function (jsonRpcResponse) {
        var data = jsonRpcResponse.getValue();
        // If we got data, it will be an array of hashes of trans info.
		if (data) {
		    var transList = $A(data);
		    transList.each ( function(transInfo) {
		        this.pendingOrderList[this.pendingOrderList.length] = $H(transInfo);
		    }, 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;
	},
	
	getLastOrder: function() {
	    // We get the orders sorted by trans id.  Thus, assume last on the list is most recent.
	    var lastOrder = ( this.pendingOrderList.length > 0 ?
	                      this.pendingOrderList[this.pendingOrderList.length-1] :
	                      this.pendingOrderList[0] );
	    return lastOrder;
	}
	
	
});

