// JavaScript Document

/* FLASH API */
function flashResult(arg){
  FlashPreview.result(arg);
}

var FlashPreview = {
	
	init: function(){
		
		this.container = new Element('div', { id: 'flash-preview-container' }).inject(document.body);
			
		this.flash = new Swiff('/flash/zoom.swf', {
			id: 'fjs',
			width: 451,
			height: 426,
			container: 'flash-preview-container',
			params: {
					wmode: 'transparent',
					bgcolor: '#ffffff'
			}
		});
		
		this.closeBtn = new Element('div', {
		  'class': 'flash-preview-close-btn'
		}).inject(this.container);
		
		this.closeBtn.addEvent('click', function(event){
		  event.stop();
			this.hide();
		}.bind(this));
		
		this.hide();
		
		this.image = '';
		
		// IE6
		if (Browser.Engine.trident && Browser.version < 5) this.setStatus('lte IE6', true);
		
		if (this.is('lte IE6')){
			this.container.setStyle('position', 'absolute');
			document.body.addEvent('mousewheel', function(){
				this.reset();
			}.bind(this));
		
		  this.reset();
		}
		
	},
	
	status: new Hash({
	  'loading': false
	}),
	
	setStatus: function(key, value){
		this.status.set(key, value);
	},
	
	getStatus: function(key){
	  return this.status.get(key);
	},
	
	is: function(key){
		return this.getStatus(key);
	},
	
	isNot: function(key){
		return !this.is(key);
	},
	
	reset: function(){
		var windowSize = window.getSize();
		var scrolled = document.body.getScroll();
		this.container.setStyle('top', (windowSize.y/2 + scrolled.y).toInt());
	},
	
	show: function(){
		this.container.setStyles({
		  width: 451,
			height: 426
		});
	},
	
	hide: function(){
		this.container.setStyles({
		  width: 1,
			height: 1
		});
	},
	
	load: function(img){
		this.setStatus('loading', true);
		this.image = img;
		this.flash.object.sendName(img);
	},
	
	cancel: function(){
		this.setStatus('loading', false);
		this.image = '';
	},
	
	result: function(response){
		if (this.is('loading') && response == 'nacteno'){
			this.fireEvent('load', this.image);
			this.image = '';
			this.show();
		}
	}
	
 };

$extend(FlashPreview, new Events());

var Giant = {
	
	init: function(){
		this.container = document.id('giant');
		this.logo  = this.container.getElement('img');
		this.anchor = this.container.getElement('a');
		
		this.logo.setStyle('cursor', 'pointer');
		this.logo.addEvent('click', function(){
		  window.open(this.anchor.get('href'));
		}.bind(this));
	}
	
 };

var RadioGroup = new Class({

  Implements: [Events, Options],
	
	options: function(){
		//onChange: $empty(radio)
	},
	
	initialize: function(radioGroup, options){
		this.group = $$(radioGroup);
		
		this.setOptions(options);
		
		this.current = false;
	  
		this.group.each(function(radio, index){
			var span = radio.getParent('span');
			span.addClass('ready');
		  var label = radio.getParent('label');
			label.addEvent('click', function(event){
			  event.preventDefault();
				this.check(index);
			}.bind(this));
		}, this);
		
		this.check();
		
		return this;
		
	},
	
	check: function(radioIndex){
		this.group.each(function(radio, index){
			if ($defined(radioIndex)) radio.checked = (radioIndex == index);
		  if (radio.checked){
				radio.getParent('span').addClass('checked');
				this.fireEvent('change', [radio, this.group.indexOf(radio)]);
			} else {
				radio.getParent('span').removeClass('checked');
			}
		}, this);
	},
	
	getElements: function(){
		return this.group;
	}

});

var Checkbox = new Class({

  Implements: [Events, Options],
	
	options: function(){
		//onChange: $empty(radio)
	},
	
	initialize: function(element, options){
		this.element = document.id(element);
		
		this.setOptions(options);
	  
		this.span = this.element.getParent('span');
    this.span.addClass('ready');
		this.label = this.element.getParent('label');
		this.label.addEvent('click', function(event){
			event.preventDefault();
			this.check();
		}.bind(this));
		
		this.check(true);
		
		return this;
		
	},
	
	check: function(onload){
		if (!onload) this.element.checked = !this.element.checked;
		this.checked = this.element.checked;
		this.element.checked ? this.span.addClass('checked') : this.span.removeClass('checked');
    if (!onload) this.fireEvent('change', this.element);
	},
	
	checked: false

});

