var Leaflet = Class.create({
	container: null,
	leafletAddHandler: null,
	dialogOverlay: null,
	
	initialize: function(container) {
		this.container = container;
		this.leafletAddHandler = new Array();
		this.leafletRemoveHandler = new Array();
		this.container.select('a').each(function(link) {
			if(link.readAttribute('rev') != 'leaflet') {
				return;
			}
			
			switch(link.readAttribute('rel')) {
				case 'add':
					this.leafletAddHandler.push(new leafletAddHandler(link, link.readAttribute('href')));
					link.writeAttribute('href', 'javascript:;');
					break;
				case 'remove':
					break;
				case 'list': 
					this.dialogOverlay = new DialogOverlay( link.readAttribute('href'), $$('body').first(), link);
					break;
				default: return;
			}
		}.bind(this));
	}
});

var SendformLeafletHandler = Class.create({
	container: null,
	data: null,
	request: null,
	state: null,
	trigger: null,
	url: '?eID=updateLeaflet',
	
	initialize: function(container) {
		this.container = container;
		this.trigger = this.container.select('.overlay-submit-button').first();
		this.trigger.observe('click', this.submit.bindAsEventListener(this));
	},
	
	submit: function(event) {
		if(this.state) {
			return;
		}

		var addresser = $F(this.container.select('input')[0]);
		var addresser_mail = $F(this.container.select('input')[1]);
		var recipient = $F(this.container.select('input')[2]);
		var recipient_mail = $F(this.container.select('input')[3]);
		var identifier = $F(this.container.select('input')[4]);
		var language = $F(this.container.select('input')[5]);

		this.trigger.writeAttribute('disabled', 'true');
		this.state = 'sending';
		this.request = new Ajax.Request(this.url+'&identifier='+identifier+'&language='+language+'&mode=send&addresser='+addresser+'&addresser_mail='+addresser_mail+'&recipient_mail='+recipient_mail+'&recipient='+recipient , {
			//parameter: 'mode=send', 'addresser='+addresser, 'addresser_mail='+addresser_mail, 'recipient_mail='+recipient_mail, 'recipient='+recipient },
			onSuccess: function(response) {
				if(response.responseText == '1') {
					this.container.select('.validation-error').each(function(item) {
						item.setStyle({ display: 'none' });
					});
					this.container.select('.send-succesful').first().setStyle({ display: 'block' });
				}
				else {
					try {
						var data = response.responseText.evalJSON();
						this.displayValidationError(data);
					}
					catch(e) {
					}
					this.container.select('.send-succesful').first().setStyle({ display: 'none' });
				}
				this.trigger.removeAttribute('disabled');
				this.state = false;
			}.bind(this),
			onFailure: function(response) {
				this.trigger.removeAttribute('disabled');
				this.state = false;
				this.container.select('.send-succesful').first().setStyle({ display: 'none' });
			}.bind(this)
		});
	},
	
	displayValidationError: function(data) {
		this.container.select('.validation-error').each(function(item) {
			item.setStyle({ display: 'none' });
		});
		if(data.addresser) {
			this.container.select('.validation-error')[0].setStyle({ display: 'block' });
		}
		if(data.addresser_mail) {
			this.container.select('.validation-error')[1].setStyle({ display: 'block' });
		}
		if(data.recipient) {
			this.container.select('.validation-error')[2].setStyle({ display: 'block' });
		}
		if(data.recipient_mail) {
			this.container.select('.validation-error')[3].setStyle({ display: 'block' });
		}
	},
	
	validate: function(value, regEx) {
		return regEx.match(value);
	}
});

var leafletAddHandler = Class.create({
	container: null,
	url: null,
	request: null,
	state: false,
	toclose: false,
	
	initialize: function(container, url) {
		this.container = container;
		this.url = url;

		this.container.observe('click', this.click.bindAsEventListener(this));
	},
	
	click: function(event) {
		if(this.state) {
			return;
		}
		this.activate();
		this.request = new Ajax.Request(this.url, {
			onSuccess: function(response) {
				if(response.responseText == '1') {
					this.deactivate();
				}
				else {
					this.deactivate();
				}
			}.bind(this),
			onFailure: function(response) {
				this.deactivate();
			}.bind(this)
		});
	},
	
	activate: function() {
		this.state = 'opening';
		new Effect.Morph(this.container, {
			style: 'opacity: 0.5;',
			duration: 0.5,
			afterFinish: function() {
				this.deactivate(true);
			}.bind(this)
		});
	},
	
	deactivate: function(test) {
		if(this.state == 'opening' && !test) {
			this.toclose = true;
			return;
		}
		if(test && !this.toclose) {
			return;
		}
		this.state = 'closing';
		new Effect.Morph(this.container, {
			style: 'opacity: 1;',
			duration: 0.5,
			afterFinish: function() {
				this.state = false;
			}.bind(this)
		});
	}
});

