$(window).addEvent('domready', function() {
	Info = new Hash({
		'element': {
			'overlay': $('overlay'),
			'overlayClose': $('overlay_close'),
			'overlayContent': $('overlay_content'),
			'overlayBackground': $('overlay_background'),
			'backgroundContentContainer': $('content'),
			//'backgroundContent': $(document.body).getElement('.mod_article'),
			'backgroundContent': $('main_inner'),
			'backgroundContentPagination': $('background_content_pagination'),
			'mainNavigation': $('nav_main'),
			'leftColumn': $('top')
		},
		'size': {
			'viewport': {},
			'windowScroll': {},
			'leftCol': {
				'x': 340
			},
			'overlay': {},
			'content': {},
			'top': {},
			'overlayMarginBottom': 60
		},
		'overlay': {
			'layouts': ['layout1', 'layout2', 'layout3']
		},
		'backgroundContent': {
			'minValues': {
				'cols': 3,
				'rows': 2
			},
			'maxValues': {
				'cols': 99999,
				'rows': 99999
			},
			'elementSize': {
				'x': 210,
				'y': 191
			},
			'showDelay': 15
		},
		'misc': {
			'leftColumnUrl': 'left.html',
			'logoutUrl': 'logout.html',
			'standardBackgroundContentUrl': '/startseite/',
			'standardLayout': 'layout3',
			'xhrMethod': 'post',
			'NavigationHideDelay': 1000,
			'pageTitlePrefix': 'EntryStandardNews - ',
			'facebookLoginUrl': 'facebook-connect.html',
			'facebookApiKey': '699df99c017d9ebb79c8e2ae064363b6'
		}
	});
	
	PageUrl = new Hash();
	pageTitle = new Hash();
	regeneratePageUrl();
	
	OverlayObj = new Overlay();
	XHRContentObj = new XHRContent();
	XHRRequestObj = new XHRRequest();
	NewsXTObj = new NewsXT();
	CallbackObj = new Callback();
	
	initPageContent();
	
	initEvents();
});

var Callback = new Class({
	'exec': function(callback, args) {
		switch(callback) {
			case '1': this.callbacks.cb1.run(args); break;
			case '2': break;
			case '3': this.callbacks.cb3.run(args); break;
			case '4': this.callbacks.cb4.run(args); break;
			case '5': this.callbacks.cb5.run(args); break;
		}
	},
	'callbacks': {
		'cb1': cb_closeOverlayReloadLeftColumn,
		'cb3': cb_reloadOverlay,
		'cb4': cb_reload,
		'cb5': cb_json
	}
});

function calculateSizes() {
	Info.size.viewport = $(window).getSize();
	Info.size.windowScroll = $(window).getScrollSize();
	Info.size.overlay = $('overlay').getComputedSize();
	Info.size.content = $('content').getComputedSize();
	Info.size.top = $('top').getComputedSize();
}

