/*****
 * Scripts, based on the mootools set
 * by Benjamin Mack (2009)
 */

/*****
 * overriding mootools, so the scripts are not stripped
 * after a request is finished, and so we can evaluate the script
 * right after the inclusion of the response in a value
 */
Request.prototype.processScripts = function(text) {
	if (this.options.evalResponse || (/(ecma|java)script/).test(this.getHeader('Content-type'))) return $exec(text);
	return text;
}


/*****
 * Teaser Slideshow
 */
var TeaserSlideshow = {
	slides: [],	// the sources to the images
	activeSlide: null,
	duration: 1000,
	delay: 5000,
	activeEffects: [],
	container: 'teaser',
	

	init: function() {
		this.activeSlide = null;
		this.stopActiveEffects();
		this.slides = this.cleanSlides(this.slides);

		// only a single image
		if (this.slides.length == 1) {
			$('teaser').set('html', '<img src="' + this.slides[0] + '" id="heroimage" width="1000" height="300" alt="" />');
		} else {
			var html = '';
			this.slides.each(function(img) {
				html += '<div id="heroimage_' + this.slides.indexOf(img) + '" style="display: none; position: absolute; opacity: 0;"><img src="' + img + '" width="1000" height="300" alt="" /></div>';
			}.bind(this));
			$('teaser').set('html', html);
			if (window.ie6) try {document.execCommand("BackgroundImageCache", false, true);} catch(e){};
			this.showNow(0);
			this.next.delay(this.delay, this);
		}
	},
	
	showNow: function(i) {
		if (this.activeSlide) {
			$(this.activeSlide).setStyles({ opacity: 0 });
		}
		$('heroimage_' + i).setStyles({
			opacity: 1,
			display: 'block'
		});
		this.activeSlide = $('heroimage_' + i);
	},

	next: function(i) {
		if (!i && i != 0) {
			var i = 0;
			if (this.activeSlide != null) {
				this.slides.each(function(sl) {
					if (this.activeSlide && $(this.activeSlide) && $(this.activeSlide).getFirst() && $(this.activeSlide).getFirst().get('src').contains(sl)) {
						i = this.slides.indexOf(sl)+1;
					}
				}.bind(this));
			}
		}
		this.stopActiveEffects();
		if (this.slides.length == i) { i = 0; }	// reset

		var nextSlide = $('heroimage_' + i);

			// fade out active slide
		if (this.activeSlide) {
			this.activeEffects.fadeOut = new Fx.Tween(this.activeSlide, {
				duration: this.duration,
				link: 'chain',
				transition: Fx.Transitions.Circ.easeOut
			});
			this.activeEffects.fadeOut.start('opacity', 0);
		}
			// fade in new slide
		if (nextSlide) {
			nextSlide.setStyles({
				display: 'block',
				opacity: 0
			});
			this.activeEffects.fadeIn = new Fx.Tween(nextSlide, {
				duration: this.duration,
				link: 'chain',
				transition: Fx.Transitions.Circ.easeOut
			});
			this.activeEffects.fadeIn.addEvent('onComplete', function() {
				this.activeSlide = nextSlide;
					// start next transition
				this.next.delay(this.delay, this);
			}.bind(this));
			this.activeEffects.fadeIn.start('opacity', 1);
		}
	},

	updateSlides: function(newSlides) {
		var slides = this.cleanSlides(newSlides);
		if (slides.length) {
			// see if the new slides are changed in any way
			var restartSlideshow = slides.every(function(item, index) {
				return !this.slides.contains(item);
			}.bind(this));
			
			if (restartSlideshow) {
				this.slides = slides;
				this.init();
			}
		}
	},
	
	// remove the empty slides
	cleanSlides: function(slides) {
		return slides.filter(function(slide) {
			return (slide != '');
		});
	},
	
	stopActiveEffects: function() {
		this.activeEffects.each(function(fx) {
			fx.cancel();
		});
	}
}
window.addEvent('domready', TeaserSlideshow.init.bind(TeaserSlideshow));


/*****
 * Accordion: Simple function to init the accordion
 *            for the navigation
 */
