(function () {
	
var View = {
	LIST: 0,
	GRID: 1
};

Hedera.Catalog = new Class
({
	Extends: Hedera.Form
	
	,_menuShown: false

	,open: function ()
	{
		this.close ();
		this.isOpen = true;
	
		if (!localStorage.getItem ('hederaGuest'))
		{		
			Hedera.BasketChecker.check (this.conn, this.hash,
				this.onBasketCheck.bind (this));
		}
		else
		{
			var query = 'CALL basket_configure_for_guest ()';
			this.conn.execQuery (query, this.loadUi.bind (this));
		}
	}

	,onBasketCheck: function (isOk)
	{
		if (isOk)
			this.loadUi ();
	}
	
	,activate: function ()
	{
		this.$.items.setInfo ('a', 'Articles', 'vn2008', ['item_id']);
		document.body.appendChild (this.$.rightPanel);
	
		if (localStorage.getItem ('hederaView'))
			this.setView (parseInt (localStorage.getItem ('hederaView')));
		else
			this.setView (View.GRID);

		this.onRealmChange ();
		this.refreshTitle ();
		this.onParamsChange ();
	}

	,deactivate: function ()
	{
		this.hideMenu ();
		this.gui.$.topBar.style.backgroundColor = '';
		Vn.Node.remove (this.$.rightPanel);
	}

	,setView: function (view)
	{
		if (view === View.GRID)
		{
			this.$.viewButton.setProperties ({
				icon: 'view-list',
				tip: _('List view')
			});
			this.view = View.GRID;
			var className = 'grid-view';
		}
		else
		{
			this.$.viewButton.setProperties ({
				icon: 'view-grid',
				tip: _('Grid view')
			});
			this.view = View.LIST;
			var className = 'list-view';
		}
		
		var node = this.$.gridView.node;
		node.className = className;
		localStorage.setItem ('hederaView', this.view);
	}
	
	,onSwitchViewClick: function ()
	{
		this.setView (this.view === View.LIST ?
			View.GRID : View.LIST);
	}
	
	,onBasketReady: function (form)
	{
		if (form.get ('method') != 'PICKUP')
			Vn.Node.setText (this.$.method, _('Agency'));
		else
			Vn.Node.setText (this.$.method, _('Warehouse'));
	}
	
	,onOrderChange: function (e)
	{
		var value = e.target.value;	
		var sortField = value.substr (2);
		var sortWay = value.charAt (0) === 'A' ?
			Db.Model.SortWay.ASC : Db.Model.SortWay.DESC;
		
		if (sortField)
			this.$.items.sortByName (sortField, sortWay);
		
		this.hideMenu ();
	}

	,onParamsChange: function ()
	{
		var params = this.params.$;
		var shouldRefresh = params.search ||
			params.realm && (
				params.type ||
				params.color ||
				params.origin ||
				params.category ||
				params.producer
			);

		if (shouldRefresh)
		{
			var filterSql = this.$.filter.render (params);
			var modelParams = {
				filter: new Sql.String ({query: filterSql})
			};
			this.$.items.refresh (modelParams);

			this.hideMenu ();
			this.$.order.style.display = 'block';
		}
		else
		{
			this.$.items.clean ();
			this.$.order.style.display = 'none';
		}
	}
	
	,onRealmChange: function ()
	{
		var newValue = this.params.$.realm;
		this.$.filters.style.display = newValue ? 'block' : 'none';
		this.$.realmMsg.style.display = newValue ? 'none' : 'block';
		this.refreshTitleColor ();
	}

	,refreshTitleColor: function ()
	{
		var realms = this.$.realms;
		var realm = this.params.$.realm;
		var color = null;

		if (realm)
		{
			var row = realms.search ('id', realm);

			if (row != -1)
				color = '#'+ realms.get (row, 'color');
		}

		this.gui.$.topBar.style.backgroundColor = color;
	}
	
	,refreshTitle: function ()
	{
		var types = this.$.types;
		var type = this.params.$.type;		
		var title = _('Catalog');

		if (type)
		{
			var row = types.search ('tipo_id', type);

			if (row != -1)
				title = types.get (row, 'name');
		}

		Vn.Node.setText (this.$.title, title);
	}

	,onRightPanelClick: function (event)
	{
		event.stopPropagation ();
	}

	,onShowMenuClick: function (event)
	{
		this._menuShown = true;
		event.stopPropagation ();
		this.gui.showBackground ();
		Vn.Node.addClass (this.$.rightPanel, 'show');
		this.hideMenuCallback = this.hideMenu.bind (this);
		document.addEventListener ('click', this.hideMenuCallback);
	}

	,hideMenu: function ()
	{
		if (!this._menuShown)
			return;

		this.gui.hideBackground ();
		Vn.Node.removeClass (this.$.rightPanel, 'show');
		document.removeEventListener ('click', this.hideMenuCallback);
		this.hideMenuCallback = null;
	}
	
	,isGuest: function ()
	{
		if (localStorage.getItem ('hederaGuest'))
		{
			Htk.Toast.showError (_('YouMustBeLoggedIn'));
			return true;
		}
		
		return false;
	}
	
	,onBasketClick: function ()
	{
		if (this.isGuest ())
			return;

		this.hash.$ = {form: 'ecomerce/basket'};
	}
	
	,onConfigureClick: function ()
	{
		if (this.isGuest ())
			return;

		this.hash.$ = {form: 'ecomerce/checkout'};
	}

	,onAddItemClick: function (button, form)
	{
		if (this.isGuest ())
			return;

		this.onEraseClick ();
		this.$.card.row = form.row;
		this.$.cardLot.assign ({item: form.$.item_id});
		this.$.cardPopup.show (button.node);
	}
	
	,onAddLotClick: function (column, value, rowIndex)
	{
		var row = this.$.itemLots.getObject (rowIndex);
		var lotAmount = this.items[row.warehouse];

		if (lotAmount === undefined)
			lotAmount = 0;
		
		if (lotAmount < row.available)
		{
			var newAmount = lotAmount + row.grouping;
		
			if (newAmount > row.available)
				newAmount = row.available;
		
			this.items[row.warehouse] = newAmount;
			this.$.amount.value += newAmount - lotAmount;
		}
		else
			Htk.Toast.showError (_('NoMoreAmountAvailable'));
	}
	
	,onConfirmClick: function ()
	{
		var sql = '';
		var query = 'CALL basket_item_add (#warehouse, #item, #amount);';
		var amountSum = 0;

		for (var warehouse in this.items)
		{
			var amount = this.items[warehouse];
			amountSum += amount;
			
			var params = {
				item: this.$.cardItem.value,
				warehouse: warehouse,
				amount: amount
			};
			sql += this.conn.render (query, params);
		}

		if (amountSum > 0)
		{
			this.conn.execQuery (sql);

			var itemName = this.$.card.$.Article;
			Htk.Toast.showMessage (
				sprintf (_('Added%dOf%s'), amountSum, itemName));
		}

		this.$.cardPopup.hide ();
	}
	
	,onEraseClick: function ()
	{
		this.$.amount.value = 0;
		this.items = {};
	}
	
	,onPopupClose: function ()
	{
		this.onEraseClick ();
		this.$.card.row = -1;
		this.$.cardItem.value = undefined;
	}

	,onStatusChange: function ()
	{
		this.$.cardPopup.reset ();
	}
});

Vn.Filter = new Class
({
	Extends: Htk.Field
	,Tag: 'vn-filter'
	,Properties:
	{
		model:
		{
			type: Db.Model
			,set: function (x)
			{
				this._model = x;
				this._select.model = x;
				this._refreshModelLot ();
			}
			,get: function ()
			{
				return this._model;
			}
		},
		placeholder:
		{
			type: String
			,set: function (x)
			{
				this._select.placeholder = x;
				this._placeholder = x;
			}
			,get: function ()
			{
				return this._placeholder;
			}
		},
		filter:
		{
			type: Sql.Filter
			,set: function (x)
			{
				this._filter = x;
				this._modelLot.assign ({filter: x});
				this._refreshModelLot ();
			}
			,get: function ()
			{
				return this._filter;
			}
		},
		lot:
		{
			type: Vn.LotIface
			,set: function (x)
			{
				this._modelLot.source = x;
				this._setLot (x);
			}
			,get: function ()
			{
				return this._lot;
			}
		},
		name:
		{
			type: String
			,set: function (x)
			{
				this._modelLot.fields = [x];
				this._setName (x);
			}
			,get: function ()
			{
				return this._name;
			}
		}
	}
	
	,_valueColumnIndex: 0
	,_showColumnIndex: 1
	
	,initialize: function (props)
	{
		var node = this.createRoot ('div');
		node.className = 'vn-filter';
		
		this._select = new Htk.Combo ();
		this._select.on ('mousedown', this._onMouseDown, this);
		this._select.on ('changed', this._onChange, this);
		this._select.on ('ready', this._onReady, this);
		this.node.appendChild (this._select.node);
		
		this._ul = this.createElement ('ul');
		this.node.appendChild (this._ul);
		
		this._modelLot = new Vn.LotQuery ();
		this.parent (props);
	}

	,_refreshModelLot: function ()
	{
		if (this._model && this._filter)
			this._model.lot = this._modelLot;
	}
	
	,_onMouseDown: function ()
	{
		if (this._model && this._model.status === Db.Model.Status.CLEAN)
		{
			var params = {
				filter: this._filter
			};

			this._model.refresh ();
		}
	}
	
	,_onUnselectClick: function ()
	{
		this._removeSelectionNode ();
		this.valueChanged (undefined);
	}
	
	,_removeSelectionNode: function ()
	{
		if (this._lastLi)
		{
			Vn.Node.remove (this._lastLi);
			this._lastLi = null;
			this._label = null;
		}		
	}
	
	,_onChange: function ()
	{
		if (this._select.value === null
		|| this._select.value === undefined)
			return;
		
		var value = this._select.value;
		this._selectValue (value);
		this.valueChanged (value);
	}
	
	,_onReady: function ()
	{
		if (this._emptyLabel)
			this._refreshLabel ();
	}
	
	,_onTimeout: function ()
	{
		this._select.value = null;
	}
	
	,putValue: function (value)
	{
		this._selectValue (value);
	}
		
	,_selectValue: function (value)
	{
		this._removeSelectionNode ();

		if (value === null || value === undefined)
			return;

		var li = this._lastLi = this.createElement ('li');
		this._ul.appendChild (li);
			
		var button = this.createElement ('button');
		button.addEventListener ('click',
			this._onUnselectClick.bind (this, li));
		li.appendChild (button);
		
		var icon = new Htk.Icon ({
			icon: 'close',
			alt: _('Close')
		});
		button.appendChild (icon.node);

		var text = this._label = this.createTextNode ('');
		li.appendChild (text);
		
		setTimeout (this._onTimeout.bind (this));

		this._refreshLabel ();
	}
	
	,_refreshLabel: function ()
	{
		if (!this._label)
			return;
	
		var row = -1;

		if (this._model && this._model.ready)
			row = this._model.searchByIndex (this._valueColumnIndex, this._value);

		if (row != -1)
		{
			var label = this._model.getByIndex (row, this._showColumnIndex);
			this._label.nodeValue = label;
			this._emptyLabel = false;
		}
		else
		{
			this._emptyLabel = true;
			this._label.nodeValue = _('Loading...');
		}
	}

	,_destroy: function ()
	{
		this._select.unref ();
		this._modelLot.unref ();
		this.parent ();
	}
});

})();
