// compatibility
document.id = function(element){
	return $(element);
};

var Price = new Class({

  Implements: Options,
	
	options: {
	  currency: 'CZK',   // currency code
		symbol: 'Kč',
		decimal: ',',
		digit: ' ',
		group: 3,
		position: 'after',
		space: true,
		suffix: ',-'      // number suffix like 350,-
	},

  initialize: function(price, options){
		this.setOptions(options);
		this.options = new Hash(this.options);
		this.raw = new String(price);
		
		this.raw = this.raw.replace('€', '&euro;');
		// default currencies
		this._currencies = new Hash({
			'CZK': {currency: 'CZK', symbol: '', decimal: ',', digit: ' ', group: 3, position: 'after', space: false, suffix: ',-'},
			'EUR': {currency: 'EUR', symbol: '&euro;', decimal: '.', digit: ',', group: 3, position: 'before', space: true, suffix: false},
			'USD': {currency: 'USD', symbol: '$', decimal: '.', digit: ',', group: 3, position: 'before', space: false, suffix: false}
	  });
		
		// try to read price and set currency
		this._currencies.each(function(value, key){
			if (value.symbol.length){
  		  if (this.raw.contains(value.symbol)) {
					this.set('currency', value.currency);
					this.raw = this.raw.replace(value.decimal, '.').replace(value.digit, '');
				}
			}
		}, this);
		
		// convert input to number
		this.raw = this.raw.replace(/[^\d\.\,]/g, '').replace(/,/g,'.').toFloat();

		return this;
	},
	
	set: function(param, value){
	  if ($type(param) == 'object'){
		  this.options = $extend(this.options, param);
		} else {
		  if (param == 'currency'){
			  if (this._currencies.has(value)) this.options = $extend(this.options, this._currencies.get(value));
			} else {
     	  this.options.set(param, value);
			}
		}
	  return this;
	},
	
	get: function(param){
	  switch(param){
		  case 'raw':
			  return this.raw;
			break;
			default:
    	  return this.options.get(param);
		}
	},
	
	format: function(settings){
	  // some inplace settings
	  if ($type(settings) == 'object'){
		  this.options = $extend(this.options, settings);
		}
		
		// raw price
		var price = this.raw.toString();
		
		// check decimal places
		var parts = price.split('.');
		if (parts.length > 1 && parts[1].toInt() > 0 && parts[1].toInt() < 10) price += '0';
		
		// replace decimal separator
		price = price.replace('.', this.options.decimal);
		
		// add suffix
		if (this.options.suffix && (price == price.toInt())) price += this.options.suffix;
		
		// add symbol
		if (this.options.position == 'before'){
		  price = this.options.symbol + (this.options.space?' ':'') + price;
		} else {
		  price = price + (this.options.space?' ':'') + this.options.symbol;
		}
		
		return price;
	}

});

var Rendl = {
	
	  init: function(){
			
			// test
			//if ($('left-menu').getElement('a[text=Platby]')) {
//			  Loading.init($('left-menu').getElement('a[text=Platby]'), 'Data se připravují');
//			}
			
			// footer giant
			var giant = $('giant');
			giant.getElement('a').addEvent('click', function(event){event.stop;});
			giant.getElement('a').setStyle('cursor', 'default');
			giant.getElement('strong').setStyles({
			  'text-decoration' : 'underline',
				'cursor' : 'pointer'
			});
			giant.getElement('strong').addEvent('click', function(){window.open('http://www.giant.cz');});
			
			// fake emails
			$$('.erplc').each(function(email){
			  var value = email.get('text').split('').reverse().join('');
			  var mailto = new Element('a', {'href' : 'mailto:'+value, 'text': value}).replaces(email);
			});
			
			// Closeable blocks
			Closable.init();
			
			// ReMooz for product list
			$$('#product-list a.zoom').each(function(element) {
		 
						new ReMooz(element, {
								openFxMorph : { 
									'border' : '10px solid #CFCFCF',
									'border-left-color' : '#E6E6E6',
									'border-bottom-color' : '#E6E6E6'
								},
								closeFxMorph : {
									'border-color' : '#FFFFFF',
									'border-width': '0'
								},
								resizeOptions : {
									duration: 400,
									transition: Fx.Transitions.Quart.easeOut
								},
								opacityResize: 0,
								cutOut: false,
								shadow: false,
								origin: element.getParent('div.item').getElement('img'),
								generateTitle: function(el) {
									var text = el.getParent('div.item').getElement('p.bubble');
									if (!text) return false;
									var title = text.get('html').split('|');
									var head = new Element('h6', {'html': title[0]});
									return (title[1]) ? [head, new Element('p', {'html': title[1]})] : head;
								}
						});
		 
				});
			
			// ReMooz for product images
			$$('#product-img a').each(function(element){
					 
					 new ReMooz(element, {
								openFxMorph : { 
									'border' : '10px solid #CFCFCF',
									'border-left-color' : '#E6E6E6',
									'border-bottom-color' : '#E6E6E6'
								},
								closeFxMorph : {
									'border-color' : '#FFFFFF',
									'border-width': '0'
								},
								resizeOptions : {
									duration: 400,
									transition: Fx.Transitions.Quart.easeOut
								},
								opacityResize: 0,
								cutOut: false,
								shadow: false,
								origin: element.getElement('img')
						});			
			});
			
			// Detail product images
			if ($('product-img-content')) ProductImages.init();
			
			// Detail info togglers
			if ($$('.info-toggler') && $$('.product-info')){
				var infoTogglers = $$('.info-toggler');
				var productInfos = $$('.product-info');
				var productInfosFx = new Array();
				infoTogglers.each(function(element, index){
				  if (productInfos[index]){
					  productInfosFx[index] = new Fx.Slide(productInfos[index], {duration: 200, link: 'cancel', transition: Fx.Transitions.Quad.easeInOut});
						productInfosFx[index].hide();
						element.setStyle('cursor', 'pointer');
						element.addEvent('click', function(){
						  productInfosFx[index].toggle();
							if (element.hasClass('active')){
								element.removeClass('active');
							} else {
								element.addClass('active');
							}
						});
					}
				});
			}
			
  		// Roller
			if ($('product-list-wrapper')) {
				RendlRollerTabs.init();
			}
			
			// Basket
			if ($('product-detail')){
				Basket.init();
				if ($('models-3d')) Models3D.init();
			}
			
			// Suggest
			if ($('form-search')) {
				new RendlSuggest('form-search');
			}
			
			// Switcher
			if ($('contact-wrapper')) {
				new GSwitcher('contact-wrapper', {toggler: '#left-menu a', anchors: true});
			}
			
			// Homepage boxes
			if ($('boxes')){
				var boxes = $$('#boxes .box');
				boxes.each(function(box){
				  if (!box.hasClass('not-clickable')){
						box.setStyle('cursor', 'pointer');
						box.addEvent('click', function(event){
							event.stop();
							window.location = this.getElement('a').get('href');
						});

					}
				});
			}
			
			// objednat katalog boxes
			
				var boxes = $$('#obj-boxes .katalog-box');
				boxes.each(function(box){
				 	box.setStyle('cursor', 'pointer');
					box.addEvent('click', function(event){
						event.stop();	
						boxes.each(function(box){
							box.getElement('input').setProperty('checked','false');
							box.removeClass('selected-box');
						});
						box.addClass('selected-box');
						box.getElement('input').setProperty('checked','true');
					});
					box.getElement('input').addEvent('click', function(event){
					  event.stopPropagation();
						boxes.each(function(box){
							box.removeClass('selected-box');
						});
						box.addClass('selected-box');
					});
				});
			
		
			// Filter
			if ($('filter')) 	RendlFilter.init();
			
			// Basket form
			if ($('form-basket')) FormBasket.init();
			
			// Wholesale cart
			if ($('form-wholesale-cart')) FormWholesaleCart.init();
			
			// Slides for adnvance info
			$$('.advanced-info').each(function(element){
			  var slideFx = new Fx.Slide(element.getElement('div.slide'), {duration: 500, transition: Fx.Transitions.Quint.easeInOut, link: 'cancel'});
				slideFx.hide();
				element.getElement('.toggler a').addEvent('click', function(event){
				  event.stop();
					slideFx.toggle();
				});
			});
			
			// Form - fast search
			if ($('form-fast-search')){
				var fastForm = $('form-fast-search');
				var fastInput = fastForm.getElement('input[type=text]');
				fastInput.addEvents({
				  'focus' : function(){
						if (this.value == this.defaultValue) this.value = '';
					},
					'blur' : function(){
						if (this.value == '') this.value = this.defaultValue;
					}
				});
				
				fastForm.addEvent('submit', function(event){
				  if (fastInput.value == '' || fastInput.value == fastInput.defaultValue) event.stop();
				});
			}
			
			// Form - newsletter
			if ($('form-newsletter')){
				var newsForm = $('form-newsletter');
				var newsInput = newsForm.getElement('input[type=text]');
				newsInput.addEvents({
				  'focus' : function(){
						if (this.value == this.defaultValue) this.value = '';
					},
					'blur' : function(){
						if (this.value == '') this.value = this.defaultValue;
					}
				});
			}
			
			
			// Popups
			$$('a[rel^=popup]').each(function(link){
			  var rel = link.get('rel');
				var dim = rel.replace(/[^\[]*\[([^\]]*)\]/, '$1').split(',').associate(['width', 'height']);
				link.addEvent('click', function(event){
				  event.stop();
					window.open(link.get('href'),'','width='+dim.width+',height='+dim.height);
				});
			});
			
			if ($('form-newsletter')) Newsletter.init();
			if ($('catalog-download')) CatalogDownload.init();
			
			// IE 6 fixes
			if (Browser.Engine.trident4){
				IE6Fixes.init();
			}
			
			// Expandable tables 
			$$('table.expandable').each(function(table){
			  var toggles = table.getElements('a.table-toggle');
				var wrappers = table.getElements('div.wrapper');
				var wrapperFx = new Array();
				wrappers.each(function(wrapper, index){
				  wrapperFx[index] = new Fx.Slide(wrapper, {duration: 200, link: 'cancel'}).hide();
				});
				toggles.each(function(toggle, index){
					var img = toggle.getElement('img');
					var imgFx = new Fx.Tween(img, {property: 'opacity', duration: 400, link: 'cancel'});
					var open = false;
					toggle.addEvent('click', function(event){
					  event.stop()
						if (open){
							wrapperFx[index].slideOut();
							imgFx.start(1);
							open = false;
						} else {
							wrapperFx[index].slideIn();
							imgFx.start(0);
							open = true;
						}
					});
				});
			});
			
			$$('.product-list-article').each(function(article){
			  new ProductArticle(article);
			});
			
			if ($('form-partners')) FormPartners.init(); 
			if ($('form-order')) FormOrder.init();
			if ($('form-catalog-error-email-request')) CatalogError.init();
			if ($('product-image-list')) ProductImageList.init();
			if ($('block-catalog-search')) BlockCatalogSearch.init();
			
		}
 };