var leafletRemoveHandler = Class.create({
	container: null,
	target: null,
	url: null,
	request: null,
	state: false,
	toclose: false,
	listener: null,
	
	initialize: function(container) {
		this.container = container;
		this.target = this.container.up('li');
		this.url = this.container.readAttribute('href');
		this.container.writeAttribute('href', 'javascript:;');

		this.listener = this.container.observe('click', this.click.bindAsEventListener(this));
	},
	
	click: function(event) {
		if(this.state) {
			return;
		}
		this.activate();
		this.request = new Ajax.Request(this.url, {
			onSuccess: function(response) {
				if(response.responseText == '1') {
					this.remove();
				}
				else {
					this.deactivate();
				}
			}.bind(this),
			onFailure: function(response) {
				this.deactivate();
			}.bind(this)
		});
	},
	
	remove: function() {
		this.target.fade({
			duration: 0.5,
			afterFinish: function() {
				this.target.remove();
				this.listener = null;
			}.bind(this)
		});
	},
	
	activate: function() {
		this.state = 'opening';
		new Effect.Morph(this.container, {
			style: 'opacity: 0.5;',
			duration: 0.5,
			afterFinish: function() {
				this.deactivate(true);
			}.bind(this)
		});
	},
	
	deactivate: function(test) {
		if(this.state == 'opening' && !test) {
			this.toclose = true;
			return;
		}
		if(test && !this.toclose) {
			return;
		}
		this.state = 'closing';
		new Effect.Morph(this.container, {
			style: 'opacity: 1;',
			duration: 0.5,
			afterFinish: function() {
				this.state = false;
			}.bind(this)
		});
	}
});

