// JavaScript Document
Number.implement({

  generatePrice: function(){
		// separate by 3 decimal places
		var priceArray = this.toInt().toString().split('').reverse();
		var length = priceArray.length;
		var newPrice = new Array();
		for (var i = 0; i < length; i++){
			newPrice[i] = (i%3 ? priceArray[i] : priceArray[i]+' ');
		}
		newPrice = newPrice.reverse().join('').trim() + ',- Kč';
		return newPrice;
	}

});

String.implement({
	parsePrice: function(){
		var price = this.replace(' ', '').toInt();
		if (isNaN(price)) price = 0;
		return price;
	}
});

Element.implement({

  makeClickable: function(){
		var anchor = this.getElement('a');
		if (anchor){
			this.setStyle('cursor', 'pointer');
			this.addEvent('click', function(event){
			  if (document.id(event.target).get('tag') != 'a') window.location = anchor.href;

			});
		}
	}

});

Browser.IE6 = (Browser.Engine.trident && Browser.Engine.version == 4);

/* MODIFIED SLIDER FROM MOOTOOLS MORE */
/* Fixed positions, prevent click event on range bar */
var Slider = new Class({

	Implements: [Events, Options],

	Binds: ['clickedElement', 'draggedKnob', 'scrolledElement'],

	options: {/*
		onTick: $empty(intPosition),
		onChange: $empty(intStep),
		onComplete: $empty(strStep),*/
		onTick: function(position){
			if (this.options.snap) position = this.toPosition(this.step);
			this.knob.setStyle(this.property, position);
		},
		snap: false,
		offset: 0,
		range: false,
		wheel: false,
		steps: 100,
		mode: 'horizontal'
	},

	initialize: function(element, knob, options){
		this.setOptions(options);
		this.element = document.id(element);
		this.knob = document.id(knob);
		this.previousChange = this.previousEnd = this.step = -1;
		var offset, limit = {}, modifiers = {'x': false, 'y': false};
		switch (this.options.mode){
			case 'vertical':
				this.axis = 'y';
				this.property = 'top';
				offset = 'offsetHeight';
				break;
			case 'horizontal':
				this.axis = 'x';
				this.property = 'left';
				offset = 'offsetWidth';
		}
		this.half = this.knob[offset] / 2;
		this.full = this.element[offset] - this.knob[offset] + (this.options.offset * 2);
		this.min = $chk(this.options.range[0]) ? this.options.range[0] : 0;
		this.max = $chk(this.options.range[1]) ? this.options.range[1] : this.options.steps;
		this.range = this.max - this.min;
		this.steps = this.options.steps || this.full;
		this.stepSize = Math.abs(this.range) / this.steps;
		this.stepWidth = this.stepSize * this.full / Math.abs(this.range) ;

		this.knob.setStyle(this.property, - this.options.offset);
		modifiers[this.axis] = this.property;
		limit[this.axis] = [- this.options.offset, this.full - this.options.offset];

		this.bound = {
			clickedElement: this.clickedElement.bind(this),
			scrolledElement: this.scrolledElement.bindWithEvent(this),
			draggedKnob: this.draggedKnob.bind(this)
		};

		var dragOptions = {
			snap: 0,
			limit: limit,
			modifiers: modifiers,
			onDrag: this.bound.draggedKnob,
			onStart: this.bound.draggedKnob,
			onBeforeStart: (function(){
				this.isDragging = true;
			}).bind(this),
			onComplete: function(){
				this.isDragging = false;
				this.draggedKnob();
				this.end();
			}.bind(this)
		};
		if (this.options.snap){
			dragOptions.grid = Math.ceil(this.stepWidth);
			dragOptions.limit[this.axis][1] = this.full;
		}

		this.drag = new Drag(this.knob, dragOptions);
		this.attach();
	},

	attach: function(){
		//this.element.addEvent('mousedown', this.bound.clickedElement);
		if (this.options.wheel) this.element.addEvent('mousewheel', this.bound.scrolledElement);
		this.drag.attach();
		return this;
	},

	detach: function(){
		//this.element.removeEvent('mousedown', this.bound.clickedElement);
		this.element.removeEvent('mousewheel', this.bound.scrolledElement);
		this.drag.detach();
		return this;
	},

	set: function(step){
		if (!((this.range > 0) ^ (step < this.min))) step = this.min;
		if (!((this.range > 0) ^ (step > this.max))) step = this.max;

		this.step = Math.round(step);
		this.checkStep();
		this.fireEvent('tick', this.toPosition(this.step));
		this.end();
		return this;
	},

	clickedElement: function(event){
		if (this.isDragging || event.target == this.knob) return;

		var dir = this.range < 0 ? -1 : 1;
		var position = event.page[this.axis] - this.element.getPosition()[this.axis] - this.half;
		position = position.limit(-this.options.offset, this.full -this.options.offset);

		this.step = Math.round(this.min + dir * this.toStep(position));
		this.checkStep();
		this.fireEvent('tick', position);
		this.end();
	},

	scrolledElement: function(event){
		var mode = (this.options.mode == 'horizontal') ? (event.wheel < 0) : (event.wheel > 0);
		this.set(mode ? this.step - this.stepSize : this.step + this.stepSize);
		event.stop();
	},

	draggedKnob: function(){
		var dir = this.range < 0 ? -1 : 1;
		var position = this.drag.value.now[this.axis];
		position = position.limit(-this.options.offset, this.full -this.options.offset);
		this.step = Math.round(this.min + dir * this.toStep(position));
		this.checkStep();
	},

	checkStep: function(){
		if (this.previousChange != this.step){
			this.previousChange = this.step;
			this.fireEvent('change', this.step);
		}
	},

	end: function(){
		if (this.previousEnd !== this.step){
			this.previousEnd = this.step;
			this.fireEvent('complete', this.step + '');
		}
	},

	toStep: function(position){
		var step = (position + this.options.offset) * this.stepSize / this.full * this.steps;
		return this.options.steps ? Math.round(step -= step % this.stepSize) : step;
	},

	toPosition: function(step){
		return (this.full * Math.abs(this.min - step)) / (this.steps * this.stepSize) - this.options.offset;
	}

});