var IE6Fixes = {
	
	  init: function(){
			
			// hover fix
			$$('#product-list .item, #product-list-filter-groups ul, #product-list-filter-groups li').each(function(item){
			  item.addEvents({
				  'mouseenter' : function(){
						item.addClass('hover');
					},
					'mouseleave' : function(){
						item.removeClass('hover');
					}
				});
			});
			
			// first child
			$$('#product-list-filter-groups ul').each(function(ul){
			  ul.getElement('li').addClass('first-child');
			});
			
		}
		
 };

var RendlRollerTabs = {
	
	init: function(){
		
		  // tabs
			var tabs = $$('#product-list-tabs li');
			var lists = $$('#product-list .list');
			
			// tabs event 
			tabs.each(function(tab){
			  tab.getElement('a').addEvent('click', function(event){
				  event.stop();
					lists.removeClass('active');
					lists[tabs.indexOf(tab)].addClass('active');
					tabs.removeClass('active');
					tab.addClass('active');
				});
			});
		  // init rollers
		  $$('#product-list .list').each(function(list){
				var gType = list.get("id").replace("type-", "");
				
				new RendlRoller(list,{gType: gType});
			});
	}
	
 };

var RendlRoller = new Class({
  
	Implements: [Options],
	
	options: {
		buttonLeft: 'a.move-left',
		buttonRight: 'a.move-right',
		countField: 'span.count',
		positionWrapper: '.position',
		itemSelector: '.item',
		itemWidth: 194,
		buttonDisabledClass: '.disabled',
		loadedClass: '.loaded',
		visibleItemCount: 4,
		url: '/ajax/roller/',
		gType: 'category',
		fxOptions: {
			duration: 600,
			link: 'cancel',
			transition: Fx.Transitions.Quad.easeInOut
		}
	},
	
	initialize: function(element, options){
    this.container = element;
		this.setOptions(options);
		
		// roller loaded
		this.container.addClass('loaded');

    // basic elements
		this.buttonLeft = this.container.getElement(this.options.buttonLeft);
		this.buttonRight = this.container.getElement(this.options.buttonRight);
		this.countField = this.container.getElement(this.options.countField);
		this.positionWrapper = this.container.getElement(this.options.positionWrapper);
		
		// parsing count field
		this.totalItemCount = this.countField.get('text').replace(/[^z]*z(.*)/,'$1').toInt();
		
		// vars
		// current position
		this.current = 0;
		// item list
		this.items = this.container.getElements(this.options.itemSelector);
		// number of loaded items
		this.count = this.items.length;
		
  	// position wrapper fx
		this.position = new Fx.Tween(this.positionWrapper, $merge({property: 'left'}, this.options.fxOptions));
		this.position.set(0);
		// set proper width of wrapper
		this.positionWrapper.setWidth = function(){
			this.positionWrapper.setStyle('width', this.count * this.options.itemWidth );
		}.bind(this);
		this.positionWrapper.setWidth();
		
		// add events to buttons
		this.buttonLeft.addEvent('click', function(event){
		  event.stop();
			if (!this.buttonLeft.hasClass('disabled')){
				this.move('right');
			}
		}.bind(this));
		
		this.buttonRight.addEvent('click', function(event){
		  event.stop();
			if (!this.buttonRight.hasClass('disabled')){
				this.move('left');
				this.preload();
			}
		}.bind(this));
		
		// request
		this.requestItems = new Request.JSON({
			url: this.options.url,
		  onComplete: function(jsonObj){
				if (jsonObj && jsonObj.items) {
				  this.addItems(jsonObj.items);
				}
			}.bind(this),
			onFailure: function(){}
		});
		
		// preload items
		this.preload();
		
		// reset buttons
		this.buttonLeft.addClass('disabled');
		if (this.count < 5){
			this.buttonRight.addClass('disabled');
		}

	},
	
	// returns first element founded with CSS selector
	getOneElement: function(selector){
		return $$(selector)[0];
	},
	
	getItemCount: function(){
		return this.container.getElements(this.options.itemSelector).length;
	},
	
	// move items
	move: function(direction){
		var delta = 0;
		switch (direction) {
			case 'left':
			  delta = Math.min(this.options.visibleItemCount, this.count - this.current - this.options.visibleItemCount);
			  break;
			case 'right':
			  delta = -Math.min(this.options.visibleItemCount, this.current);
			  break;
		}
		this.current = this.current + delta;
		this.position.start(-this.current * this.options.itemWidth);

    // reset buttons
		this.current + this.options.visibleItemCount < this.count ? this.buttonRight.removeClass('disabled') : this.buttonRight.addClass('disabled');
		this.current > 0 ? this.buttonLeft.removeClass('disabled') : this.buttonLeft.addClass('disabled');
		// set numbers
		this.countField.set('html', (this.current+1) + '&ndash;' + (this.current + this.options.visibleItemCount) + ' z ' + this.totalItemCount);
	},
	
	// preload items
	preload: function(){
		if (this.current + 2*this.options.visibleItemCount > this.count){
  		this.requestItems.get({
				'type' : 'product',
				'gType' : this.options.gType,
				'start' : this.current + this.options.visibleItemCount,
				'limit' : this.options.visibleItemCount
			});
		}
	},
	
	addItems: function(items){
		if (Browser.Engine.trident){
			var newItems = new Array();
			items.each(function(item, index){
			  if (index < 4){
					newItems[index] = items[index];
				}
			});
			items = newItems;
		}
		var anchors = new Array();
		items.each(function(dataItem, index){
			var dataItem = new Hash(dataItem);
			if (dataItem.title != undefined){
				var e = new Element('div', {'class' : 'item'});
				e.innerHTML = '<div class="img-wrapper"><a href="/detail/' +  dataItem.link + '/"><img src="' + dataItem.tn + '" width="120" height="120" alt="' + dataItem.title + '" /></a></div><h3>' + dataItem.title + '</h3><p class="price">' + (dataItem.from ? '<span>Cena od: </span>' : '') + (new Price(dataItem.price).format()).replace(' Kč','') + '</p><p><a href="/detail/' +  dataItem.link + '/" class="button"><span><span>detail</span></span></a></p><a href="' + dataItem.image + '" class="zoom"><img src="/images/ico-zoom.png" width="10" height="10" alt="Zoom" /></a>'+ (dataItem.label ? '<span class="label '+ dataItem.label + '">' + dataItem.labelText + '</span>' : '');
				anchors[index] = e.getElement('a.zoom');
				e.inject(this.positionWrapper);
			}
	  }.bind(this));
		
		this.count = this.getItemCount();
		this.positionWrapper.setWidth();
		
		// reset right button
		this.current + this.options.visibleItemCount < this.count ? this.buttonRight.removeClass('disabled') : this.buttonRight.addClass('disabled');
		
		// add ReMooz
		anchors.each(function(element){
			new ReMooz(element, {
				openFxMorph : { 
					'border' : '10px solid #CFCFCF',
					'border-left-color' : '#E6E6E6',
					'border-bottom-color' : '#E6E6E6'
				},
				closeFxMorph : {
					'border-color' : '#FFFFFF',
					'border-width': '0'
				},
				resizeOptions : {
					duration: 400,
					transition: Fx.Transitions.Quart.easeOut
				},
				opacityResize: 0,
				cutOut: false,
				shadow: false,
				origin: element.getParent('div.item').getElement('img')
			});
		});
	}
	
});

