var requests = new Array();
var fx = null;

window.addEvent('domready', function() {
	$$('.projectPreviewContainer').each(function(el) {
		var name = el.get('rel');
		var width = el.getSize().x;
		var height = el.getSize().y;
		var elUrl = 'ajax/deliver-project-preview.php?q='+name+'&w='+width+'&h='+height;
		var r = new Request.HTML({
			'url': elUrl,
			'method': 'get',
			'update': el,
			'onSuccess': function() {
				var btn = el.getElement('.projectPreviewButton');
				btn.set('rel', name);
				btn.addEvent('click', showProjectInFull);
				makeNextRequest();

			}
		});
		requests.push(r);
	});

	$('wupaLogoImage').addEvent('click', showProjectInFull);

	makeNextRequest();
	hauwech.periodical(2000);
});

function hauwech() {
	var emptyCells = $$('.CELL_EMPTY');
	if(emptyCells.length > 0) {
		var topOfFirstEmptyCell = emptyCells[0].getPosition().y;
		$('container').setStyle('height', topOfFirstEmptyCell);
	}

	var containerHeight = $('container').getSize().y;
	var windowHeight = window.getSize().y;
	var containerWidth = $('container').getSize().x;
	var windowWidth = window.getSize().x;
	var maxHeight = containerHeight < windowHeight ? containerHeight : windowHeight;
	var maxWidth = containerWidth < windowWidth ? containerWidth : windowWidth;

	$('mitte').setStyles({
		'top': Math.round(maxHeight/2),
		'left': Math.round(maxWidth/2)
	});
	$('singleProjectContainer').setStyles({
		'top': Math.round(maxHeight/2)-12,
		'left': Math.round(maxWidth/2)
	});

	$('linie').setStyle('width', maxWidth);
	$('linie').setStyle('left', Math.round(maxWidth/-2));


}

function makeNextRequest() {
	if (requests.length == 0)
		return;

	var nextRequest = requests.getRandom();
	requests.erase(nextRequest);

	nextRequest.send();
}

function showProjectInFull() {
	if(this.id == 'wupaLogoImage')
		$('overlay').setStyle('z-index', 10);
	else
		$('overlay').setStyle('z-index', 40);
	overlayFade('in');
	var r = new Request.HTML({
		'url': 'ajax/deliver-single-project.php?q='+this.get('rel')+'&i=0',
		'method': 'get',
		'update': $('singleProjectContainer')
	}).send();
}


function hideProject() {
	overlayFade('out');
	$('singleProjectContainer').empty();

}

function overlayFade(how) {
	$('overlay').set('tween', {
		'duration': 500,
		'onComplete': function() {
			if ($('overlay').getStyle('opacity') == 0.8) {
				$('overlay').addEvent('click', hideProject);
			}
			else {
				$('overlay').removeEvent('click', hideProject);
				$('overlay').setStyle('display', 'none');
			}
		}
	});

	if(how == 'in') {
		$('overlay').setStyle('display', 'block');
		$('overlay').setStyle('opacity', 0);
		$('overlay').fade(0.8);
	}
	else
		$('overlay').fade(0);
}


