window.addEvent('domready',function(){
	initCufon();
	initInputs();
	initBoxes();
	initBanner();
});

function initCufon() {
	Cufon.replace('#header .row h2', { fontFamily: 'Gotham Rounded Book Italic' });
	Cufon.replace('#header .button2 strong, #header .button2 span span', { fontFamily: 'Gotham Rounded Bold' });
	Cufon.replace('#nav a', { fontFamily: 'Gotham Rounded Bold', hover: true });
	Cufon.replace('#header .button span', { fontFamily: 'Gotham Rounded Book', hover: true });
	Cufon.replace('.text-box h2, .text-box h3, .subtext > span', { fontFamily: 'Gotham Rounded Medium'});
	Cufon.replace('.action-box .num-holder em', {color: '-linear-gradient(#7a7878, 0.35=#c6c5c5, 0.65=#fff, #fff)', fontFamily: 'Gotham Rounded Medium' });
	Cufon.replace('ul.tabset a', { fontFamily: 'RosewoodStd', hover: true });
	Cufon.replace('.example h3', { fontFamily: 'BirchStd'});
	Cufon.replace('.example p', { fontFamily: 'ComicSans', hover: true});
	Cufon.replace('.effects-test .shadow', { textShadow: '#555 1px 1px, #000 2px 2px', fontFamily: 'Frutiger' });
	Cufon.replace('.effects-test .gradient', { color: '-linear-gradient(#aaa, 0.45=#888, 0.45=#555, #000)', fontFamily: 'Frutiger' });
}

function initBanner(){
	$$('ul.rotator').each(function(holder){
		new slideshow(holder);
	});
}

function initBoxes(){
	var holder = $$('div.picture');
	if (!holder.length) return;
	var links = holder[0].getElements('div.menu-box ul > li > a'); 
	var boxes = holder[0].getElements('div.additional-box');
	
	var activeBox = -1;
	
	boxes.each(function(box,i){
		box.setStyles({opacity:0,display:'none'});
		var closeLink = box.getElement('a.close-link');
		var link = links[i];
		var openFx = new Fx.Morph(box,{duration:350});
		var closeFx = new Fx.Morph(box,{duration:350,onComplete:function(){
			box.setStyles({display:'none'});
		}});
		
		link.addEvent('mouseenter',open);
		
		box.addEvent('close',close);
		closeLink.addEvent('click',close);
		
		function close(){
			openFx.cancel();
			closeFx.start({opacity:0});
			activeBox = -1;
			return false;
		}
		
		function open(){
			if (activeBox != -1) activeBox.fireEvent('close');
			
			box.setStyles({display:'block'});
			closeFx.cancel();
			openFx.start({opacity:1});
			activeBox = box;
			return false;
		}
	});
}

// clear inputs on focus
function initInputs() {
	// replace options
	var opt = {
		clearInputs: true,
		clearTextareas: true,
		clearPasswords: true
	}
	// collect all items
	var inputs = [].concat(
		PlaceholderInput.convertToArray(document.getElementsByTagName('input')),
		PlaceholderInput.convertToArray(document.getElementsByTagName('textarea'))
	);
	// apply placeholder class on inputs
	for(var i = 0; i < inputs.length; i++) {
		if(inputs[i].className.indexOf('default') < 0) {
			var inputType = PlaceholderInput.getInputType(inputs[i]);
			if((opt.clearInputs && inputType === 'text') ||
				(opt.clearTextareas && inputType === 'textarea') || 
				(opt.clearPasswords && inputType === 'password')
			) {
				new PlaceholderInput({
					element:inputs[i],
					wrapWithElement:false,
					showUntilTyping:false,
					getParentByClass:false,
					placeholderAttr:'value'
				});
			}
		}
	}
}

