Object.extend(String.prototype, (function() {
	function escapeSpecialChars() {
		return this.replace(/&/g,'&amp;').replace(/"/g,'&quot;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
	}
	
	return {
		escapeSpecialChars: escapeSpecialChars
	}
})());

function isIE6OrLess(){
	var agt=navigator.userAgent.toLowerCase();
	var is_major = parseInt(navigator.appVersion);
	var is_minor = parseFloat(navigator.appVersion);
	var is_ie     = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
	return (is_ie && (is_major == 4) && (agt.search(/msie [56]\./)!=-1) );
}
/**
 * Stellt Debug-Messages für Firefox, IE8, Opera, Safari, Chrome (Konsole) und IE<8 (alert) zur Verfügung.
 * @param string text
 * @return void
 */
function lg(text) {
	if (false)
	{
		if (typeof(opera) != "undefined" && opera != null) {
			opera.postError(text);
			return;
		}
		else 
			if (typeof(console) != "undefined" && console != null) {
				console.log(text);
				return;
			}	
//			else {
//				alert(text);
//			}
	}
}

/**
 * Prueft, ob point innerhalb der Grenzen von elm liegt. Gibt true oder false zurueck.
 * @param {x:integer, y:integer} point
 * @param {Object} elm
 * @return boolean true, wenn point innerhalb von elm liegt, sonst false
 */
function isInElement(point, elm) {
	var x = point.x;
	var y = point.y;
	var elm = elm;

	 var dOffset = document.viewport.getScrollOffsets();

	if ((x > elm.viewportOffset()[0]+elm.cumulativeScrollOffset()[0]+dOffset[0]+elm.getWidth() || x < elm.viewportOffset()[0]+elm.cumulativeScrollOffset()[0]+dOffset[0])
	|| (y > elm.viewportOffset()[1]+elm.cumulativeScrollOffset()[1]+dOffset[1]+elm.getHeight() || y < elm.viewportOffset()[1]+elm.cumulativeScrollOffset()[1]+dOffset[1])) {
		return false;
	} else {
		return true;
	}
}

var Pulldown = Class.create({
	initialize: function(elm) {
		lg("start initializing Pulldown");
		this.element = elm;
		this.trigger = this.element.down(".pdhandler");
		this.content = this.element.down('.pdflesh');
		this.closeBtn = this.element.down(".pdclose") || null;
		this.opened = false;
		
		this.setLinkTabIndex(-1);

		var bordertop = 0;
		var borderbottom = 0;
		// Mindestbreite auf die Breite des Trigger setzen
		if (this.content.getWidth() < this.trigger.getWidth()) {
			this.content.setStyle({
				width: (this.trigger.getWidth() - parseInt(this.trigger.getStyle("borderLeftWidth")) - parseInt(this.trigger.getStyle("borderRightWidth")) ) + "px"
			});
		}

		this.trigger.writeAttribute('aria-controls', this.content.identify());
		this.trigger.writeAttribute('aria-expanded', 'false');

		this.boundBodyClicked = this.bodyClicked.bindAsEventListener(this);

		this.trigger.observe("click", this.click.bindAsEventListener(this));

		// wenn ein CloseButton angegeben wurde (optional), dann mit Schließmechanik versehen.
		if (this.closeBtn) {
			this.closeBtn.observe("click", this.hide.bindAsEventListener(this));
		}
		
		// wenn schon mit Klasse "active" versehen, dann soll das Pulldown initial geöffnet sein
		if (this.element.hasClassName("active")) {
			this.show();
		}
		lg("end initializing Pulldown");
		
		return this;
	},
	setLinkTabIndex: function(tabindex){
		var links = this.content.select('a');
		links.each(function(link){
			link.writeAttribute('tabindex', tabindex);
		});
	},
	click: function(event) {
		event.stop();
		if (this.opened) {
			this.hide();
		} else {
			this.show();
		}
	},
	show: function() {
		if (!this.opened) {
			this.content.setStyle({position:"relative",left:"0"});
			this.content.writeAttribute('aria-hidden', 'false');
			this.trigger.writeAttribute('aria-expanded', 'true');
			this.setLinkTabIndex(0);
			this.opened = true;
			this.element.addClassName("active");

			// this checks if tooltip would be outside of the document and moves it to the left until it fits in
			var dims = this.content.getDimensions();
			var vport = document.viewport.getDimensions();
			
			while (parseInt(this.content.viewportOffset().left)+dims.width+2 > vport.width) {
				this.content.setStyle({
					left: (parseInt(this.content.getStyle("left"))-2)+"px"
				});
			}

			var that = this;
			var temp = function() {
				document.observe("mousedown", that.boundBodyClicked);
			}.delay(0.2);
			
			
		}
	},
	hide: function() {
		if (this.opened) {
			this.content.setStyle({position:"absolute",left:"-10000px"});
			this.content.writeAttribute('aria-hidden', 'true');
			this.trigger.writeAttribute('aria-expanded', 'false');
			this.setLinkTabIndex(-1);
			this.opened = false;
			this.element.removeClassName("active");

			document.stopObserving("click", this.boundBodyClicked);
		}
	},
	bodyClicked: function(event) {
		var sOffset = document.viewport.getScrollOffsets();
		var pos = {
			x: event.pointer().x + sOffset[0],
			y: event.pointer().y + sOffset[1]
		};
		if (!isInElement(pos, this.content)) {
			this.hide();
			document.stopObserving("mousedown", this.boundBodyClicked)
		}
	}
});

var Filterpulldown =  Class.create(Pulldown, {
	initialize: function($super, ancestor) {
		this.ancestor = ancestor;
		this.textLength = 15;
			
		this.createFakePulldown();
		
		$super($(this.ancestor.identify()+'-mirror'));
		
		this.content.select("a.option").each(function(link){
			link.observe("click", this.itemChanged.bindAsEventListener(this, link))
		}.bind(this));
	},
	createFakePulldown: function() {
		var activeText = this.ancestor.select("option").find(function(option) {
			return option.selected
		}).innerHTML;
		
		var flesh = '<div class="pdflesh noprint" aria-hidden="true"><div class="pdtop"></div><ul class="pdcontent">';
		this.ancestor.select('option').each(function(option) {
			flesh += '<li><a href="#" class="option">' + option.innerHTML + '</a></li>';
		});
		flesh += '</ul><div class="pdbottom"></div></div>';
		
		this.ancestor.insert({
			before: '<div class="pulldown" id="'+this.ancestor.identify()+'-mirror"><a href="#" class="pdhandler" title="'+activeText+'">'+activeText.truncate(this.textLength, "...")+'</a>'+flesh+'</div>'
		});
		
		this.ancestor.hide();	
	},
	itemChanged: function(event, link) {
		event.stop();
		if (!this.ancestor.options[link.up("li").previousSiblings().length].selected) {
			this.ancestor.options[link.up("li").previousSiblings().length].selected = true;
			this.trigger.update(link.innerHTML.truncate(this.textLength, "..."));
			this.trigger.writeAttribute("title", link.innerHTML);
			if (this.ancestor.up("form")) {
				this.ancestor.up("form").submit();
			}
		}
		this.hide();
	},
	show: function($super) {
		$super();
		
		if (this.opened) {
			this.content.setStyle("position:absolute; left:-2px;")
		}
	}
});

var Datefilterpulldown =  Class.create(Filterpulldown, {
	initialize: function($super, ancestor){
		this.defaultDate = "TT.MM.JJJJ";
		
		$super(ancestor);
		
		this.content.down(".btn-apply").observe("click", this.applyDate.bindAsEventListener(this));
	},
	createFakePulldown: function($super) {
		$super();
		
		var fromdate = this.defaultDate;
		var todate =this.defaultDate;
		
		if ($('fromdate')) {
			fromdate = $F('fromdate') || this.defaultDate;
			$('fromdate').remove();
		}
		if ($('todate')) {
			todate = $F('todate') || this.defaultDate;
			$('todate').remove();
		}
		
		if (fromdate != this.defaultDate && todate != this.defaultDate) {
			$(this.ancestor.identify()+'-mirror').down(".pdhandler").update("Zeitrahmen");
		}
		
		var datefilter = '<div class="timeentry"><label for="'+this.ancestor.identify()+'-l1'+'">von</label><input type="text" name="fromdate" value="'+fromdate.escapeSpecialChars() +'" maxlength="10" id="'+this.ancestor.identify()+'-l1'+'" /></div>';
		datefilter += '<div class="timeentry"><label for="'+this.ancestor.identify()+'-l2'+'">bis</label><input type="text" name="todate" value="'+todate.escapeSpecialChars()+'" maxlength="10" id="'+this.ancestor.identify()+'-l2'+'" /></div>';
		datefilter += '<a class="btn-apply" href="#"><img src="img/btn_anwenden.png" alt="anwenden" /></a>';
		
		$(this.ancestor.identify()+'-mirror').down("ul").insert({
			bottom: "<li class='zeitrahmen'>Zeitrahmen</li><li class='datefilter'>" + datefilter + "</li>"
		});
		
		$$('#' + this.ancestor.identify()+'-l1, #' + this.ancestor.identify()+'-l2').each(function(input) {
			input.observe("focus", function(event) {
				if (input.value == this.defaultDate) {
					input.value= "";
				}
			}.bindAsEventListener(this));
			
			input.observe("blur", function(event) {
				if (input.value == "") {
					input.value= this.defaultDate;
				}
			}.bindAsEventListener(this));
		}.bind(this));
	},
	applyDate: function(event) {
		event.stop();
		if ($F(this.ancestor.identify()+'-l2').match(/\d{2}\.\d{2}\.\d{4}$/) && $F(this.ancestor.identify()+'-l1').match(/\d{2}\.\d{2}\.\d{4}$/)) {
			$("date").value = '';
			this.trigger.update("Zeitrahmen");
			this.content.select('p.error').invoke("remove");
			
			if (this.ancestor.up("form")) {
				this.ancestor.up("form").submit();
			}

			this.hide();
		} else {
			if (this.content.down('li.datefilter p.error')) {
				this.content.down('li.datefilter p.error').highlight({duration:2, endcolor:"#c9e4fa"});
			} else {
				this.content.down('li.datefilter').insert({
					top: "<p class='error'>Bitte Zeitangaben &uuml;berpr&uuml;fen</p>"
				});
			}
		}
	},
	itemChanged: function($super, event, link) {
		this.content.select('p.error').invoke("remove");
		$(this.ancestor.identify()+'-l2').value = this.defaultDate;
		$(this.ancestor.identify()+'-l1').value = this.defaultDate;
		
		$super(event, link);
	}
});






Event.observe(document, "dom:loaded", function(){
	
	$(document.body).addClassName('dynd');
	var filter = $$(".datefilter")[0];
	if (! isIE6OrLess() && filter)
		new Datefilterpulldown( filter );

	
});