function applyEvents(area) {
	if(!area) {
		area = $(document.body);
	}
	area.getElements('a.xhr').removeEvents('click').addEvent('click', function(event) {
		event.stop();
		var url = this.href.toURI();
		XHRContentObj.get(this.href, url.getData('layout'), url.getData('area'), null, null, url.getData('cb'));
	});
	
	backgroundContentEvents(area.getElements('a.bc'));
	
	area.getElements('form.xhrr').removeEvents('submit').addEvent('submit', function(event) {
		event.stop();
		var url = this.getAttribute('action').toURI();
		var param = this.toQueryString().parseQueryString();
		var method = this.method;
		XHRRequestObj.get(this.getAttribute('action'), param, method, url.getData('cb'));
	});
	
	area.getElements('form.xhr').removeEvents('submit').addEvent('submit', function(event) {
		event.stop();
		var url = this.getAttribute('action').toURI();
		var param = this.toQueryString().parseQueryString();
		var method = this.method;
		XHRContentObj.get(this.getAttribute('action'), url.getData('layout'), url.getData('area'), param, method, url.getData('cb'));
	});
	
	area.getElements('a.xhrr').removeEvents('click').addEvent('click', function(event) {
		event.stop();
		var url = this.href.toURI();
		XHRRequestObj.get(this.href, null, null, url.getData('cb'));
	});
	
	area.getElements('.box').addEvents({
		'mouseenter': function() {
			this.addClass('hover');
		},
		'mouseleave': function() {
			this.removeClass('hover');
		},
		'click': function(event) {
			if(this.getElement('a.xhr')) {
				this.getElement('a.xhr').fireEvent('click', event);
			}
		}
	});
	
	area.getElements('a.disabled').removeEvents('click').addEvent('click', function(event){
		event.stop();
	});
	
	area.getElements('.rating.allowed p.rate a, .rating.allowed p.rate').addEvents({
		'mouseenter': function() {
			this.addClass('hover');
			this.getAllPrevious().addClass('hover');
		},
		'mouseleave': function() {
			this.removeClass('hover');
			this.getAllPrevious().removeClass('hover');
		}
	});
	if(area == $(document.body) || area == Info.element.leftColumn) {
		initMainNavigationEvents();
		backgroundContentEvents('#top ul li.unternehmen a, #top ul li.news-archiv a');
	}
	
	$$($('form-suche').getElements('input.text'), '.ce_comments textarea[name=comment]', '#suchergebnisse #keywords').addEvents({
		'focus': function() {
			if(!this.getAttribute('value')) {
				this.setAttribute('value', this.get('value'));
			}
			if(this.value == this.getAttribute('value')) {
				this.value = '';
			}
		},
		'blur': function() {
			if(this.value == '') {
				this.value = this.getAttribute('value');
			}
		}
	});
}

function initEvents() {
	$$(Info.element.overlayClose, Info.element.overlayBackground).addEvent('click', function() {
		OverlayObj.close();
	});
	NewsXTObj.observe();
	
	//initMainNavigationEvents();
	
	//backgroundContentEvents('#top ul li.unternehmen a, #top ul li.entry-standard a, #top ul li.news-archiv a');
	
	$(window).addEvent('resize', function() {
		calculateSizes();
		OverlayObj.resize();
	});
	
	applyEvents();
}

function initMainNavigationEvents() {
	Info.element.mainNavigation.getElements('ul').each(function(el){
		el.set('tween', {'link': 'cancel'});
		el.store('height', el.getDimensions().y);
		el.setStyle('height', 0);
		el.setStyle('display', 'block');
	});
	Info.element.mainNavigation.getChildren('li').addEvents({
		'mouseenter': function() {
			var el_ul = this.getElement('ul');
			
			if(el_ul) {
				if(el_ul.retrieve('hide_timer')) {
					el_ul.store('hide_timer', $clear(el_ul.retrieve('hide_timer')))
				}
				el_ul.tween('height', el_ul.retrieve('height'));
			}
		},
		'mouseleave': function() {
			var el_ul = this.getElement('ul');
			if(el_ul) {
				var hide_timer = (function(){ el_ul.tween('height', 0); }).delay(Info.misc.NavigationHideDelay);
				el_ul.store('hide_timer', hide_timer);
			}
		}
	});
}

function backgroundContentEvents(selector) {
	$$(selector).removeEvents('click');
	$$(selector).addEvent('click', function(event){
		event.stop();
		OverlayObj.close();
		var options_url = this.href.toURI().toAbsolute();
		NewsXTObj.options.url = options_url;
		NewsXTObj.reset();
	});
}

function updatePageUrl(key, value) {
	if(value == false) {
		PageUrl.erase(key);
	} else {
		PageUrl.set(key, value);
	}
	var hash = '';
	if(PageUrl.has('BC')) {
		hash += 'BC='+PageUrl.get('BC').replace(/(&)/g, ':');
	}
	if(PageUrl.has('BC') && PageUrl.has('OC')) {
		hash += '&';
	}
	if(PageUrl.has('OC')) {
		hash += 'OC='+PageUrl.get('OC').replace(/(&)/g, ':');
	}
	window.location.hash = hash;
}