// input type placeholder class
;(function(){
	PlaceholderInput = function() {
		this.options = {
			element:null,
			showUntilTyping:false,
			wrapWithElement:false,
			getParentByClass:false,
			placeholderAttr:'value',
			inputFocusClass:'focus',
			inputActiveClass:'text-active',
			parentFocusClass:'parent-focus',
			parentActiveClass:'parent-active',
			labelFocusClass:'label-focus',
			labelActiveClass:'label-active',
			fakeElementClass:'input-placeholder-text'
		}
		this.init.apply(this,arguments);
	}
	PlaceholderInput.convertToArray = function(collection) {
		var arr = [];
		for (var i = 0, ref = arr.length = collection.length; i < ref; i++) {
		 arr[i] = collection[i];
		}
		return arr;
	}
	PlaceholderInput.getInputType = function(input) {
		return (input.type ? input.type : input.tagName).toLowerCase();
	}
	PlaceholderInput.prototype = {
		init: function(opt) {
			this.setOptions(opt);
			if(this.element && this.element.PlaceholderInst) {
				this.element.PlaceholderInst.refreshClasses();
			} else {
				this.element.PlaceholderInst = this;
				if(this.elementType == 'text' || this.elementType == 'password' || this.elementType == 'textarea') {
					this.initElements();
					this.attachEvents();
					this.refreshClasses();
				}
			}
		},
		setOptions: function(opt) {
			for(var p in opt) {
				if(opt.hasOwnProperty(p)) {
					this.options[p] = opt[p];
				}
			}
			if(this.options.element) {
				this.element = this.options.element;
				this.elementType = PlaceholderInput.getInputType(this.element);
				this.wrapWithElement = (this.elementType === 'password' || this.options.showUntilTyping ? true : this.options.wrapWithElement);
				this.setOrigValue( this.options.placeholderAttr == 'value' ? this.element.defaultValue : this.element.getAttribute(this.options.placeholderAttr) );
			}
		},
		setOrigValue: function(value) {
			this.origValue = value;
		},
		initElements: function() {
			// create fake element if needed
			if(this.wrapWithElement) {
				this.element.value = '';
				this.element.removeAttribute(this.options.placeholderAttr);
				this.fakeElement = document.createElement('span');
				this.fakeElement.className = this.options.fakeElementClass;
				this.fakeElement.innerHTML += this.origValue;
				this.fakeElement.style.color = getStyle(this.element, 'color');
				this.fakeElement.style.position = 'absolute';
				this.element.parentNode.insertBefore(this.fakeElement, this.element);
			}
			// get input label
			if(this.element.id) {
				this.labels = document.getElementsByTagName('label');
				for(var i = 0; i < this.labels.length; i++) {
					if(this.labels[i].htmlFor === this.element.id) {
						this.labelFor = this.labels[i];
						break;
					}
				}
			}
			// get parent node (or parentNode by className)
			this.elementParent = this.element.parentNode;
			if(typeof this.options.getParentByClass === 'string') {
				var el = this.element;
				while(el.parentNode) {
					if(hasClass(el.parentNode, this.options.getParentByClass)) {
						this.elementParent = el.parentNode;
						break;
					} else {
						el = el.parentNode;
					}
				}
			}
		},
		attachEvents: function() {
			this.element.onfocus = bindScope(this.focusHandler, this);
			this.element.onblur = bindScope(this.blurHandler, this);
			if(this.options.showUntilTyping) {
				this.element.onkeydown = bindScope(this.typingHandler, this);
				this.element.onpaste = bindScope(this.typingHandler, this);
			}
			if(this.wrapWithElement) this.fakeElement.onclick = bindScope(this.focusSetter, this);
		},
		togglePlaceholderText: function(state) {
			if(this.wrapWithElement) {
				this.fakeElement.style.display = state ? '' : 'none';
			} else {
				this.element.value = state ? this.origValue : '';
			}
		},
		focusSetter: function() {
			this.element.focus();
		},
		focusHandler: function() {
			this.focused = true;
			if(!this.element.value.length || this.element.value === this.origValue) {
				if(!this.options.showUntilTyping) {
					this.togglePlaceholderText(false);
				}
			}
			this.refreshClasses();
		},
		blurHandler: function() {
			this.focused = false;
			if(!this.element.value.length || this.element.value === this.origValue) {
				this.togglePlaceholderText(true);
			}
			this.refreshClasses();
		},
		typingHandler: function() {
			setTimeout(bindScope(function(){
				if(this.element.value.length) {
					this.togglePlaceholderText(false);
					this.refreshClasses();
				}
			},this), 10);
		},
		refreshClasses: function() {
			this.textActive = this.focused || (this.element.value.length && this.element.value !== this.origValue);
			this.setStateClass(this.element, this.options.inputFocusClass,this.focused);
			this.setStateClass(this.elementParent, this.options.parentFocusClass,this.focused);
			this.setStateClass(this.labelFor, this.options.labelFocusClass,this.focused);
			this.setStateClass(this.element, this.options.inputActiveClass, this.textActive);
			this.setStateClass(this.elementParent, this.options.parentActiveClass, this.textActive);
			this.setStateClass(this.labelFor, this.options.labelActiveClass, this.textActive);
		},
		setStateClass: function(el,cls,state) {
			if(!el) return; else if(state) addClass(el,cls); else removeClass(el,cls);
		}
	}
	
	// utility functions
	function hasClass(el,cls) {
		return el.className ? el.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)')) : false;
	}
	function addClass(el,cls) {
		if (!hasClass(el,cls)) el.className += " "+cls;
	}
	function removeClass(el,cls) {
		if (hasClass(el,cls)) {el.className=el.className.replace(new RegExp('(\\s|^)'+cls+'(\\s|$)'),' ');}
	}
	function bindScope(f, scope) {
		return function() {return f.apply(scope, arguments)}
	}
	function getStyle(el, prop) {
		if (document.defaultView && document.defaultView.getComputedStyle) {
			return document.defaultView.getComputedStyle(el, null)[prop];
		} else if (el.currentStyle) {
			return el.currentStyle[prop];
		} else {
			return el.style[prop];
		}
	}
}());