var MiniSlideshow = new Class({

  Implements: [Options, Events],
	
	Binds: ['move'],
	
	options: {
		slide: 'img',
		duration: 200,
		interval: 1500,
		transition: 'sine:in:out'
	},
	
	initialize: function(container, options){
		
		this.container = document.id(container);
				
		this.setOptions(options);
		
		this.slides = this.container.getElements(this.options.slide);
		
		this.slideFx = new Array();
		
		this.current = 0;
		this.count = this.slides.length;
		
		this.slides.each(function(slide, index){
		  var fx = new Fx.Tween(slide, { property: 'opacity', duration: this.options.duration, transition: this.options.transition, link: 'cancel' });
			index == this.current ? fx.set(1) : fx.set(0);
			slide.setStyle('position', 'absolute');
			this.slideFx[index] = fx;
		}, this);
		
		this.container.addClass('loaded');
		
		return this;
	},
	
	show: function(){
		this.container.show();
		this.start();
		return this;
	},
	
	hide: function(){
		this.stop();
		this.container.hide();
		return this;
	},
	
	start: function(){
		if (this.count > 1){
  		this.timer = this.move.periodical(this.options.interval);
		}
	},
	
	stop: function(){
		$clear(this.timer);
	},
	
	move: function(){
		var next = ((this.current+1)%this.count);
		this.slideFx[this.current].start(0);
		this.slideFx[next].start(1);
		this.current = next;
	}

});