var InputValidator = new Class({

  Implements: [Options, Events],
	
  options: {
		required: false,
		tests: [],
		position: 'left'
	},
	
  initialize: function(input, options){
		this.setOptions(options);
		this.input = document.id(input);
		this.tests = new Array(this.options.tests).flatten();
		this.errors = [];
		this.input.addEvent('blur', function(){
		  this.validate();
		}.bind(this));
		
		this.errorMark = null;
		
		// events
		this.addEvent('error', function(event){
		  this.placeErrors();
		});
		this.addEvent('success', function(){
		  this.removeErrors();
		});
		
		return this;
	},
	
	addTest: function(test, message){
		this.tests.include(test, message);
	},
	
	validate: function(){
		this.errors.empty();
		var value = this.input.value.trim();
		if (value == ''){
			if (this.options.required) this.errors.include('Toto pole je povinné.');
		} else {
			this.tests.each(function(test){
				value.test(test.regexp) ? this.errors.erase(test.message) : this.errors.include(test.message);
			}, this);
		}
		this.errors.length ? this.fireEvent('error') : this.fireEvent('success');
		
		return this;
	},
	
	getError: function(){
		return this.errors;
	},
	
	placeErrors: function(){
	  var parent = this.input.getParent('p')
		var target = parent.getElement('span.error-help');
		var message = this.errors.join('<br />');
		if (this.errorMark) this.errorMark.destroy();
		this.errorMark = new Element('span',{
		  'class': ['error-mark', this.options.position].join(' '),
			'html': message
		}).inject(target);
		parent.addClass('error');
	},
	
	removeErrors: function(){
	  var parent = this.input.getParent('p');
		parent.removeClass('error');
		if (this.errorMark) this.errorMark.destroy();
	},
	
	isEmpty: function(){
		return this.input.value == '';
	}
	
});

// Main object
var Polo = {
	
	init: function(){
		
		this.container = document.id('main-content');
		
		if (document.id('color-filter') && !document.id('active-filter')) Polo.ColorFilter.init();
		
		// Giant commons
		Giant.init();
		
		// Form Loader
		Polo.Form.init();
		
		// Range list
		this.rangeListItems = this.container.getElements('ul.range-list li');
		if (this.container.hasClass('page-homepage')) this.rangeListItems = new Array(this.rangeListItems, this.container.getElements('div.collection-type')).flatten();
		this.rangeListItems.each(function(rangeListItem){
		  var anchor = rangeListItem.getElement('a');
			rangeListItem.addEvent('click', function(event){
			  if (event.target != anchor) window.location = anchor.get('href');
			});
			rangeListItem.setStyle('cursor', 'pointer');
		});
		
		// Product list CSS fix
		if (Browser.Engine.trident && Browser.Engine.version >= 5){
			this.productListItems = this.container.getElements('ul.product-list li:nth-child(4n+1)');
			this.productListItems.each(function(item){ item.addClass('nth-child-4n1'); });
		}
		
		// color pallete loader
		this.colorPalletes = this.container.getElements('ul.color-pallete > li');
		this.colorPalletes = this.colorPalletes.filter(function(colorPallete){
		  return !colorPallete.hasClass('head');
		});
		this.colorPalletes.each(function(colorPallete){
		  new Polo.ColorPallete(colorPallete);
		});
		
		// selected products
	  this.container.getElements('div.selected-products').each(function(element){
		  new Polo.SelectedProducts(element);
		});
		
		// flash
		if (document.id('flash')){
			var topFlash = new Swiff('/flash/slideshow.swf', {
				id: 'topFlash',
				container: document.id('flash'),
				width: 825,
				height: 325,
				params: {
					wmode: 'transparent',
					flashvars: 'param='+flashParams
				}
		  });
		}
		
		// target: _blank
		$$('a._blank').each(function(a){
		  a.addEvent('click', function(event){
			  event.preventDefault();
				window.open(this.href);
			});
		});
		
		// flash preview
		if ($$('div.leather-preview').length) FlashPreview.init();
				
	}
	
 };