var Basket = {
		
	  init: function(){
			
			var result = 0;
			var current = null;
		  var diff = 10;
			var blockShift = 300;
			var url = '/vybrane-produkty/pridat-ajax';
			var amount = $('user-products').getElement('a');
			
			// confirm block and events
			var confirmBlock = new Element('div', {
			  'id' : 'basket-confirm',
				'html' : '<div id="basket-confirm-wrapper"><div id="basket-confirm-content"><h2>Produkt byl označen</h2><p>Produkt <strong>##</strong> byl označen a&nbsp;přidán k&nbsp;vybraným produktům.</p><p class="note">Množství kusů lze upravit v sekci &bdquo;vybrané produkty&ldquo;.</p><p><a href="/vybrane-produkty" id="btn-basket" class="button small"><span><span>Přejít k vybraným produktům</span></span></a> <a href="#" id="btn-continue" class="button small red"><span><span>Pokračovat</span></span></a></p><a href="#" id="btn-close">x</a><div class="clear"></div></div></div>'
			}).inject(document.body);
			
			var confirmBlockFx = new Fx.Morph(confirmBlock, {duration: 200, link: 'cancel'});
			confirmBlockFx.set({opacity : 0});
			
			$('btn-close').addEvent('click', function(event){
			  event.stop();
				var pos = confirmBlock.getPosition();
				confirmBlockFx.start({
				  'top' : pos.y+diff,
					'opacity' : 0
				});
			});
			
			$('btn-continue').addEvent('click', function(event){
			  event.stop();
				var pos = confirmBlock.getPosition();
				confirmBlockFx.start({
				  'top' : pos.y+diff,
					'opacity' : 0
				});
			});
			
			
			// add events to buttons
			var buttons = $$('.buy .add');
			
			buttons.each(function(button){
				// parse params
				button.title = button.getParent('tr').getFirst('td').get('html').replace(/([^<]*)(.*)/,'$1').trim();
				button.id = button.get('href').replace(/.*\/([^\/]*)\/$/, '$1');
        button.addEvent('click', function(event){
				  event.stop();
					current = button;
					basketReq.get(url + button.id + '/');
				}.bind(this));
			}.bind(this));
			
		  var basketReq = new Request.JSON({
				url: url,
				onComplete: function(jsonObj){
					// display confirmation block with proper data
					result = jsonObj.result;
					var productCount = jsonObj.productCount;
					if (result != 0){
						if (confirmBlock.getStyle('opacity') > 0){
							var pos = confirmBlock.getPosition();
							confirmBlockFx.start({
								'top' : pos.y+diff,
								'opacity' : 0
							}).chain(function(){displayPopup();});
						} else {
              displayPopup();
						}
						amount.set('text', (productCount == 1 ? '1 produkt' : (productCount < 5 ? productCount + ' produkty' : productCount + ' produktů')));
					}
				},
				onFailure: function(){}
			});
			
			var displayPopup = function(){
				var position = current.getPosition();
				confirmBlock.getElement('strong').set('text', current.title);
				confirmBlock.setStyles({
				  'left' : position.x-blockShift,
					'top'  : position.y-diff
				});
				confirmBlockFx.start({
				  'top' : position.y,
					'opacity' : 1
				});
			};
		}
 };

var RendlSuggest = new Class({
	
	  Implements: [Options],
		
	  options: {
			url: '/ajax/suggest/',
			template: '<a href="/{link}"><img src="{img}" /><span class="category">{category}</span><span class="title">{title}</span><span class="price">{price}</span><span class="detail">detail</span></a>',
			display: false
		},
	
	  initialize: function(form, options){
		
			this.form = $(form);
      this.setOptions(options || {});
			
			// basic vars
			this.suggest = ''; // #suggest
			this.count = ''; // #suggest .count em 
			this.list = ''; // #suggest-list
			this.input = this.form.getElement('input[name=s]');
			
			// build html code
			this.build();
			
			// suggest fx
			this.suggestFx = new Fx.Tween(this.suggest, {property: 'opacity', duration: 100, link: 'cancel'});
			this.suggestFx.set(0);
			
			this.request = new Request.JSON({
				url: this.options.url,
				onRequest: function(){
					this.input.addClass('active');
				}.bind(this),
				onComplete: function(jsonObj){
					if (jsonObj && jsonObj.items) {
						this.refresh(jsonObj.count, jsonObj.items);
					} else {
						this.suggestFx.set(0);
					}
					this.input.removeClass('active');
				}.bind(this),
				onCancel: function(){
					this.input.removeClass('active');
				}.bind(this),
				onFailure: function(){
				  this.input.removeClass('active');
				}.bind(this)
				
			});
			
			
			// input events
			this.input.addEvents({
			  focus: function(){
					if (this.input.value == this.input.defaultValue){
						this.input.value = '';
					}
				}.bind(this),
				
				blur: function(){
					this.request.cancel();
					this.input.removeClass('active');
					if (this.input.value == ''){
						this.input.value = this.input.defaultValue;
					}
					if (!this.options.display){
  					this.suggestFx.set(0);
					}
				}.bind(this),
				
				keyup: function(){
					this.options.display = false;
					if (this.input.value.length > 3 && (this.input.value != this.input.defaultValue)){
						this.request.cancel();
						this.request.get({s: this.input.value});
					}
					if (!this.input.value || this.input.value == this.input.defaultValue){
					}
					if (this.input.value.length <= 3) {
						this.suggestFx.set(0);
					}
				}.bind(this)
				
			});
			
			// form events
			this.form.addEvent('submit', function(event){
			  event.stop();
				if (this.input.value && this.input.value != this.input.defaultValue) {
				  window.location = this.form.get('action') + '?s=' + this.input.value;
				}
			}.bind(this));
			
			// view all event
			this.form.getElement('p.view-all a').addEvent('click', function(event){
			  event.stop();
				if (this.input.value && this.input.value != this.input.defaultValue){
					window.location = this.form.get('action') + '?s=' + this.input.value;
				}
			}.bind(this));
			
			
			
		},
		
		// html code
		build: function(){
			// main div
			var suggest = new Element('div', {'id' : 'suggest'});
			suggest.inject(this.form);
			this.suggest = suggest;
			
			// flag
			this.suggest.addEvents({
			  'mouseenter': function(){
					this.options.display = true;
				}.bind(this),
				'mouseleave': function(){
					this.options.display = false;
				}.bind(this)
			});
			
			// wrapper
			var wrapper = new Element('div', {'id' : 'suggest-wrapper'});
			wrapper.inject(suggest);
			
			// result item count
			var count = new Element('p', {
			  'class' : 'count',
				'html' : '<strong>Hledání odpovídá:<span></span></strong> <em></em>'
			});
			count.inject(wrapper);
			this.count = count.getElement('em');
			
			// list
			var list = new Element('div', {'id' : 'suggest-list', 'html' : '<div></div>'});
			list.inject(wrapper);
			this.list = list.getElement('div');
			
			// view all
			var viewAll = new Element('p', {
			  'class' : 'view-all',
				'html' : '<a href="#">Zobrazit kompletní výpis</a>'
			});
			viewAll.inject(wrapper);
			
		},
		
		refresh: function(count, items){
			if (items.length) {
				// count
				var countText = '';
				if (count == 0) countText = '0 produktů';
				if (count == 1) countText = '1 produkt';
				if (count > 1 && count < 5) countText = count + ' produkty';
				if (count > 4) countText = count + ' produktů';
				if (count == 0 && items.lenght > 0) countText = 'tyto produkty';
				this.count.set('text', countText);
				var temp = new Element('div');
				items.each(function(item, index){
					 var template = this.options.template;
					 var hash = new Hash(item);
					 hash.each(function(value, key){
 					   template = template.replace('{'+key+'}', (key == 'price' ? new Price(value).format() : value));
					 });
					 new Element('div', {'class' : (index == 0 ? 'first' : '')}).set('html', template).inject(temp);
				}, this);
				if (Browser.Engine.trident) temp.getElements('a')[temp.getElements('a').length - 1].destroy();
				temp.replaces(this.list);
				this.list = temp;
				this.suggestFx.set(1);
			} else {
				this.suggestFx.set(0);
			}
		}
		
		
});