function regeneratePageUrl() {
	var pageUrlObj = ('?'+window.location.hash.substring(1)).toURI().getData();
	PageUrl = new Hash(pageUrlObj);
	if(PageUrl.has('OC')) {
		PageUrl.set('OC', PageUrl.get('OC').replace(/(:)/g, '&'));
	}
	if(PageUrl.has('OCR')) {
		PageUrl.set('OCR', PageUrl.get('OCR').replace(/(:)/g, '&'));
	}
	if(PageUrl.has('BC')) {
		PageUrl.set('BC', PageUrl.get('BC').replace(/(:)/g, '&'));
	}
}

function initPageContent() {
	if(PageUrl.get('BC')) {
		NewsXTObj.options.url = PageUrl.get('BC');
	} else {
		NewsXTObj.options.url = Info.misc.standardBackgroundContentUrl;
	}
	NewsXTObj.check();
	if(PageUrl.get('OC')) {
		var url = PageUrl.get('OC').toURI();
		XHRContentObj.get(url.toAbsolute(), url.getData('layout'), url.getData('area'), null, null);
	}
	if(PageUrl.get('OCR')) {
		var url = PageUrl.get('OCR').toURI();
		XHRRequestObj.get(url.toAbsolute(), null, null);
	}
}

function loading(status) {
	if(status) {
		$(document.body).addClass('loading');
	} else {
		$(document.body).removeClass('loading');
	}
}

function updatePageTitle(type, title) {
	if(title == false && type) {
		title = pageTitle.get(type);
	} else {
		pageTitle.set(type, title);
	}
	if(!Browser.Engine.trident) {
		$(document.head).getElement('title').set('text', Info.misc.pageTitlePrefix+title);
	} else {
		document.title = Info.misc.pageTitlePrefix+title;
	}
}

function reloadLeftColumn() {
	loading(true);
	Info.element.leftColumn.set('load', {'onSuccess': function() {
		Info.element.mainNavigation = Info.element.leftColumn.getElementById('nav_main');
		applyEvents(Info.element.leftColumn);
		loading(false);
	}});
	Info.element.leftColumn.load(Info.misc.leftColumnUrl);
}

function scrollToTop() {
	new Fx.Scroll(document.body, {duration: 250}).toTop();
}

function cb_closeOverlayReloadLeftColumn() {
	OverlayObj.close();
	reloadLeftColumn();
}

function cb_reloadOverlay() {
	XHRContentObj.get(PageUrl.OC, PageUrl.OC.toURI().getData('layout'));
}

function cb_reload() {
	window.location.reload();
}

function cb_json(response) {
	if(response.status == 'reload') {
		if(response.area) {
			if(response.area.contains('OC')) {
				cb_reloadOverlay();
			}
			if(response.area.contains('LC')) {
				reloadLeftColumn();
			}
			if(response.area.contains('BC')) {
				NewsXTObj.reset();
			}
		} else {
			cb_reload();
		}
	}
	if(response.close) {
		if(response.close == 'OC') {
			OverlayObj.close();
		}
	}
	if(response.status == 'redirect' && response.url) {
		if(response.external) {
			window.location.href = response.url;
		} else {
			layout = Info.misc.standardLayout;
			if(response.layout) {
				layout = response.layout;
			}
			XHRContentObj.get(response.url, layout);
		}
	}
	if(response.status == 'content' && response.html) {
		layout = null;
		
		if(OverlayObj.isOpen()) {
			layout = OverlayObj.options.lastLayout;
		}
		OverlayObj.open(response.html, layout);
	}
	if(response.status == 'facebook') {
		facebookConnect();
	}
}