Polo.ColorFilter = {
	
	init: function(){
		
		this.container = document.id('color-filter');
		
		this.trigger = this.container.getElement('p.trigger');
		
		this.slide = this.container.getElement('div#color-filter-slide');
		
		this.closeBtn = this.container.getElement('.close');
		
		this.items = this.container.getElements('li');
		this.items.each(function(item){
		  var anchor = item.getElement('a');
			item.addEvent('click', function(event){
				if (event.target != anchor)  window.location = anchor.get('href');
			});
		});
		
		this.slideFx = new Fx.Slide(this.slide, { duration: 500, link: 'cancel', transition: Fx.Transitions.Quint.easeOut });
		this.slideFx.hide();
		
		this.trigger.addEvent('click', function(){
		  this.toggle();
		}.bind(this));
		
		if (this.closeBtn){
			this.closeBtn.addEvent('click', function(event){
				event.preventDefault();
				this.close();
			}.bind(this));
		}
		
	},
	
	open: function(){
		this.trigger.addClass('on');
		this.slideFx.slideIn();
	},
	
	close: function(){
		this.slideFx.slideOut();
		this.trigger.removeClass('on');
	},
	
	toggle: function(){
		this.trigger.hasClass('on') ? this.close() : this.open();
	}
	
 };
 
Polo.ColorPallete = new Class({
	
	Implements: [Options, Events],
	
	options: {
		selectable: false,
		selector: {
			preview: 'div.mask-container',
      items: 'div.leather-colors li',
			label: 'div.leather-label'
		}
	},
	
	initialize: function(container, options){
		
		this.container = document.id(container);
		
		this.setOptions(options);
		
		// basic elements
    this.items = this.container.getElements(this.options.selector.items);
		this.preview = (this.options.selector.preview ? new Polo.ColorPallete.Preview(this.container.getElement(this.options.selector.preview)) : null);
    this.label = (this.options.selector.label ? new Polo.ColorPallete.Label(this.container.getElement(this.options.selector.label)) : null);
		// currently selected item
		this.selected = null
		
		this.offsetParent = document.body;

		this.bubble = new Polo.ColorPallete.Bubble(this.offsetParent);
				
		// items behaviour
		this.items.each(function(item){
		  var anchor = item.getElement('a');
			var img = item.getElement('img');
			var alt = img.get('alt').split(' ');
			var type = alt[0];
			var id = alt[2];
			var title = alt.filter(function(value, index){ return index > 2; }).join(' ');
			var checkbox = item.getElement('input');
			

      // bubble
			if ($defined(id)){
  		  var bubbleText = '{type} &ndash; {id}<br />{title}'.substitute({type: type, id: id, title: title});
			} else {
				var bubbleText = img.get('alt');
			}
			item.getElement('span').addEvents({
			  'mouseenter': function(){
					var position = item.getPosition(this.offsetParent);
					this.bubble.set({
					  'styles': {
							'top': position.y + 45,
							'left': position.x + 40
						},
						'html': bubbleText
					});
					this.bubble.open();
				}.bind(this),
				'mouseleave': function(){
					this.bubble.close();
				}.bind(this)
			}, this);
			
			// anchor click kill
			anchor.addEvent('click', function(event){ event.preventDefault(); });
			
			// item event
			item.addEvent('click', function(event){
				if (this.label){
					this.label.set({
					 'label' : {
						 'type': type,
						 'id': id,
						 'title': title
					 },
					 'link': anchor.get('href')
					}).open();
				}
				// select item
				this.select(item);
				// preview load
				if (this.preview) this.preview.show(img.get('src'));
			}.bind(this));
			
			// checkbox init
			if (this.options.selectable && checkbox && checkbox.checked){
				this.selected = item;
			}
		}, this);
		
		
		// oninit select
		if (this.selected) this.select(this.selected);
		return this;

	},
	
	select: function(item){
		if (this.selected){
			this.selected.removeClass('selected');
			if (this.options.selectable) this.selected.getElement('input').checked = false;
		}
		this.selected = item;
		this.selected.addClass('selected');
		if (this.options.selectable) this.selected.getElement('input').checked = true;
		this.fireEvent('select', item);
	},
	
	reset: function(){
		if (this.selected){
			this.selected.removeClass('selected');
			if (this.options.selectable) this.selected.getElement('input').checked = false;
			this.selected = null;
		}
	},
	
	getColors: function(){
		return this.items;
	}
	
});

