// OBSERVER CLASS :: kassens
var Observer = new Class({

	Implements: [Options, Events],

	options: {
		interval: 100,
		duration: 0
	},

	initialize: function(element, property, options){
		this.setOptions(options);
		this.element = $(element);
		this.element.store('valueObserver', this);
		this.property = property;
		this.value = this.element.get(property);
		this.start();
	},

	check: function() {
		var value = this.element.get(this.property);
		if (value == this.value || value == 'search') return;
		this.value = value;
		this.fireEvent('onChange', [value]);
	},

	start: function() {
		this.stop();
		this.interval = this.check.periodical(this.options.interval, this);
	},

	stop: function() {
		$clear(this.interval);
	},
	
	set: function(value) {
		this.stop();
		this.value = value;
		this.element.set(this.property, value);
		this.start();
	}

});

Element.Events.observedChange = {

	onAdd: function(fn){
		new Observer(this, 'value', {onChange: fn});
	}

};

// FALLBACK FOR IE :: kassens
Element.implement({

	fadeOut: function(){
		this.fade(Browser.Engine.trident ? 'hide' : 'out');
	},

	fadeIn: function(){
		this.fade(Browser.Engine.trident ? 'show' : 'in');
	}

});

Element.Properties.pageLink = {
	get: function(){
		return this.retrieve('pageLink');
	}
};

Element.Properties.pageHref = {
	get: function(){
		return this.getElement('a').get('href');
	}
};

function sanitizePath(path){
	var i = path.indexOf('/');
	if(i>0)
		return path.slice(i+1);
	else return path;
}