function facebookConnect() {
	FB.init(Info.misc.facebookApiKey, "/xd_receiver.htm");
	FB.ensureInit(function() {
		FB.Connect.get_status().waitUntilReady( function( status ) {
			switch ( status ) { 
				case FB.ConnectState.connected: 
					ConntectedIn = true; 
					break; 
				case FB.ConnectState.appNotAuthorized: 
				case FB.ConnectState.userNotLoggedIn: 
					FB.Connect.requireSession(function(){
						XHRRequestObj.get(Info.misc.facebookLoginUrl);
					}); 
			} 
		}); 
	});
}

var Overlay = new Class({
	'options': {
		'lastLayout': ''
	},
	'initialize': function() {
		Info.element.overlayBackground.fade('hide');
		Info.element.overlay.fade('hide');
	},
	'open': function(data, layout, area) {
		loading(true);
		var delay = 0;
		// set layout
		if(!layout) {
			layout = Info.misc.standardLayout;
		}
		this.options.lastLayout = layout;
		Info.overlay.layouts.each(function(item){
			Info.element.overlay.removeClass(item);
		});
		Info.element.overlay.addClass(layout);
		// insert data
		if(!area) {
			area = Info.element.overlayContent;
		}
		$(area).set('html', data);
		applyEvents(area);
		calculateSizes();
		this.resize();
		this.background();
		var pageTitle = Info.element.overlayContent.getElements('div.pagetitle').getLast();
		if(pageTitle) {
			updatePageTitle('OC', pageTitle.get('html'));
		}
		Info.element.overlay.fade(1);
		scrollToTop();
		loading(false);
	},
	'close': function() {
		updatePageUrl('OC', false);
		updatePageTitle('BC', false);
		Info.element.overlay.fade(0);
		Info.element.overlayBackground.fade(0);
		scrollToTop();
		this.clear.delay(500);
		calculateSizes.delay(550);
		this.resize.delay(600, null, true);
	},
	'clear': function() {
		Info.element.overlayContent.empty();
	},
	'background': function() {
		Info.element.overlayBackground.fade(1);
	},
	'resize': function(obg) {
		if(!obg) {
			var overlayHeight = Info.size.viewport.y - Info.size.overlayMarginBottom;
			Info.element.overlayContent.setStyle('min-height', overlayHeight);
		}
		var width = Info.size.windowScroll.x - Info.size.leftCol.x;
		//var height = Info.size.windowScroll.y;
		var height = 0;
		[Info.size.overlay.totalHeight, Info.size.top.totalHeight, Info.size.content.totalHeight, Info.size.viewport.y].each(function(h){
			if(h > height) {
				height = h;
			}
		});
		Info.element.overlayBackground.setStyle('width', width);
		Info.element.overlayBackground.setStyle('height', height + 25);
	},
	'isOpen': function() {
		if(Info.element.overlay.getStyle('visibility') != 'hidden') {
			return true;
		}
		return false;
	}
});

var XHRRequest = new Class({
	'options': {
		'url': null,
		'method': null,
		'param': {},
		'callback': {}
	},
	'initialize': function() {
		this.options.method = Info.misc.xhrMethod;
	},
	'connection': {},
	'get': function(url, param, method, callback) {
		this.options.callback = callback;
		this.options.url = url;
		this.options.param = param;
		if(method) {
			this.options.method = method;
		}
		this.request();
	},
	'parse': function(response, responseText) {
		if(this.options.callback) {
			CallbackObj.exec(this.options.callback, response);
			this.options.callback = false;
		} else {
			if(!response && responseText) {
				response = {'status': 'content', 'html': responseText};
			}
			CallbackObj.exec('5', response);
		}
		this.options.method = Info.misc.xhrMethod;
	},
	'request': function() {
		this.setupConnection(this.options.url);
		if(this.options.method == 'post') {
			this.connection.post($merge({'xhr': true}, this.options.param));
		} else {
			this.connection.get($merge({'xhr': true}, this.options.param));
		}
	},
	'setupConnection': function(url) {
		this.connection = new Request.JSON({
			'url': url,
			'onSuccess': this.parse.bind(this)
		});
	}
});