var slideshow = new Class({
	Implements : [Options, Events],
	options:{
		slides:'> li',
		nextBtn:'a.next',
		prevBtn:'a.prev',
		pagingHolder:'div.switcher',
		pagingTag:'li',
		slidesActiveClass:'active',
		pagingActiveClass:'active',
		autoHeight:false,
		createPaging:false,
		autoPlay:true,
		dynamicLoad:false,
		imgAttr:'alt',
		effect:'fade',//fade, slideX, slideY,
		startSlide:false,
		switchTime:5000,
		animSpeed:700
	},
	initialize:function(element, options) {
		this.mainHolder = $(element);
		this.setOptions(options);
		this.slides = this.mainHolder.getElements(this.options.slides);		
		if (!this.slides.length) return;
		this.slides.length < 2 ? this.disabled = true : this.disabled = false;
		if (this.options.nextBtn) this.nextBtn = this.mainHolder.getElement(this.options.nextBtn);
		if (this.options.prevBtn) this.prevBtn = this.mainHolder.getElement(this.options.prevBtn);
		
		if (this.disabled) {
			if (this.nextBtn) this.nextBtn.setStyles({visibility:'hidden'});
			if (this.prevBtn) this.prevBtn.setStyles({visibility:'hidden'});
		}
		
		this.previous = -1;
		this.loadingFrame = 1;
		this.busy = false;
		this.direction = 1;
		this.timer;
		this.pagingArray = new Array;
		this.loadArray = new Array;
		this.preloader = new Array;
		this.slidesParent = this.slides[0].getParent();
		this.slideW = this.slidesParent.getSize().x;
		this.slideH = this.slidesParent.getSize().y;
		this.autoPlay = this.options.autoPlay;
		
		this.initStartSlide();
		this.initPaging();
		this.setStyles();
		this.bindEvents();
		this.showSlide();
	},
	
	initStartSlide:function(){
		if (this.options.startSlide) this.current = this.options.startSlide
		else {
			var active = -1;
			for(var i = 0; i< this.slides.length-1; i++) {
				if (this.slides[i].hasClass(this.options.slidesActiveClass)) {
					active = i;
					break;						
				}
			}
			if (active != -1) this.current = active;
			else this.current = 0;
		}
	},
	
	initPaging:function(){
		this.pagingHolder = this.mainHolder.getElements(this.options.pagingHolder);
		
		if (this.options.createPaging && !this.disabled) {
			this.pagingHolder.each(function(paging,i){
				paging.empty();
				var list = new Element('ul');
				var html = '';
				for (var i = 0; i < this.slides.length; i++) {
					html += '<li><a href="#">' + (i + 1) + '</a></li>';
				}
				list.innerHTML = html;
				list.inject(paging);
			}.bind(this));
		}
		
		this.pagingHolder.each(function(paging){
			this.pagingArray.push(paging.getElements(this.options.pagingTag))
		}.bind(this));
	},
	
	setStyles:function(){
		//loader
		if (this.options.dynamicLoad) {
			this.loader = new Element('div').addClass('loader');
			this.loaderDiv = new Element('div').inject(this.loader);
			this.loader.inject(this.slidesParent);
		}
		
		//slides
		this.slides.each(function(slide,i){
			if (this.options.effect == 'fade') {
				if (i != this.current) slide.setStyles({display:'none'});
				else slide.setStyles({display:'block'});
			} else if (this.options.effect == 'slideX'){
				if (i != this.current) slide.setStyles({display: 'none',left:-this.slideW});
				else slide.setStyles({display:'block',left:0});
			} else if (this.options.effect == 'slideY'){
				if (i != this.current) slide.setStyles({display:'none',top:-this.slideH});
				else slide.setStyles({display:'block',top:0});
			}
		}.bind(this));
		
		if (this.options.autoHeight) {
			this.slidesParent.setStyles({
				height:this.slides[this.current].getSize().y
			});
		}
	},
	
	bindEvents:function(){
		if (this.nextBtn) this.nextBtn.addEvent('click',function(){
			if (!this.busy && !this.disabled) this.nextSlide();
			return false;
		}.bind(this));
		
		if (this.prevBtn) this.prevBtn.addEvent('click',function(){
			if (!this.busy && !this.disabled) this.prevSlide();
			return false;
		}.bind(this));
		this.pagingArray.each(function(paging){
			paging.each(function(btn,i){
				btn.addEvent('click',function(){
					if (i != this.current && !this.busy && !this.disabled) {
						this.previous = this.current;
						this.current = i;
						if (this.previous > i) this.direction = -1
						else this.direction = 1;
						this.showSlide();
					}
					return false;
				}.bind(this));
			}.bind(this));
		}.bind(this));
		
		if (this.options.dynamicLoad) this.loader.addEvent('click',this.abortLoading.bind(this));
	},
	
	nextSlide:function(){
		this.previous = this.current;
		if (this.current < this.slides.length-1) this.current++
		else this.current = 0;
		this.direction = 1;
		this.showSlide();
	},
	
	prevSlide:function(){
		this.previous = this.current;
		if (this.current > 0) this.current--
		else this.current = this.slides.length-1;
		this.direction = -1;
		this.showSlide();
	},
	
	showSlide:function(){
		if (this.previous == this.current) return; 
		var _current = this.current;
		this.busy = true;
		clearTimeout(this.timer);
		if (typeof this.loadArray[_current] != 'undefined' || !this.options.dynamicLoad) {
			//slide already loaded
			this.switchSlide();
		} else {
			//slide not loaded
			this.showLoading();
			var images = this.slides[this.current].getElements(this.options.dynamicLoad);
			if (images.length) {
				var counter = 0;
				images.each(function(img){
					var preloader = new Image;
					this.preloader.push(preloader);
					preloader.onload = function(){
						counter++;
						checkImages.apply(this);
					}.bind(this);
					preloader.onerror = function(){
						//ignore errors
						counter++;
						checkImages.apply(this);
					}.bind(this);
					preloader.src = img.getProperty(this.options.imgAttr);
				}.bind(this));
				
				function checkImages(){
					if (counter == images.length) {
						images.each(function(img){
							img.setProperty('src',img.getProperty(this.options.imgAttr));
						}.bind(this));
						successLoad.apply(this);
					}
				}
			} else successLoad.apply(this);
		}
		
		function successLoad(){
			this.loadArray[_current] = 1;
			this.hideLoading();
			this.switchSlide();
		}
	},
	
	switchSlide:function(){
		var obj = this;
		
		if (this.previous != -1) {
			var nextSlide = this.slides[this.current];
			var prevSlide = this.slides[this.previous];
			nextSlide.setStyles({display:'block'});
				
				
			if (this.options.effect == 'slideX'){
				this.slideW = this.slides[this.current].getSize().x;
				var nextFx = new Fx.Morph(nextSlide,{duration:this.options.animSpeed});
				var prevFx = new Fx.Morph(prevSlide,{duration:this.options.animSpeed,onComplete:callback.bind(this)});
				
				nextSlide.setStyles({left:this.slideW*this.direction})
				nextFx.start({left:0});
				prevFx.start({left:-this.slideW*this.direction});
			} else if (this.options.effect == 'slideY'){
				this.slideH = this.slides[this.current].getSize().y
				var nextFx = new Fx.Morph(nextSlide,{duration:this.options.animSpeed});
				var prevFx = new Fx.Morph(prevSlide,{duration:this.options.animSpeed,onComplete:callback.bind(this)});
				
				nextSlide.setStyles({top:this.slideH*this.direction});
				nextFx.start({top:0});
				prevFx.start({top:-this.slideH*this.direction});
			} else {
				var nextFx = new Fx.Morph(nextSlide,{duration:this.options.animSpeed,onComplete:function(){
					nextSlide.setStyles({opacity:'auto'});
				}});
				var prevFx = new Fx.Morph(prevSlide,{duration:this.options.animSpeed,onComplete:callback.bind(this)});
				nextSlide.setStyles({display:'block',opacity:0});
				nextFx.start({opacity:1});
				prevSlide.setStyles({opacity:1});
				prevFx.start({opacity:0});
			}
			
			if (this.options.autoHeight) {
				this.slideH = this.slides[this.current].getSize().y
				var parentFx = new Fx.Morph(this.slidesParent,{duration:this.options.animSpeed});
				parentFx.start({height:this.slideH});
			}
		} else {
			if (this.autoPlay && !this.disabled) this.startAutoPlay();
			this.busy = false;
		}
		
		this.refreshStatus();
		
		function callback(){
			prevSlide.setStyles({display:'none'});
			if (this.autoPlay) this.startAutoPlay();
			this.busy = false;
		}
	},
	
	refreshStatus:function(){
		if (this.pagingArray.length) {
			this.pagingArray.each(function(paging){
				if (paging.length) {
					if (this.previous != -1) paging[this.previous].removeClass(this.options.pagingActiveClass);
					paging[this.current].addClass(this.options.pagingActiveClass);
				}
			}.bind(this));
		}
		if (this.previous != -1) this.slides[this.previous].removeClass(this.options.pagingActiveClass);
		this.slides[this.current].addClass(this.options.pagingActiveClass);
	},
	
	showLoading:function(){
		this.loader.setStyles({display:'block'});
		clearInterval(this.loadingTimer);
		this.loadingTimer = setInterval(animateLoading.bind(this), 66);
		
		function animateLoading(){
			this.loaderDiv.setStyles({'top': this.loadingFrame * -40});
			this.loadingFrame = (this.loadingFrame + 1) % 12;
		}
	},
	
	hideLoading:function(){
		this.loader.setStyles({display:'none'});
		clearInterval(this.loadingTimer);
	},
	
	abortLoading:function(){
		this.busy = false;
		this.hideLoading();
		this.current = this.previous;
		for (var i = 0; i < this.preloader.length; i++) {
			this.preloader[i].onload = null;
			this.preloader[i].onerror = null;
		}
		if (this.autoPlay) this.startAutoPlay();
	},
	
	startAutoPlay:function(){
		clearTimeout(this.timer);
		this.timer = setTimeout(this.nextSlide.bind(this),this.options.switchTime);
	}
});