Polo.ColorPallete.Label = new Class({

  Implements: Options,
	
	options: {
		labelTemplate: '{type} &ndash; {id}<br />{title}',
		labelSelector: 'p.label',
		anchorSelector: 'p.more a',
		maxHeight: 93,
		slideDuration: 200,
		morph: {
			from: {
				'height': 0,
				'opacity': 0
			},
			to: {
				'height': 93,
				'opacity': 1
			}
		}
	},
	
	initialize: function(container, options){
		this.container = container;
		
		this.setOptions(options);
		
		this.fx = new Fx.Morph(this.container, { duration: this.options.slideDuration, link: 'cancel' });
		this.fx.set(this.options.morph.from);
		
		this.label = this.container.getElement(this.options.labelSelector);
		
		this.anchor = this.container.getElement(this.options.anchorSelector);
		
		if (!this.anchor) this.options.morph.to.height = 30;
		
		this.isOpen = false;
		
		return this;
	},
	
	open: function(){
		if (!this.isOpen){ this.fx.start(this.options.morph.to); this.isOpen = true; }
	},
	
	close: function(){
		this.fx.start(this.options.morph.from);
		this.isOpen = false;
	},
	
	set: function(type, val){
		var settings = ($type(type) == 'object' ? new Hash(type) : new Hash({type: val}));
		
		settings.each(function(setting, key){
			switch (key){
				case 'label':
					this.setLabel(setting);
				break;
				case 'link':
					this.setLink(setting);
				break;
			}
		}, this);
		return this;
	},
	
	setLabel: function(textObject){
		this.label.set('html', this.options.labelTemplate.substitute(textObject));
		return this;
	},
	
	setLink: function(href){
		if (this.anchor) this.anchor.set('href', href);
	}

});

