// JavaScript Document

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) != anchor) window.location = anchor.href;

			});
		}
	}

});

Element.implement({

	  makeClickableLiveHelp: function(){
			var anchor = this.getElement('a');
			if (anchor){
				this.setStyle('cursor', 'pointer');
				this.addEvent('click', function(event){
//				  if (document.id(event.target) != anchor) window.location = anchor.href;
					if(navigator.userAgent.toLowerCase().indexOf('opera') != -1  &&  window.event.preventDefault) 
						window.event.preventDefault();this.newWindow = window.open('http://livehelp.ijv.cz/client.php?locale=cs&amp;url='+escape(document.location.href)+'&amp;referrer='+escape(document.referrer), 'webim', 'toolbar=0,scrollbars=0,location=0,status=1,menubar=0,width=640,height=480,resizable=1');

				   this.newWindow.focus();
				   this.newWindow.opener=window;
				   return false;
				});
			}
		}

	});

Array.implement({

  toInt: function(){
		var intArray = new Array();
		for (var i = 0; i < this.length; i++){
			intArray[i] = this[i].toInt();
		}
		return intArray;
	}

});

// observe click events and calls registered methods
var Observer = {
	
	init: function(){
		this.body = document.id(document.body);
		
		this.body.addEvent('click', this.check.bind(this));
		
		this.stack = new Array();
		
	},
	
	register: function(func, bind){
		this.stack.include(func.bind(bind));
		return func;
	},
	
	unregister: function(func){
		this.stack.erase(func);
		return func;
	},
	
	check: function(){
		this.stack.each(function(func){
		  if (func != undefined) func.run();
			this.unregister(func);
		}, this);
	}
 };

var Status = new Class({

  status: null,
	
	is: function(type){
		return (this.status != null ? this.status.get(type) : null);
	},
	
	isNot: function(type){
		return !this.is(type);
	},
	
	setStatus: function(type, value){
		if (this.status == null) this.status = new Hash();
		this.status.set(type, value)
	},
	
	getStatus: function(type){
	  return (this.status != null ? this.status.get(type) : null);
	},
	
	getStatusData: function(){
		return this.status;
	}

});

var RadioGroup = new Class({

  Implements: [Events, Options],
	
	options: function(){
		//onChange: $empty(radio, index),
		//onCheck: $empty(radio, index),
		//onUncheck: $empty(radio, index)
	},
	
	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);
			var parent = radio.getParent('span');
		  if (radio.checked){
				parent.addClass('checked');
				this.fireEvent('check', [radio, index]);
				this.fireEvent('change', [radio, index]);
			} else {
				if (parent.hasClass('checked')){
					parent.removeClass('checked');
					this.fireEvent('uncheck', [radio, index]);
				}
			}
		}, 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 Tabs = new Class({

  Implements: [Events, Options],
	
	options: {
		tabs: '.tab-anchors li',
		panels: '.tab-panel',
		disableClass: 'disabled',
		start: 0,
		observeDuration: 250
		//onShow: $empty(tab, panel, anchor),
		//onClose: $empty(tab, panel, anchor)
	},
	
	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.defaultTab = 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()
				 });
			 }
			 if (handler.hasClass('default')){
				 this.defaultTab = link.get('href').replace('#','');
			 }
		}, this);
		
		// init default tab
		if (!this.defaultTab) 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.container.addClass('ready');
		this.fireEvent('ready', this);
		
		return this;
		
	},
	
	addTab: function(handler){
		var anchor = handler.getElement('a').get('href');
    if (anchor.test(/^#(.)+$/)){
			var panel =  this.container.getElement(anchor);
			if (panel){
				anchor = anchor.replace('#', '');
				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.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').blur();
			tabPanel.panel.show();
			this.current = tabPanel;
			this.fireEvent('show', [tabPanel.tab, tabPanel.panel, id]);
			
			this.fireEvent('change', [tabPanel.tab, tabPanel.panel, id]);
		}
	},
	
	observe: function(){
		var hash = window.location.hash.replace('#', '');
		if (hash != this.current.anchor){
      this.show(hash);
		}
	}
		
});

