var i4_Popup_instance = Class.create({ 
	initialized: false,
	
	class_name: 'i4_popup',
	id_prefix: 'popup_',
	id_name: '',
	child_popup: '',
	
	class_draggable: 'popup_draggable',
	
	visible: true,
	overlay: true,
		
	get_id_name: function(){ return this.id_name; },
	set_child_popup: function(popup){ this.child_popup = popup; return this; },
	set_overlay: function(overlay){ this.overlay = overlay; return this; },
		
	/**
	* erstellt den popup container
	*/
	initialize: function() {
		// popup
		this.id_name = this.id_prefix+i4_Popup.get_count();
		$$('body')[0].appendChild(Builder.node('div', {
			id: this.id_name,
			className: this.class_name
		}));
		$(this.id_name).setStyle({
			'position': 'absolute',
			'top': '10px',
			'minHeight': '10px',
			'fontSize': '11px',
			'display': 'none'
		});
		this.initialized = true;
		this.top();
	},
	
	set_parent_popup: function(popup) { 
		if (popup != '') {
			popup.set_child_popup(this);
		}
		return this;
	},

	/**
	* zeigt das popup mit ajax inhalt.
	*/
	set_ajax: function(ajax_file){
		if(!this.initialized){ this.initialize(); }
	
		// inhalt mit ajax holen.
		new Ajax.Updater(this.id_name, ajax_file,{ 
			evalScripts:true, 
			asynchronous:true,
			onSuccess: (function(transport){
				// eval scripts
//				this.eval_scripts(transport.responseText); 
			}).bind(this),
			onComplete: (function(transport){
				// run form js 
				if($$('#'+this.id_name+' .form_javascript')[0]){		
					var js_code = this.html_entity_decode($$('#'+this.id_name+' .form_javascript')[0].innerHTML);
					
					// alert(js_code);
					
					this.eval_scripts(js_code); 
					if(window.execScript) {
						window.execScript(js_code);
					}else{ 
						window.setTimeout(js_code, 0);	
					}
					
					$$('#'+this.id_name+' .form_javascript')[0].remove();
					
				}

				this.make_draggable();
				
				// zentriert das popup
				this.center();
				
				this.generate_close_buttons();
				
				// popup anzeigen
				$(this.id_name).appear({duration: 0.3});
				
			}).bind(this)
		});
		
		
		return this;
	}, 
	
	set_dom: function(html){
		if(!this.initialized){ this.initialize(); }
		$(this.id_name).update(html);

		this.center();
	
		return this;
	},
	
	show: function(){
		if (this.overlay) {
			i4_Overlay.show();
		}
		$(this.id_name).appear({duration: 0.3});
		return this;
	},
	
	add_class_name: function(class_name){
		$(this.id_name).addClassName(class_name);
		return this;
	},
	
	make_draggable: function(){
		$(this.id_name).observe('click', (function(event){
			var element = Event.element(event);
			if (element.tagName != 'A' && element.tagName != 'IMG') {
				this.top();
			}		
		}).bind(this));
		
		// popup draggable
		new Draggable(this.id_name, { handle: this.class_draggable });
		$$('.'+this.class_draggable).each(function(item){
			item.setStyle({
				'cursor': 'move'	
			});
		});
		
		return this;
	},
	
	generate_close_buttons: function(){
		$$('#'+this.id_name+' .close_popup').each(function(item){
			item.observe('click', function(){
				i4_Popup.remove(item);
			});
			
		});
		
		return this;
	},
	
	top: function(){
		// alert(this.id_name+' '+i4_Popup.get_zindex());
		if($(this.id_name)){
			$(this.id_name).setStyle({
				'zIndex': i4_Popup.get_zindex()	
			});
		}
		return this;
	},
	
	eval_scripts: function(scripts){
		try{	
			
			if(scripts != ''){	
				var script = "";
				var scripts = scripts.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi, function(){
					if (scripts !== null){
						script += arguments[1] + '\n';
					}else{
						return '';
					}
	 	        });
				
				if(script){
					if(window.execScript) {
						window.execScript(script);
					}else{ 
						window.setTimeout(script, 0);	
					}
				}
			}
			
			return false;
		}catch(e){
//			alert(e.description);
		}

	},
	
	html_entity_decode: function(str) {
 		var ta = document.createElement('textarea');
		ta.innerHTML = str.replace(/</g,'&lt;').replace(/>/g,'&gt;');
  		return ta.value;
	},
	
	hide: function() {
		$(this.id_name).hide();
		this.visible = false;
	},
	
	/**
	* löscht das popup
	*/
	remove: function(){
		if ($(this.id_name)) {
			$(this.id_name).remove();
			
			if (this.child_popup != '') {
				this.child_popup.remove();
			}
		}
	},
	
	/**
	* popup zentrieren.
	*/
	center: function(){
		if(!this.initialized){ this.initialize(); }
		
		// get dimensions
		var popup_dimensions = $(this.id_name).getDimensions();
		var body_dimensions = $$('body')[0].getDimensions();
		
		// calculate center of the page
		var x = (body_dimensions.width - popup_dimensions.width) / 2;
		var y = document.viewport.getScrollOffsets().top+10;

		
		$(this.id_name).setStyle({
			'left': x+'px',
			'top': y+'px'	
		});
		
		return this;
	},
	
	clone_position: function(clone_element_id) {
		// ie7 needs the try-catch block
		try{
			$(this.id_name).clonePosition(clone_element_id, {
				'setWidth': false,
				'setHeight': false
			});
		}catch(e){}
		
		return this;
	}
});