Polo.ColorPallete.Preview = new Class({

  Implements: [Events, Options],
	
	options: {
		selector: {
			imgLayer: 'div.leather-container',
			zoomLayer: 'div.zoom-layer'
		},
		fx: {
			overlay: {from: 0,    to: 0.5, duration: 100},
			img:     {from: 0,    to: 1,   duration: 100},
			text:    {from: 0,    to: 1,   duration: 200},
			zoom:    {from: 0.01, to: 1,   duration: 0}
		},
	  img: {
			regexp: 'leathers/',
			modifier: 'leathers/m/'
		},
		largeImg: {
			regexp: '/m/',
			modifier: '/l/'
		}
	},
	
	initialize: function(container, options){
		
		this.container = container;
		
		this.setOptions(options);
		
		// current img url
		this.current = '';

		// status hash
		this.status = new Hash({
			'loading': false,
			'imgLoaded': false
		}),
		
		// main fx object
		this.fx = {};
		
		// help text fx
		this.text = this.container.getElement('p');
		this.fx.text =  new Fx.Tween(this.text, {property: 'opacity', duration: this.options.fx.text.duration, link: 'cancel'});
		this.fx.text.set(this.options.fx.text.to);
		
		// img layer		
		this.imgCache = new Hash();
		this.imgLayer = this.container.getElement(this.options.selector.imgLayer);
		this.fx.img = new Fx.Tween(this.imgLayer, {property: 'opacity', duration: this.options.fx.img.duration, link: 'chain'});
		this.fx.img.set(this.options.fx.img.from);
		
	  // zoom layer
		this.zoomLayer = this.container.getElement(this.options.selector.zoomLayer);
		this.fx.zoom = new Fx.Tween(this.zoomLayer, {property: 'opacity', duration: this.options.fx.zoom.duration, link: 'cancel'});
		this.fx.zoom.set(this.options.fx.zoom.from);
		this.zoomLayer.addEvents({
		  'mouseenter': function(){
				if (this.is('imgLoaded')){
					this.fx.zoom.start(this.options.fx.zoom.to);
					this.zoomLayer.setStyles({
						'cursor': 'pointer',
						'cursor': '-moz-zoom-in'
					});
				}
			}.bind(this),
			'mouseleave': function(){
		    this.fx.zoom.start(this.options.fx.zoom.from);
			}.bind(this),
			'click': function(){
				if (this.is('imgLoaded')){
					this.fx.overlay.start(this.options.fx.overlay.to);
					this.fx.zoom.start(this.options.fx.zoom.from);
					this.fireEvent('flashPreviewStart');
				}
			}.bind(this)
		});
	
		// overlay - spinner
		this.overlay = new Element('div', {'class': 'overlay'}).inject(this.imgLayer, 'after');
		this.fx.overlay = new Fx.Tween(this.overlay, {property: 'opacity', duration: this.options.fx.overlay.duration, link: 'cancel'});
		this.fx.overlay.set(this.options.fx.overlay.from);
		
		// self events
		this.addEvents({
		  'placeImgComplete': function(){
				this.current = this.imgLayer.getElement('img').get('src');
				this.fx.text.start(0);
				this.fx.overlay.start(this.options.fx.overlay.from);
				this.fx.img.start(this.options.fx.img.to);
			}.bind(this),
			'imgLoadStart': function(){
				this.fx.img.start(this.options.fx.img.from);
				this.fx.overlay.start(this.options.fx.overlay.to);
			}.bind(this),
			'imgLoadComplete': function(){
			}.bind(this),
			'imgLoadError': function(){
				this.fx.text.start(1);
				this.fx.overlay.start(this.options.fx.overlay.from);
			}.bind(this),
			'flashPreviewStart': function(){
				FlashPreview.load(this.current.replace(this.options.largeImg.regexp, this.options.largeImg.modifier));
			},
			'flashPreviewCancel': function(){
				FlashPreview.cancel();
			},
			'flashPreviewComplete': function(imgSrc){
				if (imgSrc == this.current.replace(this.options.largeImg.regexp, this.options.largeImg.modifier)){
					this.fx.overlay.start(this.options.fx.zoom.from);
				}
			}
		});
		
		// Flash preview events
		FlashPreview.addEvent('load', function(imgSrc){
		  this.fireEvent('flashPreviewComplete', imgSrc);
		}.bind(this));
		
	},
	
	show: function(imgUrl){
		this.fireEvent('showStart');
		// modify url
		if (this.options.img.regexp) imgUrl = imgUrl.replace(this.options.img.regexp, this.options.img.modifier);
		if (imgUrl != this.current){
			if (this.imgCache.has(imgUrl)){
				this.current = imgUrl;
				this.fx.img.start(this.options.fx.img.from).chain(function(){
					this.placeImage(this.imgCache.get(imgUrl));
				}.bind(this));
			} else {
				this.fireEvent('imgLoadStart');
				
				var img = new Asset.image(imgUrl, {
					onload: function(){
						if (img.width){
							this.imgCache.set(imgUrl, img);
							this.fireEvent('imgLoadComplete');
							this.placeImage(img);
						} else {
							this.fireEvent('imgLoadError');
						}
					}.bind(this)
				});
			}
		}
		this.fireEvent('showEnd');
	},
	
	is: function(status){
		return this.status.get(status);
	},
	
	isNot: function(status){
	  return !this.is(status);
	},
	
	placeImage: function(imgEl){
		this.fx.img.start(this.options.fx.img.from).chain(function(){
			this.imgLayer.empty();
			imgEl.inject(this.imgLayer);
			this.status.set('imgLoaded', true);
			this.fireEvent('placeImgComplete');
		}.bind(this));
	}


});

