function BillItem() {
	this.id = 0;
	this.name = '';
	this.price = 0;
	this.count = 0;
	this.options = 0;	
	this.discount = 0;
}

function Bill() {
	this.bill = [];

	this.addItem = __addItem;
	this.removeItem = __remItem;
	this.getBill = __getBill;
	this.onchange = new Event();
	this.__getItemIndex = __getItemIndex;
}

function __getItemIndex(id) {
	for (var i = 0; i < this.bill.length; i++) {
		if (this.bill[i].id == id) {
			return i;
		}
	}
	return -1;
}

function __addItem(id, count, price, name, options, discount) {
	var index = this.__getItemIndex(id);
	if (index == -1) {
		var item = new BillItem();
		item.id = id;
		item.name = name;
		item.count = count;
		item.price = price;
		item.options = options;
		item.discount = discount;

		this.bill.push(item);
	} else {
		this.bill[index].count += count;
	}
	this.onchange.trigger(this);
}

function __remItem(id, count) {
	var index = this.__getItemIndex(id);
	
	if (index > -1) {
		this.bill[index].count -= count;
		if (this.bill[index].count <= 0) {
			//really delete item
			this.bill.splice(index, 1);
		}
	}

	this.onchange.trigger(this);
}

function __sortBillItemsById(item1, item2) {
	return item1.id - item2.id;
}

function __getBill() {
	result = new Array();

	for (var i = 0; i < this.bill.length; i++) {
		if (this.bill[i].count > 0) {
			result.push(this.bill[i]);
		}
	}
	result.sort(__sortBillItemsById);

	return result;
}


var bill = new Bill();