var GSwitcher = new Class({
  
	Implements: [Options],
	
	options: {
		duration: 1000,
		transition: Fx.Transitions.Quint.easeInOut,
		fixed: false,
		position: '.position-wrapper',
		slide: '.slide',
		toggler: '.toggler',
		anchors: false,
		start: 0,
		maxHeight: 0
	},
  
  initialize: function(container, options){
		this.container = $(container);
		this.setOptions(options);
		this.position = this.container.getElement(this.options.position);
		this.slides = this.container.getElements(this.options.slide);
		this.count = this.slides.length;
    this.slideWidth = this.container.getElement(this.options.slide).getSize().x;
		this.togglers = $(document).getElements(this.options.toggler);
		this.heights = new Array();
		
		// max value in array
		Array.implement({
			getMax: function(){
				var max = 0;
				this.each(function(e){
				  if (e > max) max = e;
				});
				return max;
			}
		});
		
		// get heights of all slides
		this.slides.each(function(element, index){
      this.heights[index] = element.getSize().y;		
		}, this);
		this.options.maxHeight = this.heights.getMax();
		
		
		// setting proper styles
		this.container.setStyles({
		  'position' : 'relative',
			'height' : this.slides[this.options.start].getSize().y,
			'overflow' : 'hidden'
		});
		
		this.position.setStyles({
			'position' : 'absolute',
			'left' : 0,
			'top' : 0,
		  'height' : this.options.maxHeight,
			'width' : this.count * this.slideWidth
		});
		
		this.slides.setStyles({
		  'float' : 'left',
			'width' : this.slideWidth
		});
		
		// move effect
		this.slideFx = new Fx.Morph(this.position, {duration: this.options.duration, transition: this.options.transition, link: 'cancel'});
		this.fxSettings = {}
		this.fxSettings.left = 0;
		this.slideFx.set(this.fxSettings);
		
		// height effect
		if (this.options.fixed){
			this.slides.setStyle('height', this.options.maxHeight);
			this.position.setStyle('height', this.options.maxHeight);
			this.container.setStyle('height', this.options.maxHeight);
		} else {
			this.heightFx = new Fx.Tween(this.container, {property: 'height', duration: this.options.duration, link: 'cancel'})
			this.heightFx.set(this.slides[this.options.start].getSize().y);
		}
		
		// togglers
		this.togglers.each(function(element, index){
			element.addEvent('click', function(event){
				event.stop();
				//this.move(this.slides.indexOf($(element.get('href').replace(/[^#]*#(.*)/, '$1'))));
				this.move(index);
				this.togglers.each(function(toggler){
					toggler.getParent('li').removeClass('active');
				});
				element.getParent('li').addClass('active');
				}.bind(this));
		}, this);
		
		// init if anchor
		if (this.options.anchors){
			this.defaultSlide = this.togglers.indexOf($(document).getElement('a[href$=' + this.getAnchor() + ']'));
			if (this.defaultSlide >= 0 && this.defaultSlide < this.count){
				this.move(this.defaultSlide);
				this.togglers.each(function(toggler){
					toggler.getParent('li').removeClass('active');
				});
				this.togglers[this.defaultSlide].getParent('li').addClass('active');
			}
		}
	
	},
	
	move: function(sIndex){
		this.fxSettings.left = -sIndex*this.slideWidth;
		this.slideFx.start(this.fxSettings);
		if (!this.options.fixed){
			this.heightFx.start(this.slides[sIndex].getSize().y);
		}
	},
	
	getAnchor: function(){
		return document.URL.replace(/[^#]*#([a-zA-Z\-]+)/, '$1');
	}
	
});

var Closable = {
	
	init: function(){
		$$('.closeable').each(function(element, index){
			element.setStyle('position','relative');
		  var elementFx = new Fx.Slide(element, {duration: 400});
		  element.getElements('.btn-close').each(function(e){
			  e.addEvent('click', function(event){
				  event.stop();
					elementFx.slideOut();
				});
			});
			var boxID = 'closedbox' + index;
			var closed = Cookie.read(boxID);
			if (closed){
				element.destroy();
				//elementFx.hide();
			} else {
				Cookie.write(boxID, 'closed', {duration: 0});
			}
		});
	}
 };

var FilterFieldset = new Class({
		
		options: {
			collapsible: false,
			image: '/images/ico-collapse.png',
			selected: '#FBFBFB'
		},
		
  	initialize: function(fieldset){
			this.fieldset = $(fieldset);
			this.status = 1;
			
			if (this.fieldset.hasClass('collapsible')){
				this.options.collapsible = true;
			}
			
			// collapse event
			if (this.options.collapsible){
				
				// wrapper
				this.wrapper = this.fieldset.getElement('div');
				this.wrapper.setStyles({
				  'overflow' : 'hidden'
				});
				this.height = this.wrapper.getSize().y;
			  this.slideFx = new Fx.Morph(this.wrapper, {duration: 300, link: 'cancel'});
				
				// toggler
				this.toggler = this.fieldset.getElement('p');
				this.toggler.setStyles({
				  'cursor' : 'pointer'
				});
				
				this.toggler.addEvent('click', function(){
				  if (this.status){
						this.close();
					} else {
						this.open();
					}
				}.bind(this));
			}
			
			// highlight effect
			this.fieldsetFx = new Fx.Tween(this.fieldset, {property: 'background-color', duration: 300, link: 'cancel'});
			
		},
		
		getData: function(){
			
		},
		
		close: function(){
			if (this.options.collapsible){
				this.status = 0;
				this.slideFx.start({
					'opacity' : 0,
					'height' : 0
				});
				this.toggler.setStyle('background-position', 'right -20px');
				if (this.isSelected()){
					this.toggler.setStyle('font-weight', 'bold');
					this.fieldsetFx.start(this.options.selected);
				}
			}
		},
		
		open: function(){
			this.status = 1;
			this.slideFx.start({
			  'opacity' : 1,
				'height' : this.height
			});
			this.toggler.setStyle('background-position', 'right top');
			if (this.isSelected()){
				this.toggler.setStyle('font-weight', 'normal');
				this.fieldsetFx.start('#FFFFFF');
			}
		},
		
		isSelected: function(){
			var items = this.fieldset.getElements('input');
			var selected = false;
			items.each(function(item){
			  if (item.checked) selected = true;
			});
			return selected;
		}
		
});

var RendlFilter = {
	
	  init: function(){
			var filter = $('filter');
			var filterList = new Array();
			filter.getElements('fieldset').each(function(fieldset, index){
         filterList[index] = new FilterFieldset(fieldset);
				 filterList[index].close();
			});
			
			$('knob-min-tip').getElement('span.value').set('text', $('input-start').value + ',-');
			$('knob-max-tip').getElement('span.value').set('text', $('input-end').value + ',-');
			var knobFx = {
				min : new Fx.Tween('knob-min-tip', {property: 'opacity', duration: 150, link: 'cancel'}),
				max : new Fx.Tween('knob-max-tip', {property: 'opacity', duration: 150, link: 'cancel'})
			};
			knobFx.min.set(0);
			knobFx.max.set(0);
			
			$('knob-min').addEvents({
			  'mousedown' : function(){
			    knobFx.min.start(1);
				}
			});
			
			$('knob-max').addEvents({
			  'mousedown' : function(){
					knobFx.max.start(1);
				}
			});
			
			var defaultSteps = {
				min: (($('input-start').value - $('input-min').value)/($('input-max').value - $('input-min').value)*100).toInt(),
				max: (($('input-end').value - $('input-min').value)/($('input-max').value - $('input-min').value)*100).toInt()
			};
			
	    new Slider($('slider').getElement('div'), $('knob-min'), {
				offset: 2,
				knobheight: 17,
				onComplete: function(step){
					var min = $('input-min').value.toInt();
					var max = $('input-max').value.toInt();
					var newMin = Math.round(min + (max-min)/100*step.minpos.toInt());
					var newMax = Math.round(min + (max-min)/100*step.maxpos.toInt());
					var currency = $('input-currency').value;
					$('knob-min-tip').setStyle('left', (135/100*step.minpos + 5).toInt());
					$('knob-min-tip').getElement('span.value').set('text', newMin + ',-');
					$('knob-max-tip').setStyle('left', (135/100*step.maxpos + 5).toInt());
					$('knob-max-tip').getElement('span.value').set('text', newMax + ',-');
					$('input-start').value = newMin;
					$('input-end').value = newMax;
					$('price-range').set('html', newMin + ' &ndash; ' + newMax + ' ' + currency);
					this.knob.removeClass('tick');
					this.maxknob.removeClass('tick');
					knobFx.min.start(0);
					knobFx.max.start(0);
				},
				onChange: function(step){
					var min = $('input-min').value.toInt();
					var max = $('input-max').value.toInt();
					var newMin = Math.round(min + (max-min)/100*step.minpos.toInt());
					var newMax = Math.round(min + (max-min)/100*step.maxpos.toInt());
					$('knob-min-tip').setStyle('left', (135/100*step.minpos + 5).toInt());
					$('knob-min-tip').getElement('span.value').set('text', newMin + ',-');
					$('knob-max-tip').setStyle('left', (135/100*step.maxpos + 5).toInt());
					$('knob-max-tip').getElement('span.value').set('text', newMax + ',-');
				}
			}, $('knob-max')).set(defaultSteps.min, defaultSteps.max);
		}
 };
 
var FormInput = new Class({

  Implements: Options,
	
	options: {
		types: ['numbers', 'all'],
		type: 'all',
		keys: {
			common: [
			  8,  // backspace
				9,  // tab
				13, // enter
				16, // shift
				17, // ctrl
				18, // alt
				19, // pause/break
				20, // caps lock
				27, // escape
				33, // page up
				34, // page down
				35, // end
				36, // home
				37, // left arrow
				38, // up arrow
				39, // right arrow
				40, // down arrow
				45, // insert
				46, // delete
      ],
		  numbers: [48, 49, 50, 51, 52, 53, 54, 55, 56, 57,       // numkeys
								96, 97, 98, 99, 100, 101, 102, 103, 104, 105  // numpad
			],
			price: [110, 188, 190] // decimal point, comma and period
		}
	},
	
  initialize: function(input, options){
		this.setOptions(options);
		
		this.element = document.id(input);
		
		this.codes = [];
		this.setCodes();
		
		this.pressed = {
			ctrl: false,
			shift: false,
			alt: false
		}
		
		this.element.addEvent('keydown', function(event){
			switch (event.code){
				case 17: // ctrl
				  this.pressed.ctrl = true;
				break;
				case 16: // shift
				  this.pressed.shift = true;
				break;
				case 18: // alt
				  this.pressed.alt = true;
			  break;
				default:
				  switch (event.code){
						case 86: // v
						  if (this.pressed.ctrl){
								this.pressed.ctrl = false;
							} else {
								event.stop();
							}
						break;
						default:
						  if (!this.codes.contains(event.code)) event.stop();
					}
			}
		}.bind(this));
		
		return this;
	},
	
	setType: function(type){
		if (this.options.types.contains(type)){
			this.options.type = type;
			this.setCodes();
		}
	},
	
	setCodes: function(){
		switch (this.options.type){
			case 'numbers':
			  this.codes = new Array([this.options.keys.common, this.options.keys.numbers]).flatten();
			break;
			case 'price':
			  this.codes = new Array([this.options.keys.common, this.options.keys.numbers, this.options.keys.price]).flatten();
			break;
		}
	}
});

var FormBasket = {
	
	  init: function(){
			
			var formSend = $('form-basket-send');
			var formSendFx = new Fx.Tween(formSend, {property: 'opacity', duration: 300, link: 'cancel'});
      formSendFx.set(0);
			formSend.setStyles({
        'position' : 'absolute',
				'top' : 5,
				'left' : 53,
				'margin' : 0
			});
			
			// close btn
			var btnClose = new Element('a',{
			  'href' : '#',
				'class' : 'btn-close',
				'events' : {
					'click' : function(event){
						event.stop();
						formSendFx.start(0);
					}
				}
			}).inject(formSend);
			
			// block what next events
			var actionBlock = $('block-what-next');
			if (actionBlock){
				// print event
				actionBlock.getElement('li.print a').addEvent('click', function(event){
				  event.stop();
					window.print();
				});
				actionBlock.getElement('li.send a').addEvent('click', function(event){
				  event.stop();
					formSendFx.start(1);
				});
			}
			
			// block next step events
			var nextStepBlock = $('block-next-step');
			if (nextStepBlock){
				// print event
				nextStepBlock.getElement('.print a').addEvent('click', function(event){
				  event.stop();
					window.print();
				});
				/*nextStepBlock.getElement('li.send a').addEvent('click', function(event){
				  event.stop();
					formSendFx.start(1);
				});*/
			}
			
			// inputs behavior
			var inputs = $$('.basket-list input');
			inputs.each(function(input){
				var price = input.getParent('div').getElement('p.price strong');
				var defaultPrice = new Price(input.getParent('div').getElement('.basic-price').get('text'));

        var inputReq = new Request.JSON({
				  url: '/ajax/basketCnt/',
					onComplete: function(jsonObj){
						if (jsonObj){
							var newPrice = new Price(input.value * defaultPrice.get('raw'));
							newPrice.set('currency', defaultPrice.get('currency'));
						  price.set('html', newPrice.format());
						}
					}
				});
				
				input.addEvents({
				  'keyup' : function(){
						if (input.value != ''){
              input.value = input.value.toInt();
							var newPrice = new Price(input.value * defaultPrice.get('raw'));
							newPrice.set('currency', defaultPrice.get('currency'));
						  price.set('html', newPrice.format());
						}
					},
					
					'blur' : function(){
						if (!input.value) input.value = 1;
						var params = {
							'id' : input.get('name').replace(/product\[([^\]]*)\]/, '$1'),
							'count' : input.value
						};
						inputReq.get(params);
					}
				});
				
				
			});
			
			// anchor events
			this.anchorIndex = document.URL.indexOf('#');
			if (this.anchorIndex > 0){
				this.action = document.URL.slice(this.anchorIndex + 1);
				switch (this.action){
					case 'tisk':
					  window.print();
					break;
					case 'odeslat':
					  formSendFx.start(1);
					break;
				}
			}
			
			
		}
 };

var FormWholesaleCartItem = new Class({

  Implements: Events,

  initialize: function(item){
		this.wrapper = item;
		this.inputs = {
			count: this.wrapper.getElement('input[name^=product]'),
			price: this.wrapper.getElement('input[name^=price]')
		}
		this.priceTarget = this.wrapper.getElement('p.price strong');
		
		// count input event
		this.inputs.count.addEvent('keyup', function(){
		  var value = this.inputs.count.get('value');
			if (value != ''){
  		  this.inputs.count.set('value', value.toInt());
				this.update();
			}
		}.bind(this));
		
		this.inputs.count.addEvent('blur', function(){
		  var value = this.inputs.count.get('value');
			if (value == ''){
				this.inputs.count.set('value', 1);
				this.update();
			}
		}.bind(this));
		
		// price input event
		this.inputs.price.addEvent('keyup', function(){
		  var value = this.inputs.price.get('value');
			if (value != ''){
				this.update();
			}
		}.bind(this));
		
		this.inputs.price.addEvent('blur', function(){
		  var value = this.inputs.price.get('value');
			if (value == ''){
				this.inputs.price.set('value', this.inputs.price.defaultValue);
				this.update();
			}
		}.bind(this));
		
	},
	
	getPrice: function(){
		return new Price(this.inputs.price.get('value')).get('raw');
	},
	
	getCount: function(){
		return this.inputs.count.get('value');
	},
	
	update: function(){
		var newPrice = new Price(this.getCount() * this.getPrice());
		newPrice.set('currency', new Price(this.priceTarget.get('html')).get('currency'));
		this.priceTarget.set('html', newPrice.format());
	}
	
});

var FormWholesaleCart = {
	
	  init: function(){
			
			this.form = $('form-wholesale-cart');
			this.items = this.form.getElements('.item');
			
			this.items.each(function(item){
        new FormWholesaleCartItem(item);
			}, this);
			
		}
 };
 
var FormPartners = {
	
	init: function(){
		
		this.container = $('form-partners');
		
		// read structure data
		this.prepare();
		
		// filtered output
		this.output = $('form-partners-output');
		
		// type menu
		this.types = $('form-partners-type').getElement('select');
		this.types.addEvent('change', function(){
		  if (this.types.selectedIndex == 0){
				this.output.addClass('all');
			} else {
				this.output.removeClass('all');
			}
			this.filter();
		}.bind(this));
		
		// type hash
		this.typeHash = new Hash();
		this.types.getElements('option').each(function(option){
			if (option.get('value')) this.typeHash.set(option.get('value'), option.get('text'));
		}, this);
		
		
		// town section
		this.citySection = $('form-partners-city');
		
		// maps
		this.mapaCR = new Map('form-partners-province-cz');
		this.mapaSR = new Map('form-partners-province-sk');
		this.mapaSR.hide();
		
		// flag switch
		this.flags = this.container.getElements('.flags');
		this.flags.each(function(flag){
			flag.setStyle('cursor', 'pointer');
			flag.addEvent('click', function(event){
				if (flag.hasClass('sk')){
					this.mapaCR.hide();
					this.mapaSR.show();
				} else {
					this.mapaCR.show();
					this.mapaSR.hide();
				}
			}.bind(this));
		}, this);
		
		// filter events		
		this.mapaCR.container.addEvent('click', function(event){
		  this.filter();
		}.bind(this));
		
		this.mapaSR.container.addEvent('click', function(event){
		  this.filter();
		}.bind(this));
		
		// validation event
		this.container.addEvent('submit', function(event){
			event.stop();
		  this.validate();
		}.bind(this));
		
		
		// init
		this.filter();
		
	},
	
	getSelectedCount: function(){
		return this.mapaCR.getSelectedCount() + this.mapaSR.getSelectedCount();
	},
	
	getSelectedItems: function(){
		return [this.mapaCR.getSelectedItems(), this.mapaSR.getSelectedItems()].flatten();
	},
	
	prepare: function(){
	  var temp = new Hash(structure);
		this.structure = new Hash();
		temp.each(function(cities, region){
			var cityHash = new Hash();
		  cities.each(function(city){
			  cityHash.set(city.name, city.types);
			});
			this.structure.set(region, cityHash);
		}, this);
	},
	
	filter: function(){
		if (this.getSelectedCount() > 0){
			this.citySection.setStyle('display', 'block');
			this.build(this.getSelectedItems());
		} else {
			this.output.empty();
			this.citySection.setStyle('display', 'none');
		}
	},
	
	build: function(regions){
		var items = [];
		var index = 0;
		var selectedIndex = this.types.selectedIndex;
		var type = this.types.options[selectedIndex].get('value').toInt();
		var typeHash = this.typeHash;
		regions.each(function(region){
		  var cities = this.structure.get(region.replace('kraj','').trim());
			if (cities){
				cities.each(function(types, title){
					//var types = [].combine(types);
					if (types.contains(type) || selectedIndex == 0){
						
						// create row
						var row = new Element('li', {
							'class': (index%2 ? 'even' : '')
						});
						
						// create town
						row.adopt(new Element('label', {'html': '<input type="checkbox" name="towns[]" value="'+title+'" /> '+title+'<span class="bubble">Pokud víte, prosím zvolte typ partnera</span>'}));
						
						// bubble
						var bubble = row.getElement('span.bubble');
						var bubbleFx = null;
						if (bubble){
							bubbleFx = new Fx.Tween(bubble, {property: 'opacity', duration: 200, link: 'cancel'});
							bubbleFx.set(0);
						}
						// create type items and checkboxes
						var typeItems = '';
						types.each(function(type){
						  typeItems += '<li><label><input type="checkbox" name="branch[{town}][]" value="{typeID}" disabled="disabled" /> {typeTitle}</label></li>'.substitute({town: title, typeID: type, typeTitle: typeHash.get(type)});
						});
						row.adopt(new Element('ul', {
							'html': typeItems
						}));
						
						// clearing element
						row.adopt(new Element('div', {'class': 'clear'}));
						
						// checkbox events
						var townCheckbox = row.getElement('input[type=checkbox]');
						var typeCheckboxes = row.getElements('input[name^=branch]');
						townCheckbox.addEvent('change', function(){
						  if (townCheckbox.checked){
								row.addClass('selected');
								if (bubbleFx) bubbleFx.start(1);
								typeCheckboxes.each(function(checkbox){
									if (selectedIndex == 0 || (type == checkbox.value)){
  								  checkbox.disabled = false;
	  								//checkbox.checked = true;
									} else {
										checkbox.checked = false;
										checkbox.disabled = true;
									}
								});
							} else {
								row.removeClass('selected');
								if (bubbleFx) bubbleFx.start(0);
								typeCheckboxes.each(function(checkbox){checkbox.disabled = true;});
							}
						});
						
						items[index] = row;
						index++;
					}
				});
			}
		}, this);
		
		if (items.length == 0){
			items[0] = new Element('li', {'text' : 'Ve zvolených krajích nemáme žádného partnera.'});
		}
		
		this.output.empty();
		items.each(function(item){
		  item.inject(this.output);
		}, this);
	},
	
	validate: function(form){
			var err = new Array();
			var fields = new Array();
			var form = this.container;
			
			// contact information
			var contactFields = ['name', 'surname', 'phone', 'email'];
			contactFields.each(function(value){
			    if ($('form-partners-'+value).value == ''){
					    fields.include(form.getElement('label[for=form-partners-' + value + ']').get('text').replace(':','')); 
			  	}
			});
			
			if (fields.length > 0){
					err.include('Je nutné vyplnit i následující položky:\n' + fields.join(', '));
			}
			
			
			// email address
			if ($('form-partners-email').value){
					var mail = $('form-partners-email').value;
					mail = mail.replace(/^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-]+)+/, 'valid');
					if (mail != 'valid'){
						  err.include('Zadaná emailová adresa je neplatná. Prosím, zkontrolujte její zadání.');
					}
			}
			
			// phone
			if ($('form-partners-phone').value){
				  var phone = $('form-partners-phone').value;
			    phone = phone.replace(/\+?([0-9 ]{9,20})/, 'valid');
					if (phone != 'valid'){
					    err.include('Telefonní číslo je neplatné. Prosím zadejte pouze čísla (min. 9 znaků), případně mezeru a znaménko +.');
					}
			}
			
			// vyhodnoceni
			if (err.length){
			  	alert(err.join('\n\n'));
			} else {
				var partners = false;
				$('form-partners-output').getElements('input[type=checkbox]').each(function(item){
				  if (item.checked) partners = true;
				});
				if (partners) {
					form.submit();
				} else {
				  if (confirm('Nevybrali jste žádného partnera. Opravdu chcete objednávku odeslat?')) form.submit();
				}
			  	
			}

			
		}
	
 };
 
