
//----------------------------
// basisfunktionen
//----------------------------
function isIE(version){
	if(navigator.appName == "Microsoft Internet Explorer"){
		if(! version)
			return true;
		if(version == 6 && navigator.appVersion.search(/MSIE 6.0/) != -1)
			return true;
		if(version == 8 && navigator.appVersion.search(/MSIE 8.0/) != -1)
			return true;
	}
	return false;
}



// begrenzung von zeichen in einer textarea auf maximal-laenge
function checkMax(field, max) {
	var fieldLength = field.value.length;
	if (fieldLength>max) {
		field.value = field.value.substr(0,max);
		alert('Es sind max. '+max+' Zeichen erlaubt.');
	}
}

// begrenzung von zeichen in einer textarea auf maximal-laenge unter einbeziehung eines textes aus einem pulldown
function checkMaxMulti(f, fieldTXT, fieldPD, max) {
	var FieldTXT = f.elements[fieldTXT];
	var FieldPD = f.elements[fieldPD];
	var txtFieldLength = FieldTXT.value.length;
	var pdFieldLength = FieldPD.options[FieldPD.options.selectedIndex].value.length+1;
	if (pdFieldLength+txtFieldLength>max) {
		FieldTXT.value = FieldTXT.value.substr(0,max-pdFieldLength);
		alert('Es sind max. '+max+' Zeichen erlaubt.');
	}
}

// begrenzung von zeichen in einer textarea auf maximal-laenge (ausgabe in HTML-elementen anstatt alert)
function checkMaxTwitter(max) {
	var $ = jQuery;
	var fieldLength = $('#statement').val().length;
	if (fieldLength>max) {
		$('#statement-remaining').hide();
		$('#statement-remaining-count').html(0);
		$('#statement-shorten-count').html(fieldLength-max);
		$('#statement-shorten').show();
		$('#twitter-submit')[0].disabled = true;
	}
	else {
		$('#statement-remaining-count').html(max-fieldLength);
		$('#statement-remaining').show();
		$('#statement-shorten-count').html(0);
		$('#statement-shorten').hide();
		$('#twitter-submit')[0].disabled = false;
	}
}