var XHRContent = new Class({
	'options': {
		'url': null,
		'layout': null,
		'area': null,
		'param': {},
		'method': null,
		'callback': {}
	},
	'initialize': function() {
		this.options.method = Info.misc.xhrMethod;
	},
	'connection': {},
	'get': function(url, layout, area, param, method, callback) {
		loading(true);
		this.options.callback = callback;
		this.options.url = url;
		this.options.layout = layout;
		this.options.area = area;
		this.options.param = param;
		if(method) {
			this.options.method = method;
		}
		this.request();
	},
	'parse': function(responseTree, responseElements, responseHTML, responseJavaScript) {
		loading(false);
		if(this.options.callback) {
			CallbackObj.exec(this.options.callback, [responseTree, responseElements, responseHTML, responseJavaScript]);
			this.options.callback = false;
		} else {
			var ol_url = this.options.url.toURI().toAbsolute();
			updatePageUrl('OC', ol_url);
			OverlayObj.open(responseHTML, this.options.layout, this.options.area);
		}
		this.options.method = Info.misc.xhrMethod;
	},
	'request': function() {
		this.setupConnection(this.options.url);
		if(this.options.method == 'post') {
			this.connection.post($merge({'xhr': true}, this.options.param));
		} else {
			this.connection.get($merge({'xhr': true}, this.options.param));
		}
	},
	'setupConnection': function(url) {
		this.connection = new Request.HTML({
			'url': url,
			'onSuccess': this.parse.bind(this)
		});
	}
});

