/*
* CartController
* ----------------------------------------
* @last_modified: 2007-12-26
* @author: Filatov Dmitry <alpha@design.ru>
*/

function CartController(
	aWidgetsNumber,
	oWidgetTotal,
	aElementsPrice,
	aElementsSum,
	aElementsRemove,
	oElementTotal
	) {

	this.aWidgetsNumber = aWidgetsNumber;
	this.oWidgetTotal = oWidgetTotal;
	this.aElementsPrice = aElementsPrice;
	this.aElementsSum = aElementsSum;
	this.aElementsRemove = aElementsRemove;
	this.oElementTotal = oElementTotal;

	this.aIds = [];
	this.aPrices = [];

	this.init();

}

CartController.COOKIE_NAME = 'order';

CartController.prototype = {

	init : function() {

		if(!this.aWidgetsNumber[0]) {
			return;
		}

		this.aWidgetsNumber[0].oForm.attachOuterObserver(this);

		for(var i = 0, oThis = this; i < this.aWidgetsNumber.length; i++) {

			this.aIds.push(this.aWidgetsNumber[i].getId().match(/^product_(.+)$/)[1]);
			this.aPrices.push(parseInt(this.aElementsPrice[i].innerHTML, 10));

			Common.Event.add(
				this.aElementsRemove[i],
				'click',
				function(iIndex) {

					return function(oEvent) {

						Common.Event.cancel(oEvent);

						oThis.removeByIndex(iIndex);

					}

				}(i)
				);

		}

		this.update();

	},

	// this method called by this.oForm on update
	update : function() {

		var
			iTotal = 0,
			sCookie = ''
			;

		for(var i = 0, iSum = 0, iNumber = 0; i < this.aElementsSum.length; i++) {

			iNumber = Math.floor(this.aWidgetsNumber[i].getValue().get());
			iSum = this.aPrices[i] * iNumber;
			iTotal += iSum;

			this.aElementsSum[i].innerHTML = iSum.formatNumber();

			if(iNumber > 0) {
				sCookie += (sCookie != ''? ',' : '') + this.aIds[i] + '=' + iNumber;
			}

		}

		Common.Cookie.set(CartController.COOKIE_NAME, sCookie, null, '/');

		this.oElementTotal.innerHTML = iTotal.formatNumber();
		this.oWidgetTotal.setValue(new Value(iTotal));

	},

	removeByIndex : function(iIndex) {

		this.aWidgetsNumber[iIndex].setValue(new ValueNumber(0));

	}

};


// this static method uses XForm for validation

CartController.checkCartItem = function(oWidget) {

	return !oWidget.getValue().isEmpty() && oWidget.getValue().get() >= 1;

};