var PageSlider = new Class({
	Implements: [Options, Events],

	Binds: [
		'goPrevious', 'goNext',
		'requestStarted', 'requestSuccess'
	],

	options: {
		transition: {
			duration: 500,
			transition: 'linear'
		},
		
		autoTransition: false,
		autoTransitionPeriod: 4000
	},

	initialize: function(el, options){
		this.setOptions(options);
		this.element = $(el);
		this.setupUI();
		
		if(window.location.hash){
			var self = this;
			this.pagination.items.each(function(item, idx){
				if('#'+sanitizePath(item.get('pageHref') && idx != 0) == window.location.hash){
					self.showPage(item);
				}
			})
		}
	},

	setupUI: function(){
		var self = this;
		this.previous = this.element.getElement('.previous');
		this.next = this.element.getElement('.next');
		this.setupPagination();
		this.setupArrows();
		this.slideshowContainer = this.element.getElement('.slideshow_container');
		this.setupSlideshow();
		this.request = new Request({
			link: 'chain',
			method: 'get'
		});
		
		this.spinner = this.element.getElement('.spinner');
		
		if(!this.spinner)
			this.spinner = new Element('div', {'class': 'spinner'}).inject(this.element, 'bottom');
			
		this.spinner.fade('hide');
		
		this.request.addEvents({
			request: this.requestStarted,
			success: this.requestSuccess
		});
		
		$(document).addEvent('keydown', function(event){
			switch(event.key){
				case 'left':
					self.goPrevious(event);
					break;
				case 'right':
					self.goNext(event);
					break;
			}
		});
		
		this.guard = false;
		
		this.addEvents({
			'transitionstarted': function(ev){
				self.guard = true;
			},
			
			'transitioncompleted': function(ev){
				self.guard = false;
			}
		})
		
		this.timer = false;
		this.setupTimer();
		
	},
	
	setupTimer: function(){
		if(this.options.autoTransition) {
			this.timer = (function(){
				var li = this.pagination.current.getNext('li');
				if(!li) li = this.pagination.items[0];
				this.showPage(li);
			}).periodical(this.options.autoTransitionPeriod, this);
		}
	},

	setupArrows: function(){
		this.previous.addEvent('click', this.goPrevious);
		this.next.addEvent('click', this.goNext);
		if(this.pagination.items.length == 1)
			$$([this.next, this.previous]).addClass('inactive');
		else {
			if(this.pagination.current == this.pagination.items[0])
				this.previous.addClass('inactive');
		}

	},

	hideUI: function(){
		$$(this.pagination.container, this.previous, this.next).addClass('hidden');
	},

	setupPagination: function(){
		var self = this;
		this.pagination = {};
		this.pagination.container = this.element.getElement('#pagination');
		var items = this.pagination.container.getElements('li');

		if(items.length == 1) this.hideUI();

		items.each(function(item){
			if(item.hasClass('active')) 
				self.pagination.current = item;
			var a = item.getElement('a');
			item.store('pageLink', a.href);
			a.addEvent('click', self.pageClicked.bindWithEvent(self, [a, item]));
		});

		this.pagination.items = items;

	},

	pageClicked: function(ev, link, page){
		if(ev) ev.stop();
		if(this.guard) return;
		this.showPage(page);
	},

	goPrevious: function(ev){
		if(ev) ev.stop();
		if(this.guard) return;
		if(this.options.autoTransition) {
			$clear(this.timer);
			var self = this;
			var f = function(){
				self.removeEvent('transitioncompleted', f);
				self.setupTimer();
			}
			this.addEvent('transitioncompleted', f);
		}
		if(this.previous.hasClass('inactive')) return false;
		var li = this.pagination.current.getPrevious('li');
		if(li) this.showPage(li);

		return true;
	},

	goNext: function(ev){
		if(ev) ev.stop();
		if(this.guard) return;
		if(this.options.autoTransition) {
			$clear(this.timer);
			var self = this;
			var f = function(){
				self.removeEvent('transitioncompleted', f);
				self.setupTimer();
			}
			this.addEvent('transitioncompleted', f);
		}
		if(this.next.hasClass('inactive')) return false;
		var li = this.pagination.current.getNext('li');
		if(li) this.showPage(li);
		return true;
	},

	showPage: function(page){
		this.pagination.nextPage = page;
		this.request.get(page.retrieve('pageLink'));
	},

	requestStarted: function(){
		this.spinner.fade('in');
	},

	requestSuccess: function(data){
		this.spinner.fade('out');
		var e = new Element('div', {html: data});
		e = e.getElement('.artical').dispose();
		e.setStyles({
			'top': 0,
			'left': 900,
			'position': 'absolute'
		});
		this.slideshowContainer.adopt(e, 'bottom');

		var items = this.pagination.items;
		var next = this.pagination.nextPage;
		var current = this.pagination.current;
		this.startFx();

		// next.setAttribute('active', '');
		if(next) next.addClass('active');

		// current.removeAttribute('active');
		current.removeClass('active');

		this.pagination.current = this.pagination.nextPage;
		this.pagination.nextPage = false;

		$$([this.next, this.previous]).removeClass('inactive');
		if(this.pagination.current == this.pagination.items.getLast()) {
			this.next.addClass('inactive');
		}

		if(this.pagination.current == this.pagination.items[0]) {
			this.previous.addClass('inactive');
		}
		
		window.location.hash = sanitizePath(this.pagination.current.getElement('a').get('href'));
		
		

	},

	startFx: function(){
		var self  = this;
		var els = this.slideshowContainer.getElements('.artical');
		var fx = new Fx.Elements(els, this.options.transition);

		var items = this.pagination.items;
		var next = this.pagination.nextPage;
		var current = this.pagination.current;

		var direction = items.indexOf(next) > items.indexOf(current) ? "left": "right";

		fx.addEvent('complete', function(){
			els[0].dispose();
			self.fireEvent('transitioncompleted');
		});

		if(direction == 'left') {
			fx.start({
				0: { left: -900},
				1: { left: 0}
			});
		} else {
			e.setStyle('left', -900);
			fx.start({
				0: { left: 900},
				1: { left: 0}
			});
		}
		self.fireEvent('transitionstarted');
	},

	setupSlideshow: $empty
});

var VariableHeightSlider = new Class({
	Extends: PageSlider,

	setupSlideshow: function(){
		var ct = this.slideshowContainer;
		var article = ct.getElement('.artical');

		var height = article.getDimensions().y;
		this.extraHeight = ct.getDimensions().y - height;

		ct.setStyles({
			'height': height,
			'position': 'relative',
			'overflow': 'hidden'
		});

		article.setStyle('position', 'absolute');

	},

	startFx: function(){
		var self = this;
		var els = this.slideshowContainer.getElements('.artical');
		var fx = new Fx.Elements($$(els, this.slideshowContainer), this.options.transition);

		var items = this.pagination.items;
		var next = this.pagination.nextPage;
		var current = this.pagination.current;

		var direction = items.indexOf(next) > items.indexOf(current) ? "left": "right";

		fx.addEvent('complete', function(){
			els[0].dispose();
			self.fireEvent('transitioncompleted');
		});

		var e = els[1];
		var height = e.getDimensions().y;

		if(direction == 'left') {
			fx.start({
				0: { left: -900},
				1: { left: 0},
				2: { height: height}
			});
		} else {
			e.setStyle('left', -900);
			fx.start({
				0: { left: 900},
				1: { left: 0},
				2: { height: height}
			});
		}
		
		self.fireEvent('transitionstarted');
	}
});