Polo.ColorPallete.Bubble = new Class({

  Implements: [Events, Options],
	
	options: {
	  element: 'span',
		'class': 'label-bubble',
		title: '',
		autoShow: false
  },
	
	initialize: function(container, options){
		
		this.container = document.id(container);
		
		this.setOptions(options);
		
		this.timer = null;
		
		this.bubble = new Element(this.options.element, {
		  'class': this.options['class'],
			'html': this.options.title
		});
		
		this.bubble.inject(this.container);
		this.bubble.hide();
		
		return this;
		
	},
	
	set: function(settings){
		this.bubble.set(settings);
	},
	
	open: function(){
		if (this.timer) $clear(this.timer);
		this.bubble.show();
	},
	
	close: function(){
		this.timer = this.bubble.hide.delay(100, this.bubble);
	}
  
});

Polo.Form = {
	
	init: function(){
		
		if (document.id('form-basket')) Polo.Form.Basket.init();
		if (document.id('form-order')) Polo.Form.Order.init();
		if (document.id('form-contact')) Polo.Form.Contact.init();
		
	}
	
 };

Polo.Form.Input = new Class({

  Implements: Options,
	
	options: {
		defaultValue: null,
		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));
		
		if (this.options.defaultValue){
			this.element.addEvent('blur', function(){
			  if (this.element.value == '') this.element.value = this.options.defaultValue;
			}.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;
		}
	}
});

Polo.Form.Basket = {
	
	init: function(){
		
		this.form = document.id('form-basket');
		
		this.step = null;
		
		this.current = -1;
		
		this.leatherLabel = this.form.getElement('p.leather-color-label');
		
		this.status = {
			undetermined: false
		}
		
		// fieldsets
		this.group = {
			type: document.id('form-basket-group-type'),
			color: document.id('form-basket-group-color'),
			quantity: document.id('form-basket-group-quantity')
		};
		
		// fieldset legends
		this.legend = {
			type: this.group.type.getElement('legend'),
			color: this.group.color.getElement('legend'),
			quantity: this.group.quantity.getElement('legend')
		}
		
		this.setStep('1');
	
	  this.colorBlocks = this.form.getElements('div.leather-color-block').fade('hide');
		this.colorBlockMaxHeight = 0;
    this.colorBlocks.each(function(colorBlock){
      var height = colorBlock.getSize().y;
			if (height > this.colorBlockMaxHeight) this.colorBlockMaxHeight = height;
		}, this);
		this.colorBlocks.addClass('loaded');
		
		this.group.color.getElement('div.leather-colors').setStyle('height', this.colorBlockMaxHeight);
		
		// color pallete
  	this.colorPallete = new Polo.ColorPallete(this.group.color, {
  		selector: {
				preview: null,
				label: null
			},
			selectable: true,
		  onSelect: function(item){
				this.leatherLabel.set('html', ['Vybraná farba:', '<strong>', item.getElement('img').get('alt'), '</strong>'].join(' '));
				this.setStep('3');
			}.bind(this)
		});
		
		
		// radio buttons
		this.radioGroup = new RadioGroup(this.group.type.getElements('input[type=radio]'), {
		  onChange: function(radio, index){
				this.status.undetermined = radio.getParent('li').hasClass('undetermined');
        this.filter(index);
				this.setStep('2');
			}.bind(this)
		});
		
		// quantity keyboard limiter
		new Polo.Form.Input(this.group.quantity.getElement('input'), { type: 'numbers', defaultValue: 1 });

	},
	
	filter: function(blockIndex){
		if (this.current != blockIndex){
			if (this.current > -1) this.colorBlocks[this.current].fade('hide');
			this.colorBlocks[blockIndex].fade('show');
			this.current = blockIndex;
		}
	},
	
	setStep: function(step){
		if (step != this.step){
			this.form.set('class', 'step-'+step);
			this.step = step;
		}
		this.refresh();
	},
	
	// refresh form status
	refresh: function(){
		switch (this.step){
			case '1':
			  this.legend.color.set('text', '2) Volba farby koža');
			break;
			case '2':
			  this.colorPallete.reset();
				this.leatherLabel.set('html', this.status.undetermined ? 'Kliknutím vyberte požadovaný odtieň' : 'Kliknutím vyberte požadovanú farbu.');
			  this.legend.type.set('text', '1) Typ kože');
				this.legend.color.set('text', this.status.undetermined ? '2) Vyberte farebné odtiene' : '2) Vyberte typ kože');
				this.legend.quantity.set('text', '3) Volba počtu kusov');
			break;
			case '3':
			  this.legend.color.set('text', this.status.undetermined ? '2) Farebné odtiene' : '2) Farba koža');
				this.legend.quantity.set('text', '3) Zvolte počet kusov');
			break;
		}
	}
	
 };
 