var TableSlider = new Class({

  Implements: [Options, Events],
	
	options: {
		toggle: 'td.col-code a',
		rowClass: 'row-slide',
		slide: 'div.slide'
	},
	
	initialize: function(table, options){
		
		this.table = document.id(table);
		
		this.toggles = this.table.getElements(this.options.toggle);
		
		this.toggles.addEvent('click', function(event){
		  event.preventDefault();
		  var clicked = document.id(event.target);
			this.toggle(clicked);
		}.bind(this));
	},
	
	toggle: function(clicked){
	  var sourceRow = clicked.getParent('tr');
		var slideRow = sourceRow.getNext();
		if (slideRow && slideRow.hasClass(this.options.rowClass)){
			if (sourceRow.hasClass('open')){
				this.hide(sourceRow, slideRow);
			} else {
				this.show(sourceRow, slideRow);
			}
		}
	},
	
	show: function(sourceRow, slideRow){
		var slide = slideRow.getElement(this.options.slide);
		if (slide){
			slide.show();
			sourceRow.addClass('open');
		}
	},
	
	hide: function(sourceRow, slideRow){
		var slide = slideRow.getElement(this.options.slide);
		if (slide){
			slide.hide();
			sourceRow.removeClass('open');
		}
	}

});

var Video = new Class({

  Implements: [Options, Events, Status],
	
	options: {
		slide: 'div.video-slide',
		content: 'div.video-content',
		thumbnails: 'ul.video-thumbnails li',
		hideOnLoad: true,
		fx: {
			duration: 400,
			transition: 'sine:in:out',
			link: 'chain'
		},
		template: '<object width="500" height="377"><param name="movie" value="{link}&autoplay=1"></param><param name="allowFullScreen" value="true"></param><param name="allowScriptAccess" value="always"></param><embed src="{link}&autoplay=1" type="application/x-shockwave-flash" allowfullscreen="true" allowScriptAccess="always" width="500" height="377"></embed></object>'
	},
	
	initialize: function(container, options){
		
		this.container = document.id(container);
		this.setOptions(options);
		
		this.slideEl = this.container.getElement(this.options.slide);
		this.slideFx = new Fx.Slide(this.slideEl, this.options.fx);
		this.content = this.container.getElement(this.options.content);
		this.setStatus('open', true);
		if (this.options.hideOnLoad){
			this.slideFx.hide();
			this.setStatus('open', false);
		}
		
		this.thumbnails = this.container.getElements(this.options.thumbnails);
		this.thumbnails.each(function(thumbnail){
		  thumbnail.getElement('a').addEvent('click', function(event){ event.preventDefault(); });
		  thumbnail.addEvent('click', function(event){
        event.stop();
				this.open(thumbnail.getElement('a').get('href'));
      }.bind(this));
		}, this);
		
		this.container.addClass('ready');
		
		return this;
	},
	
	open: function(link){
		this.slideFx.slideIn();
		this.setStatus('open', true);
		this.content.empty();
		var template = this.options.template.substitute({link: link});
		this.content.set('html', template);
		return this;
	},
	
	close: function(){
		this.slideFx.slideOut();
		this.setStatus('open', false);
		return this;
	},
	
	play: function(){
		return this;
	}

});

