/**
 * @author tfuhlroth maxomedia - agentur für crossmedia-kommunikation bsw
 * @version 1.0 (12.01.2008)
 */

if (window['console'] === undefined) window.console = { log: $empty };
var ERAW = {};


/* -------------------------------------------------- */
/* =welcome */
 
ERAW.welcome = {
	
	init: function () {
		this.container = $('welcome-container');
		this.screenBlocker = new ScreenBlocker({
			fadeIn: true
		});
		this.screenBlocker.addEvent('show', this.showMessage.bind(this));
		this.show();
	},
	
	show: function () {
		this.screenBlocker.show();
	},
	
	showMessage: function () {
		this.container.setStyle('display', 'block');
	},
	
	hide: function () {
		this.container.setStyle('display', 'none');
		this.screenBlocker.hide();
	}
	
};


/* -------------------------------------------------- */
/* =popup */

ERAW.popup = {
	
	init: function () {
		$$('.popup').forEach(function (anchor) {
			anchor.addEvent('click', this.launch.bindWithEvent(this, anchor));
		}, this);
	},
	
	launch: function (event, anchor, width, height) {
		event.stop();
		window.open(anchor.href, 'sbbpopup', 'width=' + (width || 680) + ',height=' + (height || 490) + ',toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1');
	}
	
};
window.addEvent('domready', function () {
	ERAW.popup.init();
});


/* -------------------------------------------------- */
/* =gruppen-tool */

window.addEvent('domready', function () {
	if ($('gruppentool-launch')) {
		$('gruppentool-launch').addEvent('click', function (event) {
			ERAW.popup.launch(event, this, 820, 700);
		});
	}
});

var GT = {
    showProcessingInfo: function() {
        $$('select').setStyle('visibility', 'hidden');
        var overlay = $('processing-info-overlay');
        var container = $('processing-info-container');
        var windowScrollHeight = window.getScrollHeight();
        var windowHeight = window.getHeight();
        var scrollTop = window.getScrollTop();
        overlay.setStyles({
            'height': windowScrollHeight,
            'opacity': 0.3,
            'display': 'block'
        });
        container.setStyles({
            'margin-top': scrollTop + (windowHeight / 2 - 75),
            'display': 'block'
        });
    },
    hideProcessingInfo: function() {
        $$('select').setStyle('visibility', 'visible');
        var overlay = $('processing-info-overlay');
        var container = $('processing-info-container');
        overlay.setStyles('display', 'none');
        container.setStyle('display', 'none');
    },
    openPopUp: function(href) {
        var popup = window.open(href, 'popup', 'width=650, height=600');
        popup.focus();
    }
};

/* -------------------------------------------------- */
/* =Dict */

var Dict = new Class({
	
	Implements: Events,
	
	initialize: function (dictJSON) {
		this.items = new Hash(dictJSON);
		this.fireEvent('complete');
	},
	
	get: function (key) {
		return (this.items.has(key)) ? this.items.get(key) : '[' + key + ']';
	}
	
});


Dict.Remote = new Class({
	
	Extends: Dict,
	
	initialize: function (serviceurl) {
		new Request({
			url: serviceurl,
			async: false,
			onSuccess: this.parse.bind(this)
		}).send();
	},
	
	parse: function (responseText, responseXML) {
		this.items = new Hash();
		var items = responseXML.getElementsByTagName('item');
		for (var i = 0, len = items.length; i < len; i++) {
			this.items.include(items[i].getAttribute('key'), this.getNodeValue(items[i]));
		}
	},
	
	getNodeValue: function (node) {
		if (node.textContent) return node.textContent;
		else if (node.nodeValue) return node.nodeValue;
		else if (node.text) return node.text;
	}
	
});

ERAW.dict = new Dict.Remote('/DictionaryGet.ashx');


/* -------------------------------------------------- */
/* =Sidenav */

var Sidenav = new Class({
	
	initialize: function (container) {
		this.container = $(container);
		this.anchors = this.container.getElements('a').filter(function (anchor) {
			return (anchor.getNext('ul'))
		}, this);
		this.anchors.forEach(function (anchor) {
			if (!anchor.hasClass('active')) {
				anchor.getNext('ul').setStyle('display', 'none');
				anchor.store('isOpen', false);
			} else {
				anchor.store('isOpen', true);
			}
			anchor.addEvent('click', this.toggle.pass(anchor, this));
		}, this);
	},
	
	toggle: function (anchor) {
		if (anchor.retrieve('isOpen')) {
			anchor.store('isOpen', false);
			anchor.getNext('ul').setStyle('display', 'none');
		} else {
			anchor.store('isOpen', true);
			anchor.getNext('ul').setStyle('display', 'block');
		}
		
	}
	
});