Polo.Form.Order = {
	
	validators: {
		'name': {required: true},
		'lastname': {required: true},
		'email': {required: true, tests: {regexp: /[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}/, message: 'Zadaná emailová adresa nie je platná.'}},
		'phone': {tests: {regexp: /^[0-9 ]{9,12}$|^[0-9\+ ]{13,16}$/, message: 'Neplatný formát telefónneho čísla. Príklad: <strong>+420123456789</strong>'}},
		'invoice-street': {required: true},
		'invoice-city': {required: true},
		'invoice-zip': {required: true,	tests: {regexp: /^[0-9]{3}[ ]?[0-9]{2}$/,	message: 'Neplatný formát PSČ. Príklad: <strong>123 45</strong>'}},
		'invoice-ic': {tests: {regexp: /[0-9]{8}/, message: 'Neplatný formát IČ. Príklad: <strong>12345678</strong>'}},
		'invoice-dic': {tests: {regexp: /[A-Z]{2}[0-9]{10}/, message: 'Neplatný formát DIČ. Príklad: <strong>SK1234567890</strong>'}},
		'invoice-company': {} // empty test
	},
	
	init: function(){
		this.form = document.id('form-order');
		
		this.button = this.form.getElement('button[type=submit]');
		
		this.prefix = 'form-order-';
		
		// invoice slider
		this.invoice = {
			slide: document.id('form-order-invoice-slide').getElement('div.slide'),
			trigger: document.id('form-order-invoice-slide').getElement('input[type=checkbox]')
		}

		this.invoice.fx = new Fx.Slide(this.invoice.slide, { duration: 300, link: 'cancel', transition: Fx.Transitions.Quad.easeOut });
		
		this.invoice.checkbox = new Checkbox(this.invoice.trigger, {
		  onChange: function(checkbox){
				checkbox.checked ? this.invoice.fx.slideIn() : this.invoice.fx.slideOut();
			}.bind(this)
		});
		this.invoice.checkbox.checked ? this.invoice.fx.show() : this.invoice.fx.hide();
		
		// delivery slider
		this.delivery = {
			slide: document.id('form-order-delivery-slide').getElement('div.slide'),
			trigger: document.id('form-order-delivery-slide').getElement('input[type=checkbox]')
		}

		this.delivery.fx = new Fx.Slide(this.delivery.slide, { duration: 300, link: 'cancel', transition: Fx.Transitions.Quad.easeOut });
		
		this.delivery.checkbox = new Checkbox(this.delivery.trigger, {
		  onChange: function(checkbox){
				checkbox.checked ? this.delivery.fx.slideOut() : this.delivery.fx.slideIn();
			}.bind(this)
		});
		this.delivery.checkbox.checked ? this.delivery.fx.hide() : this.delivery.fx.show();
		
		// validators
		this.validators = new Hash(this.validators);
		this.validatedItems = new Hash();
		this.validators.each(function(settings, name){
		  this.validatedItems.set(name, new InputValidator(this.getID(name), settings));
		}, this);
		
		this.agreement = new Checkbox(this.form.getElement('input#form-order-agreement'));
		this.agreement.element.getParent('label').getElement('a').addEvent('click', function(event){ event.stopPropagation(); });
		
		this.form.addEvent('submit', function(event){
		  event.stop();
		  if (this.isValid()){
				if (this.agreement.checked){
					this.button.disabled = true;
					this.form.submit();
				} else {
					alert('Pred odoslatim objednávky je treba súhlasiť so Všeobecnými nákupnými podmienkami.');
				}
			} else {
				alert('Prosím vyplňte všetky požadované polia.');
			}
		}.bind(this));
		
	},
	
	isValid: function(){
		var errors = 0;
		this.validatedItems.get('invoice-company').setOptions({required: this.invoice.checkbox.checked});
		this.validatedItems.get('invoice-dic').setOptions({required: this.invoice.checkbox.checked});
		this.validatedItems.get('invoice-ic').setOptions({required: this.invoice.checkbox.checked});
		this.validatedItems.each(function(item, name){
			item.validate();
			errors += item.getError().length;
		});
		
		return !errors;
	},
	
	getID: function(name){
		return this.prefix + name;
	}
	
 };
 