var ShowMotive = new Class({
 	
	initialize: function(){
	
	  		var w = Math.max(
				Math.max(document.body.scrollWidth, document.documentElement.scrollWidth),
				Math.max(document.body.offsetWidth, document.documentElement.offsetWidth),
				Math.max(document.body.clientWidth, document.documentElement.clientWidth)
				);
				
			if(w < 1300){
			$("upper-wrapper").setStyle("margin","0px 0px 0px 20px");
				
			}
			else{
			$("upper-wrapper").setStyle("margin","0px auto");
			}
	}

});


var Blender = new Class({

  Implements: [Options, Events],
  
	Binds: ['blend'],	
	
	options: {
		slide: 'div',
		duration: 200,
		interval: 5000
	},
	
	initialize: function(container, options){
		
		this.container = document.id(container);
		this.setOptions(options);
		this.slides = this.container.getElements(this.options.slide);
		this.current = 0;
		this.slideFx = new Array();
		this.count = this.slides.length;

		this.slides.each(function(slide, index){
		  var fx = new Fx.Tween(slide, { property: 'opacity' });
			index == this.current ? fx.set(1) : fx.set(0);
			this.slideFx[index] = fx;
		}, this);
	},
	

	start: function(){
  		this.timer = this.blend.periodical(this.options.interval);
	},
	
	
	blend: function(){
		var next = ((this.current+1)%this.count);
		this.slideFx[this.current].start(0);
		this.slideFx[next].start(1);
		this.current = next;
	}

});


var Zazitky = {
	
	init: function(){
		this.container = document.id('main-content');
		
		this.loader = new Hash({
		  'homepage' : Zazitky.Homepage.init,
			'category': Zazitky.Category.init,
			'experience-detail': Zazitky.Detail.init
		});
		
		this.sectionClass = this.container.get('class');
		if (this.loader.has(this.sectionClass)) this.loader.get(this.sectionClass).call();
		
		$$('.experience-list li, #sidebar-payment, #gem-basket, ul.icons-free li').makeClickable();
		
		new Map('select-map');
		new DoubleSlider('price-range');
		
		// Form loader
		Zazitky.Form.init();
		
		// target=_blank
		$$('a._blank').set('target', '_blank');
		
	
	
		$$('div.main-tab').each(function(element){
			var tabs = element.getElements('div.tabs');
			var bookmark = element.getElements('span.bookmark');
			
			bookmark.each(function(book, index){
				book.addEvent('click', function(){
					tabs.hide();
					tabs[index].show();
					bookmark.removeClass('active');
					this.addClass('active');
				});
				
				
			});
		});
		
	  if (document.id('sidebar-payment')) new MiniSlideshow('sidebar-payment').start();
	  
	  if (document.id('guarantee')) new Blender('guarantee').start();
		
	  if(document.id('accordion-qa')) new Fx.Accordion($('accordion-qa'), '#accordion-qa h2', '#accordion-qa .content', { display: -1, alwaysHide: true });
	  
	  new ShowMotive();
	  
		window.onresize = function() {
		new ShowMotive();
		}	
		
	}
	
 };
 
 
