(function(){
	/*
	---

	script: Group.js

	description: Class for monitoring collections of events

	license: MIT-style license

	authors:
	- Valerio Proietti

	requires:
	- core:1.2.4/Events
	- /MooTools.More

	provides: [Group]

	...
	*/

	var Group = new Class({

		initialize: function(){
			this.instances = Array.flatten(arguments);
			this.events = {};
			this.checker = {};
		},

		addEvent: function(type, fn){
			this.checker[type] = this.checker[type] || {};
			this.events[type] = this.events[type] || [];
			if (this.events[type].contains(fn)) return false;
			else this.events[type].push(fn);
			this.instances.each(function(instance, i){
				instance.addEvent(type, this.check.pass([type, instance, i], this));
			}, this);
			return this;
		},

		check: function(type, instance, i){
			this.checker[type][i] = true;
			var every = this.instances.every(function(current, j){
				return this.checker[type][j] || false;
			}, this);
			if (!every) return;
			this.checker[type] = {};
			this.events[type].each(function(event){
				event.call(this, this.instances, instance);
			}, this);
		}

	});

	window.addEvent('domready', function(){
		if(document.getElement('.gallery-big')){
			var gallery = document.getElement('.gallery-big')
			gallery.set('spinner', {'message': 'Galerie wird geladen...'});
			gallery.spin();
		
			document.id('master-of-all').addClass('big-gallery');
			var notInCache = document.getElements('.gallery-big img').filter(function(img){
				return (img.getHeight()<369);
			});
			var pageEls = document.getElements('.page a');
			var init = function(){
				var slider = new SpaceSlider('.gallery-big>ul', {
					'offset': 110,
					'fxOpts': {
						'duration': 1500,
						'link': 'cancel'
					},
					'interval': 5500,
					'autoPlay': true,
					'autoPlayDirection': 'next',
					'elementsAfter': 2,
					'onShow': function(curEl, curIndex, prevEl, prevIndex){
						prevEl.removeClass('active');
						prevEl.getElement('.remooz').removeEvents('click');
						pageEls[prevIndex].removeClass('active');
						pageEls[curIndex].addClass('active');
					},
					'onShowComplete': function(curEl){
						curEl.addClass('active');
						SqueezeBox.assign(curEl.getElement('.remooz'));
						SqueezeBox.removeEvents().addEvents({
							'close': function(){
								slider.play();
							},
							'open': function(){
								slider.stop();
							}
						});
					}
				}).prepare('prev').slideTo(0);

				document.getElement('.page').addEvent('click:relay(a)', function(e){
					e.stop();
					slider.stop().slideTo(this.get('href')).playDelayed(8000);
				});

				document.getElement('.gallery-big').addEvent('click:relay(li)', function(e){
					e.stop();
					slider.stop().slideTo(this).playDelayed(8000);
				});
				gallery.unspin();
			};

			if(notInCache.length){
				new Group(notInCache).addEvent('load', init);
			}
			else{
				init();
			}
		}
	});
})();