Polo.Form.Contact = {
	
	validators: {
		'name': {required: true},
		'email': {required: true, tests: {regexp: /[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}/, message: 'Zadaná emailová adresa nie je platná.'}},
		'phone': {tests: {regexp: /^[0-9 ]{9,12}$|^[0-9\+ ]{13,16}$/, message: 'Neplatný formát telefónneho čísla. Príklad: <strong>+420123456789</strong>'}, position: 'right'}
	},
	
	init: function(){
		
		this.form = document.id('form-contact');
		this.prefix = 'form-contact-';
		
		this.slideFx = new Fx.Slide(this.form.getElement('div.slide'), { duration: 400, link: 'cancel', transition: Fx.Transitions.Quad.easeOut });
		this.slideFx.hide();

		this.radioGroup = new RadioGroup(this.form.getElements('input[type=radio]'),{
      onChange: function(radio, index){
				index == 1 ? this.slideFx.slideIn() : this.slideFx.slideOut();
			}.bind(this)
		});
		
		this.checkboxes = this.form.getElements('input[type=checkbox]');
		this.checkboxes.each(function(checkbox){
		  new Checkbox(checkbox);
		}, this);
		
		// validators
		this.validators = new Hash(this.validators);
		this.validatedItems = new Hash();
		this.validators.each(function(settings, name){
		  this.validatedItems.set(name, new InputValidator(this.getID(name), settings));
		}, this);
		
		this.form.addEvent('submit', function(event){
		  event.stop();
		  if (this.isValid()){
				this.form.submit();
			} else {
				alert('Prosím vyplňte všetky požadované polia.');
			}
		}.bind(this));
	},
	
	isValid: function(){
		var errors = 0;
		this.validatedItems.each(function(item, name){
			item.validate();
			errors += item.getError().length;
		});
		return !errors;
	},
	
	getID: function(name){
		return this.prefix + name;
	}
	
 };

Polo.SelectedProducts = new Class({
	
	initialize: function(container){
		this.container = document.id(container);
		
		this.container.addEvent('click:relay(a)', function(event){
			event.preventDefault();
			if (event.target.hasClass('del')){
				if (confirm('Opravdu si přejte odstranit tento produkt z košíku?')){
					window.location = event.target.get('href');
				}
			}
			if (event.target.hasClass('inc') || event.target.hasClass('dec')) this.modify(event.target);
		}.bind(this));
		
		this.total = this.container.getElement('tfoot td.col-price');
		
		this.basket = document.id('basket');
		this.basket = this.basket ? this.basket.getElement('a') : null;
	},
	
	modify: function(element){
		var url = element.get('href');
		var cell = element.getParent('td');
		var row = element.getParent('tr');
		var output = cell.getElement('strong');
		var footerBasket = document.id('footer-basket');
		var price = row.getElement('td.col-price').get('text').replace('€','').split('-');
		price.each(function(item, index){ price[index] = (item.trim().toInt() || 0); });
		var totalPrice = row.getElement('td.col-price strong.total');
		new Request.JSON({
		  url: url,
			onSuccess: function(responseJSON){
				if (responseJSON && responseJSON.quantity){
					output.set('html', responseJSON.quantity);
					if (responseJSON.total){
						var text = responseJSON.total + ' ' + (responseJSON.total == 1 ? 'produkt' : (responseJSON.total < 5 ? 'produktov' : 'produktov'));
						footerBasket.set('text', text); 
						if (this.basket) this.basket.set('text', text);
						price.each(function(item, index){ price[index] = item*responseJSON.quantity.toInt(); });
						totalPrice.set('text', price.join(' - '));
					}
					if (responseJSON.price){
						this.total.set('text', responseJSON.price);
					}
				}
			}.bind(this)
		}).get();
	}
	
});

window.addEvent('domready', function(){
  Polo.init();
});