var SimpleCarousel = new Class({

  Extends: Fx.Scroll,
	
	options: {
		// Fx.Scroll options
		duration: 500,
		link: 'cancel',
		transition: 'cubic:out',
		mode: 'horizontal',
		wheelStops: false,
		// static carousel options
		loop: true,
		auto: false,
		interval: 0,
		visible: 1,  // number of visible items
		size: false, // overrides item dimensions
		childSelector: ':first-child > div',
		contentSelector: ':first-child'
	},
	
	initialize: function(element, options){
		this.parent(element, options);
		
		this.elements = this.element.getElements(this.options.childSelector);
		this.count = this.elements.length;
		this.content = this.element.getElement(this.options.contentSelector);
		this.current = 0;
		this.index = 0;
		
		// set width
		this.size = this.options.size ? this.options.size : this.elements[0].getSize().x;
		this.content.setStyle('width', this.elements.length*this.size);

		// auto move
		this.scrollTimer = null;
		if (this.options.auto){
			this.autoScroll('start');
		}
		
		// self events
		this.addEvents({
		  'complete': function(){
				this.fireEvent('scrollComplete', this.index);
			}
		});
		this.fireEvent('ready');
		
		return this;
		
	},
	
	getCount: function(){
		return this.elements.length;
	},
	
	getCurrent: function(){
		return this.index;
	},
	
	toNext: function(steps){
		if (steps == undefined) steps = 1;
		for (var i = 0; i<steps; i++){
			if (this.current+this.options.visible == this.count){
				if (this.options.loop){
					var scroll = this.element.getScroll();
					var element = this.content.getFirst();
					element.dispose();
					this.set(scroll.x-this.size, scroll.y)
					element.inject(this.content, 'bottom');
					this.index = ++this.index%this.count;
				} else {
					this.current = 0;
					this.index = 0;
				}
			} else {
				this.current++;
				this.index = ++this.index%this.count;
			}
		}
		this.toElement(this.elements[this.index]);
		
		return this;
	},
	
	toPrevious: function(steps){
		if (steps == undefined) steps = 1;
		for (var i = 0; i<steps; i++){
			if (this.current == 0){
				if (this.options.loop){
					var scroll = this.element.getScroll();
					var element = this.content.getLast();
					element.dispose();
					this.set(scroll.x+this.size, scroll.y)
					element.inject(this.content, 'top');
					this.index--;
					if (this.index < 0) this.index = this.count-1;
				} else {
					this.current = this.count-1;
					this.index = this.count-1;
				}
			} else {
				this.current--;
				this.index--;
				if (this.index < 0) this.index = this.count-1;
			}
		}
		this.toElement(this.elements[this.index]);
		
		return this;
	},
	
	toItem: function(index){
	  if (this.options.auto) this.autoScroll('stop');
		
		if (index == 'next') index = (this.index+1)%this.count;
		if (index == 'prev') index = this.index-1;
		if (index < 0) index = this.count-1;
	

		var stepToPrevious = (index < this.index ? this.index - index : this.index + this.count - index);
		var stepToNext = (index > this.index ? index - this.index : index + this.count - this.index);

    if (stepToPrevious < stepToNext){
			this.toPrevious(stepToPrevious);
		} else {
			this.toNext(stepToNext);
		}
		
		if (this.options.auto) this.autoScroll('start');
		return this;
	},
	
	autoScroll: function(command){
		switch (command){
			case 'start':
			  this.scrollTimer = this.toNext.periodical(this.options.interval, this);
			break;
			case 'stop':
			  $clear(this.scrollTimer);
			break;
		}
		
		return this;
	}


});

var StatusBar = new Class({

  Implements: [Options, Events],
	
	options: {
		// onclick
		count: 0
	},
	
	initialize: function(element, options){
		this.element = document.id(element);
		
		this.setOptions(options);
		
		this.items = new Array();
		
		this.element.addEvent('click:relay(span)', function(event){
		  var clicked = document.id(event.target);
			this.fireEvent('click', this.items.indexOf(clicked));
		}.bind(this));
		
		this.build();
		
		return this;
		
	},
	
	build: function(){
		
		var count = this.options.count;
		var temp = new Element('div');
		for (var i = 0; i < count; i++){
			new Element('span').inject(temp);
		}
		
		this.element.set('html', temp.get('html'));
		
		this.items = this.element.getElements('span');
		return this;
	},
	
	highlight: function(start, count){
		var itemCount = this.items.length;
		this.items.removeClass('active');
		for (var i = 0; i < count; i++){
			this.items[(i+start)%itemCount].addClass('active');
		}
		
		return this;
	},
	
	toElement: function(){
		return this.element;
	}

});

