defaultNS.ModuleShop = function() {


	var cookieProvider = new Ext.state.CookieProvider({
		path : '/',
		expires : new Date(new Date().getTime() + (1000 * 60 * 60 * 24 * 30))
	});
	Ext.state.Manager.setProvider(cookieProvider);

	// zjistí zda je položka v seznamu zapamatovaných
	var itemExistInCart = {
		toRemove : {},
		exist : function(_input) {
			var itemExist = false;
			var cartContent = cookieProvider.get('cartContent', 'notSet');

			// zjisti zda objekt je již v poli pro zapamatování
			Ext.each(cartContent, function(obj) {

				// pokud se id objektu zapamatovaného a nového shodují
				if(obj.shopVariationId == _input.shopVariationId) {

					// ulož jej por pozdější práci
					itemExistInCart.toRemove = obj;
					itemExist = true;
				}
			});
			return itemExist;
		}
	};

	var cart = {
		deliveryOption : [],
		setup : function() {

			// zkusíme vzít zapamatované z cookie
			var cartContent = cookieProvider.get('cartContent', 'notSet');

			// cookie neexistuje zadefinujeme jej
			if(cartContent == 'notSet') {

				// seznam zapamatovaných jako prázdné pole
				cookieProvider.set('cartContent', []);
				cartContent = cookieProvider.get('cartContent');

			}

			cart.updateCount();
			cart.submitOrderButton();
			cart.deliveryOptionOnChange();
		},
		clear : function() {
			cookieProvider.clear('cartContent');
			cookieProvider.clear('cartContentAsString');
			cart.updateCount();
		},

		// po změně volby doručení přepočti cenu
		deliveryOptionOnChange : function () {
			Ext.select('input[name="deliveryOption"]').each(function(item) {
				item.on('change', function(evt, target) {
					Ext.get('cartPriceBeforeSubmit').update(String.format('{0} Kč', cart.getCartPrice() + cart.getPostagePrice()));
				});
			});
		},
		submitOrderButton : function() {
			var confirmationDefinition = [
				{
					tag : 'div',
					cls : 'deco top'
				},
				{
					tag : 'div',
					cls : 'small',
					id: 'contentHeader',
					cn : [
						{
							tag : 'h1',
							cls : 'title',
							html: 'Košík'
						}
					]},
				{
					tag : 'div',
					cls : 'items',
					cn : [
						{
							tag : 'div',
							cls : 'item article',
							cn : [
								{

									tag : 'h2',
									html : 'Vaše objednávka byla úspěšně přijata. Děkujeme za objednávku a přejeme pěkný den.'
								}
							]
						}
					]
				},
				{
					tag : 'div',
					cls : 'deco bottom'
				}
			];

			var submitOrderButton = Ext.get('send');
			if(submitOrderButton) {
				submitOrderButton.on('click', function(evt, target) {
					Ext.getBody().mask('Zpracování objednávky.');
					defaultNS.ModuleFormError({
						selectMessage : '#formOrder p.error'
					}).resetError();

					Ext.Ajax.request({
						url : baseUrl + '/default/shop/cart',
						method : 'POST',
						params : Ext.Ajax.serializeForm('formOrder'),
						success : function(response, options) {
							Ext.getBody().unmask();
							var obj = Ext.decode(response.responseText);
							if(obj.success === false) {
								defaultNS.ModuleFormError({
									selectMessage : '#formOrder p.error'
								}).evalError.formElement(obj.data);
								Ext.Msg.show({
									title: 'Objednávka nebyla odeslána!',
									msg: 'Formulář obsahuje chyby. Prosím, opravte je a opakujte odeslání objednávky.',
									buttons: Ext.Msg.OK,
									animeEl: submitOrderButton,
									icon: Ext.MessageBox.ERROR
								});
							}
							else {
								googleAnalytics.addTransaction(obj.orderInformation);
								Ext.each(obj.cartItem, function(obj) {
									googleAnalytics.addItem(obj);
								});
								googleAnalytics.trackTransaction();

								cart.clear();
								Ext.DomHelper.overwrite(Ext.get('content'), confirmationDefinition);
								Ext.MessageBox.alert('Pozor!', 'Vaše objednávka byla <b>úspěšně přijata</b>. Děkujeme za objednávku a přejeme pěkný den.');
							}
						},
						failure : function(response, options) {
							Ext.getBody().unmask();
						}
					});
				});
			}
		},

		// přidá nebo upraví počet položek zboží v košíku
		addToCart : function(_input) {
			//console.log(_input);

			// objekt odkazu který byl stisknut dále není potřeba
			delete _input.el;

			var cartContent = cookieProvider.get('cartContent', 'notSet');

			// kolik kusů má být přidáno
			var cartGetCount = cart.getCount({
				item : Ext.get('addCartCount' + _input.id)
			});

			// jestliže počet vadný přeruším přidání
			if(cartGetCount) {
				_input.count = cartGetCount;
			}
			else {
				Ext.MessageBox.alert('Pozor!', String.format('Nelze přidat počet <strong>{0}</strong>', Ext.get('addCartCount' + _input.id).getValue()));
				return false;
			}

			var count = 0;

			// položka je již nastavena k zapamatování pak aktualizuj počet
			// jinak přidá jako novou
			if(itemExistInCart.exist(_input)) {

				Ext.each(cartContent, function(obj) {

					itemExistInCart.toRemove = {};

					// pokud se id objektu zapamatovaného a nového shodují
					if(obj.shopVariationId == _input.shopVariationId) {

						// jedná se o editaci košíku pak v poli nechám zadanou hodnotu
						// ve výpise však nastavím po přidání 1
						if(_input.cartEdit) {
							obj.count = count = _input.count;
						}
						else {
							obj.count = count = obj.count + _input.count;
							Ext.get('addCartCount' + _input.id).dom.value = 1;
						}
						return false;
					}
				});
			}
			else {
				cartContent.push(_input);
			}

			// animujeme tlačítko
			Ext.get('addToCartButton' + _input.id).fadeIn({duration:1});

			cart.updateCount();
			cart.notifyContentChange({
				id: _input.id,
				title : 'Položka přidána do košíku'
			});

			if(_input.cartEdit) {
				var cartEditRowPrice = count * _input.price;
				Ext.select('#cartContentRow' + _input.id + ' .info p').item(2).select('strong').item(0).update(String.format('{0} Kč', cartEditRowPrice));
				Ext.get('cartPriceBeforeSubmit').update(String.format('{0} Kč', cart.getCartPrice() + cart.getPostagePrice()));
			}

			// pole ulož do cookie
			cookieProvider.set('cartContent', cartContent);
		},

		notifyContentChange : function (_input) {
			var cartCount = Ext.select('#basket strong').item(0).dom.innerHTML;
			var cartPrice = Ext.select('#basket strong').item(1).dom.innerHTML;

			Ext.MessageBox.show({
				title: _input.title,
				msg: String.format('Košík obsahuje {0} v hodnotě {1}.', cartCount, cartPrice),
				buttons: Ext.MessageBox.OK,
				animEl: 'addToCartButton' + _input.id,
				icon:  Ext.MessageBox.INFO
			});
		},

		removeFromCart : function(_input) {

			// objekt odkazu který byl stisknut dále není potřeba
			delete _input.el;

			// položka je nastavena k zapamatování pak ji odeber
			if(itemExistInCart.exist(_input)) {
				var cartContent = cookieProvider.get('cartContent', 'notSet');
				cartContent.remove(itemExistInCart.toRemove);
			}

			Ext.get('cartContentRow' + _input.id).remove();
			cart.updateCount();
			cart.notifyContentChange({
				id: _input.id,
				title : 'Položka odebrána z košíku'
			});
			Ext.get('cartPriceBeforeSubmit').update(String.format(' {0} Kč', cart.getCartPrice() + cart.getPostagePrice()));

			// pole ulož do cookie
			cookieProvider.set('cartContent', cartContent);

			// nic v košíku pak odstraníme formulář
			if(cart.getCartCount() == 0) {
				Ext.get('formOrder').parent().remove();
				var removeDefinition = [
					{
						tag : 'div',
						cls : 'deco top'
					},
					{
						tag : 'div',
						cls : 'small',
						id: 'contentHeader',
						cn : [
							{
								tag : 'h1',
								cls : 'title',
								html :'Košík'
							}
						]},
					{
						tag : 'div',
						cls : 'items',
						cn : [
							{
								tag : 'div',
								cls : 'item article',
								cn : [
									{

										tag : 'h2',
										html : 'Košík neobsahuje žádné zboží.'
									}
								]
							}
						]
					},
					{
						tag : 'div',
						cls : 'deco bottom'
					}
				];
				Ext.DomHelper.overwrite(Ext.get('content'), removeDefinition);
			}
		},

		getCount: function(_input) {
			var count = false;
			count = parseInt(_input.item.getValue());
			count = Ext.isNumber(count) ? count : false;
			return count;
		},

		// id zapamatovaných položek jako řetězec
		storeCartAsString : function() {
			var cartContentAsString = [];
			var cartContent = cookieProvider.get('cartContent', 'notSet');
			Ext.each(cartContent, function(_input) {
				cartContentAsString.push(_input.shopVariationId + '-' + _input.count);
			});
			cookieProvider.set('cartContentAsString', cartContentAsString.join(','));
			//console.log(cartContentAsString.join(','));
		},

		// změní počet ks a cenu košíku v záhlaví
		updateCount : function() {
			var cartCount = cart.getCartCount();
			var cartPrice = cart.getCartPrice();

			var cartIcon;

			if(Ext.select('#basket').item(0)) {
				Ext.select('#basket strong').item(0).update(String.format('{0} ks', cartCount));
				Ext.select('#basket strong').item(1).update(String.format('{0} Kč', cartPrice));
				cartIcon = Ext.select('.basketIcon').item(0);
				cartCount > 0 ? cartIcon.addClass('full') : cartIcon.removeClass('full');
			}

			// košík v záhlaví
			cartIcon = Ext.select('.basketIcon').item(0);
			cart.getCartCount() > 0 ? cartIcon.addClass('full') : cartIcon.removeClass('full');

			cart.storeCartAsString();
		},

		// celkový počet položek v košíku
		getCartCount : function() {
			var cartContent = cookieProvider.get('cartContent', 'notSet');
			var cartCount = 0;
			Ext.each(cartContent, function(_input) {
				cartCount = cartCount + _input.count;
			});
			return cartCount;
		},

		// celkový cena košíku
		getCartPrice : function() {
			var cartContent = cookieProvider.get('cartContent', 'notSet');
			var cartPrice = 0;
			Ext.each(cartContent, function(_input) {
				cartPrice = cartPrice + (_input.count * _input.price);
			});
			return cartPrice;
		},

		// cena poštovného
		getPostagePrice : function () {
			var deliveryOption = 0;
			var postagePrice = 0;

			// zjistí který zp. doručení je zvolen
			Ext.select('input[name="deliveryOption"]').each(function(item) {
				if(item.dom.checked) {
					deliveryOption = item.getValue();
					return false;
				}
			});

			switch (parseInt(deliveryOption)) {
				case 1:
					postagePrice = 130;
					break;
				case 2:
					postagePrice = 100;
					break;
				case 3:
					postagePrice = 0;
					break;
				case 4:
					postagePrice = 120;
					break;
				case 5:
					postagePrice = 250;
					break;
				default:
					break;
			}
			return postagePrice;
		},

		addDeliveryOption : function () {

		}
	};
	var filter = {
		setup : function() {
			if(Ext.get('filterPriceContainer')) {

				// z hidden pole vezmu hodnotu např. 500,19900
				// pokud se split nepovede tzn. neodpovídá formátu nastavím výchozí
				var sliderData = [];
				Ext.each(Ext.get('hNFilterPrice').getValue().split(','), function(gateValue) {
					sliderData.push(parseInt(gateValue));
				});
				sliderData = sliderData.length < 2 ? [0, 20000] : sliderData;

				new Ext.Slider({
					renderTo: 'filterPriceContainer',
					id: 'filterPrice',
					xtype: 'slider',
					isFormField: true,
					width   : 250,
					minValue: 0,
					maxValue: 20000,
					increment : 100,
					values  : sliderData,
					plugins : new Ext.slider.Tip({
						getText: function(thumb) {
							var thumbValue = thumb.value;
							if(thumb.value == 20000) {
								thumbValue = String.format('{0} a více', '20000');
							}
							return String.format('<strong>{0}</strong> Kč', thumbValue);
						}
					}),
					listeners: {
						changecomplete: function(slider) {
							Ext.get('hNFilterPrice').set({
								value : slider.getValues().toString()
							});
							var sliderTitle = slider.getValues()[1];
							if(slider.getValues()[1] == 20000) {
								sliderTitle = 'max';
							}
							Ext.select('#priceSlider h2').item(0).update(String.format('Cena od <strong>{0}</strong> do <strong>{1}</strong> Kč:', slider.getValues()[0], sliderTitle));
						},
						render : function (slider) {
							var sliderTitle = slider.getValues()[1];
							if(slider.getValues()[1] == 20000) {
								sliderTitle = 'max';
							}
							Ext.select('#priceSlider h2').item(0).update(String.format('Cena od <strong>{0}</strong> do <strong>{1}</strong> Kč:', slider.getValues()[0], sliderTitle));
						}
					}
				});
			}
		},
		filter : function(_input) {
			var parameter = '';
			switch (_input.cmd) {
				case 'list':
					parameter = Ext.Ajax.serializeForm('shopFilterList');
					parameter = parameter.length > 0 ? parameter + '&' : parameter;
					parameter = parameter + Ext.Ajax.serializeForm('shopFilterOrder');
					break;
				case 'left':
					parameter = Ext.Ajax.serializeForm('shopFilterLeft') + '&disableFilterList=true';
					break;
				default:
					break;
			}
			window.location.href = _input.url + '/' + parameter;
		}
	};

	var common = {
		setupShareEMail : function() {
			var submitShareEMailButton = Ext.get('submitShareEMail');
			if(submitShareEMailButton) {
				submitShareEMailButton.on('click', function(evt, target) {
					Ext.getBody().mask('Odeslání zprávy.');
					defaultNS.ModuleFormError({
						selectMessage : '#formShareEMail p.error'
					}).resetError();

					var parameter = '';
					parameter = Ext.Ajax.serializeForm('formShareEMail');
					parameter = parameter.length > 0 ? parameter + '&' : parameter;
					parameter = parameter + 'shopId=' + Ext.select('.shareEMailActive').elements[0].id.split('shareEMail')[1];

					Ext.Ajax.request({
						url : baseUrl + '/default/shop/share-e-mail',
						method : 'POST',
						params : parameter,
						success : function(response, options) {
							Ext.getBody().unmask();
							var obj = Ext.decode(response.responseText);
							if(obj.success === false) {
								defaultNS.ModuleFormError({
									selectMessage : '#formShareEMail p.error'
								}).evalError.formElement(obj.data);
								Ext.Msg.show({
									title: 'Zpráva nebyla odeslána!',
									msg: 'Formulář obsahuje chyby. Prosím, opravte je a opakujte odeslání zprávy.',
									buttons: Ext.Msg.OK,
									animeEl: submitShareEMailButton,
									icon: Ext.MessageBox.ERROR
								});
							}
							else {
								Ext.get('mailBubble').setStyle('display', 'none');
								Ext.get('modal').setStyle('display', 'none');
								Ext.get('formShareEMail').dom.reset();
								Ext.MessageBox.alert('Pozor!', 'E - mail <b>byl odeslán</b>.');
							}
						},
						failure : function(response, options) {
							Ext.getBody().unmask();
						}
					});
				});
			}
		}
	};

	var googleAnalytics = {
		addTransaction : function (_input) {
			_gaq.push(['_addTrans',
					   _input.id,
					   '',
					   _input.price,
					   _input.tax,
					   _input.delivery_option_price,
					   _input.invoice_city,
					   '',
					   _input.invoice_country]);
		},
		addItem : function (_input) {
			_gaq.push(['_addItem',
					   _input.shop_order_id,
					   _input.code,
					   _input.title,
					   _input.menu_category,
					   _input.price,
					   _input.cart_count]);

		},
		trackTransaction : function () {
			_gaq.push(['_trackTrans']);
		}
	};

	return {

		// veřejně přistupný alias pro nastavení zapamatování
		addToCart : cart.addToCart,
		addDeliveryOption : cart.addDeliveryOption,
		removeFromCart : cart.removeFromCart,
		filter : filter.filter,

		init : function(_input) {
			cart.setup();
			filter.setup();
			common.setupShareEMail();
		}
	};
}
		;