var DialogOverlay = Class.create({
	viewport: null,
	container: null,
	trigger: null,
	url: null,
	content: null,
	background: null,
	overlay: null,
	dialog: null,
	state: null,
	request: null,
	border: 32,
	size: 48,
	margin: 80,
	contentMargin: 300,
	width: 640,
	height: 480,
	opacity: 0.4,
	buttonWidth: 16,
	buttonHeight: 16,
	buttonMargin: 8,
	
	initialize: function(url, container, trigger) {
		this.container = container;
		this.trigger = trigger;
		this.url = url; //+'&type=72&no_cache=1';
		this.content = '';
		this.state = false;
		
		this.viewport = this.getViewport();
		
		this.background = new Element('div').hide();
		this.overlay = new Element('div').hide();
		this.dialog = new Element('div');
		this.closeButton = new Element('div').hide();

		this.dialog.insert(this.content);
		this.overlay.insert(this.dialog);
		this.container.insert(this.overlay);
		this.overlay = this.container.childElements().last();
		this.dialog = this.overlay.childElements().last();
		this.container.insert(this.background);
		this.background = this.container.childElements().last();
		this.container.insert(this.closeButton);
		this.closeButton = this.container.childElements().last();
		
		this.trigger.writeAttribute('href', 'javascript:;');
		this.background.addClassName('overlay-background');
		this.overlay.addClassName('overlay');
		this.dialog.addClassName('dialog');
		this.closeButton.addClassName('overlay-close-button');
		this.background.setOpacity(this.opacity);
		
		Event.observe(this.trigger, 'click', this.show.bindAsEventListener(this));
		Event.observe(this.closeButton, 'click', this.hide.bindAsEventListener(this));
	},
	
	getViewport: function() {
		var dim = document.viewport.getDimensions();
		var pos = document.viewport.getScrollOffsets();
		
		return { left: pos.left, top: pos.top, width: dim.width, height: dim.height };
	},
	
	evalCenterPos: function() {
		return { left: (this.viewport.width / 2) +  this.viewport.left, top: (this.viewport.height / 2) + this.viewport.top };
	},
	
	getOverlayDimensions: function() {
		var visible = this.overlay.getStyle('display') == 'none'?false:true;
		if(!visible) {
			this.overlay.show();
		}
		var dim = this.overlay.getDimensions();
		if(!visible) {
			this.overlay.hide();
		}
		return dim;
	},
	
	loadContent: function() {
		var width = this.width;
		if(!this.width) {
			width = this.viewport.width - this.contentMargin;
		}
		var height = this.height;
		if(!this.height) {
			height = this.viewport.height - this.contentMargin;
		}
		var pos = this.evalCenterPos();
		
		this.dialog.fade({
			afterFinish: function() {
				this.dialog.removeClassName('loading');
				new Effect.Morph(this.overlay, {
					style: 'width: '+width+'px; height: '+height+'px; left: '+(pos.left-(width / 2))+'px; top: '+(pos.top-(height / 2))+'px;',
					duration: 0.5,
					afterFinish: function() {
						this.dialog.innerHTML = this.content;
						this.dialog.appear();
						this.closeButton.setStyle({ left: ((pos.left-(width / 2))+width-this.buttonWidth-this.buttonMargin-/* scrollbar width */15)+'px', top: ((pos.top-(height / 2))+this.buttonMargin)+'px' });
						this.closeButton.appear();
						this.addRemoveLinkHandling();
						this.addSendformHandling();
					}.bind(this)
				});
				new Effect.Morph(this.background, {
					style: 'width: '+(width+this.border)+'px; height: '+(height+this.border)+'px; left: '+(pos.left-((width+this.border) / 2))+'px; top: '+(pos.top-((height+this.border) / 2))+'px;',
					duration: 0.5,
					afterFinish: function() {
					}.bind(this)
				});
			}.bind(this)
		});
	},
	
	addRemoveLinkHandling: function() {
		this.dialog.select('a').each(function(link) {
			if(link.readAttribute('rel') != 'remove') {
				return;
			}
			new leafletRemoveHandler(link);
		}.bind(this));
	},
	
	addSendformHandling: function() {
		new SendformLeafletHandler(this.dialog.select('.leaflet-send-form').first());
	},
	
	positionOverlay: function() {
		this.viewport = this.getViewport();
		var pos = this.evalCenterPos();
		
		/* fixed size of the Overlay */
		this.overlay.setStyle({ width: this.size+'px',  height: this.size+'px' });
		this.background.setStyle({ width: this.size+this.border+'px',  height: this.size+this.border+'px' });

		var dim = this.getOverlayDimensions();
		var target =  { left: pos.left-(dim.width / 2)+'px', top: pos.top-(dim.height / 2)+'px' };
		this.overlay.setStyle(target);
		this.overlay.setStyle({ maxWidth: (this.viewport.width - this.margin)+'px',  maxHeight: (this.viewport.height - this.margin)+'px' });

		var target =  { left: pos.left-((dim.width + this.border) / 2)+'px', top: pos.top-((dim.height + this.border) / 2)+'px' };
		this.background.setStyle(target);
		this.background.setStyle({ maxWidth: (this.viewport.width - this.margin - this.border)+'px',  maxHeight: (this.viewport.height - this.margin - this.border)+'px' });
	},
	
	show: function() {
		if(Prototype.Browser.IE && (parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6)) {
			$$('select', 'object', 'embed').each( function(element) { element.hide(); } );
		}
		this.request = new Ajax.Request(this.url, {
			onSuccess: function(response) {
				this.content = response.responseText;
				this.loadContent();
			}.bind(this),
			onFailure: function(response) {
				this.content = 'Der Inhalt konnte nicht geladen werden!';
				this.loadContent();
			}.bind(this)
		});
		this.positionOverlay();
		this.dialog.addClassName('loading');
		new Effect.Appear(this.overlay, { duration: 0.5,  to: 1 });
		new Effect.Appear(this.background, { duration: 0.5,  to: this.opacity });
		this.state = true;
		return this;
	},
	
	hide: function() {
		new Effect.Fade(this.overlay, { duration: 0.5,  to: 0, afterFinish: function() {
			if(Prototype.Browser.IE && (parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6)) {
				$$('select', 'object', 'embed').each( function(element) { element.show(); } );
			}
			this.dialog.innerHTML = '';
		}.bind(this) });
		new Effect.Fade(this.closeButton, { duration: 0.5,  to: 0 });
		new Effect.Fade(this.background, { duration: 0.5,  to: 0 });
		/*this.overlay.hide();*/
		this.state = false;
		return this;
	}
});

Event.observe(document,'dom:loaded', function (event) {
	$$('.leaflet-link').each( function(container) {
		new Leaflet(container);	
	});
});