var GMap = new Class({

  Implements: [Options, Events],
	
	options: {
		map: {
		  zoom: 10,
			center: {
				lat: 49.817492,
				lng: 15.472962
			},
			type: 'roadmap'
		},
		markers: [],
		bubbleTemplate: '',
		canvas: 'div.google-map-canvas',
		toggle: null,
		minHeight: null,
		maxHeight: 500
	},
	
	initialize: function(element, options){
		
		this.element = document.id(element);
		
		this.canvas = this.element.getElement(this.options.canvas);
		
		this.setOptions(options);
		
		this.options.minHeight = this.canvas.getSize().y;
		
		this.isBig = false;
		
    // initialize map
		this.map = new google.maps.Map(this.canvas, {
		  zoom: this.options.map.zoom,
			center: this.parseLatLng(this.options.map.center),
			mapTypeId: google.maps.MapTypeId[this.options.map.type.toUpperCase()]
		});
		
		this.markers = new Array();
		
		if (this.options.toggle){
			this.toggle = this.element.getElement(this.options.toggle);
			if (this.toggle){
				this.toggle.addEvent('click', function(){
					if (this.isBig){
						this.canvas.setStyle('height', this.options.minHeight);
						this.toggle.set('html', '<span>Zobrazit vetší mapu</span>');
						this.isBig = false;
					} else {
						this.canvas.setStyle('height', this.options.maxHeight);
						this.isBig = true;
						this.toggle.set('html', '<span>Zobrazit menší mapu</span>');
					}
					google.maps.event.trigger(this.map, 'resize');
					this.map.setCenter(this.parseLatLng(this.options.map.center));
				}.bind(this));
			}
		}
		
		if (this.options.markers.length) this.addMarker(this.options.markers);
		
		
	},
	
	addMarker: function(markers){
		var markers = new Array(markers).flatten();
		var map = this.map;
		markers.each(function(markerOptions, index){
			// create marker
			var marker = new google.maps.Marker({
				position: this.parseLatLng(markerOptions.position), 
				map: map, 
				title: markerOptions.title,
				icon: (markerOptions.icon ? this.parseIcon(markerOptions.icon) : null)
			});
			this.markers.push(marker);
			
			// create info window
			if (markerOptions.data){
				var infoWindow = new GMap.Window(markerOptions.data, this.options.bubbleTemplate);
				google.maps.event.addListener(marker, 'click', function(){ infoWindow.open(map, marker); });
			}
		}, this);
		
	},
	
	parseLatLng: function(position){
		return new google.maps.LatLng(position.lat, position.lng);
	},
	
	parseIcon: function(icon){
		var image = icon.image;
		var size = new google.maps.Size(icon.size[0], icon.size[1]);
		var origin =  new google.maps.Point(icon.origin[0], icon.origin[1]);
		var anchor = new google.maps.Point(icon.anchor[0], icon.anchor[1]);
		
		return new google.maps.MarkerImage(image, size, origin, anchor);
	}

});

GMap.Window = new Class({

  initialize: function(data, template){
		
		this.template = template;
		this.data = data;
		
		this.infoWindow = new google.maps.InfoWindow({content: this.template.substitute(this.data)});
		
		return this.infoWindow;
	}

});


