// JavaScript Document

var Giant = {
	
	init: function(){
		this.container = document.id('giant');
		
		this.logo = this.container.getElement('img');
		
		this.logo.setStyle('cursor', 'pointer');
		this.logo.addEvent('click', function(){
		  window.location = this.container.getElement('a').get('href');
		}.bind(this));
	}
	
}


var Slideshow = new Class({

  Implements: [Events, Options],
	
	options: {
		slide: '.slide',
		width: 0,
		duration: 300,
		moveAfter: 5000,
		start: 0,
		prevButton: '',
		nextButton: '',
		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: 'left', duration: this.options.duration, link: 'chain', transition: Fx.Transitions.Quint.easeInOut });
		this.moveFx.set(0);
		
		// generate paging if available
		if (this.options.paging){
			this.options.prevButton = new Element('a', {'class': this.options.pagingClass.prev, 'html': '&laquo;' });
			this.options.prevButton.inject(this.options.paging);
			for (var i = 1; i <= this.count; i++){
				this.pages[i-1] = new Element('a', {'class' : this.options.pagingClass.page, 'html': i }).inject(this.options.paging);
			}
			this.options.nextButton = new Element('a', {'class': this.options.pagingClass.next, 'html': '&raquo;' });
			this.options.nextButton.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);
		}
		
		// buttons
		if (this.options.prevButton){
			this.options.prevButton.addEvent('click', function(event){
			  event.stop();
				this.repeater = $clear(this.repeater);
				this.move(this.current - 1);
				if (this.options.resume) (this.repeater = this.move.periodical(this.options.moveAfter, this));
			}.bind(this));
		}
		
		if (this.options.nextButton){
			this.options.nextButton.addEvent('click', function(event){
			  event.stop();
				this.repeater = $clear(this.repeater);
				this.move(this.current + 1);
				if (this.options.resume) (this.repeater = this.move.periodical(this.options.moveAfter, this));
			}.bind(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(){
		if (this.options.counter){
			this.options.counter.set('text', this.options.counterTemplate.substitute({ current: this.current+1, count: this.count }));
		}
		// hide buttons
		if (this.options.prevButton){
			this.current == 0 ? this.options.prevButton.setStyle('visibility', 'hidden') : this.options.prevButton.setStyle('visibility', 'visible');
		}
		
		if (this.options.nextButton){
			this.current == this.count - 1 ? this.options.nextButton.setStyle('visibility', 'hidden') : this.options.nextButton.setStyle('visibility', 'visible');
		}
		
		this.pages.each(function(page, index){
		  index == this.current ? page.addClass('active') : page.removeClass('active');
		}, this);
		
	}

});


var Bubble = new Class({

  Implements: Options,
	
	options: {
		bubbleClass: '.tooltip',
		duration: 200,
		bottomStart: 0,
		bottomEnd: 45,
		transition: Fx.Transitions.Linear
	},
	
	initialize: function(container, options){
		this.container = document.id(container);
		
		this.setOptions(options);
		
		this.bubble = this.container.getElement(this.options.bubbleClass);
		
		if (!this.bubble) return this;
		
		this.bubble.show();
		this.options.bottom = this.bubble.getStyle('bottom').toInt();
		
		this.fx = new Fx.Morph(this.bubble, { duration: this.options.duration, transition: this.options.transition, link: 'cancel' });
		
		this.fx.set({
		  'opacity': 0,
			'bottom': this.options.bottomStart
		});
		
		// hover event
		this.container.addEvents({
		  'mouseenter': function(){
				this.fx.start({
				  'opacity': 1,
					'bottom' : this.options.bottomEnd
				});
			}.bind(this),
			'mouseleave': function(){
				this.fx.start({
				  'opacity': 0,
					'bottom' : this.options.bottomStart
				});
			}.bind(this)
		});
		
	}
	
});

var InputValidator = new Class({

  Implements: [Options, Events],
	
  options: {
		required: false,
		tests: []
	},
	
  initialize: function(input, options){
		this.setOptions(options);
		this.input = $(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');
	},
	
	getError: function(){
		return this.errors;
	},
	
	placeErrors: function(){
	  var parent = this.input.getParent('td');
		var message = this.errors.join('<br />');
		if (this.errorMark) this.errorMark.destroy();
		this.errorMark = new Element('span',{
		  'class': 'error-mark',
			'text': message
		}).inject(parent);
		parent.addClass('error');
	},
	
	removeErrors: function(){
	  var parent = this.input.getParent('td');
		parent.removeClass('error');
		if (this.errorMark) this.errorMark.destroy();
	}
	
});

var FormOrder = {
	
	init: function(){

		this.form = $('form-order');
		
		if ($$('.form-inquiry')) {
			this.validatedItems = [
				new InputValidator('form-order-name',    { required: true }),
				new InputValidator('form-order-email',   { required: true, tests: { regexp: /[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}/, message: 'Zadaná emailová adresa je neplatná.' } }),
				new InputValidator('form-order-phone',   { required: true, tests: { regexp: /^[0-9 ]{9,12}$|^[0-9\+ ]{13,16}$/, message: 'Neplatný formát telefonního čísla.' } })
			];
		} else {
			this.validatedItems = [
				new InputValidator('form-order-name',    { required: true }),
				new InputValidator('form-order-surname',    { required: true }),
				new InputValidator('form-order-email',   { required: true, tests: { regexp: /[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}/, message: 'Zadaná emailová adresa je neplatná.' } }),
				new InputValidator('form-order-phone',   { required: true, tests: { regexp: /^[0-9 ]{9,12}$|^[0-9\+ ]{13,16}$/, message: 'Neplatný formát telefonního čísla.' } }),
				new InputValidator('form-order-street',    { required: true }),
				new InputValidator('form-order-city',    { required: true }),
				new InputValidator('form-order-psc',    { required: true })
			];
		}
	
		this.form.addEvent('submit', function(event){
		  event.stop();
		  if (this.isValid()){
				this.form.submit();
			} else {
				alert('Prosím, vyplňte správně všechna požadovaná pole.');
			}
		}.bind(this));
		
		// anti
		this.form.getElement('noscript').destroy();
		new Element('input', {
		  'type': 'hidden',
			'name': 'anti',
			'value': 'střecha'
		}).inject(this.form);

	},
	
	isValid: function(){
		var errors = 0;
		this.validatedItems.each(function(item){
			item.validate();
			errors += item.getError().length;
		});
		return !errors;
	}
	
};


var BlockScroll = {
	  
		init: function(){
			var slideEffect = new Fx.Tween('left', {property: 'top', wait:false, duration:800, transition:Fx.Transitions.Cubic.easeOut});
				var top = document.id('left').getPosition().y - 30;
				slideEffect.start.delay(0, slideEffect, Math.max(0, document.documentElement.scrollTop - top).toInt());
				window.addEvent('scroll', function(){
					slideEffect.start.delay(0, slideEffect, Math.max(0, document.documentElement.scrollTop - top).toInt());
					//document.id('left').setStyle('background','#FF0000')
				});
		}
};

var Toggling = {
	  
		config: {
	    toggler : '.toggler',
			toggled : '.toggled',
			duration : 500
		},
		
		init: function(options){
			  
				options = Object.extend(this.config, options || {});
				
				var togglers = $$(options.toggler);
				var slides = $$(options.toggled);

				togglers.each(function(element){
				    
						// css
						
						var slideFx = new Fx.Slide(slides[togglers.indexOf(element)], { duration: options.duration, transition: Fx.Transitions.Cubic.easeOut }).hide();
						
						element.addEvent('click', function(e){
					      slideFx.toggle();
								this.toggleClass('on');
						});
						
				});
				
		}
};

window.addEvent('domready', function(){
	
	if ($('pama-video')){	
		// image path
		flashvars.imagePath			= "/flash/pama.jpg";
		
		// video path
		flashvars.videoPath 		= "/flash/pama.flv";
		
		new Swiff('/flash/player.swf', {
			container: 'pama-video',
			width: 480,
			height: 272+29,
			params: {
				flashvars: $H(flashvars).toQueryString(),
			  scale: 'noscale',
			  allowfullscreen: 'true',
			  salign: "tl",
			  bgcolor: "000000"
			}
		});
	}
	
	if ($$('.toggler').length) {
		Toggling.init();
	}
	
	if (document.id('left')){
		BlockScroll.init();
	}
	
	if (document.id('giant')) Giant.init();
	
	// Slideshow
	if (document.id('box-news')){
		new Slideshow('box-news', document.id('box-news').getElement('ul'), {
			slide: 'li',
			width: 320,
			duration: 400,
		  prevButton: document.id('nav-left'),
			nextButton: document.id('nav-right'),
			counter: document.id('nav-page')
		});
	}
	
	// Bubbles
	if (document.id('brands')){
		var bubbleElements = document.id('brands').getElements('li');
		bubbleElements.each(function(bubbleElement){
		  new Bubble(bubbleElement,{
			  duration: 150,
				bottomStart: 35,
				bottomEnd: 50
			});
		});
	}
	
	// Homepage flash
	if (document.id('hp')){
		new Swiff('/flash/hp2.swf', {
			container: 'flash',
			width: 620,
			height: 250,
			params: {
				wmode: 'transparent'
			}
		});
	}
	// upoutavka flash zima
	if (document.id('upoutavka-flash-content-hp')){
		new Swiff('/flash/upoutavka-zima.swf', {
			container: 'upoutavka-flash-content-hp',
			width: 500,
			height: 580,
			params: {
				wmode: 'transparent'
			}
		});
	}
	// upoutavka flash leto 2
	if (document.id('upoutavka-flash-2')){
		new Swiff('/flash/upoutavka-leto-2.swf', {
			container: 'upoutavka-flash-2',
			width: 780,
			height: 330,
			params: {
				wmode: 'transparent'
			}
		});
	}

	if ($('form-order')) FormOrder.init();
	
	// upoutavka
			if ($('upoutavka')){
				var bannerFx = new Fx.Tween('upoutavka', { property: 'opacity', duration: 250 });
				bannerFx.set(1);
				$('upoutavka-close').addEvent('click', function(event){
				  event.stop();
					bannerFx.start(0);
				});
			}
});

/* flash banner communication */
function upoutavkaDeactivator() {
	if (document.id('upoutavka-flash-1')) {
		document.id('upoutavka-flash-1').setStyle('display','none');
		document.id('upoutavka-flash-1').destroy();
	}
	if (document.id('upoutavka-flash-2')) {
		document.id('upoutavka-flash-2').setStyle('display','none');
		document.id('upoutavka-flash-2').destroy();
	}
}
