
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.onBasketCheck.bind (this));
		}
		else
		{
			var query = 'CALL basketConfigureForGuest';
			this.conn.execQuery (query, this.loadUi.bind (this));
		}
	}

	,onBasketCheck: function (isOk)
	{
		if (isOk)
			this.loadUi ();
	}
	
	,activate: function ()
	{
		document.body.appendChild (this.$('right-panel'));
	
		this.$('items-model').setInfo ('i', 'item', 'vn', ['id']);
		
		if (localStorage.getItem ('hederaView'))
			this.setView (parseInt (localStorage.getItem ('hederaView')));
		else
			this.setView (Hedera.Catalog.View.GRID);
	}
	
	,deactivate: function ()
	{
		this.hideMenu ();
		this.gui.$('top-bar').style.backgroundColor = '';
		Vn.Node.remove (this.$('right-panel'));
	}
	
	,setView: function (view)
	{
		if (view === Hedera.Catalog.View.GRID)
		{
			this.$('view-button').setProperties ({
				icon: 'view-list',
				tip: _('List view')
			});
			this.view = Hedera.Catalog.View.GRID;
			var className = 'grid-view';
		}
		else
		{
			this.$('view-button').setProperties ({
				icon: 'view-grid',
				tip: _('Grid view')
			});
			this.view = Hedera.Catalog.View.LIST;
			var className = 'list-view';
		}
		
		var node = this.$('grid-view').node;
		node.className = className;
		localStorage.setItem ('hederaView', this.view);
	}
	
	,onSwitchViewClick: function ()
	{
		this.setView (this.view === Hedera.Catalog.View.LIST ?
			Hedera.Catalog.View.GRID : Hedera.Catalog.View.LIST);
	}
	
	,onBasketReady: function (form)
	{
		if (form.get ('method') != 'PICKUP')
			Vn.Node.setText (this.$('method'), _('Agency'));
		else
			Vn.Node.setText (this.$('method'), _('Warehouse'));
	}
	
	,onItemsChange: function (model, status)
	{
		if (status !== Db.Model.Status.CLEAN)
			this.$('order').style.display = 'block';
		else
			this.$('order').style.display = 'none';
	}
	
	,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-model').sortByName (sortField, sortWay);
		
		this.hideMenu ();
	}
	
	,onFilterChange: function (param, newValue)
	{
		if (newValue)
			this.hideMenu ();
	}
	
	,realmRenderer: function (builder, form)
	{
		var link = builder.$('link');
		link.href = this.hash.make ({
			'form': this.hash.get ('form'),
			'realm': form.get ('id')
		});
		
		var img = builder.$('image');
		img.src = 'image/family/light/'+ form.get ('id') +'.svg';
		img.title = form.get ('name');
		img.alt = img.title;
	}
	
	,onRealmChange: function (param, newValue)
	{
		if (newValue)
		{
			this.$('filters').style.display = 'block';
			this.$('realm-msg').style.display = 'none';
		}
		else
		{
			this.$('filters').style.display = 'none';
			this.$('realm-msg').style.display = 'block';
		}
	
		this.refreshTitleColor ();
		this.refreshFilter (newValue, undefined);
	}

	,onTypeChange: function (param, newValue)
	{
		this.onFilterChange (param, newValue);
		this.refreshTitle ();
		this.refreshFilter (undefined, newValue);
	}
	
	,refreshFilter: function (realm, type)
	{
		var batch = this.$('filter-batch');
		batch.block ();
		this.$('realm-value').value = realm;
		this.$('type-value').value = type;
		this.$('search').value = undefined;
		this.$('color').value = undefined;
		this.$('origin').value = undefined;
		this.$('category').value = undefined;
		this.$('producer').value = undefined;
		batch.unblock ();
		batch.changed ();
	}
	
	,refreshTitleColor: function ()
	{
		var realms = this.$('realms-model');

		if (!realms.ready)
			return;

		var color = null;
		var realm = this.$('realm').value;
		
		if (realm)
		{
			var row = realms.search ('id', realm);

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

		this.gui.$('top-bar').style.backgroundColor = color;
	}
	
	,refreshTitle: function ()
	{
		var types = this.$('types-model');
		
		if (!types.ready)
			return;
		
		var title = _('Catalog');
		var type = this.$('type').value;
		
		if (type)
		{
			var row = types.search ('id', type);

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

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

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

	,onShowMenuClick: function (event)
	{
		this._menuShown = true;
		event.stopPropagation ();
		this.gui.showBackground ();
		Vn.Node.addClass (this.$('right-panel'), '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.$('right-panel'), '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.set ({'form': 'ecomerce/basket'});
	}
	
	,onConfigureClick: function ()
	{
		if (this.isGuest ())
			return;

		this.hash.set ({'form': 'ecomerce/checkout'});
	}

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

		this.onEraseClick ();
		this.$('card').row = form.row;
		this.$('card-item').value = form.get ('id');
		this.$('card-popup').show (button.node);
	}
	
	,onAddLotClick: function (column, value, row)
	{
		var model = this.$('item-lots');
		var grouping = model.get (row, 'grouping');
		var warehouse = model.get (row, 'warehouseFk');
		var available = model.get (row, 'available');

		var lotAmount = this.items[warehouse];

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

		for (var warehouse in this.items)
		{
			var amount = this.items[warehouse];
			amountSum += amount;
		
			batch.addValue ('warehouse', warehouse);
			batch.addValue ('item', this.$('card-item').value);
			batch.addValue ('amount', amount);
			sql += query.render (batch);
		}
	
		if (amountSum > 0)
		{
			this.conn.execQuery (sql);

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

		this.$('card-popup').hide ();
	}
	
	,onEraseClick: function ()
	{
		this.$('amount').value = 0;
		this.items = {};
	}
	
	,onPopupClose: function ()
	{
		this.onEraseClick ();
		this.$('card').row = -1;
		this.$('card-item').value = undefined;
	}
	
	,onCardLoad: function ()
	{
		this.$('card-popup').reset ();
	}
});

Hedera.Catalog.extend
({
	View: {
		LIST: 0,
		GRID: 1
	}
});

Vn.Filter = new Class
({
	Extends: Htk.Field
	,Tag: 'vn-filter'
	,Child: 'model'
	,Properties:
	{
		model:
		{
			type: Db.Model
			,set: function (x)
			{
				x.batch = this._batch;
				this._model = x;
				this._select.model = x;
			}
			,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._batch.addObject ('filter', x);
			}
			,get: function ()
			{
				return this._filter;
			}
		},
	}
	
	,_valueColumnIndex: 0
	,_showColumnIndex: 1
	
	,initialize: function (props)
	{
		var node = this.createRoot ('div');
		node.className = 'vn-filter';
		
		this._select = new Htk.Select ();
		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._batch = new Sql.Batch ();
		this.parent (props);
	}
	
	,_onMouseDown: function ()
	{
		if (this._model && this._model.status === Db.Model.Status.CLEAN)
			this._model.refresh ();
	}
	
	,_onCloseClick: function ()
	{
		this._removeSelectionNode ();
		this._changeValue (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;
			
		this._realSetValue (this._select.value);
	}
	
	,_onReady: function ()
	{
		if (this._emptyLabel)
			this._refreshLabel ();
	}
	
	,_changeValue: function (newValue)
	{
		this._batch.block ();
		this.value = newValue;
		this._batch.unblock ();
	}
	
	,_onTimeout: function ()
	{
		this._select.value = null;
	}
	
	,putValue: function (value)
	{
		this._onMouseDown ();
		this._realSetValue (value);
	}
		
	,_realSetValue: 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._onCloseClick.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._changeValue (value);
		this._refreshLabel ();
	}
	
	,_refreshLabel: function ()
	{
		if (!this._label)
			return;
	
		var row = -1;

		if (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...');
		}
	}
});