// Main object
var IJV = {
	
	init: function(){
		
		if (document.id('page-homepage')){
			var tabPanels = $$('div.tab-panel');
			tabPanels.setStyle('height', tabPanels.getStyle('height').toInt().max() - 38);
		}
		
		var googleMapEl = document.id('google-map');
		var googleMapLoaded = false;
		
		$$('div.tabs').each(function(element){
			new Tabs(element, { onChange: function(tab, panel, id){
					Cufon.refresh('ul.tab-anchors');
					if (googleMapEl && id == 'mapa' && !googleMapLoaded){
						var googleMap = new GMap('google-map', {
							map: {
								zoom: 16,
								center: {
									lat: 50.080886,
									lng: 14.426408
								}
							},
							markers: [
								{
									position: {
										lat: 50.080886,
										lng: 14.426408
									},
									title: 'Institut jazykového vzdělávání, s.r.o.',
									data: {
										name: 'Institut jazykového vzdělávání, s.r.o.',
										address: 'Štěpánská 704/61 (Palác Lucerna), Praha'
									},
									icon: {
										image: '/images/map-marker.png',
										size: [44, 43],
										origin: [0, 0],
										anchor: [22, 40]
									}
								}
							],
							bubbleTemplate: '<div class="map-bubble"><div class="map-bubble-name">{name}</div><div class="map-bubble-address">{address}</div></div>'
						});
						googleMapLoaded = true;
					}
				}
			});
		});
		
		// Small Google Map
		var googleMapSmall = document.id('google-map-small');
		if (googleMapSmall){
			var googleMapSmallObj = new GMap('google-map-small', {
				map: {
					zoom: 16,
					center: {
						lat: 50.080886,
						lng: 14.426408
					}
				},
				markers: [
					{
						position: {
							lat: 50.080886,
							lng: 14.426408
						},
						title: 'Institut jazykového vzdělávání, s.r.o.',
						data: {
							name: 'Institut jazykového vzdělávání, s.r.o.',
							address: 'Štěpánská 704/61 (Palác Lucerna), Praha'
						},
						icon: {
							image: '/images/map-marker.png',
							size: [44, 43],
							origin: [0, 0],
							anchor: [22, 40]
						}
					}
				],
				bubbleTemplate: '<div class="map-bubble"><div class="map-bubble-name">{name}</div><div class="map-bubble-address">{address}</div></div>'
			});
		}
		
		$$('ul.box-list li, div.course-block, div.reference-block div.item').makeClickable();
		$$('#block-online-chat').makeClickableLiveHelp();
		
		$$('div.course-list table, div.complete-schedule table').each(function(table){
		  new TableSlider(table);
		});
		
		// ReMooz
		$$('div.thumbnail a').each(function(element){
		  new ReMooz(element, {
        centered: true,
			  opacityResize: 0,
				cutOut: false,
        origin: element.getElement('img')
      });
		});
		
		// _blank
		$$('a._blank').set('target', '_blank');
		
		// Form loader
		IJV.Form.init();
		
		// Reference blocks
		var referenceBlocks = $$('div.reference-block');
		referenceBlocks.each(function(referenceBlock){
			var element = referenceBlock.getElement('div.carousel');
			var carousel = new SimpleCarousel(element, {
			  size: 228,
				duration: 500,
				interval: 7000,
				loop: true,
				auto: true,
				childSelector: 'div.item',
				contentSelector: 'div.item-list'
			});
			var nextBtn = referenceBlock.getElement('a.next');
			nextBtn.addEvent('click', function(event){
			  event.preventDefault();
				carousel.toItem('next');
			});
			var prevBtn = referenceBlock.getElement('a.prev');
			prevBtn.addEvent('click', function(event){
			  event.preventDefault();
				carousel.toItem('prev');
			});
		});
		
		// Homepage carousel
		var flashGrid = document.id('flash-grid');
		if (flashGrid){
			var statusBar = null;
			
			var carousel = new SimpleCarousel('flash-grid-wrapper', {
			  size: 250,
				visible: 4,
				duration: 800,
				interval: 7000,
				loop: true,
				auto: true,
				childSelector: 'div.course-block',
				contentSelector: 'div.course-block-list',
				onStart: function(){
					statusBar.highlight(carousel.getCurrent(), 4);
				}
			});
			
			statusBar = new StatusBar('flash-grid-status', {
				count: carousel.getCount(),
				onClick: function(index){
					carousel.toItem(index);
				}
			}).highlight(0, 4);
		}

		
		// Menu
		if (document.id('menu')) IJV.Menu.init();
		
		// Language Tabs
		if (document.id('course-offer')) IJV.LanguageTabs.init();
		
		// Login Layer
		if (document.id('login-layer')) IJV.LoginLayer.init();
		
		// Section languages
		if (document.id('section-languages')) IJV.SectionLanguages.init();
		
		// Video (if any)
		$$('div.video').each(function(element){ new Video(element); });
		
		// Online reservation button
		if (document.id('left-column')){
  		var scrollEl = document.id('left-column').getElement('a[href*=kontaktni-formular]');
		} else {
			var scrollEl = false;
		}
		var scrollBtns = $$('p.button-online-reservation a');
		if (scrollEl) scrollBtns.include(scrollEl);
		if (scrollBtns.length){
			var body = document.id(document.body);
			var bodyScroll = new Fx.Scroll(body, { duration: 800, transition: 'cubic:out'});
			scrollBtns.each(function(button){
				var target = body.getElement('div.tabs');
			  if (target){
					var pos = target.getPosition(body);
					button.addEvent('click', function(event){
						bodyScroll.start(0, pos.y-10);
					});
				}
			});
		}
		
	}
	
 };

IJV.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 (IJV.Form[objectTitle]){
          IJV.Form[objectTitle].init(form);
				} else {
					var checkboxes = form.getElements('input[type=checkbox]');
					checkboxes.each(function(checkbox){
						new Checkbox(checkbox);
					});
				}
			}
		});
		
	}

 };
 
IJV.Form.Reservation = {
	
	init: function(form){
		this.form = form;
		
		var checkboxes = this.form.getElements('span.checkbox input');
		checkboxes.each(function(checkbox){
		  if (checkbox.hasClass('on-change-slide')){
				var slide = checkbox.getParent('div.section').getElement('div.slide');
				var slideFx = new Fx.Slide(slide, { duration: 500, link: 'cancel' });
				slideFx.hide();
				new Checkbox(checkbox, {
				  onChange: function(element){
						element.checked ? slideFx.slideIn() : slideFx.slideOut();
					}
				});
			} else {
  		  new Checkbox(checkbox);
			}
		});
		
		var inputGroups = this.form.getElements('div.input-group');
		inputGroups.each(function(inputGroup){
		  var radioGroup = inputGroup.getElements('input[type=radio]');
			if (radioGroup.length) new RadioGroup(radioGroup);
		});
				
		var paymentTypeRadioElements = this.form.getElements('#form-reservation-group-payment-type input');
		var paymentTypeRadioGroup = new RadioGroup(paymentTypeRadioElements, {
		  onCheck: function(radio, index){
				var label = radio.getParent('label');
				if (label) label.addClass('selected');
			},
			onUncheck: function(radio, index){
				var label = radio.getParent('label');
				if (label) label.removeClass('selected');
			}
		});
	}
 };
 