var FormOrder = {
	
	init: function(){
		
		this.container = $('form-order');
		
		// validation event
		this.container.addEvent('submit', function(event){
			event.stop();
		  this.validate();
		}.bind(this));
		
		// payment block
		this.blockPayment = this.container.getElement('#form-order-payment');
		if (this.blockPayment){
			this.slide = this.blockPayment.getElement('.slide');
			this.checkbox = this.blockPayment.getElement('input[type=checkbox]');
			
			this.slideFx = new Fx.Slide(this.slide, {duration: 500, link: 'cancel', transition: Fx.Transitions.Quad.easeOut});
			this.checkbox.addEvent('change', this.checkPayment.bind(this));
			if (Browser.Engine.trident){
				this.checkbox.getParent('label').addEvent('click', function(event){
					this.checkbox.blur();
				}.bind(this));
			}
			// on init check
			this.checkPayment(true);
			
			// radio buttony
			this.radioSections = ['div.price-box','div.payment-box'];
			this.radioSections.each(function(section){
				var blocks = this.blockPayment.getElements(section);
				blocks.each(function(block){
					var radio = block.getElement('input[type=radio]');
					block.addEvent('click', function(event){
						if (event.target != radio && !radio.checked){radio.checked = !radio.checked;}
						blocks.each(function(block){this.checkBlock(block);}, this);
					}.bind(this));
					// on init check
					this.checkBlock(block);
				}, this);
			}, this);
			
			// price input
			this.priceInput = this.blockPayment.getElement('input[type=text]');
			new FormInput(this.priceInput, {type: 'numbers'});
		}
		
	},
	
	checkBlock: function(block){
		var radio = block.getElement('input[type=radio]');
		var input = block.getElement('input[type=text]');
		(radio && radio.checked) ? block.addClass('selected') : block.removeClass('selected');
		if (input && radio && radio.checked){input.focus();}
	},
	
	validate: function(form){
			var err = new Array();
			var fields = new Array();
			var form = this.container;
			
			// contact information
			var contactFields = ['name', 'surname', 'phone', 'email'];
			contactFields.each(function(value){
			    if ($('form-order-'+value).value == ''){
					    fields.include(form.getElement('label[for=form-order-' + value + ']').get('text').replace(':','')); 
			  	}
			});
			
			if (fields.length > 0){
					err.include('Je nutné vyplnit i následující položky:\n' + fields.join(', '));
			}
			
			
			// email address
			if ($('form-order-email').value){
					var mail = $('form-order-email').value;
					mail = mail.replace(/^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-]+)+/, 'valid');
					if (mail != 'valid'){
						  err.include('Zadaná emailová adresa je neplatná. Prosím, zkontrolujte její zadání.');
					}
			}
			
			// phone
			if ($('form-order-phone').value){
				  var phone = $('form-order-phone').value;
			    phone = phone.replace(/\+?([0-9 ]{9,20})/, 'valid');
					if (phone != 'valid'){
					    err.include('Telefonní číslo je neplatné. Prosím zadejte pouze čísla (min. 9 znaků), případně mezeru a znaménko +.');
					}
			}
			
			// price control
			if (this.blockPayment){
				if ($('form-order-payment').getElement('input[type=checkbox]').checked){
					// selection control: price
					var priceRadios = $('form-order-payment').getElements('div.price-box input[type=radio]');
					var checked = false;
					priceRadios.each(function(priceRadio){
						if (priceRadio.checked) checked = true;
					});
					if (!checked) err.include('Zvolte částku, kterou si přejete uhradit.');
					
					// variable price control
					if ($('form-order-payment').getElement('div.price-box.last input[type=radio]').checked){
						var currentPrice = $('form-order-payment').getElement('input[type=text]').value;
						if (currentPrice == ''){
							err.include('Zadejte částku, kterou chcete uhradit.');
						} else {
							var maxPrice = $('form-order-payment').getElement('div.price-box strong').get('text').replace(' ', '').toInt();
							var halfPrice = Math.ceil(maxPrice/2);
							if (currentPrice < halfPrice || currentPrice > maxPrice) err.include('Zadaná částka musí být mezi ' + halfPrice + ',- a ' + maxPrice + ',- Kč.'); 
						}
					}
					
					// selection control: payment
					var paymentRadios = $('form-order-payment').getElements('div.payment-box input[type=radio]');
					var checked = false;
					paymentRadios.each(function(paymentRadio){
						if (paymentRadio.checked) checked = true;
					});
					if (!checked) err.include('Zvolte typ platby');
					
				}
			}
			
			// vyhodnoceni
			if (err.length){
			  	alert(err.join('\n\n'));
			} else {
				form.submit();
			}
		},
		
	checkPayment: function(type){
		if ($type(type) == 'string'){
  	  this.checkbox.checked ? this.slideFx.show() : this.slideFx.hide();
		} else {
			this.checkbox.checked ? this.slideFx.slideIn() : this.slideFx.slideOut();
		}
	}
	
 };
 