var NewsXT = new Class({
	'options': {
		'limit': 0,
		'offset': 0,
		'count': 0,
		'countPossible': 0,
		'page': 1,
		'pid': 0,
		'url': null
	},
	'initialize': function() {
		this.options.count = this.countItems(Info.element.backgroundContent.getElements('div.box'));
	},
	'calculate': function() {
		var contentSize = Info.element.backgroundContentContainer.getSize();
		var viewportSize = $(window).getSize();
		var cols = Math.floor((viewportSize.x - Info.size.leftCol.x - 15) / Info.backgroundContent.elementSize.x).limit(Info.backgroundContent.minValues.cols, Info.backgroundContent.maxValues.cols);
		var rows = Math.floor((viewportSize.y - 75) / Info.backgroundContent.elementSize.y).limit(Info.backgroundContent.minValues.rows, Info.backgroundContent.maxValues.rows);
		this.options.countPossible = cols * rows;
		this.options.limit = this.options.countPossible;
		/*if(this.options.count < this.options.page * this.options.countPossible) {
			this.options.offset = ((this.options.page - 1) * this.options.countPossible) + this.options.count;
		}*/
		this.options.offset = (this.options.page - 1) * this.options.limit;
	},
	'getData': function() {
		var req = new Request.JSON({
			'url': this.options.url+'limit/'+this.options.limit+'/count/'+this.options.count+'/page/'+this.options.page+'.html',
			'onSuccess': this.handleData.bind(this)
		});
		req.get();
		updatePageUrl('BC', this.options.url);
	},
	'handleData': function(data, html) {
		if(!data) {
			this.handleHtmlData(html);
			return;
		}
		var count = data.items.length;
		this.updatePager(data.pager);
		if(count > 0) {			
			for(var i = 0; i < count; i++) {
				if(data.items[i].length > 0) {
					this.insertContent(data.items[i]);
				}
			}
			this.options.count = this.countItems(Info.element.backgroundContent.getElements('.box'));
			applyEvents(Info.element.backgroundContent);
		}
		if(data.pagetitle) {
			updatePageTitle('BC', data.pagetitle);
		}
		this.hideElements();
		this.showElements();
	},
	'handleHtmlData': function(html) {
		var els_wrapper = Elements.from(html);
		if(els_wrapper && els_wrapper.getLast()) {
			var els = els_wrapper.getLast().getElements('.box');
			els.fade('hide');
			els.inject(Info.element.backgroundContent);
			
			//Info.element.backgroundContent.set('html', html);
			applyEvents(Info.element.backgroundContent);
			this.hideElements();
			this.showElements();
		}
	},
	'countItems': function(list) {
		var counter = 0;
		list.each(function(item){
			if(item.hasClass('wide') || item.hasClass('tall')) {
				counter += 2;
			} else {
				counter += 1;
			}
		});
		return counter;
	},
	'updatePager': function(pager) {
		Info.element.backgroundContentPagination.fade('hide');
		(function(pager){
			Info.element.backgroundContentPagination.set('html', pager);
			Info.element.backgroundContentPagination.fade(1);
			this.updatePagerEvents();
		}).delay(0, this, pager);
	},
	'updatePagerEvents': function() {
		Info.element.backgroundContentPagination.getElements('a').addEvent('click', function(event) {
			event.stop();
			var url = this.get('href').toURI();
			NewsXTObj.options.page = url.get('fragment');
			NewsXTObj.check(true);
		});
	},
	'insertContent': function(data) {
		var el = Elements.from(data).getLast();
		if(el.hasClass('box')) {
			el.fade('hide');
		} else if(el.getChildren('.box')) {
			el.getChildren('.box').fade('hide');
		}
		
		el.inject(Info.element.backgroundContent);
	},
	'showElements': function() {
		var els = this.elementsInRange();
		for(i = 0; i < els.length; i++) {
			(function(el){
				el.setStyle('display', 'block');
				el.fade(1);
			}).delay(i * Info.backgroundContent.showDelay, this, els[i]);
		}
	},
	'hideElements': function() {
		var els = this.elementsInRange(true);
		for(i = 0; i < els.length; i++) {
			els[i].setStyle('display', 'none');
			els[i].fade(0);
			/*(function(el){
				el.fade(0);
				(function(el){
					el.setStyle('display', 'none');
				}).delay(500, this, el);
			}).delay(i * 50, this, els[i]);*/
		}
	},
	'elementsInRange': function(inverse) {
		/*var els = Info.element.backgroundContent.getChildren('div.box').filter((function(item, index){
			var cond = (index >= ((this.options.page - 1) * this.options.limit) && index < (this.options.page * this.options.limit));
			return (inverse ? !cond : cond );
		}).bind(this));
		return els;*/
		els = [];
		counter = 0;
		Info.element.backgroundContent.getElements('.box').each(function(el){
			var cond = (counter >= ((this.options.page - 1) * this.options.limit) && counter < (this.options.page * this.options.limit));
			if(el.hasClass('wide') || el.hasClass('tall')) {
				counter += 2;
			} else {
				counter += 1;
			}
			if(cond && !inverse || !cond && inverse) {
				els.include(el);
			}
		}, this);
		return els;
	},
	'check': function(force) {
		var countPossible = this.options.countPossible;
		var page = this.options.page;
		this.calculate();
		if(countPossible != this.options.countPossible || force) {
			if(page != 1 && countPossible < this.options.countPossible) {
				var newPage = Math.ceil(((page - 1) * countPossible) / this.options.countPossible);
				this.options.page = newPage;
			}
			this.getData();
		} else {
			this.hideElements();
		}
	},
	'observe': function() {
		$(window).addEvent('resize', this.check.bind(this));
	},
	'reset': function() {
		Info.element.backgroundContent.empty();
		Info.element.backgroundContentPagination.empty();
		this.options.page = 1;
		this.options.count = 0;
		this.check(true);
	}
});

function setChartsTab(id) {
	$('company_charts').getElement('a.active').removeClass('active');
	$('charts_tab_'+id).getElement('a').addClass('active');
	$('company_charts').getElements('.images img').setStyle('display', 'none');
	$('chart_'+id).setStyle('display', 'block');
	return false;
}