var WortAccordion = {
	instance: null,
	activePos: -1,

	init: function() {
		var togglers = $$('.firstnav');
		var elements = $$('.subnav');

		var i = 0;
		togglers.each(function(el) {
			if (el.getParent().hasClass('firstnav-initial-active')) {
				this.activePos = i;
			}
			i++;
		}.bind(this));
		
		this.instance = new Accordion(togglers, elements, {
			display: this.activePos,
			alwaysHide: true,
			onActive: function(toggler, element) {
				toggler.onmouseover();
				$(toggler).fireEvent('mouseover');
				$(toggler).accfunc = $(toggler).onmouseout;
				$(toggler).onmouseout = null;
			},
			onBackground: function(toggler, element) {
				if ($(toggler).onmouseout == null) {
					$(toggler).onmouseout = $(toggler).accfunc;
					$(toggler).onmouseout();
				}
			}
		});
	},
	
	closeAll: function() {
		this.open(-1);
	},
	
	open: function(pos) {
		if (this.instance && pos != this.activePos) {
			this.instance.display(pos);
			this.activePos = pos;
		}
	}
}
window.addEvent('domready', WortAccordion.init.bind(WortAccordion));


/*****
 * Client Scroller: Functions for having to scroll through
 *                 the list of client logos, only if it is loaded though
 */
var ImageScroller = {
	instance: null,
	speed: 4000,
	container: 'clients',

	init: function() {
		var container = $(this.container);
		if (container) {
			var images = $$('#clients-scroller-inner img');
			// middle align all images
			var maxHeight = container.getSize().y;
			images.each(function(el) {
				var height = el.getSize().y;
				el.setStyle('marginTop', Math.floor((maxHeight - height) / 2));
			});
			this.instance = new Fx.Scroll(container, {
				duration: this.speed * images.length,
				link: 'chain',
				transition: 'linear',
				wheelStops: false
			});
 			var scrollTo = $('clients-scroller-inner').getSize().x;
			this.instance.start(scrollTo, 0);
			this.instance.addEvent('chainComplete', function() {
				this.instance.set(-200, 0);
				this.init();
			}.bind(this));
		}
	},

	stop: function() {
		if (this.instance) {
			this.instance.cancel();
		}
	}
};
window.addEvent('load', ImageScroller.init.bind(ImageScroller));


/*******
 * AJAX/TYPO3: This object handles everything to navigate through
 *             the page with AJAX, instead of the real calls to the full page
 */
var AJAXHandler = {
	urlHistory: [],	// page visited before the current page
	clickHistory: [],	// link clicked to load this page
	
	init: function() {
		this.urlHistory.push(window.location.href);
		this.replaceContentLinks();
		var nav = $$('#mainnav a.active');
		if (nav.length) {
			this.clickHistory.push(nav[0]);
		}
	},

	replaceContentLinks: function() {
		$$('#body a').each(function(el) {
			if (el.getProperty('id') == 'backlink') {
				el.addEvent('click', function(ev) {
					AJAXHandler.loadPrevPage(this);
					ev.stop();
				});
			} else {
				var link = el.getProperty('href');
				var isAlreadyLinked = el.retrieve('ajax');
				var isValidLink = !el.hasClass('firstnav');
				isValidLink = true;
				var isExternalLink = (link && link.contains('://') && !link.contains(window.location.host));
				var isEmailLink    = (link && link.contains('javascript'));
				var isFileLink     = (link && link.contains('fileadmin/daten'));
				if (!isAlreadyLinked && isValidLink && !isExternalLink && !isEmailLink && !isFileLink) {
					el.addEvent('click', function(ev) {
						ev.stop();
						AJAXHandler.loadPage(this);
					});
					el.store('ajax', true);
				}
			}
		}.bind(this));
	},

	loadPage: function(el) {
		var link = el.getProperty('href');
		this.clickHistory.each(function(oldAnchor) {
			if ($(oldAnchor) && !link.contains($(oldAnchor).href)) {
				oldAnchor.removeClass('active');		
			}
		});
		if (el.hasClass('homepage')) {
			WortAccordion.closeAll();
		}
		el.addClass('active');
		this.clickHistory.push(el);
		this.urlHistory.push(link);
		this._loadContent(link);
	},


	loadPrevPage: function(el) {
		if (this.clickHistory.length) {
			// remove the page visiting now
			this.urlHistory.pop();
			this.clickHistory.pop();
			var link = this.urlHistory.getLast();
			if (this.clickHistory.length) {
				var lastAnchor = $(this.clickHistory.getLast());
				if (lastAnchor) {
					lastAnchor.addClass('active');
				}
			}
			this._loadContent(link);
		}
	},
	
	highlightNavigation: function(link) {
		$$('#mainnav a').each(function(el) {
			if (link.contains(el.getProperty('href'))) {
				el.addClass('active');
				// is on first level
				if (el.hasClass('firstnav')) {
					var li = el.getParent();
				} else {
					// find the number of which
					var li = el.getParent().getParent().getParent();
				}
				var pos = li.getAllPrevious('.subnav').length;
				WortAccordion.open(pos);
			} else {
				el.removeClass('active');			
			}
		});
	},

		// do the AJAX call
	_loadContent: function(link) {
		var rq = new Request({ url: link, method: 'get', evalResponse: false, evalScripts: false });

		// show spinner and remove the old content
		rq.addEvent('request', function() {
			$('content').empty();
			$('ajax-spinner').setStyle('opacity', '1');
			$('ajax-spinner').setStyle('display', 'block');
			ImageScroller.stop();
		});

		rq.addEvent('success', function(responseText, responseXML) {
			$('ajax-spinner').tween('opacity', 0);
			$('content').set('html', responseText);
			responseText.stripScripts(true);
			ImageScroller.init();
			AJAXHandler.replaceContentLinks();
		});

		rq.send('type=13');
		this.highlightNavigation(link);
	}
}