var MapArea = new Class({
												
	Implements: Options,

  options: {
		area: '',
		dimensions: '',
		container: ''
	},
	
  initialize: function(options){
		this.setOptions(options);

    if (!this.options.area) return null;
		
		this.area = this.options.area;
		this.container = this.options.container;
		this.params = this.area.get('id').split(':');
		this.id = this.params[0];
		this.coord = this.params[1].split(',');
		this.coords = {
			col: this.coord[0].toInt(),
			row: this.coord[1].toInt()
		}
		this.coord = null;
		
		this.checkbox = $('chk-'+this.id);
		
		// active area
		this.active = false;
		this.enabled = true;
		
		
		// create new layer
		this.layer = new Element('div', {
		  'class': 'layer',
			'id': 'layer-'+this.id,
			'styles': {
				'background-position': (-this.coords.col*this.options.dimensions.width)+'px '+(-this.coords.row*this.options.dimensions.height)+'px'
			}
		});
		this.hide();
		this.layer.inject(this.container, 'top')
		
		// area event
		this.area.addEvents({
		  'mouseenter': function(){this.show();}.bind(this),
			'mouseleave': function(){this.hide();}.bind(this)
		});
		
		this.title = this.area.get('title');
		this.area.removeProperty('title');
		this.area.removeProperty('alt');

  },
	
	show: function(){
		if (this.enabled) this.layer.setStyle('display', 'block');
	},
	
	hide: function(){
		if (!this.active) this.layer.setStyle('display', 'none');
	},
	
	click: function(){
		if (this.active){
			this.layer.removeClass('active');
			this.checkbox.checked = false;
			this.active = false;
		} else {
			if (this.enabled){
				this.layer.addClass('active');
				this.checkbox.checked = true;
				this.active = true;
			}
		}
	},
	
	getTitle: function(){
		return this.title;
	},
	
	disable: function(){
		this.enabled = false;
		this.checkbox.disabled = true;
		this.active = false;
	},
	
	enable: function(){
		this.enabled = true;
		this.checkbox.disabled = false;
		this.hide();
	}
	
});