IJV.Form.Test = {
	
	init: function(form){
		this.form = form;
		
		var checkboxes = this.form.getElements('input[type=checkbox]');
		checkboxes.each(function(checkbox){
		  new Checkbox(checkbox);
		});
	}
 };
 
IJV.Form.Search = {
	
	init: function(form){
		
		this.form = form;
		
		this.languages = this.form.getElements('#form-search-group-languages li');
		this.current = {};
		
		
		// Languages
		this.languages.each(function(language){
		  var radio = language.getElement('input');
			var img = language.getElement('img');
			img.set('tween', {property: 'opacity', duration: 300, link: 'cancel'}).get('tween').set(0.01);
			
			var label = language.getElement('label');
			var width = label.measure(function(){ return this.getSize().x; });
			label.set('tween', {property: 'width', duration: 200, link: 'cancel'}).get('tween').set(35);
			
			label.addEvent('click', function(event){
				event.stop();
			  if (this.current.imgFx) this.current.imgFx.start(0);
				if (this.current.labelFx) this.current.labelFx.start(35);
				if (this.current.radio) this.current.radio.checked = false;
				this.current.imgFx = img.get('tween').start(1);
				this.current.labelFx = label.get('tween').start(width);
				this.current.radio = radio;
				radio.checked = true;
				if (window.getSelection){
					var selection = window.getSelection()
					if (selection && selection.collapse) selection.collapse(label, 0);
				}
			}.bind(this));
			
			if (radio.checked){
				this.current.imgFx = img.get('tween').set(1);
				this.current.labelFx = label.get('tween').set(width);
				this.current.radio = radio;
			}
		}, this);
		
		// Level
		var groupLevel = document.id('form-search-group-level');
		var levelSelect = groupLevel.getElement('select');
		var levelOptions = levelSelect.getElements('option');
		var levelRange = groupLevel.getElement('div.range');
		var levelKnob = groupLevel.getElement('span.knob');
		this.levelSlider = new Slider(levelRange, levelKnob, {
		  range: [0, levelOptions.length-1],
			steps: levelOptions.length-1,
			snap: true,
			offset: 0,
			onComplete: function(step){
				levelSelect.selectedIndex = step;
			}
		});
		
		// time
		var groupTime = document.id('form-search-group-time');
		var checkboxes = groupTime.getElements('input');
		checkboxes.each(function(checkbox){ new Checkbox(checkbox); });
		
	}
 };
 
IJV.Form.Competition = {
	
	init: function(form){
		
		this.form = form;
		
		this.radioGroupContainers = this.form.getElements('ol.numbered-list > li');
		
		this.radioGroupContainers.each(function(radioGroupContainer){
		  var radioGroup = radioGroupContainer.getElements('input[type=radio]');
			new RadioGroup(radioGroup);
		});
		
		this.checkboxes = this.form.getElements('input[type=checkbox]');
		this.checkboxes.each(function(checkbox){
		  new Checkbox(checkbox);
		});
		
	}
	
 };

IJV.Menu = {
	
	init: function(){
		this.container = document.id('menu');
		
		this.menu = this.container.getElement('ul.menu');
		
		this.items = this.menu.getElements('li');
		
		this.layerContainer = new Element('div', {'id': 'menu-layers'});
		
		// request layers
		this.requeststatic = new Request.HTML({
		  url: '/aliased/menu-layers.php',
			onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript){
				if (responseHTML){
					this.layerContainer.set('html', responseHTML).inject(this.menu, 'after');
					this.prepare();
				}
			}.bind(this)
		}).get();
		
	},
	
	prepare: function(){
		this.items.each(function(item){
			var isActive = item.hasClass('active');
			if (!isActive){
				item.addEvents({
					'mouseenter': function(){ item.addClass('active'); },
					'mouseleave': function(){ item.removeClass('active'); }
				});
			}
			new IJV.Menu.Item(item);
		});
		
	}
	
 };

