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

	initialize: function(element){
		this.element = element = $(element);
		this.text = element.value;
		element.addEvents({
			focus: (function(){
				if (element.value == this.text){
					element.value = '';
					element.removeClass('default_text');
				}
			}).bind(this),
			blur: (function(){
				if (element.value == ''){
					element.value = this.text;
					element.addClass('default_text');
				}
			}).bind(this)
		});
	}
});

// OBSERVER CLASS :: JanK
var Observer = new Class({
	
	Implements: [Options, Events],
	
	options: {
		interval: 100,
		duration: 0
	},

	initialize: function(element, property, options){
		this.setOptions(options);
		this.element = $(element);
		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 == 'Suchen') 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);
	}
	
});

Element.Events.observedChange = {
	
	onAdd: function(fn){
		new Observer(this, 'value', {onChange: fn});
	}

};

// LIVE SEARCH :: JanK
function liveSearch(){
	var selected = null;
	var search = $('search_input');
	if (!(results = $('search_results'))) return;
	var resultWrapper = results.getParent().set('tween', {duration: 250}).fade('hide');
	var request = new Request({
		url: 'suche',
		link: 'cancel',
		onRequest: function(){
			search.addClass('search_loading');
		},
		onSuccess: function(html){
			results.set('html', html);
			resultWrapper.fade(.9);
			selected = results.getElement('li').addClass('search_entry_selected');
			results.getElements('a.boxed').addEvent('click', select);
		},
		onComplete: function(){
			search.removeClass('search_loading');
		}
	});
	var hideResults = function(){
		resultWrapper.fade('out');
		request.cancel();
		search.removeClass('search_loading');
		selected = null;
	};
	function move(direction){
		if(!selected) return;
		var other;
		switch ($type(direction)) {
			case 'event':
				other = $(direction.target);
				if (!other.match('li.search_result')) other = other.getParent('li.search_result');
				break;
			case 'string':
				other = selected[(direction == 'up') ? 'getPrevious' : 'getNext']('li.search_result');
		}
		if (!other) return;
		selected.removeClass('search_entry_selected');
		other.addClass('search_entry_selected');
		selected = other;
	}
	function select(e){
		var el;
		if (e){
			el = e.stop().target;
			if (el.get('tag') != 'a') el = el.getParent('a');
		} else if (!selected) return;
		else el = selected.getElement('a');
		if (el.hasClass('boxed')) FilmBox.fromElement(el);
		window.location.href = el.get('href');
		hideResults();
	}
	document.addEvent('click', function(e){
		if (!$(e.target).getParent('div.search_menu_container')) hideResults();
	});
	search.addEvents({
		observedChange: function(value){
			if (value.length > 2) request.post({search: value});
			else hideResults();
		},
		keydown: function(event){
			switch(event.key){
				case 'esc': hideResults();
					break;
				case 'up': case 'down':
					move(event.key);
					break;
				case 'enter':
					select();
			}
		}
	});
	resultWrapper.addEvent('mouseover', move);
}
window.addEvent('domready', liveSearch);

// SimpleSlideShow CLASS :: JanK_
var SimpleSlideShow = new Class({
	
	Implements: Options,
	
	options: {
		fadeTime: 1000,
		stayTime: 4000
	},
	
	initialize: function(wrapper, images, options) {
		this.setOptions(options);
		this.wrapper = $('main_image');
		this.images = images.map(function(image){
			return new Element('img', {
				src: image, width: '100%', height: '100%',
				tween: {duration: this.options.fadeTime}
			});
		}, this);
		this.index = 0;
		this.topImage = this.images[0].inject(this.wrapper);
		this.fade.periodical(this.options.stayTime + this.options.fadeTime, this);
	},
	
	fade: function() {
		this.index = (this.index + 1) % this.images.length;
		this.bottomImage = this.topImage;
		this.topImage = this.images[this.index]
			.fade('hide')
			.inject(this.wrapper)
			.fade('in');
	}

});

// window.addEvent('load', function() {
// 	$$('img').tween('opacity', 1);
// 	$('side_menu').tween('opacity', 1);
// });
// 
// window.addEvent('domready', function() {
// 	
// 	var img = $$('img').setStyle('opacity', 0).set('tween', {duration: 1000});