var Map = new Class({

  initialize: function(container){
		this.container = $(container);
		
		this.areas = this.container.getElements('area');
		
		this.img = this.container.getElement('img');
		this.img.setStyle('opacity', 0.001);
		this.dimensions = {
			width: this.img.get('width'),
			height: this.img.get('height')
		};
		
		this.mapAreas = [];
		this.areas.each(function(area, index){
		  this.mapAreas[index] = new MapArea({area: area, dimensions: this.dimensions, container: this.container});
			this.mapAreas[index].area.addEvent('click', function(event){
			  event.preventDefault();
				this.click(this.mapAreas[index]);
			}.bind(this));
		}, this);
		
		this.selectedAreas = [];
		this.selectedTitles = [];
		
		this.selected = this.container.getElement('.selected em');
		this.selected.getParent('p').setStyle('visibility', 'hidden');
		
		this.origin = new Element('div', {'class': 'origin'}).inject(this.container, 'top');

  },
	
	click: function(area){
		if (area.active){
			area.click();
			this.selectedAreas.erase(area);
			this.selectedTitles.erase(area.getTitle());
		} else {
			if (this.selectedAreas.length < 3){
				area.click();
				this.selectedAreas.push(area);
				this.selectedTitles.push(area.getTitle());
			} else {
				alert('Vybrat můžete maximálně 3 kraje');
			}
		}
		
		this.selectedAreas.length == 0 ? this.selected.getParent('p').setStyle('visibility', 'hidden') : this.selected.getParent('p').setStyle('visibility', 'visible');

    // set output text
		this.selected.set('text', '- '+this.selectedTitles.join(', '));

	},
	
	hide: function(){
		this.container.setStyle('display', 'none');
		this.mapAreas.each(function(mapArea){
		  mapArea.disable();
		});
		this.selectedAreas.empty();
		this.selectedTitles.empty();
	},
	
	show: function(){
		this.container.setStyle('display', 'block');
		this.mapAreas.each(function(mapArea){
		  mapArea.enable();
		});
	},
	
	getSelectedCount: function(){
		return this.selectedAreas.length;
	},
	
	getSelectedItems: function(){
    return this.selectedTitles;
	}
	
});