/* -------------------------------------------------- */
/* =CustomSelect */

var CustomSelect = new Class({
	
	Implements: [Options, Events],
	
	options: {
		zIndex: 500,
		zIndexActive: 1000
	},
	
	initialize: function (selectElement) {
		this.selectElement = $(selectElement);	
		this.selectOptions = this.selectElement.getElements('option');
		if (!this.selectOptions.length) return false;
		this.bound = {
			hideOptions: this.hideOptions.bind(this)	
		};
		this.build();
		this.populateOptions();
		this.selectedIndex = 0;
		this.setValue(this.selectedIndex);
		this.selectElement.setStyle('display', 'none');
	},
	
	build: function () {
		this.element = new Element('div', {
			'class': 'custom-select',
			'styles': {
				'z-index': this.options.zIndex
			}
		})
		this.header = new Element('div', {
			events: {
				click: this.toggleOptions.bind(this)
			}	
		}).inject(this.element);
		this.display = new Element('span').inject(this.header);
		this.list = new Element('ul').inject(this.element);
		this.element.inject(this.selectElement, 'after');
	},
	
	populateOptions: function () {
		this.items = [];
		this.selectOptions.forEach(function (option, index) {
			this.items.push(new Element('li', {
				text: option.get('text'),
				events: {
					click: this.setValue.pass(index, this)
				}
			}).inject(this.list));
		}, this);
	},
	
	setValue: function (index) {
		this.selectedIndex = index;
		var option = this.selectOptions[this.selectedIndex];
		var currentValue = this.selectElement.get('value');
		if (currentValue != option.get('value')) {
			this.selectElement.set('value', option.get('value'));
			this.selectElement.fireEvent('change');
			this.fireEvent('change');
		}
		this.display.set('text', option.get('text'));
		this.fireEvent('set');
		this.hideOptions();
	},
	
	showOptions: function () {
		this.element.setStyle('z-index', this.options.zIndexActive);
		this.list.setStyle('display', 'block');
		(function () {
			$(document.body).addEvent('click', this.bound.hideOptions);
		}).delay(10, this);
		this.fireEvent('show');
	},
	
	hideOptions: function () {
		this.element.setStyle('z-index', this.options.zIndex);
		this.list.setStyle('display', 'none');
		$(document.body).removeEvent('click', this.bound.hideOptions);
		this.fireEvent('hide');
	},
	
	toggleOptions: function () {
		(this.list.getStyle('display') === 'none') ? this.showOptions() : this.hideOptions();
	}
	
});

/*
window.addEvent('domready', function () {
	$('group-1').addEvent('change', function () {
		//console.log('group-1: ' + $('group-1').get('value'));
	});
	var customSelect = new CustomSelect('group-1');
	var plateWrapper = $('group-1').getParent('.plate-wrapper');
	customSelect.addEvent('show', function () {
		plateWrapper.addClass('plate-active');
	});
	customSelect.addEvent('hide', function () {
		plateWrapper.removeClass('plate-active');
	});
	new CustomSelect('group-2');
	new CustomSelect('group-3');
	new CustomSelect('group-5');
	new CustomSelect('group-6');
});
*/


/* -------------------------------------------------- */
/* =ScreenBlocker */