window.addEvent('domready', AJAXHandler.init.bind(AJAXHandler));


/*******
 * Form: Check for default values in a form
 *       and submit it with an AJAX call
 */
var ContactForm = {
	formEl: null,
	messageEl: 'form-message',
	requiredText: null,
	requiredFields: [],

	// initialize the form
	init: function(formId, requiredFields) {
		this.requiredFields = requiredFields;
		this.formEl = $(formId);
		this.formEl.addEvent('submit', function(ev) {
			if (ContactForm.requiredFieldsFilled()) {
				if (ContactForm.fieldIsEmpty('tipafriendComment')) {
					$('tipafriendComment').value = '';
				}
				if (ContactForm.fieldIsEmpty('company')) {
					$('company').value = '';
				}
				var str = ContactForm.formEl.toQueryString();
				var rq = new Request({ url: ContactForm.formEl.getProperty('action'), method: 'post' });
				rq.addEvent('success', function(responseText) {
					$(ContactForm.messageEl).set('html', responseText);
				});
				rq.send(str);
			}
			ev.stop();
		});
		this.requiredText = $(this.messageEl).get('text');
		$(this.messageEl).set('text', '');
	},

	// setup a field by storing the default value
	setupField: function(field, value, defaultValue) {
		var el = $(field);
		el.store('defaultValue', defaultValue);
		ContactForm.checkValue(el, value);
		el.addEvent('focus', function() {
			if (el.hasClass('disabled')) {
				el.value = '';
				el.removeClass('disabled');
			}
		});
		el.addEvent('blur', function() {
			ContactForm.checkValue(el, el.value);
		});
	},

	// check if the value is a default value and then set the class and function
	checkValue: function(el, value) {
		if (value != '') {
			el.value = value;
		} else {
			el.value = el.retrieve('defaultValue');
			el.addClass('disabled');
		}
	},
	
	// check if the current value is empty or it's the default value
	fieldIsEmpty: function(field) {
		var el = $(field);
		if (el) {
			return (el.value == el.retrieve('defaultValue') || el.value == '');
		} else {
			return false;
		}
	},

	// see if all required fields are filled out
	requiredFieldsFilled: function() {
		var allFieldsFilled = true;
		this.requiredFields.each(function(el) {
			if (this.isDefaultValue(el)) {
				allFieldsFilled = false;
			}
		}.bind(this));
		if (allFieldsFilled) {
			$(this.messageEl).set('html', '');
		} else {
			$(this.messageEl).set('html', this.requiredText);
		}
		return allFieldsFilled;
	},

	// see if the value of a field is the default value
	isDefaultValue: function(field) {
		return ($(field).value == $(field).retrieve('defaultValue'));
	}
};