var DoubleSlider = new Class({

  Implements: [Options, Events],
	
	options: {
		knob: {
			min: '.knob-min',
			max: '.knob-max'
		},
		limit: {
			min: '.input-min',
			max: '.input-max'
		},
		output: {
			min: '.output-min',
			max: '.output-max'
		},
		range: '.range',
		loadedClass: 'loaded',
		diff: 100,
		steps: 101
	},
	
	initialize: function(container, options){
		
		this.setOptions(options);
		this.container = document.id(container);
		this.range = this.container.getElement(this.options.range);
		
		this.knob = this.toElements(this.options.knob);
		this.knob.minText = this.knob.min.getElement('span');
		this.knob.maxText = this.knob.max.getElement('span');
		
		this.limit = this.toElements(this.options.limit);
		this.limit.minValue = this.limit.min.get('value').toInt();
		this.limit.maxValue = this.limit.max.get('value').toInt();
		
		this.output = this.toElements(this.options.output);
		
		this.start = {
			min: (this.output.min.value ? this.output.min.value.toInt() : this.limit.minValue),
			max: (this.output.max.value ? this.output.max.value.toInt() : this.limit.maxValue)
		};
		
		this.slider = {
			min: new Slider(this.range, this.knob.min, {
				range: [this.limit.minValue, this.limit.maxValue],
				offset: 0,
				steps: this.options.steps,
			  onChange: function(step){
					var limitValue = this.getKnobValue('max')-this.options.diff;
					if (step > limitValue){
						this.slider.min.set(limitValue);
						step = limitValue;
					}
					this.setKnobValue('min', step);
					this.output.min.value = step;
				}.bind(this)
			}),
			max: new Slider(this.range, this.knob.max, {
				range: [this.limit.minValue, this.limit.maxValue],
				offset: 0,
				steps: this.options.steps,
			  onChange: function(step){
					var limitValue = this.getKnobValue('min')+this.options.diff;
					if (step < limitValue){
						this.slider.max.set(limitValue);
						step = limitValue;
					}
					this.setKnobValue('max', step);
					this.output.max.value = step;
				}.bind(this)
			})
		}

    // default knob values
		this.setKnobValue('min', this.start.min);
		this.setKnobValue('max', this.start.max);
		this.slider.min.set(this.start.min);
		this.slider.max.set(this.start.max);
		
	},
	
	toElements: function(hash){
		var hash = new Hash(hash);
		hash.each(function(item, key){
		  hash.set(key, this.container.getElement(item));
		}, this);
		return hash;
	},
	
	setKnobValue: function(knobType, value){
		switch (knobType){
			case 'min':
			  this.knob.minText.set('text', value.toInt().generatePrice());
			break;
			case 'max':
			  this.knob.maxText.set('text', value.toInt().generatePrice());
			break;
		}
	},
	
	getKnobValue: function(knobType){
		switch (knobType){
			case 'min': 
			  return this.knob.minText.get('text').parsePrice();
			break;
			case 'max':
			  return this.knob.maxText.get('text').parsePrice();
			break;
		}
	}
	

});