var ScreenBlocker = new Class({
	
	Implements: [Options, Events],
	
	options: {
		backgroundColor: '#000',
		opacity: 0.7,
		zIndex: 1000,
		fadeIn: false,
		link: 'cancel',
		transition: 'sine:out',
		duration: 500
	},
	
	initialize: function (options) {
		this.setOptions(options);
		this.bound = {
			adjustSize: this.adjustSize.bind(this),
			adjustPosition: this.adjustPosition.bind(this)
		};
		this.build();
	},
	
	build: function () {
		this.element = new Element('div', {
			styles: {
				'display': 'none',
				'position': 'absolute',
				'left': 0,
				'top': 0,
				'background-color': this.options.backgroundColor,
				'opacity': (this.options.fadeIn) ? 0 : this.options.opacity,
				'z-index': this.options.zIndex
			}
		}).inject(document.body);
		if (this.options.fadeIn) {
			this.fx = new Fx.Tween(this.element, {
				property: 'opacity',
				link: this.options.link,
				transition: this.options.transition,
				duration: this.options.duration
			});
		}
	},
	
	attachEvents: function () {
		window.addEvent('resize', this.bound.adjustSize);
		window.addEvent('scroll', this.bound.adjustPosition);
	},
	
	detachEvents: function () {
		window.removeEvent('resize', this.bound.adjustSize);
		window.removeEvent('scroll', this.bound.adjustPosition);
	},
	
	show: function () {
		this.attachEvents();
		this.adjustSize();
		this.adjustPosition();
		if (this.options.fadeIn) {
			this.element.setStyle('display', 'block');
			this.fx.start(this.options.opacity).chain(function () {
				this.fireEvent('show');
			}.bind(this));
		} else {
			this.toggleDisplayMode();
			this.fireEvent('show');
		}
	},
	
	hide: function () {
		this.detachEvents();
		if (this.options.fadeIn) {
			this.fx.start(0).chain(function () {
				this.element.setStyle('display', 'none');
				this.fireEvent('hide');
			}.bind(this));
		} else {
			this.toggleDisplayMode();
			this.fireEvent('hide');
		}
	},
		
	toggleDisplayMode: function () {
		this.element.setStyle('display', (this.element.getStyle('display') === 'none') ? 'block' : 'none');
	},
	
	adjustSize: function () {
		var windowSize = window.getSize();
		this.element.setStyles({
			width: windowSize.x,
			height: windowSize.y
		});
	},
	
	adjustPosition: function () {
		var windowScroll = window.getScroll();
		this.element.setStyles({
			left: windowScroll.x,
			top: windowScroll.y
		});
	}
	
});


/* -------------------------------------------------- */
/* =Slider */

var Slider = new Class({
	
	Implements: [Options, Events],
	
	options: {
		itemMargin: {x: 0, y: 0},
		itemsPerView: {x: 1, y: 1},
		link: 'cancel',
		transition: 'sine:out',
		duration: 500,
		levelDuration: false
	},
	
	settings: {
		
	},
	
	initialize: function (items, options) {
		this.items = $$(items);
		if (!this.items.length) return false;
		this.setOptions(options);
		
		this.currentIndex = 0;
		this.settings.itemSize = this.options.itemSize || this.measureItemSize();
		this.element = this.items[0].getParent();
		this.viewport = this.element.getParent();
		
		this.viewport.setStyles({
			position: 'relative',
			left: 0,
			top: 0,
			width: ((this.settings.itemSize.x + this.options.itemMargin.x) * this.options.itemsPerView.x) - this.options.itemMargin.x,
			height: ((this.settings.itemSize.y + this.options.itemMargin.y) * this.options.itemsPerView.y) - this.options.itemMargin.y,
			overflow : 'hidden'
		});
		
		this.element.setStyles({
			position: 'absolute',
			left: 0,
			top : 0,
			width: (this.settings.itemSize.x + this.options.itemMargin.x) * ((this.options.direction === 'horizontal') ? Math.ceil(this.items.length / this.options.itemsPerView.y) : this.options.itemsPerView.x)
		});
		
		this.fx = new Fx.Tween(this.element, {property: (this.options.direction === 'horizontal') ? 'left' : 'top', link: this.options.link, transition: this.options.transition, duration: this.options.duration});
	},
	
	measureItemSize: function () {
		var itemSize = {x: 0, y: 0};
		this.items.forEach(function (item) {
			var size = item.getSize();
			if (size.x > itemSize.x) itemSize.x = size.x;
			if (size.y > itemSize.y) itemSize.y = size.y;
		}, this);
		return itemSize;
	},
		
	prevItem: function () {
		this.setItem(this.currentIndex - 1);
	},
	
	nextItem: function () {
		this.setItem(this.currentIndex + 1);
	},
		
	prevView: function () {
		this.setItem(this.constrainIndex(this.currentIndex - this.options.itemsPerView.x));
	},
	
	nextView: function () {
		this.setItem(this.constrainIndex(this.currentIndex + this.options.itemsPerView.x));
	},
		
	isValidIndex: function (index) {
		return (index >= 0 && index < this.items.length);
	}
	
});