// url parsen
function parseHost(u) {
	uw = u.replace(/:\/\//, "/");
	parts = uw.split("/");
	return(parts[1]);
}

// neues fenster
function newWin(h,t) {
	 var newwin=window.open(h, t);
	 //newwin.focus();
}

// dsi-tracking
function trackIntern(l) {
	self.location.href=rel2rootweb+'div/linktrack.php'+insertsid+'linkurl='+escape(l.href);
}

// dom-object
function oid(n) {
    return (document.getElementById?(document.getElementById(n)?document.getElementById(n):false):(document.all?(document.all(n)?document.all(n):false):false));
}
function otn(n) {
    return (document.getElementsByTagName?(document.getElementsByTagName(n)?document.getElementsByTagName(n):false):(document.all?(document.all(n)?document.all(n):false):false));
}


// timeout-cleaner
function cto(to){
	if (to!=false) window.clearTimeout(to);
}



//----------------------------
// spezielle funktionen
//----------------------------


// erlaeuterungen zu den botschafter-statements, verwendet in botschafter-galerie
var shownBotComment = 0;
function showBotComment(bid, state) {
	var lastBotComment = shownBotComment;
	var commentDiv = document.getElementById('bot-comment-'+bid);
	commentDiv.style.display = state==1?"block":"none";
	if (lastBotComment>0 && state==1) showBotComment(lastBotComment, 0);
	if (state==0) shownBotComment = 0;
	if (state==1) shownBotComment = bid;
}


// floater fuer Hauptnavigation
function getFloater(kap) {
	return oid(window.floaterPF+kap);
}
function switchFloater(kap, show) {
	var floater = getFloater(kap);
	if (floater!=false)
		floater.style.display = show==1?"block":"none";
	if (show==1) aktkap = kap;
}
function floatMN(kap, show) {
	var cornerCode = '<div class="corner"></div>';
	var floater = getFloater(kap);
	if (floater!=false)
		floater.innerHTML = "<p>"+floaterTexte[kap]+"</p>"+cornerCode;
	if (typeof aktkap!=undefined && aktkap!="" && show==1) switchFloater(aktkap, 0);
	cto(window.to);
	var secs = show==1?300:900;
	to = window.setTimeout("switchFloater('"+kap+"', "+show+")", secs);
}


// adding floater-event in mainnav-mouse-events (over'n'out)
function initMainNavFloat() {
	aktkap = "";
	floaterPF = 'mf-';
	floaterTexte = new Object();
	floaterTexte["kampagne"]		= "Informationen &uuml;ber die Kampagne";
	floaterTexte["botschafter"]		= "Selbst Botschafter werden oder Botschafter ansehen";
	floaterTexte["aktionen"]		= "Das passiert rund um den Welt-Aids-Tag";
	floaterTexte["schleifezeigen"]	= "Stoffschleifen, virtuelle Schleifen, Buttons und Banner";
	floaterTexte["meinungen"]		= "Meinungen zum Welt-Aids-Tag, Austausch";
	floaterTexte["statements"]		= "Statements zum Welt-Aids-Tag, Austausch";
	floaterTexte["blog"]			= "Neuigkeiten, Blick hinter die Kulissen, Austausch";
	floaterTexte["presse"]			= "Material f&uuml;r Journalisten (auch Sch&uuml;lerzeitungen)";
	floaterTexte["hintergruende"]	= "Das solltet ihr &uuml;ber Aids wissen";
	oid("mn-kampagne").onmouseover=function(){floatMN('kampagne', 1)};
	oid("mn-kampagne").onmouseout=function(){floatMN('kampagne', 0)};
	oid("mn-botschafter").onmouseover=function(){floatMN('botschafter', 1)};
	oid("mn-botschafter").onmouseout=function(){floatMN('botschafter', 0)};
	oid("mn-aktionen").onmouseover=function(){floatMN('aktionen', 1)};
	oid("mn-aktionen").onmouseout=function(){floatMN('aktionen', 0)};
	oid("mn-schleifezeigen").onmouseover=function(){floatMN('schleifezeigen', 1)};
	oid("mn-schleifezeigen").onmouseout=function(){floatMN('schleifezeigen', 0)};
	oid("mn-meinungen").onmouseover=function(){floatMN('meinungen', 1)};
	oid("mn-meinungen").onmouseout=function(){floatMN('meinungen', 0)};
	oid("mn-statements").onmouseover=function(){floatMN('statements', 1)};
	oid("mn-statements").onmouseout=function(){floatMN('statements', 0)};
	oid("mn-blog").onmouseover=function(){floatMN('blog', 1)};
	oid("mn-blog").onmouseout=function(){floatMN('blog', 0)};
	oid("mn-presse").onmouseover=function(){floatMN('presse', 1)};
	oid("mn-presse").onmouseout=function(){floatMN('presse', 0)};
	oid("mn-hintergruende").onmouseover=function(){floatMN('hintergruende', 1)};
	oid("mn-hintergruende").onmouseout=function(){floatMN('hintergruende', 0)};
}

var searchFieldDefault = 'Suche';
function initSearchToggler() {
	oid("suchbegriff").value = searchFieldDefault;
	oid("suchbegriff").style.color = '#888';
	oid("suchbegriff").onfocus=function(){searchFieldToggle('in')};
	oid("suchbegriff").onblur=function(){searchFieldToggle('out')};
}
function searchFieldToggle(x) {
	var f = oid("suchbegriff");
	if (x=='in') {
		if (f.value==searchFieldDefault) {
			f.value = '';
			f.style.color = '#333';
		}
	} else {
		if (f.value=='') {
			f.value = searchFieldDefault;
			f.style.color = '#888';
		}
	}
}

// main init/deinit
init = function() {
	//initMainNavFloat();
	//ariaSetRequired();
	initSearchToggler();
}
deinit = function() {
	cto(window.to);
}
//window.onload=init;
window.onunload=deinit;
window.onload=init;
//init();



//function $(id) {
//	return document.getElementById(id);
//}

function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

function addEvent(obj, typ, fun) {
	if (obj.addEventListener) {
		obj.addEventListener( typ, fun, false);
		return true;
	} else if (obj.attachEvent) {
		return obj.attachEvent("on"+typ, fun);
	}
	return false;
}



// ARIA-STUFF

function getAttributeValue(o,a) {
	if (o.getAttribute(a)) {
		return o.getAttribute(a);
	} else {
		return o.attributes[a].value;
	}
}
function setAttributeValue(o,a,v) {
	if (o.setAttribute(a,v,0)) {
		o.setAttribute(a,v,0);
	} else {
		o.attributes[a].value=v;
	}
}

function ariaSetRequired() {
	var allLabels = otn("label");
	for (l=0; l<allLabels.length; l++) {
		var labelText = allLabels[l].innerHTML;
		if (labelText.indexOf('Pflichtfeld')>0) {
			var fieldId = getAttributeValue(allLabels[l], "for");
			//alert(fieldId);
			setAttributeValue(oid(fieldId), "aria-required", "true");
		}
	}
}

/**
  * Stellt Debug-Messages fuer Firefox, IE8, Opera, Safari, Chrome (Konsole) und IE<8 (alert) zur Verfuegung.
 * @param string text
 */
function lg(text) {
	if (typeof (opera) != "undefined" && opera != null) {
		opera.postError(text);
		return;
	} else if (typeof (console) != "undefined" && console != null) {
		console.log(text);
		return;
	} else {
		alert(text);
	}
}


//////////////////////////
// Prototype-abhaengiges JS
//////////////////////////

//$(document).observe("dom:loaded", function() {
	//$$('.statements-imgnav a').each(function(elm) {
		//id = parseInt(elm.href.split("bid=")[1]);
		//new StatementTooltip(elm, id, {});
	//});

	//$$('.botschafterbox .botschafter img.burl').each(function(elm) {
		//id = parseInt(elm.className.split("bid-")[1]);
		//new StatementTooltip(elm, id, {
			//followLink: false
		//});
	//});

	//$$('.headtip').each(function(elm) {
		//id = parseInt(elm.className.split("bid-")[1]);
		//new StatementTooltip(elm, id, {
			//followLink: true,
			//followMouse: false,
			//upsideDown: true,
			//pathToContent: rel2rootweb + "div/tooltip-header.php"
		//});
	//});


	//$(document.body).addClassName("dynd");
//});


/////////////////////////
// Tooltip fuer Statements
/////////////////////////

//eingie Objekte global verfügbar machen
var StatementTooltip,
	Windowblind,
	Glider,
	GliderHoriz


(function($){
	$(document).ready(function(){
		$('.statements-imgnav a').each(function() {
			var elm = $(this);
			id = parseInt(elm.href.split("bid=")[1]);
			new StatementTooltip(elm, id, {});
		});
//		$('.botschafterbox .burl').each(function() {
//			var elm = $(this);
//			id = parseInt(elm.attr("class").split("bid-")[1]);
//			new StatementTooltip(elm, id, {
//				followLink: true
//			});
//		});

//		// Tooltip für die Botschafter-Galerie initialisieren 
//		$('#slider .burl').each(function() {
//			var elm = $(this);
//			id = parseInt(elm.attr("class").split("bid-")[1]);
//			new StatementTooltip(elm, id, {
//				followLink: true,
//				animate: false,
//				forceSwitchDelay: true
//			});
//		});

		$('#tab_statements .stmt_burl').each(function() {
			var elm = $(this);
			id = parseInt(elm.attr("class").split("bid-")[1]);
			new StatementTooltip(elm, id, {
				followLink: true,
				pathToContent: rel2rootweb + "menschen/tooltip.php"
			});
		});


		$('.headtip').each(function(){
			var elm = $(this);
			id = parseInt(elm.attr("class").split("bid-")[1]);
			new StatementTooltip(elm, id, {
				followLink: true,
				followMouse: false,
				upsideDown: true,
				pathToContent: rel2rootweb + "div/tooltip-header.php"
			});
		});

		$(".gallery").each(function(){
			new Gallery(this);
		});

		$("BODY").addClass("dynd");

		$(".equalize-heights").each(function(){
			var that = this;
			$('img', this).load(function(){
				var leftH = $(".halfsize-left", that).innerHeight();
				var rightH = $(".halfsize-right", that).innerHeight();
				if (leftH && rightH) {
					if (leftH > rightH) {
						$(".halfsize-right", that).innerHeight(leftH)
					}
					if (leftH < rightH) {
						$(".halfsize-left", that).innerHeight(rightH)
					}
				}
			});
		});
		

	});



	////////////////////////////////
	// Jalousie-Modul fuer Startseite
	////////////////////////////////
	Windowblind = function(elem, params){
		this.init(elem, params);
	};

	Windowblind.prototype = {
		init: function(elem, params){
			this.$elem = $(elem);
			this.$entries = this.$elem.find("li");
			this.$contents = this.$elem.find(".content");
			this.$scope = this.$elem.attr("id") || "pseudo-scope"+Math.round(Math.random()*1000);
			this.duration = params ? params.duration || 0.4 : 0.4;

			if (params && params.addition && $(params.addition).find("li").size() == this.$entries.size()) {
				this.$adds = $(params.addition).find("li");

				if( !this.$adds.first().find(".active") )
					this.$adds.first().addClass("active");
				this.$activeAdd = this.$adds.find(".active").first();
				this.$adds.hide();
				this.$activeAdd.show();
			}

			if(!this.$elem.find(".active").size())
				this.$entries.first().addClass("active");

			this.$active = this.$elem.find(".active").first();
			this.$activeContent = this.$active.find(".content").first();

			this.heights = [];
			var that = this;
			this.$contents.each(function() {
				var $elem = $(this);
				$elem.css({height: "auto", display: "block"});

				that.heights.push($elem.innerHeight());

				if( !$elem.parent().parent().hasClass("active") )
					$elem.css({height: "0px", display: "none"});
			});

			this.$entries.each(function(index){
				var $li = $(this);
				$li.find(".handler").first().bind("click", function(ev){ that.click(ev, index) });
			});
		},
		click: function(event, index){
			event.preventDefault();
			if(this.$entries[index] == this.active)
				return
			this.$contents.eq(index).css({display: "block"});

			var duration = 400;

			this.$contents.eq(index).animate({ height: this.heights[index] + "px" }, duration);
			jQuery(this.$entries.eq(index)).find('.contentwrapper').animate({ "background-color" : "#ffffff" }, duration);
			this.$activeContent.animate({ height: "0px"}, duration);
			jQuery(this.$active).find('.contentwrapper').animate({"background-color" : "#ececec"}, duration);
//			alert(jQuery(this.$active).html());

			if(this.$adds){
				this.$adds.eq(index).fadeIn();
				this.$activeAdd.fadeIn();
			}

			window.setTimeout($.proxy(function(){
				this.$active.removeClass("active");
				this.$activeContent.css("display", "none");
				this.$activeContent.find("A").attr("tabindex", "-1");
				this.$active = this.$entries.eq(index).addClass("active");
				this.$activeContent = this.$contents.eq(index);
				this.$activeContent.find("a").attr("tabindex", "0");
				if(this.$adds){
					this.$activeAdd.removeClass("active");
					this.$activeAdd = this.$adds.eq(index).addClass("active");
				}
			}, this),
			duration);
		}
	};


	// param animate: false verhindert die Animation beim Positionswechsel des Tooltips
	// param forceSwitchDelay : true sorgt dafür, dass beim Tooltip-Wechsel zuerst aus und dann nach delay wieder eingeblendet wird
	StatementTooltip = function(elem, id, params){
		this.init(elem, id, params);
	};
	StatementTooltip.prototype = {
		timeoutLeave: null,
		timeoutEnter: null,

		init : function(elem, id, params){
			this.$elem = $(elem);
			this.id = id;
			this.content;
			this.params = params || {};
			
			this.$tooltip = $("#tooltip").first();
			if( !this.$tooltip.size() ){
				this.$tooltip = $("<div id='tooltip' style='display:none;'><div id='tooltip-top'><div id='nurpleTop'></div></div><div id='tooltip-content'></div><div id='tooltip-bottom'><div id='nurpleBottom'></div></div></div>");
				$("body").append(this.$tooltip);
				this.$tooltip.mouseover($.proxy(function(){
					window.clearTimeout(StatementTooltip.timeoutLeave)
					StatementTooltip.timeoutLeave = null;
				}, this));
				this.$tooltip.mouseout($.proxy(this, "mouseleave"));
			}
			this.$elem.mouseenter($.proxy(this, "mouseenter"));
			this.$elem.mouseleave($.proxy(this, "mouseleave"));

			this.$elem.attr("title", "");

			if(this.params.followLink == false){
				this.$elem.click(function(ev){ev.preventDefault();});
			}
		},

		mouseenter: function(ev){
						
			window.clearTimeout(StatementTooltip.timeoutLeave);
			StatementTooltip.timeoutLeave = null;
			var fail = true;
			if( !this.content){
				var that = this;
				var pars = { bid: this.id };
				if(this.params.noSendLink)
					pars.noSendLink = this.params.noSendLink
				
				$("#tooltip-content").load(
					this.params.pathToContent || "tooltip.php",
					pars,
					function(resp){
						if(resp != ''){
							that.content = resp;
							that.show(ev);
						}
					}
				)
			}
			else{
				$('#tooltip-content').html(this.content);
				this.show(ev);
			}
		},

		mouseleave: function(){
			this.$tooltip.clearQueue();
			if(! StatementTooltip.timeoutLeave )
				StatementTooltip.timeoutLeave = window.setTimeout($.proxy( this, "hide" ), 400);
		},

		hide: function(){
			if(! isIE())
				this.$tooltip.fadeOut(400);
			else
				this.$tooltip.hide();
		},

		show: function(ev){
			if(this.params.upsideDown)
				this.$tooltip.addClass("upsideDown")
			else
				this.$tooltip.removeClass("upsideDown")
			var x,y;
			
			// Wenn es zu dem Botschafter keine Detailansicht gibt, wird die css-Klasse "tooltip-no-details" hinzugefügt.
			if(this.params.hasDetails === false) {
				jQuery("#tooltip").addClass('tooltip-no-details');
			}
			else {
				jQuery("#tooltip").removeClass('tooltip-no-details');
			}
			
			if(this.params.followMouse){
				y = event.pageY;
				x = event.pageX;
			}
			else if(this.params.upsideDown){
				y = this.$elem.offset().top + this.$elem.innerHeight();
				x = this.$elem.offset().left + (this.$elem.innerWidth() / 2) - 20;
			}
			else{
				y = this.$elem.offset().top - this.$tooltip.innerHeight() + 15;
				x = this.$elem.offset().left + 20;
				// -50 ist der Wert, den der Pfeil vom linken Rand der tooltip-borderbottom2.png entfernt ist
				// 0.66 gibt an, dass der Pfeil auf 2/3 des Bildes positioniert ist
				x = this.$elem.offset().left + parseInt(this.$elem.innerWidth()*0.66) - 50;
				
			}


			//Wenn das Tooltip Ã¼ber den rechten Rand heraus ragt
			var dw = $(document).width(),
				tw = this.$tooltip.innerWidth()
			if((x + tw) > dw){
				x = dw - tw;
				this.$tooltip.addClass("variableNurple");
				var tx = ($(ev.target).offset().left + ($(ev.target).innerWidth() / 2)) - x
				
				var $el
				if(this.params.upsideDown)
					$el = $("#nurpleTop");
				else
					$el = $("#nurpleBottom");
				$el.css({
					position: "absolute",
					top: "0",
					left: tx +"px"
				});
			}
			else
				this.$tooltip.removeClass("variableNurple");

			if(this.$tooltip.css("display") != "none" && this.params.animate !== false){
				this.$tooltip.animate({ left: x +"px", top: y +"px" }, 400);
			}
			else{
				this.$tooltip.css({ left: x +"px",
									top: y + "px",
									position: "absolute" });
			}
			if(! isIE()) {
				this.$tooltip.fadeIn(400);
			}
			else {
				this.$tooltip.show();
			}
		}
	};

	// if (!window.console || !console.firebug) {
	//     var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
	// 	    "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
	// 
	// 	window.console = {};
	// 	for (var i = 0; i < names.length; ++i)
	// 		window.console[names[i]] = function() {}
	// }

	function Gallery(elm){
		this.init(elm);
	}
	Gallery.prototype = {
		init : function(elm){
			this.isAnimating = false;
			this.currentlyShown = 0;
			this.$imgContainer;
			this.$textContainer;
			this.$elem = $(elm);
			this.$blocks = this.$elem.find(".galleryBlock");
			this.numBlocks = this.$blocks.size();
			if(this.numBlocks > 1){
				this.$blocks.hide();
				this.createMarkup();
				this.show();
			}
		},
		createMarkup: function(){
			var $html = $(""
				+ "<div class='galleryTop'><img src=''/></div>"
				+ "<div class='galleryBottom clearfix'>"
				+	'<div class="galleryText"><p class="imgDescription"></p></div>'
				+   '<div class="galleryCount"><span class="galleryCount1">1</span> / <span class="galleryCount2">' + this.numBlocks +'</span></div>'
				+   '<div class="galleryControls clearfix">'
				+	'	<img class="btn btnPrev" src="' + rel2rootweb +'/img/v07/basics/btn_prev_fotogal.gif" alt="zur&uuml;ck" />'
				+   ' 	<img class="btn btnNext" src="' + rel2rootweb +'/img/v07/basics/btn_next_fotogal.gif" alt="weiter" /> '
				+   '</div>'
				+ "</div>");
			this.$elem.append($html);
			this.$imgContainer = this.$elem.find(".galleryTop");
			this.$textContainer = this.$elem.find(".galleryText");
			$html.find(".btn").bind("click", $.proxy(this, "show"));
		},

		show: function(ev){
			if(! this.isAnimating){
				this.isAnimating = true;
				if(ev != undefined){
					if($(ev.target).hasClass("btnNext")){
						this.currentlyShown ++;
						if(this.currentlyShown >= this.numBlocks)
							this.currentlyShown = 0;
					}
					else if($(ev.target).hasClass("btnPrev")){
						this.currentlyShown --;
						if(this.currentlyShown < 0)
							this.currentlyShown = this.numBlocks - 1;
					}
				}

				var duration = 200;
				this.$imgContainer.find("IMG").fadeOut(duration);
				this.$textContainer.find(".imgDescription").fadeOut(duration, $.proxy(function(){
					this.$textContainer.html("");
					this.$imgContainer.html("");
					var $img = this.$blocks.eq(this.currentlyShown).find("IMG").first().clone();
					var $text = this.$blocks.eq(this.currentlyShown).find(".imgDescription").first().clone();
					if($text.html() == '')
						$text.html("&nbsp;");
					this.$imgContainer.append($img.hide());
					this.$textContainer.append($text.hide());
					$img.fadeIn(duration);
					$text.fadeIn(duration, $.proxy(function(){this.isAnimating = false}, this));
					this.$elem.find(".galleryCount1").html(this.currentlyShown+1);
					this.isAnimating = true;
				}, this));
			}
		}
	};



	/** GLIDER **/
	GliderHoriz = function(element, viscount){
		// find necessary elements
		this.$element = $(element);
		this.$ul = this.$element.find("ul").first();
		this.$left = this.$element.find("a.d_btnPageLeft").first();
		this.$right = this.$element.find("a.d_btnPageRight").first();
		this.$items = this.$ul.children();
		// set initial values
		this.animating = false;
		this.currentIndex = 0;
		this.itemWidth = this.$items.eq(0).innerWidth();	// get standard width of <li>-items. don't apply margins or paddings to the <li>s,  use an inner <div> with your margins/paddings instead«
		this.itemHeight = this.$items.eq(0).outerHeight(true);	// get standard width of <li>-items. don't apply margins or paddings to the <li>s,  use an inner <div> with your margins/paddings instead«
		this.count = this.$items.size();
		this.visibleElements = (viscount ? viscount : 2);	// determine, how many items fit in your scroll-window
		this.elmsToScroll = Math.min((this.count - this.visibleElements), this.visibleElements);	// how many items scroll on each click?
		this.animationDuration = Math.min(150 * this.elmsToScroll, 1300);
		this.animationEasing = "easeInOutExpo";  //easeInOutExpo, easeOutExpo, easeOutElastic, easeInOutElastic, easeInBack, easeInOutBack, easeOutBounce

		// set sizes to calculated values in case they were just estimated before
		this.$ul.css({
			width: this.itemWidth*this.count+"px",
			position: "relative",
			left: "0"
		});

		// bind event handlers to the links
		var that = this;
		this.$left.bind("click", function(){ that.pageRight();} );
		this.$right.bind("click", function(){ that.pageLeft();} );
		this.$right.attr("href","javascript: void(0)");
		this.$left.attr("href","javascript: void(0)");

		if (this.count <= this.visibleElements) {
			this.$left.hide();
			this.$right.hide();
		}
	}

	GliderHoriz.prototype = {

		pageRight: function(){
			if (!this.animating) {
				this.animating = true;
				this.currentIndex -= this.elmsToScroll;
				// if not enough elements available to perform the scroll, move them to the top of the list
				while (this.currentIndex < 0) {
					var temp = this.$items.eq(this.count-1).remove();
					this.$ul.prepend(temp);

					var left = parseInt(this.$ul.css("left")) || 0;
					this.$ul.css({
						left: (left - this.itemWidth) + "px"
					});

					this.$items = this.$ul.children();
					++this.currentIndex;
				}
				// perform the gliding effect
				var that = this;
				var left = (parseInt(this.$ul.css("left").replace("px","")) || 0) + (this.elmsToScroll * this.itemWidth);
				this.$ul.animate(
					{
						"left" : left
					},
					{
						//duration: Math.min(150 * this.elmsToScroll, 1300),
						duration: this.animationDuration,
						easing: this.animationEasing,
						complete: function(){ that.animating = false; }
					}
				);
			}
		},

		pageLeft: function() {
			if (!this.animating) {
				this.animating = true;
				this.currentIndex += this.elmsToScroll;
				// if not enough elements available to perform the scroll, move them to the end of the list
				while (this.currentIndex + this.visibleElements > this.count) {
					var el = this.$items.eq(0).remove();
					this.$ul.append(el);

					var left = parseInt(this.$ul.css("left")) || 0;
					this.$ul.css({
						left: (left + this.itemWidth) + "px"
					});
					this.$items = this.$ul.children();
					--this.currentIndex;
				}

				// perform the gliding effect
				var that = this;

				var left = (parseInt(that.$ul.css("left").replace("px", "")) || 0) - (that.elmsToScroll * that.itemWidth);
				this.$ul.animate(
					{
						"left" : left
					},
					{
						//duration: Math.min(150 * this.elmsToScroll, 1300),
						duration: this.animationDuration,
						easing: this.animationEasing,
						complete: function(){ that.animating = false; }
					}
				);
			}
		},
		pageTop: function(){
			if (!this.animating) {
				this.animating = true;
				this.currentIndex -= this.elmsToScroll;
				// if not enough elements available to perform the scroll, move them to the top of the list
				while (this.currentIndex < 0) {
					var temp = this.$items.eq(this.count-1).remove();
					this.$ul.prepend(temp);

					var top = parseInt(this.$ul.css("top")) || 0;
					this.$ul.css({
						top: (top - this.itemHeight) + "px"
					});

					this.$items = this.$ul.children();
					++this.currentIndex;
				}
				// perform the gliding effect
				var that = this;
				var top = (parseInt(this.$ul.css("top").replace("px","")) || 0) + (this.elmsToScroll * this.itemHeight);
				this.$ul.animate(
					{
						"top" : top
					},
					{
						//duration: Math.min(150 * this.elmsToScroll, 1300),
						duration: this.animationDuration,
						easing: this.animationEasing,
						complete: function(){ that.animating = false; }
					}
				);
			}
		},

		pageBottom: function() {
			if (!this.animating) {
				this.animating = true;
				this.currentIndex += this.elmsToScroll;
				// if not enough elements available to perform the scroll, move them to the end of the list
				while (this.currentIndex + this.visibleElements > this.count) {
					var el = this.$items.eq(0).remove();
					this.$ul.append(el);

					var top = parseInt(this.$ul.css("top")) || 0;
					this.$ul.css({
						top: (top + this.itemHeight) + "px"
					});
					this.$items = this.$ul.children();
					--this.currentIndex;
				}

				// perform the gliding effect
				var that = this;

				var top = (parseInt(that.$ul.css("top").replace("px", "")) || 0) - (that.elmsToScroll * that.itemHeight);
				this.$ul.animate(
					{
						"top" : top
					},
					{
						//duration: Math.min(150 * this.elmsToScroll, 1300),
						duration: this.animationDuration,
						easing: this.animationEasing,
						complete: function(){ that.animating = false; }
					}
				);
			}
		}
	};


	Glider = function (element, visibleElements){
		// find necessary elements
		this.$element = $(element);
		this.$ul = this.$element.find("ul").first();
		this.$left = this.$element.find("a.d_btnPageLeft").first();
		this.$right = this.$element.find("a.d_btnPageRight").first();
		this.$items = this.$ul.children();
		var that = this;
		// set initial values
		this.animating = false;
		this.currentIndex = 0;
		this.itemWidth = this.$items.eq(0).innerWidth();	// get standard width of <li>-items. don't apply margins or paddings to the <li>s,  use an inner <div> with your margins/paddings insteadÃ‚Â´
		this.itemHeight = this.$items.eq(0).outerHeight(true);
		var that = this;
		if(isIE(6)){ //omg IE6 is a bunch of crap
			window.setTimeout(function(){
				 that.itemHeight = that.$items.eq(0).outerHeight(true);
			}, 300);
		}
		this.count = this.$items.size();
		//this.visibleElements = Math.floor(this.$element.find("ul").first().innerHeight() / this.itemHeight);	// determine, how many items fit in your scroll-window

		if(visibleElements)
			this.visibleElements = parseInt(visibleElements);
		else
			this.visibleElements = 3;

		// this.elmsToScroll = Math.min((this.count - this.visibleElements), this.visibleElements);	// how many items scroll on each click?
		this.elmsToScroll = 1; //fest auf 1, wegen Ausblende-Effekt etc.
		this.animationDuration = Math.min(150 * this.elmsToScroll, 1300);
		this.animationEasing = "easeInOutExpo";  //easeInOutExpo, easeOutExpo, easeOutElastic, easeInOutElastic, easeInBack, easeInOutBack, easeOutBounce

		// set sizes to calculated values in case they were just estimated before
//		this.$ul.css({
//			width: this.itemWidth*this.count+"px",
//			position: "relative",
//			left: "0"
//		});


		// bind event handlers to the links
		this.$right.bind("click", function(){ that.pageBottom();} );
		this.$left.bind("click", function(){ that.pageTop();} );

		this.$right.attr("href","javascript: void(0)");
		this.$left.attr("href","javascript: void(0)");

		if (this.count <= this.visibleElements) {
			this.$left.add(this.$right).addClass("hidden");
			this.$element.addClass("noButtons");
		}

	}

	Glider.prototype = {
		pageTop: function(){
			
			if (!this.animating) {
				this.animating = true;
				this.currentIndex -= this.elmsToScroll;
				// if not enough elements available to perform the scroll, move them to the top of the list
				this.loopTimes = 1;
				// console.log("currentIndex: " + this.currentIndex)
				while (this.currentIndex < 0) {
					this.moveOneElemBottomToTop();
				}
				// perform the gliding effect
				var that = this;

				var top = (parseInt(this.$ul.css("top").replace("px","")) || 0) + (this.elmsToScroll * this.itemHeight);
				this.$ul.animate(
					{
						"top" : top
					},
					{
						//duration: Math.min(150 * this.elmsToScroll, 1300),
						duration: this.animationDuration,
						easing: this.animationEasing,
						complete: function(){ that.animating = false; }
					}
				);
			}
		},

		moveOneElemBottomToTop: function(){
			var $el = this.$items.eq(this.count-1).remove();
			this.$ul.prepend($el);

			if(! $el.hasClass("hidden")){
				var top = parseInt(this.$ul.css("top")) || 0;
				this.$ul.css({
					top: (top - this.itemHeight) + "px"
				});
				this.currentIndex++;
			}
			this.$items = this.$ul.children();
			if($el.hasClass("hidden")){
				this.moveOneElemBottomToTop();
			}
		},

		pageBottom: function() {
			if (!this.animating) {
				this.animating = true;
				this.currentIndex += this.elmsToScroll;
				// if not enough elements available to perform the scroll, move them to the end of the list
				// console.log("while " + (this.currentIndex+this.visibleElements) + " > " + this.count);
				while (this.currentIndex + this.visibleElements >= this.count) {
					this.moveOneElemTopToBottom();
				}
				// perform the gliding effect
				var that = this;

				var top = (parseInt(that.$ul.css("top").replace("px", "")) || 0) - (that.elmsToScroll * that.itemHeight);
				this.$ul.animate(
					{
						"top" : top
					},
					{
						//duration: Math.min(150 * this.elmsToScroll, 1300),
						duration: this.animationDuration,
						easing: this.animationEasing,
						complete: function(){ that.animating = false; }
					}
				);
			}
		},

		moveOneElemTopToBottom: function() {
			var $el = this.$items.eq(0).remove();
			this.$ul.append($el);
			if(! $el.hasClass("hidden")){
				var top = parseInt(this.$ul.css("top")) || 0;
				this.$ul.css({
					top: (top + this.itemHeight) + "px"
				});
				this.currentIndex--;
			}
			this.$items = this.$ul.children();

			//Sonderbehandlung, wenn das ausgeblendete Element verschoben wurde
			if($el.hasClass("hidden")){
				this.moveOneElemTopToBottom();
			}
		}

	};


})(jQuery);