var ProductImages = {
	
	  init: function(){
			var thumbnails = $$('#thumbnails img');
			var container = $('product-img-content');
			
			// loading div
			var loader = new Element('div', {
				'id' : 'main-img-loader',
				'class' : 'loading'
			});
			loader.inject(container);
			
			var loaderFx = new Fx.Tween(loader, {property: 'opacity', duration: 100, link: 'cancel'});
			loaderFx.set(0);

			var pics = new Array();
			thumbnails.each(function(img,index){
			  img.addEvent('mouseenter', function(){
						loaderFx.start(0.5);
						var bigImg = new Asset.image(img.get('src').replace(/\/82\//,'/370/'), {
							'class' : 'main-img',
							'onload': function(img){
								ProductImages.display(img, container, loaderFx);
							}
						});
				});
			});
			
		},
		
		display: function(img, container, loaderFx){
			var imgLink = new Element('a', {
				'href' : img.get('src').replace(/\/i1\/370\//, '/i2/700/')
			});
			img.inject(imgLink);
			imgLink.replaces(container.getElement('a'));
			new ReMooz(imgLink, {
					openFxMorph : { 
						'border' : '10px solid #CFCFCF',
						'border-left-color' : '#E6E6E6',
						'border-bottom-color' : '#E6E6E6'
					},
					closeFxMorph : {
						'border-color' : '#FFFFFF',
						'border-width': '0'
					},
					resizeOptions : {
						duration: 400,
						transition: Fx.Transitions.Quart.easeOut
					},
					opacityResize: 0,
					cutOut: false,
					shadow: false,
					origin: imgLink.getElement('img')
			});			
			loaderFx.start(0);
		}
		
 };

var ProductArticle = new Class({

  initialize: function(container){
		this.container = $(container);
		this.closeBtn = this.container.getElement('.btn-close');
		this.slide = this.container.getElement('.article-slide');
		
		this.slideFx = new Fx.Slide(this.slide, {duration: 700, link: 'cancel', transition: Fx.Transitions.Quint.easeOut});
		this.slideFx.hide();
		
		this.closeBtn.setStyles({
		  'cursor' : 'pointer',
			'visibility': 'visible'
		});
		
		this.closeBtn.addEvent('click', function(event){
	    event.stop();
		  if (this.closeBtn.hasClass('expand')){
				this.closeBtn.removeClass('expand').set('text', 'Skrýt text');
				this.slideFx.slideIn();
			} else {
				this.closeBtn.addClass('expand').set('text', 'Celý text');
				this.slideFx.slideOut();
			}
		}.bind(this));

	}
	
});

var Models3D = {
	
	init: function(){
		this.container = document.id('models-3d');
		if (!this.container) return;
		
		this.content = this.container.getElement('div.models-3d-content');
		
		this.slide = this.container.getElement('div.slide');
		this.slideFx = new Fx.Slide(this.slide, {duration: 200, link: 'cancel', transition: Fx.Transitions.Sine});
		this.slideFx.hide();
		
		this.title = this.container.getElement('h3');
		this.toggle = this.title.getElement('strong');
		this.toggle.addEvent('click', function(event){
		  this.title.hasClass('active') ? this.close() : this.open();
		}.bind(this));
		
		this.toggle.setStyle('cursor', 'pointer');

    this.form = this.container.getElement('form');
		this.form.addEvent('submit', function(event){
		  event.preventDefault();
			var type = this.form.getElement('input[checked]');
			if (type) type = type.get('value');
		  var email = this.form.getElement('input[type=text]').get('value');
			var pid = this.form.getElement('input[name=pid]').get('value');
			var fid = this.form.getElement('input[name=fid]').get('value');
			var cid = this.form.getElement('input[name=cid]').get('value');
			var valid = email.test(/[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}/);
			if (valid) Cookie.write('models3DEmailAddress', email);
			var timer = this.ok.delay(2000, this);
			if (valid){
				Cookie.write('models3DEmailAddress', email);
				var timer = this.ok.delay(2000, this);
				this.request = new Request.JSON({
					url: this.form.get('action'),
					onSuccess: function(responseJSON){
						$clear(timer);
						if (responseJSON && responseJSON.result){
  						this.ok();
						} else {
							//this.content.set('html', '<p style="line-height: 16px">Při odesilání formuláře nastala chyba. Zkuste obnovit stránku a&nbsp;akci opakovat.</p>');
						}
					}.bind(this),
					onFailure: function(){
						$clear(timer);
						//this.content.set('html', '<p style="line-height: 16px">Při odesilání formuláře nastala chyba. Zkuste obnovit stránku a&nbsp;akci opakovat.</p>');
					}.bind(this)
				}).get({
					type: type,
					email: email,
					pid: pid,
					cid: cid,
					fid: fid
				});
			} else {
				if (type){
  				alert('Prosím, zadejte správnou emailovou adresu.');
				} else {
  				alert('Zvolte skupinu modelů.');
				}
			}
		}.bind(this));
		
		var emailAddress = Cookie.read('models3DEmailAddress');
		if (emailAddress) this.form.getElement('input[type=text]').set('value', emailAddress);
	},
	
	open: function(){
		this.title.addClass('active');
		this.slideFx.slideIn();
	},
	
	close: function(){
		this.title.removeClass('active');
		this.slideFx.slideOut();
	},
	
	ok: function(){
		this.content.set('html', '<p style="line-height: 16px">Děkujeme za Váš zájem,<br /><br />na Vámi zadanou e-mailovou adresu zašleme odkaz na soubory ke stažení.</p>');
	}
	
 };
															
var Newsletter = {
	
	init: function(){
		
		this.form = $('form-newsletter');
		this.wrapper = this.form.getParent('div');
		this.coords = this.wrapper.getCoordinates('page-wrapper');
		this.input = this.form.getElement('input[name=email]');
		
		// set fixed height
		this.wrapper.setStyle('height', this.wrapper.getStyle('height'));

    this.overlay = new Element('div', {
		  'id' : 'overlay',
			'styles' : {
				'width' : this.coords.width,
				'height' : this.coords.height,
				'position' : 'absolute',
				'top' : -1000,
				'left' : -10000,
				'background' : '#FFFFFF url(/images/remooz/spinner.gif) no-repeat center center'
			}
		});
		this.overlay.inject(this.wrapper);
		this.overlayFx = new Fx.Tween(this.overlay, {property: 'opacity', duration: 200, link: 'cancel'});
		this.overlayFx.set(0);
		
		this.req = new Request({
		  url: this.form.get('action'),
			method: this.form.get('method'),
			onRequest: function(){
				this.showOverlay();
			}.bind(this),
			onComplete: function(){
				this.result('complete');
			}.bind(this),
			onFailure: function(){
				this.result('failure');
			}.bind(this)
		});
		
		this.form.addEvent('submit', function(event){
      event.stop();
			if (this.input.value && (this.input.value != this.input.defaultValue)){
				this.req.send('email='+this.input.value);
			}
		}.bind(this));
		
	},
	
	showOverlay: function(){
		this.overlay.setStyles({
			top: 0,
			left: 0
		});
		this.overlayFx.start(0.8);
	},
	
	hideOverlay: function(){
		this.overlayFx.start(0);
	},
	
	result: function(status){
		var output = 'Na zadanou e-mailovou adresu jsme zaslali potvrzení o přihlášení. Již brzy Vám začne chodit i náš pravidelný newsletter.';
		if (status == 'failure') output = 'Při odesílání nastala chyba.';
		this.form.destroy();
		this.wrapper.getElement('p').set('html', output);
		this.hideOverlay();
	}
	
 };
 
var CatalogDownload = {
	
	init: function(){
		
		this.wrapper = $('form-catalog-download-wrapper');
		this.form = this.wrapper.getElement('form');
		this.input = this.form.getElement('input[name=email]');
		this.content = this.wrapper.getElement('p');
		
		this.input.addEvents({
		  'focus': function(){
				if (this.value == this.defaultValue) this.value = '';
			},
			'blur': function(){
				if (this.value == '') this.value = this.defaultValue;
			}
		});
		
		// fix height
		this.wrapper.setStyle('height', this.wrapper.getStyle('height'));
		this.coords = this.wrapper.getCoordinates();
		
		this.overlay = new Element('div',{
		  'styles' : {
				'position': 'absolute',
				'top' : 0,
				'left' : 0,
				'background' : '#FFFFFF url(/images/remooz/spinner.gif) no-repeat center center',
				'width' : this.coords.width,
				'height' : this.coords.height
			}
		});
		this.fx = new Fx.Tween(this.overlay, {property: 'opacity', duration: 200, link: 'cancel'});
		this.fx.set(0);
		this.overlay.inject(this.wrapper);
		
		this.req = new Request({
		  url: this.form.get('action'),
			method: this.form.get('method'),
			onRequest: function(){
				this.fx.start(1).chain(function() {this.form.destroy();}.bind(this));
			}.bind(this),
			onSuccess: function(response){
				if (response == 1){
					this.content.set('html', 'Děkujeme. Na zadaný e-mail Vám byly zaslány instrukce pro stažení PDF verze katalogu.');
  			} else {
					this.content.set('html', 'Při zpracování Vašeho požadavku došlo k&nbsp;chybě. Zkuste stránku obnovit a akci opakovat.');
				}
  			this.fx.start(0);
			}.bind(this),
			onFailure: function(){
				this.content.set('html', 'Váš požadavek se nepodařilo odeslat');
				this.fx.start(0);
			}.bind(this)
		});
		
		this.form.addEvent('submit', function(event){
		  event.stop();
			if (this.input.value && this.input.value != this.input.defaultValue){
  			this.req.send('email='+this.input.get('value'));
			}
		}.bind(this));
	}
	
 };
 
var Loading = {
	
	init: function(button, text){
		
		this.overlay = new Element('div',{
		  'styles' : {
		    'position' : 'absolute',
				'top' : 0,
				'right' : 0,
				'bottom' : 0,
				'left' : 0,
				'height' : Math.max($('page-wrapper').getSize().y+ $('copyright').getSize().y, $(document.body).getSize().y),
				'background-color' : '#666666',
				'opacity' : 0.2,
				'display' : 'none'
			}
		}).inject($(document.body));
		
		this.position = new Element('div',{
		  'styles': {
				'width': 1,
				'height': 1,
				'position': 'absolute',
				'left': '50%',
				'top' : '30%',
				'overflow' : 'visible',
				'background-color' : '#FFFFFF',
				'display' : 'none'
			}
		}).inject($(document.body));
		
		this.box = new Element('div',{
		  'styles' : {
				'width': 200,
				'background-color': '#FFFFFF',
				'padding' : 10,
				'font-size' : '16px',
				'font-weight' : 'bold',
				'position' : 'absolute',
				'left' : -110,
				'background-image' : 'url(/images/remooz/spinner.gif)',
				'background-repeat' : 'no-repeat',
				'background-position' : '10px center'
			},
			'text' : text
		}).inject(this.position);
		
		button.addEvent('click', function(){
		  this.show();
		}.bind(this));
		
		
	},
	
	show: function(){
		this.overlay.setStyle('display', 'block');
		this.position.setStyle('display','block');
	}
 };
 
var CatalogError = {
	
	init: function(){
		
		this.form = $('form-catalog-error-email-request');
		this.wrapper = this.form.getParent('div.content');
		this.coords = this.wrapper.getCoordinates('page-wrapper');
		this.input = this.form.getElement('input[name=email]');
		
		// set fixed height
		this.wrapper.setStyle('height', this.wrapper.getStyle('height'));

    this.overlay = new Element('div', {
		  'id' : 'overlay',
			'styles' : {
				'width' : this.coords.width,
				'height' : this.coords.height,
				'position' : 'absolute',
				'top' : -1000,
				'left' : -10000,
				'background' : '#FFFFFF url(/images/remooz/spinner.gif) no-repeat center center'
			}
		});
		this.overlay.inject(this.wrapper);
		this.overlayFx = new Fx.Tween(this.overlay, {property: 'opacity', duration: 200, link: 'cancel'});
		this.overlayFx.set(0);
		
		this.req = new Request({
		  url: this.form.get('action'),
			method: this.form.get('method'),
			onRequest: function(){
				this.showOverlay();
			}.bind(this),
			onComplete: function(){
				this.result('complete');
			}.bind(this),
			onFailure: function(){
				this.result('failure');
			}.bind(this)
		});
		
		// default value
		this.input.addEvents({
		  'focus': function(){ if (this.input.value == this.input.defaultValue) this.input.value = ''; }.bind(this),
			'blur': function(){ if (this.input.value == '') this.input.value = this.input.defaultValue; }.bind(this)
		});
		
		this.form.addEvent('submit', function(event){
      event.stop();
			if (this.input.value && (this.input.value != this.input.defaultValue)){
				this.req.send('email='+this.input.value);
			}
		}.bind(this));
		
	},
	
	showOverlay: function(){
		this.overlay.setStyles({
			top: 0,
			left: 0
		});
		this.overlayFx.start(0.8);
	},
	
	hideOverlay: function(){
		this.overlayFx.start(0);
	},
	
	result: function(status){
		var output = '<h2>Žádost o kontakt</h2><p>Vaše žádost byla přijata. Jakmile opět spustíme katalog, zašleme vám informaci.</p>';
		if (status == 'failure') output = '<h2>Žádost o kontakt</h2><p>Při odesílání nastala chyba.</p>';
		this.form.destroy();
		this.wrapper.getElement('div.item').set('html', output);
		this.hideOverlay();
	}
	
 };
 
var ProductImageList = {
	
	init: function(){
		this.container = document.id('product-image-list');
		
		this.toolbar = this.container.getElement('p.toolbar');
		
		this.list = this.container.getElement('ul');
		
		this.button = {
			thumbs: this.toolbar.getElement('a.thumbs'),
			list: this.toolbar.getElement('a.list')
		}
		
		this.button.thumbs.addEvent('click', function(event){
			event.preventDefault();
			this.setView('thumbs');
		}.bind(this));

		this.button.list.addEvent('click', function(event){
			event.preventDefault();
			this.setView('list');
		}.bind(this));
		
	  this.defaultType = Cookie.read('productImageListDefaultType');
		
		if (this.defaultType) this.setView(this.defaultType);
		
	},
	
  setView: function(type){
		switch (type){
			case 'list':
			  this.button.thumbs.removeClass('active');
				this.button.list.addClass('active');
				this.list.removeClass('thumbnails');
			break;
			case 'thumbs':
				this.button.list.removeClass('active');
				this.button.thumbs.addClass('active');
				this.list.addClass('thumbnails');
			break;
		}
		Cookie.write('productImageListDefaultType', type, {duration: 365});
	}
	
	
 };
 
var BlockCatalogSearch = {
	
	init: function(){
		
		this.container = $('block-catalog-search');
		
		this.form = this.container.getElement('form');
		
		this.img = this.container.getElement('img').setStyle('cursor', 'pointer');
		
		this.formFx = new Fx.Slide(this.form, { duration: 200, link: 'cancel' });
		this.formFx.hide();
		
		this.img.addEvent('click', function(event){
		  this.formFx.toggle();
		}.bind(this));
		
	}
};


window.addEvent('domready', function(){
  Rendl.init();
});
