var Klappbox = Class.create({
	initialize: function(collapsable){
		this.collapsable = (collapsable === true);
		this.objects = [];
		this.active = false;
		this.foto = false;
		
		this.regexp = {
			open: /(.+?)_a(.+)/,
			close: /(.+?)_n(.+)/
		}
	},
	
	add: function(handler, box, opened){
		this.objects.push({
			handler: handler,
			box: box,
			opened: opened
		});
		
		handler.observe("click", this.open.bind(this));
	},
	
	addFoto: function(foto){
		this.foto = foto;
	},
	
	open: function(e){
		if(this.active === true) return;
		
		this.active = true;
		
		var clicked = (typeof e == "string") ? $(e) : e.findElement();
		clicked = this.getObject(clicked);
		var opened = this.getOpened();
		
		if(opened === false && this.collapsable){
			if(this.foto !== false){
				this.foto.className = "box closed";
			}
			
			clicked.opened = true;
			
			clicked.box.className = "box opened";
			
			this.regexp.close.exec(clicked.handler.src);
			clicked.handler.src = RegExp.$1 + "_a" + RegExp.$2;
			
			if(this.foto !== false){
				this.active = false;
				return;
			}
			
			new Effect.SlideDown('box-wrapper', {
				afterFinish: function(){
					this.active = false;
				}.bind(this)
			});
		}else if(opened === clicked && this.collapsable){
			if(this.foto !== false){
				clicked.opened = false;
				
				clicked.box.className = "box closed";
				
				this.regexp.open.exec(clicked.handler.src);
				clicked.handler.src = RegExp.$1 + "_n"+RegExp.$2;
				
				this.active = false;
				
				this.foto.className = "box opened";
				
				return;
			}
			
			new Effect.SlideUp('box-wrapper', {
				afterFinish: function(){
					clicked.opened = false;
					
					clicked.box.className = "box closed";
					
					this.regexp.open.exec(clicked.handler.src);
					clicked.handler.src = RegExp.$1 + "_n"+RegExp.$2;
					
					this.active = false;
				}.bind(this)
			});
		}else{
			opened.opened = false;
			clicked.opened = true;
			
			opened.box.className = "box closed";
			clicked.box.className = "box opened";
			
			this.regexp.open.exec(opened.handler.src);
			opened.handler.src = RegExp.$1 + "_n"+RegExp.$2;
			
			this.regexp.close.exec(clicked.handler.src);
			clicked.handler.src = RegExp.$1 + "_a"+RegExp.$2;
			
			var obj=getOverlay(clicked.handler.id);
			this.active = false;
		}
	},
	
	getObject: function(_object){
		var clicked = false;
		
		this.objects.each(function(object){
			if(object.handler === _object){
				clicked = object;
			}
		});
		
		return clicked;
	},
	
	getOpened: function(){
		var opened = false;
		
		this.objects.each(function(object){
			if(object.opened === true){
				opened = object;
			}
		});
		
		return opened;
	}
});