IJV.Menu.Item = new Class({

  Implements: [Options, Events, Status],
	
	options: {
		duration: 300,
		delay: 100
	},
	
	initialize: function(element, options){
		
		this.element = document.id(element);
		
		this.setOptions(options);
		
		var anchor = this.element.getElement('a');
		if (!anchor) return null;
		
		var rel = anchor.get('rel');
		if (!rel) return null;
		
		this.layer = document.id(rel);
		if (!this.layer) return null;
		
		this.layer.setStyle('display', 'block');
		this.slideEl = this.layer.getElement('div.menu-layer-content');
		this.fx = new Fx.Slide(this.slideEl, {
		  duration: this.options.duration,
			link: 'cancel'
		}).hide();
		
		// tabs
		this.tabs = this.layer.getElements('div.menu-layer-content > ul > li');
		this.current = null;
		this.tabs.each(function(tab){
			if (tab.hasClass('active')) this.current = tab;
			tab.addEvents({
				'mouseenter': function(){
					if (this.current != tab) this.current.removeClass('active');
					tab.hasClass('wide') ? this.layer.addClass('wide') : this.layer.removeClass('wide');
					tab.addClass('active');
					this.current = tab;
					Cufon.refresh('div.menu-layer-content > ul > li > a');
	  		}.bind(this)
			});											
		}, this);
		
		// self events
		this.element.addEvents({
		  'mouseenter': function(){ this.open(); }.bind(this),
			'mouseleave': function(){ this.close.delay(this.options.delay, this); }.bind(this)
		});
		
		this.layer.addEvents({
		  'mouseenter': function(){ this.setStatus('used', true); }.bind(this),
			'mouseleave': function(){ this.setStatus('used', false); this.close.delay(this.options.delay, this); }.bind(this)
		});
		
		Cufon.replace('div.menu-layer-content > ul > li > a');

	},
	
	open: function(){
		this.fx.slideIn();
	},
	
	close: function(){
		if (this.isNot('used')) this.fx.slideOut();
	},
	
	toElement: function(){
		return this.element;
	}

});

IJV.LanguageTabs = {


 init: function(){
	 
	 this.container = document.id('course-offer');
	 
	 this.languages = this.container.getElements('div.languages ul li');
	 
	 this.items = new Array();
	 this.tabs = new Hash();
	 this.current = null;
	 this.tabContentContainer = new Element('div');
	 this.defaultTabContent = document.id('course-tab-en');
	 
	 this.request = new Request.HTML({
		  url: '/static/course-offer-tabs.php',
			onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript){
				if (responseHTML){
					this.tabContentContainer.set('html', responseHTML).inject(this.defaultTabContent, 'after');
	      	this.prepare();
				}
			}.bind(this)
	 }).get();
	 
 },
 
 prepare: function(){
	 this.languages.each(function(language){
		 var item = new IJV.LanguageTabs.Item(language, {
		   onActive: function(){
				 this.setCurrent(item);
			 }.bind(this)
		 });
		 var rel = item.getRel();
		 var content = document.id(rel);
		 if (content) this.tabs.set(rel, content);
	   this.items.include(item)
	 }, this);
	 
   this.items[0].activate();
 
	 this.container.addClass('ready');
	 
 },
 
 setCurrent: function(item){
	 if (this.current){
		 var rel = this.current.getRel();
		 this.current.deactivate();
		 if (this.tabs.has(rel)) this.tabs.get(rel).fade('out');
	 }
	 var rel = item.getRel();
	 if (this.tabs.has(rel)){
		 this.tabs.get(rel).setStyle('opacity', 0).fade('in');
		 this.current = item;
	 }
 }
 

 };