/**
* controller für die popups
*/
var i4_Popup = {
	instances: [],
	count: 0,
	initialized: false,
	zindex: 100,
	
	key_listener: '',
	
	initialize: function(){
		if(!this.initialized){

			this.initialized = true;
		}
	},
	
	add: function(){
		this.initialize();
				
		var popup = new i4_Popup_instance();
		this.instances.push([popup.get_id_name(), popup]);
		
		if (this.key_listener === '') {
			// add key listener
			this.key_listener = i4_Document_listener.keydown({
			    keys: [27],
			    callback: function() {
			    	i4_Popup.remove_all();
			    }
			});
		}

		return popup;
	},
	
	remove: function(element){
		var instance = null;

		var popup_id = '';
		if (element.hasClassName('i4_popup')) {
			popup_id = element.readAttribute('id');
		} else {
			popup_id = element.up('.i4_popup').readAttribute('id');
		}
		instance = this.get_instance_by_popup_id(popup_id);
		
		if(instance){
			instance[1].remove();
			this.instances = this.instances.without(instance);	
		}else{
			alert('keine popup instance gefunden');	
		}
		
		// alert(this.instances.inspect());

		var open_popups = false;
		this.instances.each((function(item){
			if(!$(item[0])){
				this.instances = this.instances.without(item);
			}
		
			if($(item[0]) && $(item[0]).childElements().size() > 0 && item[1].visible){
				open_popups = true;	
			} else {
			
			}
		}).bind(this));
		
		if(!open_popups){
			this.remove_all();
		}
	},
	
	remove_all: function(){
		this.instances.each(function(item){
			item[1].remove();
		});	
		this.instances.clear();
		this.count = 0;
		
		i4_Overlay.remove();
		
		// stop key listener
		i4_Document_listener.stop_keydown(this.key_listener);
		this.key_listener = '';
	},
	
	get_count: function(){
		this.count++;
		return this.count;
	},
	
	get_zindex: function(){
		this.zindex++;
		return this.zindex;	
	},
	
	get_instance_by_popup_id: function(popup_id){
		var instance = null;
	
		this.instances.each( function(item){
			if(item[0] == popup_id){
				instance = item;
			}
		});
		
		return instance;
	},
	
	get: function(element_id){
		var result = '';
		
		if ($(element_id)) {
			// check if popup exists
			if ($(element_id).up('.i4_popup')) {
				popup_id = $(element_id).up('.i4_popup').readAttribute('id');
				instance = this.get_instance_by_popup_id(popup_id);
				result = instance[1];
			}
		} else {
			result = this.add();
		}


		return result;
	}
	
}

/**
* kontrolliert den abgedunkelten hintergrund
*/
var i4_Overlay = {
	id_bg_name: 'i4_bg_layer',
	
	show: function() {
		// bg	
		if (!$(this.id_bg_name)) {
			$$('body')[0].appendChild(Builder.node('div', {id: this.id_bg_name}));
			$(this.id_bg_name).setStyle({
				'position': 'fixed',
				'width': '100%',
				'top': '0px',
				'height': '100%',
				'left': '0px',
				'background': 'black',
				'display': 'none',
				'zIndex': '95'
			});
			$(this.id_bg_name).setOpacity('0.2');
		}
		
		$(this.id_bg_name).show();
	},
	
	remove: function(){
		if ($(this.id_bg_name)) {
			$(this.id_bg_name).fade({ duration: 0.2 });
			$(this.id_bg_name).remove();
		}	
	}
}