Slider.Horizontal = new Class({
	
	Extends: Slider,
	
	options: {
		direction: 'horizontal'
	},
	
	initialize: function (items, options) {
		this.parent(items, options);
	},
	
	setItem: function (itemIndex) {
		if (!this.isValidIndex(itemIndex)) return false;
		
		var renderIndex = this.constrainIndex(itemIndex);
		
		if (this.options.levelDuration) {
			var diff = Math.abs(this.currentIndex - renderIndex);
			var durationPerItem = Math.round(this.options.duration / this.options.itemsPerView.x);
			this.fx.options.duration = durationPerItem * diff;
		}
		
		this.currentIndex = itemIndex;
		
		var itemsPerRow = Math.ceil(this.items.length / this.options.itemsPerView.y);		
		var row = Math.floor(renderIndex / itemsPerRow) + 1;		
		var pos = itemsPerRow - (itemsPerRow * row - renderIndex);
		
		this.fx.start(-((this.settings.itemSize.x + this.options.itemMargin.x) * pos));
	},
	
	setView: function (viewIndex) {
		var itemIndex = viewIndex * this.options.itemsPerView.x;
		var itemsPerRow = Math.ceil(this.items.length / this.options.itemsPerView.y);		
		var row = Math.floor(itemIndex / itemsPerRow) + 1;
		if (row != 1) return false;
		this.setItem(itemIndex);
	},
	
	
	constrainIndex: function (itemIndex) {		
		if (itemIndex < 0) itemIndex = 0;
		var itemsPerRow = Math.ceil(this.items.length / this.options.itemsPerView.y);		
		var row = Math.floor(itemIndex / itemsPerRow) + 1;
		
		if (itemIndex >= itemsPerRow * row - this.options.itemsPerView.x) {
			itemIndex = itemsPerRow * row - this.options.itemsPerView.x;
		}
		
		return itemIndex;
	}
	
});


Slider.Vertical = new Class({
	
	Extends: Slider,
	
	options: {
		direction: 'vertical'
	},
	
	initialize: function (items, options) {
		this.parent(items, options);
	},
	
	setItem: function (itemIndex) {
		console.log('setItem');
		if (!this.isValidIndex(itemIndex)) return false;
		
		var renderIndex = this.constrainIndex(itemIndex);
		
		var newRow = Math.floor(renderIndex / this.options.itemsPerView.x);
		if (this.options.levelDuration) {
			var currentRow = Math.floor(this.currentIndex / this.options.itemsPerView.x);
			var diff = Math.abs(currentRow - newRow);
			var durationPerRow = Math.round(this.options.duration / this.options.itemsPerView.y);
			this.fx.options.duration = durationPerRow * diff;
		}
		
		this.currentIndex = itemIndex;
		this.fx.start(-((this.settings.itemSize.y + this.options.itemMargin.y) * newRow));
	},
	
	setView: function (viewIndex) {
		var itemIndex = (viewIndex * this.options.itemsPerView.x) * this.options.itemsPerView.y;
		this.setItem(itemIndex);
	},
	
	constrainIndex: function (itemIndex) {
		var offcut = this.items.length % this.options.itemsPerView.x;
		var max = this.items.length - (this.options.itemsPerView.x * this.options.itemsPerView.y - offcut);
		return itemIndex.limit(0, max);
	}
	
});


var TeaserSlider = new Class({
	
	Implements: Options,
	
	options: {
		direction: 'vertical'
	},
	
	initialize: function (container, options, sliderOptions) {
		this.container = $(container);
		this.setOptions(options);
		this.slider = (this.options.direction === 'vertical') ? new Slider.Vertical(this.container.getElements('.col'), sliderOptions) : new Slider.Horizontal(this.container.getElements('.col'), sliderOptions);
		if (!this.slider.items.length || this.slider.items.length <= this.slider.options.itemsPerView.x) return false;
		this.nav = new Element('span').inject(this.container.getElement('.h2_pagenav'), 'top');
		this.buttons = [];
		Math.floor(this.slider.items.length / (this.slider.options.itemsPerView.x * this.slider.options.itemsPerView.y)).times(function (viewIndex) {
			this.buttons.push(new Element('a', {
				text: viewIndex + 1,
				events: {
					click: this.set.pass(viewIndex, this)
				}
			}).inject(this.nav));
		}, this);
		this.currentIndex = 0;
		this.set(this.currentIndex);
	},
	
	set: function (viewIndex) {
		this.slider.setView(viewIndex);
		this.buttons[this.currentIndex].removeClass('active');
		this.currentIndex = viewIndex;
		this.buttons[this.currentIndex].addClass('active');
	}
	
});

/*
var slider, slider2;
window.addEvent('domready', function () {
	
	slider = new TeaserSlider('tipps', {}, {
		itemMargin: {x: 10, y: 0},
		itemsPerView: {x: 4, y: 1},
		duration: 750,
		transition: 'back:out'
	});
	
	slider2 = new TeaserSlider('favourites', {}, {
		itemMargin: {x: 10, y: 0},
		itemsPerView: {x: 4, y: 1},
		duration: 750,
		transition: 'back:out'
	});
	
});
*/