// // FADE IN IMAGES :: nfq
// window.addEvent('load', function() {
// 	var img = $$('img').set('opacity', 0);
// 		img.set('tween', {duration: 1000}).fade('in');
// });

window.addEvent('domready', function() {
	
	// var img = $$('img').setStyle('opacity', 0).set('tween', {duration: 1000});
	// 	var menu = $('side_menu').setStyle('opacity', 0).set('tween', {duration: 100});

	var projectNav = $E('ul.project_nav');
	if (projectNav) projectNav.scrollTo(0, projectNav.getElement('li.active').getPosition(projectNav).y - 10);

	// CONTENT LOAD PAGE FADE IN :: nfq
	// var content = $$('.content_container').set('opacity', 0);
	// 		content.set('tween', {duration: 1000}).fade('in');

	//SIDE MENU ACCODRION :: nfq, JanK
	var togglers = $$('a.menu_toggler').addEvent('click', $lambda(false));
	var active = togglers.indexOf((togglers.filterBy('.active') || [null])[0]);
	var side_menu = new Accordion(togglers, 'ul.menu_expanded', {
		opacity: false,
		duration: 300,
		show: active,
		alwaysHide: true
	}, $('side_menu'));

	// GRAB ALL INPUTS AND USE DEFAULT TEXT 'text_replace' :: JanK
	$$('input.search, input.search_loading').each(function(input){
	    new InputText(input);
	});

	// INITIALIZE TheBox :: digitarald, JanK, Rendez
	$$('a.boxed').each(function(el) {
		el.addEvent('click', function(e) {
			TheBox.fromElement(el);
			if (this.id == 'reservation_form') {
				TheBox.addEvent('onUpdate', function() {
					if (bt = $('submitter')) {
						bt.addEvent('click', function(e) {
							new Event(e).stop();
							reservationValidates();
						});
					}
				});
			}
			return false;
		});
	});
	
	// RESERVATION FORM :: Rendez
	function reservationValidates() {
		var numErrors = 0,
			counter   = 0,
			fields    = ['fe_ansprecherson', 'fe_strasse', 'fe_plz', 'fe_ort', 'fe_telefon', 'fe_email', 'fe_datum'],
			types     = ['empty', 'empty', 'empty', 'empty', 'phone', 'email', 'empty'],
			matches   = {
				'empty': function(str) {
					return (str.length > 0) ? true : false;
				},
				'email': function(str) {
					return str.test(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i);
				},
				'phone': function(str) {
					return str.test(/^([+]?[\d\ ]{7,})$/);
				}
			},
			errorDiv = new Element('div', {'class': 'error_msg'}).set('html', 'Ihre Eingabe ist unvollständig. Bitte füllen Sie alle Pflichtfelder aus. Danke!');
		
		while(counter < fields.length) {
			input = $(fields[counter]).value;
			if (!matches[types[counter]](input)) {
				numErrors++;
				$E('label[for=' + fields[counter] + ']').setStyle('color', '#933');
				$(fields[counter]).setStyles({'border-color': '#933', 'background-color': '#933', 'color': '#fff'});
			} else {
				$E('label[for=' + fields[counter] + ']').setStyle('color', '#333');
				$(fields[counter]).setStyles({'border-color': '#999', 'background-color': '#f5f5f5', 'color': ''});
			}
			counter++;
		}
		
		if (numErrors == 0) {
			return reservationSend();
		} else {
			if (!$E('#form_baseline div.error_msg')) $('form_baseline').grab(errorDiv, 'bottom');
			errorDiv = null;
		}
	}
	
	function reservationSend() {
		el = $('sendform');
		el.send();
		el.get('send').addEvent('onSuccess', function(resp){
			if (resp != 'failure') {
				var content = new Element('p', {
					styles: {
						'padding': '0 27px',
						'line-height': '460px',
						'color': '#933',
						'font-size': '14px',
						'text-align': 'center'
					}
				}).set('html', resp);
				$('the_box_content').empty().adopt(content);
			} else {
				alert('There was an error. Please try again later.');
			}
		});
	}
	
	// IMAGES ARRAY, SimpleSlideShow:: JanK_
	// new SimpleSlideShow('main_image', ['uploads/verschieden/bild_startseite1.jpg', 'uploads/verschieden/bild_startseite2.jpg', 'uploads/verschieden/bild_startseite3.jpg']);

});