var Form = new Class({

	Implements: [Options],

	options: {
		classNormal: 'normal',
		classFocus: 'focus',
		classError: 'error'
	},

	elements: {},
	voptions: {},

	Regex: {
		email: /^[a-z0-9._%-]+@[a-z0-9.-]+\.[a-z]{2,4}$/i
	},

	initialize: function(el, options){
		this.setOptions(options);

		this.el = $(el).addEvent('submit', this.submit.bindWithEvent(this));

		this.els = this.el.getElements('input[type!=submit][type!=reset], textarea').filter(function(el){
			var title = el.get('title');

			el.addEvents({
				focus: this.focus.bind(this, el),
				blur: this.blur.bind(this, el)
			});

			if(!title) return false;

			this.elements[el.id] = el;
			this.voptions[el.id] = title.split(',').map(String.trim).map(String.toLowerCase);

			el.erase('title');

			return true;
		}, this);
	},

	submit: function(e){
		this.error = false;
		this.els.each(function(el){
			this.check(el);
		}, this);

		if(this.error){
			e.stop();
			return;	
		}

		var obj = {};

		this.el.getElements('input[type!=submit][type!=reset], textarea').each(function(el){
			obj[el.name] = el.get('value');
		});

		new Request.JSON({
			url: this.el.get('action'),
			onComplete: (function(j){
				if(!j || !j.msg) return;

				this.el.getElements('input[type=submit], input[type=reset], td.required').set('tween', {duration: 200}).fade(0);
				//this.el.set('tween', {duration: 200}).fade(0);

				// $('message_sent').getElement('div.contact_msg_'+j.msg).setStyle('display', 'block');

				$('message_sent').setStyles({
					opacity: 0,
					display: 'block'
				}).set('tween', {duration: 800}).fade(1);
			}).bind(this)
		}).post(obj);
	},

	focus: function(el){
		el.morph(el.get('tag')+'.'+this.options.classFocus);
	},

	blur: function(el){
		el.morph(el.get('tag')+'.'+this.options.classNormal);
	},

	check: function(el){
		var error = false,
			value = el.get('value');
		if(this.voptions[el.id].contains('required') && (!value || value.test(/^\s+$/))){
			error = true;
		}

		Hash.each(this.Regex, function(v, i){
			if(!this.voptions[el.id].contains(i)) return;

			if(!value.test(v)) error = true;
		}, this);

		el.set('value', value.trim());

		if(error){
			this.error = error;
			el.morph(el.get('tag')+'.'+this.options.classError);
		}
	},

	reset: function(){
		this.els.fireEvent('keydown');
		this.error = false;
		this.el.getElements('input[type!=submit][type!=reset], textarea').set('value', '');
	}
});

// DEFAULT FORM ELEMENT VALUE CLASS :: kassens
var InputText = new Class({

	initialize: function(element){
		this.element = element = $(element);
		this.text = element.value;
		element.store('inputText', this);
		element.addEvents({
			focus: (function(){
				if (element.value == this.text){
					var obs = element.retrieve('valueObserver', false);
					if(obs) obs.set('');
					else element.value = '';
					element.removeClass('default_text');
				}
			}).bind(this),
			blur: (function(){
				if (element.value == ''){
					var obs = element.retrieve('valueObserver', false);
					if(obs) obs.set(this.text);
					else element.value = this.text;
					element.addClass('default_text');
				}
			}).bind(this)
		});
	}
});


window.addEvent('domready', function(){
	if($('pagination'))
		var slider = new VariableHeightSlider($$('.columns_one.container')[0], {
			autoTransition: $$('.page_type_news').length == 1
		});
	
	// REMOVE DOTTED LINES FROM IE 'a' TAGS and FORM BUTTONS
	$$('#submitForm').addEvent('focus', function() {
		this.blur();
	});
	
	// GRAB ALL INPUTS AND USE DEFAULT TEXT 'text_replace' :: kassens
	$$('input.text_replace').each(function(input){
	    new FadeOverText(input);
	});
});