/* -------------------------------------------------- */
/* =BrokenAccordion */

var BrokenAccordion = new Class({
	
	Extends: Accordion,
	
	display: function(index){
		index = ($type(index) == 'element') ? this.elements.indexOf(index) : index;
		if ((this.timer && this.options.wait) || (index === this.previous && !this.options.alwaysHide)) return this;
		this.previous = index;
		var obj = {};
		this.elements.each(function(el, i){
			obj[i] = {};
			var hide = (i != index) || (this.options.alwaysHide && (el.offsetHeight > 0));
			this.fireEvent(hide ? 'background' : 'active', [this.togglers[i], el]);
			//for (var fx in this.effects) obj[i][fx] = hide ? 0 : el[this.effects[fx]];
			for (var fx in this.effects) {
				if (i == index) {
					obj[i][fx] = hide ? 0 : el[this.effects[fx]];
					this.togglers[i].toggleClass('arrow-white-up');
				}
			}
		}, this);
		return this.start(obj);
	},
	
	expand: function () {
		var indices = $A(arguments).flatten();
		if (indices.length) {
			indices.forEach(this.open, this);
		} else {
			this.elements.each(function(el, i) {
				this.open(i);
			}, this);
		}
	},
	
	open: function(index){
		index = ($type(index) == 'element') ? this.elements.indexOf(index) : index;
		if ((this.timer && this.options.wait) || (index === this.previous && !this.options.alwaysHide)) return this;
		this.previous = index;
		var obj = {};
		this.elements.each(function(el, i){
			obj[i] = {};
			var hide = (i != index) || (this.options.alwaysHide && (el.offsetHeight > 0));
			this.fireEvent(hide ? 'background' : 'active', [this.togglers[i], el]);
			//for (var fx in this.effects) obj[i][fx] = hide ? 0 : el[this.effects[fx]];
			for (var fx in this.effects) {
				if (i == index) {
					obj[i][fx] = hide ? 0 : el[this.effects[fx]];
					this.togglers[i].toggleClass('arrow-white-up');
				}
			}
		}, this);
		return this.set(obj);
	}
	
});


/* -------------------------------------------------- */
/* =SearchResultMarker */

Element.implement({
 
	highlightTerm: function(search, insensitive, klass){
		var regex = new RegExp('(<[^>]*>)|(' + search.escapeRegExp() +')', insensitive ? 'ig' : 'g');
		return this.set('html', this.get('html').replace(regex, function(a, b, c){
			return (a.charAt(0) == '<') ? a : '<span class="'+ klass +'">' + c + '</span>'; 
		}));
	}
 
});

var SearchResultMarker = new Class({
	
	initialize: function (container, terms) {
		this.container = $(container);
		this.terms = ($type(terms) == 'array') ? terms.flatten() : [terms];
		this.terms.forEach(function (term) {
			this.container.highlightTerm(term, true, 'search-result-highlight');
		}, this);
	}
		
});


/* -------------------------------------------------- */
/* =timetable */

var TimetableAccordion = new Class({
	
	Extends: Accordion,
	
	display: function(index){
		index = ($type(index) == 'element') ? this.elements.indexOf(index) : index;
		if ((this.timer && this.options.wait) || (index === this.previous && !this.options.alwaysHide)) return this;
		this.previous = index;
		var obj = {};
		this.elements.each(function(el, i){
			obj[i] = {};
			var hide = (i != index) || (this.options.alwaysHide && (el.offsetHeight > 0));
			this.fireEvent(hide ? 'background' : 'active', [this.togglers[i], el]);
			//for (var fx in this.effects) obj[i][fx] = hide ? 0 : el[this.effects[fx]];
			for (var fx in this.effects) {
				if (i == index) {
					obj[i][fx] = hide ? 0 : el[this.effects[fx]];
					//this.togglers[i].getParent().toggleClass('collapse');
				}
			}
		}, this);
		//(this.togglers[index].getParent().hasClass('collapse')) ? this.togglers[index].getParent().removeClass('collapse') : this.togglers[index].getParent().addClass('collapse');
		this.togglers[index].getParent().toggleClass('collapse');
		return this.start(obj);
	}
	
});

/* -------------------------------------------------- */
/* =misc */

/*
<script type="text/javascript">
	window.addEvent('domready', function () {
		$('agb-trigger').setStyle('cursor', 'pointer');
		new Accordion([$('agb-trigger')], [$('agb-content')], {show: -1, opacity: false, alwaysHide: true});
	});
</script>
*/