var Tabs = new Class({

  Implements: [Events, Options],
	
	options: {
		tabs: '.tab-anchors li',
		panels: '.tab-panel',
		disableClass: 'disabled',
		start: 0,
		observeDuration: 100
		//onShow: $empty(tab, panel, anchor),
		//onClose: $empty(tab, panel, anchor),
		//onReady: $empty()
	},
	
	initialize: function(container, options){
		
		this.setOptions(options);
		
		this.container = document.id(container);
		this.tabs = new Hash(); // contains pairs of tabs and panels with anchor as id
		this.anchors = new Array(); // contains all available tab ids
		this.handlers = this.container.getElements(this.options.tabs);
		
		this.current = null;

    this.handlers.each(function(handler){
		   this.addTab(handler);
			 var link = handler.getElement('a');
			 if (handler.hasClass('disabled') && link){
				 link.addEvent('click', function(event){
				   event.preventDefault()
				 });
			 }
		}, this);
		
		// init default tab
		this.defaultTab = this.anchors[this.options.start];
		var hash = new URI().get('fragment');
    if (this.tabs.has(hash)) this.defaultTab = hash;
		if (this.defaultTab){
			this.show(this.defaultTab);
		}
		
		this.repeater = this.observe.periodical(this.options.observeDuration, this);
		
		this.fireEvent('ready', this.current);
		
	},
	
	addTab: function(handler){
		var anchor = handler.getElement('a').get('href');
    if (anchor.test(/^#(.)+$/)){
			var panel =  this.container.getElement(anchor);
			if (panel){
				anchor = anchor.replace('#', '').toString();
				this.tabs.set(anchor, {
				  tab: handler,
					panel: panel.removeProperty('id').hide(),  // remove id to prevent browser from jumping in page
					anchor: anchor
				});
				this.anchors.include(anchor);
			}
		}
	},
	
	show: function(id){
		if (id == '') id = this.defaultTab;
		if (this.tabs.has(id)){
			var tabPanel = this.tabs.get(id);
			if (this.current){
				this.current.tab.removeClass('active');
				this.current.tab.getElement('a').removeClass('active');
				this.current.panel.hide();
				this.fireEvent('close', [this.current.tab, this.current.panel, this.current.anchor]);
			}
			var tabPanel = this.tabs.get(id);
			tabPanel.tab.addClass('active');
			tabPanel.tab.getElement('a').addClass('active').blur();
			tabPanel.panel.show();
			this.current = tabPanel;
			this.fireEvent('show', [tabPanel.tab, tabPanel.panel, id]);
		}
	},
	
	observe: function(){
		var hash = window.location.hash.replace('#', '').toString();
		if (hash != this.current.anchor){
      this.show(hash);
		}
	}
	
		
});

var Slideshow = new Class({

  Implements: [Events, Options],
	
	options: {
		slide: '.slide',
		width: 0,
		duration: 300,
		moveAfter: 5000,
		start: 0,
		counter: false,
		resume: true,
		counterTemplate: '{current}/{count}',
		paging: false,
		pagingClass: {
			prev: 'slide-link-prev',
			next: 'slide-link-next',
			page: 'slide-link',
			active: 'active'
		},
		onMove: $empty()
	},
	
	initialize: function(container, positionWrapper, options){
    this.container = document.id(container);
    this.setOptions(options);
		this.position = document.id(positionWrapper);
		this.slides = this.container.getElements(this.options.slide);
		this.count = this.slides.length;
		this.current = this.options.start;
		this.pages = new Array();
		
		// try to read slide width
		if ((this.options.width == 0) && (this.count > 0)){
			this.options.width = this.slides[0].getStyle('width').toInt();
		}
		
		// set proper width
		this.position.setStyle('width', this.count*this.options.width);

    this.moveFx = new Fx.Tween(this.position, { property: 'margin-left', duration: this.options.duration, link: 'chain', transition: Fx.Transitions.Quad.easeOut });
		this.moveFx.set(0);
		
		// generate paging if available
		if (this.options.paging){
			for (var i = 1; i <= this.count; i++){
				this.pages[i-1] = new Element('a', { 'html': '<span></span>' }).inject(this.options.paging);
			}
			
			// add move events to pages
			this.pages.each(function(page, index){
			  page.addEvent('click', function(event){
				  event.stop();
  				this.repeater = $clear(this.repeater);
	  			this.move(index);
		  		if (this.options.resume) (this.repeater = this.move.periodical(this.options.moveAfter, this));
			 	}.bind(this));
			}, this);
		}
		
		this.repeater = this.move.periodical(this.options.moveAfter, this);
		this.update();

	},
	
	move: function(num){
		if (!$defined(num)) this.current = (++this.current%this.count);
		if ($defined(num))	this.current = num.limit(0, this.count-1);
		this.moveFx.start(-this.current*this.options.width);
		this.update();
		this.fireEvent('move');
	},
	
	update: function(){
		
		this.pages.each(function(page, index){
		  index == this.current ? page.addClass('active') : page.removeClass('active');
		}, this);
		
	}

});

var Map = new Class({


  Implements: Options,
	
	options: {
	  outputSelector: '#form-find-experience legend span',
		width: 0,
		height: 0
	},
	
	initialize: function(container, options){
		this.setOptions(options);
		
		this.container = document.id(container);
		
		this.checkboxes = this.container.getElements('input[type=checkbox]');
		this.areas = this.container.getElements('area');
		this.map = this.container.getElement('img');
		this.output = (this.options.outputSelector ? document.id(document.body).getElement(this.options.outputSelector) : null);
		
		/* try to read dimensions */
		this.width = (this.options.width ? this.options.width : this.map.width);
		this.height = (this.options.height ? this.options.height : this.map.height); 
		
		/* set bg to container and hide original map */
		this.container.setStyle('background-image', 'url({src})'.substitute({ src: this.map.get('src')}));
		this.container.addClass('mask');
		this.map.setStyle('opacity', 0.01);
		
		/* build layers and events */
		this.areas.each(function(area, index){
			var checkbox = this.checkboxes[index];
			var bubble = area.get('alt').replace('kraj', '').trim();
		  /* prepare layer */
			var bgPosition = {
				normal: {
					top: -this.height*index,
					left: this.width
				},
				hover: {
					top: -this.height*index,
					left: 0
				},
				selected: {
					top: -this.height*index,
					left: -this.width
				}
			}
			var layer = new Element('div', {'class': 'layer'}).inject(this.map, 'before');
		  layer.setStyle('background-position', '{left}px {top}px'.substitute(checkbox.checked ? bgPosition.selected : bgPosition.normal));
			
			/* hover effect */
			area.addEvents({
			  'mouseenter': function(){
					if (!checkbox.checked){
						layer.setStyle('background-position', '{left}px {top}px'.substitute(bgPosition.hover));
					}
					this.bubble(bubble);
				}.bind(this),
				'mouseleave': function(){
					if (!checkbox.checked){
						layer.setStyle('background-position', '{left}px {top}px'.substitute(bgPosition.normal));
					}
				},
				'click': function(event){
					event.preventDefault();
					checkbox.checked = (checkbox.checked ? false : true);
					layer.setStyle('background-position', '{left}px {top}px'.substitute(checkbox.checked ? bgPosition.selected : bgPosition.hover));
				}
			});
			
		}, this);
		
		this.container.addEvent('mouseleave', function(){
		  this.bubble('&nbsp;');
		}.bind(this));

	},
	
	bubble: function(text){
		if (this.output){
  		this.output.set('html', text);
		}
	}

});

Zazitky.Form = {
	
	init: function(){
		
		this.forms = document.getElements('form');

		this.forms.each(function(form){
			var formID = form.get('id');
			if (formID){
				var objectTitle = formID.replace('form-','').camelCase().capitalize();
				if (Zazitky.Form[objectTitle]) Zazitky.Form[objectTitle].init(form);
			}
		});
		
	}
	
 };

Zazitky.Form.Sort = {
	
	init: function(form){
		this.form = form;
		
		this.select = this.form.getElement('select');
		
		this.select.addEvent('change', function(){
		  this.form.submit();
		}.bind(this));
	}
 };
 
Zazitky.Form.Registration = {
	
	init: function(form){
		
		this.form = form;
		
		this.toggles = this.form.getElements('.on-change-toggle');
		this.slides = this.form.getElements('.slide');
		this.toggles.each(function(toggle, index){
		  var slide = this.slides[index];
			toggle.getParent().addEvent('click', function(){
				(toggle.checked) ? slide.show() : slide.hide();
			});
			// onload initialization
  		(toggle.checked) ? slide.show() : slide.hide();
		}, this);
	}
 };
 
Zazitky.Form.Newsletter = {
	
	init: function(form){
		this.form = form;
		
		var action = this.form.get('action').replace('#', '');
		
		this.url = (action ? action : '/newsletter');
		
		this.input = this.form.getElement('input');
		
		this.content = this.form.getParent('div.block-content');
		
		this.request = new Request.JSON({
		  url: this.url,
			onSuccess: function(responseJSON){
				if ($defined(responseJSON.result)){
					if (responseJSON.result){
						this.content.set('html', '<p>Děkujeme za důvěru.<br />Hned jak se šustne něco zážitkového, najdete to v&nbsp;mailu.</p>');
					} else {
						alert('Registrace se nepovedla. Zdá se, že zadaná adresa není platná.');
					}
				} else {
					alert('Ups... registrace se nepovedla. Zkuste to znovu.');
				}
			}.bind(this),
			onFailure: function(){
				alert('Ups... registrace se nepovedla. Zkuste to znovu.');
			}
		});
		
		this.form.addEvent('submit', function(event){
		  event.stop();
			this.request.get({email: this.input.value});
		}.bind(this));
	}
 };

Zazitky.Form.Order = {
	
	init: function(form){
		this.form = form;
		
		this.addBtn = this.form.getElement('button.button-add');
		this.orderBtn = this.form.getElement('button.button-order');
		
		this.request = null;
		
		this.addBtn.addEvent('click', function(event){
			event.stop();
			var messages = this.validate();
			if (messages.length){
				event.stop();
				alert(messages.join('\n'));
			} else {
				this.addRequest();
			}
		}.bind(this));
		
		this.orderBtn.addEvent('click', function(event){
			var messages = this.validate();
			if (messages.length){
				event.stop();
				alert(messages.join('\n'));
			}
		}.bind(this));
		
		this.form.addEvent('submit', function(event){
		  var messages = this.validate();
			if (messages.length){
				event.stop();
				alert(messages.join('\n'));
			}
		}.bind(this));
		
		this.basketPopup = new Zazitky.Form.Order.Popup();
		
	},
	
	validate: function(){
		var messages = new Array();
		
		var selectedVariants = this.form.getElements('input[type=radio]:checked');
		
		if (selectedVariants.length == 0) messages.push('Prosím zvolte variantu zážitku, který chcete objednat.');
		
		return messages;
	},
	
	addRequest: function(){
		if (!this.request){
			this.request = new Request.JSON({
				url: this.form.get('action'),
				onSuccess: function(responseJSON){
					if (responseJSON && responseJSON.title && responseJSON.img){
						var position = this.addBtn.getPosition('page-wrapper');
						this.basketPopup.open({
							top: position.y,
							left: position.x,
							title: responseJSON.title,
							img: responseJSON.img
						});
					} else {
						this.form.submit();
					}
				}.bind(this),
				onFailure: function(){
					this.form.submit();
				}.bind(this)
			});
		}
		this.request.get(this.form.toQueryString().parseQueryString());
	}
 };
 
Zazitky.Form.Order.Popup = new Class({
	
	Implements: [Options, Events],
	
	options: {
		title: '',
		img: '',
		top: 0,
		left: 0,
		container: 'page-wrapper',
		template: '<p class="basket-popup-title">Přidáno do košíku</p><img src="{img}" width="63" height="63" /><p class="basket-popup-content">Zážitek <strong>{title}</strong> byl přidán do košíku</p><a class="continue">Pokračovat v nákupu</a><a class="basket">Přejít do košíku</a><a class="close" title="Zavřít a pokračovat v nákupu"></a></div>',
		basketUrl: '/objednavka/'
	},
	
	initialize: function(options){
		
		this.setOptions(options);

  	this.element = new Element('div', {
			'id': 'basket-popup',
			'html': this.options.template.substitute({
				title: this.options.title,
				img: this.options.img
			}),
			'styles': {
				top: -1000,
				left: -1000
			},
			'events': {
				'click:relay(a)': function(event, clicked){
					if (clicked.hasClass('close')) this.close();
					if (clicked.hasClass('continue')) this.close();
					if (clicked.hasClass('basket')) window.location = this.options.basketUrl;
				}.bind(this)
			}
		}).inject(document.id(this.options.container));
		
		this.fx = new Fx.Tween(this.element, {property: 'opacity', duration: 300, link: 'cancel'}).set(0);
		
		this.fireEvent('ready', this);
		
		return this;
		
	},
	
	set: function(options){
		this.setOptions(options);
		this.element.set('html', this.options.template.substitute(this.options));
		
		return this;
	},
	
	open: function(options){
		this.set(options);
		
		this.element.setStyles({
			top: this.options.top,
			left: this.options.left
		});
		
		this.fx.start(1);
		
		this.fireEvent('open', this);
		return this;
	},
	
	close: function(){
		this.fx.start(0);
		this.fireEvent('close', this);
		return this;
	}
});
 
Zazitky.Form.Reservation = {
	
	init: function(form){
		
		this.form = form;
		
		// persons
		this.table = this.form.getElement('table');
		if (this.table){
			this.limit = this.table.get('limit');
			this.tbody = this.table.getElement('tbody');
			this.table.addEvent('click:relay(a)', function(event){
				event.preventDefault();
			  var element = document.id(event.target);
				if (element.hasClass('add')) this.addRow();
				if (element.hasClass('remove')) this.removeRow(element);
			}.bind(this));
		  
			this.template = this.tbody.getElement('tr').clone().removeClass('first');
			
			this.checkTable();
		}
		
		
	},
	
	checkTable: function(){
		var rowCount = this.tbody.getElements('tr').length;
		
		/*
		if (rowCount == 1){
			this.table.addClass('minimal');
		} else {
			this.table.removeClass('minimal');
		}*/
		rowCount == 0 ? this.table.addClass('empty') : this.table.removeClass('empty');

		if (this.limit && rowCount == this.limit){
			this.table.addClass('limit');
		} else {
			this.table.removeClass('limit');
		}
		
	},
	
	addRow: function(){
		var row = this.template.clone();
		var hash = new Date.now();
		var inputs = row.getElements('input');
		inputs.each(function(input){
		  input.set({
			  'value': '',
				'name': input.get('name').replace(/([^\[]*\[)([^\]]+)(\].*)/, '$1'+hash+'$3')
			});
		});
		row.inject(this.tbody);
		this.checkTable();
	},
	
	removeRow: function(element){
		var row = element.getParent('tr');
		var isFirst = row.hasClass('first');
		if (confirm('Opravdu chcete odebrat tento řádek?')){
			row.destroy();
			if (isFirst){ 
			  firstRow = this.tbody.getElement('tr');
				if (firstRow) firstRow.addClass('first');
			}
		}
		this.checkTable();
	}
	
 };

Zazitky.Homepage = {
	
	init: function(){

		$$('.tabs').each(function(tabs){
		  new Tabs(tabs);
		});
		
		if (Browser.IE6) window.location.hash = '#doporucujeme';
		
		/*var boxWhy = document.id('box-why');
		
		new Slideshow(boxWhy, boxWhy.getElement('.position-wrapper'), {
			slide: '.slide',
			width: 180,
			duration: 800,
			moveAfter: 7000,
			paging: boxWhy.getElement('.progress-bar')
		});
    boxWhy.getElements('div.slide').setStyle('cursor', 'pointer').addEvent('click', function(event){ window.location = '/co-od-nas-dostanete/'; });		*/
	}
 };

Zazitky.Category = {
	
	init: function(){}
	
 };

Zazitky.Detail = {
	
	init: function(){
		
		var tabOptions = {
			onShow: function(tab, panel, anchor){
				switch (anchor){
					case 'cenik':
					  var priceListBtn = document.id('button-price-list');
						if (priceListBtn) priceListBtn.fade('out');
					break;
					case 'objednavka-zazitku':
					  tab.getElement('a').set('text', 'Objednávka zážitku');
					break;
				}
			},
			onClose: function(tab, panel, anchor){
				switch (anchor){
					case 'cenik':
					  var priceListBtn = document.id('button-price-list');
						if (priceListBtn) priceListBtn.fade('in');
					break;
					case 'objednavka-zazitku':
					  tab.getElement('a').set('text', 'Objednat zážitek');
					break;
				}
			},
			onReady: function(currentTab){
				var panel = currentTab.panel;
				if (panel && window.location.hash.replace('#','') != ''){
					var position = panel.getPosition(document.body);
					window.scrollTo(0, position.y-85);
				} else {
				  // prevent to jump in firefox
				  window.scrollTo(0, 0);
				}
			}
		};
		
		$$('.tabs').each(function(tabs){
		  new Tabs(tabs, tabOptions);
		});
		
	}
 };
 

window.addEvent('domready', function(){

  Zazitky.init();

});

// IE 6 PNG fix
if (Browser.IE6){
	DD_belatedPNG.fix('div.experience-list .recommendation, div.experience-list .new, #category, #experience-preview img');
}

