// JavaScript Document



Array.implement({ 
  shuffle: function() { 
    //destination array 
    for(var j, x, i = this.length; i; j = parseInt(Math.random() * i), x = this[--i], this[i] = this[j], this[j] = x); 
    return this; 
  } 
});

var GuideDePrague =  {
	
	init: function(){
		
	  if (document.id('slideshow')) new Slideshow('slideshow');

		// toggler
		if ($$('.toggler').length){
			togglers = document.getElements('.toggler');
			slides = document.getElements('.toggled');
			
			togglers.each(function(element,index){
			 var slideFx = new Fx.Slide(slides[index], { duration: 500, link: 'cancel', transition: Fx.Transitions.Quad.easeInOut }).hide();
			 element.getElement('a').addEvent('click', function(event){ event.preventDefault(); });
			 element.addEvent('click', function(){slideFx.toggle()});
			},this);
		}

		// clickable blocks
		$$('.clickable').each(function(item){
		  item.setStyle('cursor', 'pointer');
			var anchor = item.getElement('a');
			if (anchor){
				item.addEvent('click', function(){
				  window.location = anchor.get('href');
				});
				anchor.addEvent('click', function(event){
				  event.stopPropagation();
				});
			}
			
		});

		if(Browser.Engine.trident && Browser.Engine.version < 5) {
			if ($('menu')) GuideDePrague.Menu.init();
		}

		if ($('form-contact')) FormContact.init();

	}
};


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('(Obligatoire)'); // Toto pole je povinne = Cette case est obligatoire
		} 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('p');
		var message = this.errors.join('<br />');
		if (this.errorMark) this.errorMark.destroy();
		this.errorMark = new Element('span',{
		  'class': 'error-mark',
			'text': message
		}).inject(parent.getElement('label'));
		parent.addClass('error');
	},
	
	removeErrors: function(){
	  var parent = this.input.getParent('p');
		parent.removeClass('error');
		if (this.errorMark) this.errorMark.destroy();
	}
	
});

var FormContact = {
	
	init: function(){

		this.form = $('form-contact');
		
		this.validatedItems = [
			new InputValidator('form-contact-name',    { required: true }),
			new InputValidator('form-contact-email',   { required: true, tests: { regexp: /[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}/, message: 'L\'adresse e-mail indiquée n\'est pas valide.' } })
		];
	
		this.form.addEvent('submit', function(event){
		  event.stop();
		  if (this.isValid()){
				this.form.submit();
			} else {
				alert('Veuillez remplir les cases ci-dessous.');
			}
		}.bind(this));
		
		// anti
		this.form.getElement('noscript').destroy();
		new Element('input', {
		  'type': 'hidden',
			'name': 'anti',
			'value': 'guide'
		}).inject(this.form);

	},
	
	isValid: function(){
		var errors = 0;
		this.validatedItems.each(function(item){
			item.validate();
			errors += item.getError().length;
		});
		return !errors;
	}
	
};


GuideDePrague.Menu = {
	
	init: function(){
		this.container = document.id('menu');
		
		this.items = $$('#menu > ul > li');
		
		this.items.each(function(item){
		  var ul = item.getElement('ul');
			if (ul){
				item.addEvents({
				  'mouseenter': function(){
						ul.addClass('block');
					},
					'mouseleave': function(){
						ul.removeClass('block');
					}
				});
			}
		});
	}
};

		
var oldIE = (Browser.Engine.trident && Browser.Engine.version < 5);

var PNGFix = new Class({

  initialize: function(img){
		this.img = $(img);
    this.src = this.img.get('src');
		this.img.set('src', '/img/blank.gif');
		this.img.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="'+this.src+'", sizingMethod="image")';
	}
	
});

var Slideshow = new Class({
	
	Implements: [Options, Events],

  options: {
		imagePath: '/img/bg-image-{i}.jpg',
		duration: 20000,
		fxDuration: 500
	},
	
  initialize: function(container, options){
		this.container = document.id(container);
		
		this.setOptions(options);
		
		var config = JSON.decode('{'+this.container.get('class')+'}');
		this.range = config.range;
		var defaultImage = config.defaultImage;
		
		this.paths = new Array();
		for (var i = 0; i < this.range; i++){
			if (i != defaultImage){
  			this.paths.push(this.options.imagePath.substitute({i: i}));
			}
		}
		this.paths.shuffle();
		
		
		this.slides = new Array();
		this.slides.push(this.container.getElement('.image'));
		this.current = 0;
		this.slideFx = new Array();
		this.slideFx[0] = new Fx.Tween(this.slides[0], { property: 'opacity', duration: this.options.fxDuration, link: 'cancel' }).set(1);
		this.count = 1;
		this.timer = null;
		
		this.images = new Asset.images(this.paths, {
		  onComplete: function(){
				this.fireEvent('build');
			}.bind(this)
		});
		
		// class events
		this.addEvents({
		  'build': function(){ this.createSlides(); },
			'start': function(){ this.start(); }
		});
		
	},
	
	createSlides: function(){
		this.images.each(function(image, index){
			this.slides[index+1] = new Element('div', {
			  'class': 'image',
				'styles': {
					'background-image': 'url('+image.src+')'
				}
			});
			this.slideFx.include(new Fx.Tween(this.slides[index+1], { property: 'opacity', duration: this.options.fxDuration, link: 'cancel' }).set(0));
			this.slides[index+1].inject(this.container);
		}, this);
		
		this.fireEvent('start');
	},
	
	start: function(){
		this.count = this.slides.length;
		this.timer = this.move.periodical(this.options.duration, this);
	},
	
	move: function(){
		this.slideFx[this.current].start(0);
		this.current = ++this.current%this.count;
		this.slideFx[this.current].start(1);
	}
	
});




window.addEvent('domready', function(){

  GuideDePrague.init();

		// png fix
		if (oldIE){
			$$('img[src$=png]').each(function(img){
				new PNGFix(img);
			});
		}

});