IJV.LanguageTabs.Item = new Class({

  Implements: [Events, Status, Options],
	
	options: {
		hover: {
			options: {
				property: 'top',
				link: 'cancel',
				duration: 150
			},
			from: 2,
			to: -10
		},
		flag: {
			options: {
				link: 'chain',
				duration: 200
			},
			from: {
				width: 33,
				left: 0,
				top: 2
			},
			middle: {
				width: 33,
				left: 0,
				top: -11
			},
			to: {
				width: 55,
				left: 0,
				top: -16
			}
		},
		shadow: {
			options: {
				link: 'cancel',
				duration: 200
			},
			from: {
				opacity: 0
			},
			to: {
				opacity: 1
			},
			delay: 200
		}
	},
	
	initialize: function(element, options){

    this.element = element;
		
		this.setOptions(options);
		
		this.flag = this.element.getElement('a');
		this.flag.addEvent('click', function(event){ event.preventDefault(); });
		
		this.rel = this.flag.get('rel');
		
		this.border = this.element.getElement('span.border');
		
		this.shadow = this.element.getElement('span.shadow');
		
		this.fx = {
			hover: new Fx.Tween(this.flag, this.options.hover.options),
			flag: new Fx.Morph(this.flag, this.options.flag.options),
			shadow: new Fx.Morph(this.shadow, this.options.shadow.options).set(this.options.shadow.from)
		}
		
		// events
		this.element.addEvents({
      'mouseenter': function(){
				if (this.isNot('active'))	this.fx.hover.start(this.options.hover.to);
			}.bind(this),
			'mouseleave': function(){
				if (this.isNot('active'))	this.fx.hover.start(this.options.hover.from);
			}.bind(this),
			'click': function(){
				this.activate();
			}.bind(this)
		});
		
	},
	
	setActive: function(){
		this.setStatus('active', true);
		this.element.setStyle('z-index', 1);
		this.border.hide();
		this.fx.flag.set(this.options.flag.to);
		this.fx.shadow.set(this.options.shadow.to);
		this.fireEvent('active');
		return this;
	},
	
	activate: function(){
		if (this.isNot('active')){
			this.setStatus('active', true);
			this.element.setStyle('z-index', 1);
			this.border.hide();
			this.fx.flag.start(this.options.flag.to);
			this.fx.shadow.start(this.options.shadow.to);
			this.fireEvent('active');
		}
		return this;
	},
	
	deactivate: function(){
		if (this.is('active')){
			this.setStatus('active', false);
			this.fx.shadow.start(this.options.shadow.from);
			this.fx.flag.start(this.options.flag.middle).chain(
				function(){
					this.element.setStyle('z-index', 0);
					this.border.show();
					this.fx.flag.start(this.options.flag.from);
				}.bind(this)
			);
		}
		return this; 
	},
	
	getRel: function(){
		return this.flag.get('rel');
	}


});

$extend(IJV.LanguageTabs, new Events());

IJV.SectionLanguages = {
	
	init: function(){
		this.container = document.id('section-languages');
		
		this.flags = this.container.getElements('a');
		
		this.flags.each(function(flag){
		  var fx = new Fx.Morph(flag, {duration: 100, link: 'cancel'});
			
			flag.addEvents({
			  'mouseenter': function(){
				  fx.start({
					  'margin-top': -12,
						'height': 40
					});
				},
				'mouseleave': function(){
				  fx.start({
					  'margin-top': 0,
						'height': 28
					});
				}
			});
		});
	}
 };

IJV.LoginLayer = {
	
	
	init: function(){
		
		this.layer = document.id('login-layer');
		
		this.trigger = document.id('menu').getElement('li.sign-in');
		
		if (!this.trigger) return;
		
		this.trigger.addEvent('click', function(event){
		  event.stop();
			this.open();
			Observer.register(this.close, this);
		}.bind(this));
	},
	
	open: function(){
		this.layer.show();
		this.layer.getElement('input').focus();
	},
	
	close: function(){
		this.layer.hide();
	}
	
 };

window.addEvent('domready', function(){

  Observer.init();

  IJV.init();
	
});

Cufon.replace('#section .section-title, div.with-tab h2');
Cufon.replace('ul.tab-anchors');
Cufon.replace('#page-homepage h1, #course-offer h2');
Cufon.replace('div.contact-block p.more');
Cufon.replace('#form-reservation > fieldset > legend, #form-reservation button span, #form-test button span, form.generic-form button span');
Cufon.replace('div.complex-block h2 span, div.price-banner span, ul.box-list a, div.reference-block h2 span');
Cufon.replace('#main-content h1, div.course-block h3, div.course-block p.price, div.course-block p.order a');
Cufon.replace('div.column-content h2 span.border, div.summary h2 span.border, div.content-padding h2.border span');
Cufon.replace('#form-search legend, #form-search-group-level span.knob, #form-search button span, #form-contact button span');
Cufon.replace('#footer div.block-social-links h2');
Cufon.replace('#form-competition span.number, #form-competition legend, #form-competition button');

swfobject.registerObject("homepage-flash", "9.0.0", "/flash/expressInstall.swf");
