// usage: log('inside coolFunc', this, arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
	log.history = log.history || [];   // store logs to an array for reference
	log.history.push(arguments);
	arguments.callee = arguments.callee.caller;
	if(this.console) console.log( Array.prototype.slice.call(arguments) );
};
// make it safe to use console.log always
(function(b){function c(){}for(var d="assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,markTimeline,profile,profileEnd,time,timeEnd,trace,warn".split(","),a;a=d.pop();)b[a]=b[a]||c;})(window.console=window.console||{});

/*
 * Author: Bastian Gutschke
 */

// is called when hyphenation is done. elements with class hyph will be hyphenated. class nohyph disables hyphenating.
function onHyphenationDone(){
	log("hyphenation done.");
};


(function($){

	// global object with settings
	var dw = {
		// get url params as object
		"params": (function(){
			var params = {};
			var rawParams = window.location.search;
			if(rawParams === ""){
				return params;
			}
			else{
				rawParams = rawParams.substring(rawParams.indexOf("?")+1).split("&");
				for(var idx in rawParams){
					var param = rawParams[idx].split("=");
					param[1] === "true" ? param[1] = true : param[1] = false;
					params[param[0]] = param[1];
				}
				return params;
			}
		})()
	};

	/* show dev comments if parameter dev === true */
	(function(){
		if(dw.params.dev){
			$(".dev, .dev_mod").show();
			$(".mod_m1").css("background-color", "#11ffff");
			$(".mod_m2").css("background-color", "#ff11ff");
			$(".mod_m3").css("background-color", "#ffff11");
			$(".mod_m4").css("background-color", "#11ff11");
			$(".mod_m5").css("background-color", "#11cc11");
			$(".mod_m6").css("background-color", "#ddaaaa");
		}
	})();


	// cookie functions
	function createCookie(name,value,days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else var expires = "";
		document.cookie = name+"="+value+expires+"; path=/";
	}

	function readCookie(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return null;
	}

	function eraseCookie(name) {
		createCookie(name, "", -1);
	}

	function wazGetUserLogin(cookieName) {
		var ssoCookie = unescape(readCookie(cookieName));
		var user = {};
		// get hash, token and loginName:
		var ssoCookieParts = ssoCookie.split(/&|=/);
		for (var i = 0; i < ssoCookieParts.length; i+=2) {
			user[ssoCookieParts[i]] = (ssoCookieParts.length > i) ? ssoCookieParts[1 + i] : "";
		}
		return (user.l !== undefined) ? user : null;
	};


	// Helper function to get the right index for galleries.
	var getIndex = function( idx, length ) {
		if( idx >= length ){
			return idx % length;
		}
		else if( length === 1) {
			return 0;
		}
		else if( idx < 0 ) {
			return getIndex( length + (idx % length) );
		}
		else {
			return idx;
		}
	};


	String.prototype.transferUmlaut = function() {
		var chars = new Array('Ä', 'ä', 'Ö', 'ö', 'Ü', 'ü', ' ');
		var transfer = new Array('Ae', 'ae', 'Oe', 'oe', 'Ue', 'ue', '-');

		var newString = this;
		for ( var i = 0; i < chars.length; i++) {
			var myRegExp = new RegExp();
			myRegExp.compile(chars[i], 'g');
			newString = newString.replace(myRegExp, transfer[i]);
		}
		return newString;
	};

	/*
	 * Override fade functions in ie7 and ie8
	 */
	(function($) {
		// Store references to the original methods.
		var originalFadeInMethod = $.fn.fadeIn;
		var originalFadeOutMethod = $.fn.fadeOut;

		// extract callback functions
		function getCallback(args) {
			var args = Array.prototype.slice.call(args);
			for(var i=0, length=args.length; i<length; i++) {
				if(typeof args[i] == "function") {
					return args[i];
				}
			}
			return;
		};

		// Define overriding fade in method.
		$.fn.fadeIn = function(){

			// switch to show if ie7/ie8
			if($("html").hasClass("ie7") || $("html").hasClass("ie8")) {
				var $elements = $(this).show();
				var callback = getCallback(arguments);
				if( typeof callback == "function" ) {
					callback.apply(this);
				}
				return $elements;
			}
			else {
				// Execute the original method.
				return originalFadeInMethod.apply( this, arguments );
			}
		};

		// Define overriding fade out method.
		$.fn.fadeOut = function(){

			// switch to hide if ie7/ie8
			if($("html").hasClass("ie7") || $("html").hasClass("ie8")) {
				var $elements = $(this).hide();
				var callback = getCallback(arguments);
				if( typeof callback == "function" ) {
					callback.apply(this);
				}
				return $elements;
			}
			else {
				// Execute the original method.
				return originalFadeOutMethod.apply( this, arguments );
			}
		};
	})($);



	$.fn.wait = function(time, type) {
		var time = time || 200;
		var type = type || "fx";

		return this.queue(type, function() {
			var that = this;
			setTimeout(function() {
				$(that).dequeue();
			}, time);
		});
	};


	//TODO Revision by Bastian (written by Ingo Kleinert, unitb consulting)////////////////////////////////////////////
	//saves last user search texts in a cookie
	$.fn.wazAddSearch = function(opts){
		var options = $.extend({
			query: null,
			maxSearches: 10
		}, opts);

		var searches = [];

		if($.cookie("mysearches")) {
			searches = $.cookie("mysearches").split(",");
		}

		if($.inArray(options.query, searches) !== 0) {
			if($.inArray(options.query, searches) > -1) {
				searches.splice($.inArray(options.query, searches),1);
			}

			searches.unshift(options.query);

			if(searches.length > options.maxSearches) {
				searches.splice(options.maxSearches, searches.length - options.maxSearches);
			}

			$.cookie("mysearches", searches.join(","), { expires: 3650, path: "/" });
		}
	};



	$.fn.wazAz = function(){
		return this.each(function(){
			if( $(".btn_active", this).size() === 0 ) {
				return;
			}

			var $active = $(".btn_active", this);
			var $btns = $(".btn", this);
			var $container = $(".links", this);

			var load = function(){
				$.ajax({
					"data": {},
					"type": "GET",
					"url": $active.attr("href")
				})
				.success(function(data, textStatus, jqXHR){
					$container.html(data);
				})
				.error(function(jqXHR, textStatus, errorThrown){
					log("error", jqXHR, textStatus, errorThrown);
				});
			};
			load();

			$btns.click(function(e){
				$active
					.removeClass("btn_active");
				$(this)
					.addClass("btn_active");
				$active = $(this);
				load();

				// TODO: Zählpixel

				return false;
			});

		});
	};


	/* 2.15. Blätterwidget */
	$.fn.wazBrowse = function(opts){
		var options = $.extend({
			"duration": 250
		}, opts);

		return this.each(function(){
			log("$.fn.wazBrowse", this);

			var $mods = $(".mod", this);
			var count = $mods.size();

			if( count < 2 ) {
				return;
			}

			var index = 0;

			var $img = $(".img", this);

			var offsetTop = $img.height()/2 - 17;
			var $prev = $("<a class=\"prev\" style=\"top: "+ offsetTop +"px\" />");
			var $next = $("<a class=\"next\" style=\"top: "+ offsetTop +"px\" />");


			// hide all mods, but the first one
			$mods
				.not(":first-child")
				.hide();

			var browse = function(idx){
				$mods
					.stop()
					.eq(index)
					.fadeOut(options.duration, function(){
						$mods
							.eq(idx)
							.fadeIn(options.duration);
					});
				index = idx;

			};

			$prev.click(function(e){
				browse(getIndex(index-1, count));

				// TODO: Zählpixel

				return false;
			});

			$next.click(function(e){
				browse(getIndex(index+1, count));

				// TODO: Zählpixel

				return false;
			});

			$img.each(function(){
				$prev
					.clone(true)
					.appendTo(this);
				$next
					.clone(true)
					.appendTo(this);
			});

		});
	};


	$.fn.wazCaroussel = function(opts){
		var options = $.extend({
			"delay": 100,
			"duration": 300,
			"lnk": true,
			"modCount": 0,
			"totalCount": 0,
			"url": null
		}, opts);

		return this.each(function(){
			log("$.fn.wazCaroussel", this);
			
			var that = this;

			var $mods = $(".mod", this);
			var $control;

			var index = 0;
			var modCount = options.modCount;
			var totalCount = options.totalCount;
			var groupCount = Math.ceil(totalCount / modCount);
			var $data = $(".mod", this);
						
			// if there is no paging, return
			if(totalCount <= modCount){ return; }
			
			// animation
			var animate = function(idx){
				$control
					.find(".group")
					.removeClass("active")
					.eq(idx)
					.addClass("active");
				
				$.ajax({
					"url": options.url,
					"data": { "start": idx*modCount, "end": idx*modCount + modCount},
					"dataType": "html"
				})
				.success(function(data, textStatus, jqXHR){
					for(var i=0, delay=0; i<modCount; i+=1, delay+=options.delay){
						(function(groupIndex, modIndex){
							window.setTimeout(function(){
								$(".mod", that).
								eq(modIndex).stop(false, true).fadeOut(options.duration, function() {
									
									$(this).html($(".mod", data).eq(modIndex).html()).fadeIn(options.duration);
                                    Hyphenator.hyphenate(this, 'de');
									if(options.lnk) {
										$(this).wazLink();
									}
								});
							}, delay);
						})(idx,i);
					}
					
				})
				.error(function(jqXHR, textStatus, errorThrown){
					log("error", jqXHR, textStatus, errorThrown);
				});
				
				index = idx;	
				
			};
			
			// build controls
			$control = [];
			$control.push("<div class=\"control\">");
				$control.push("<div class=\"groups\">");
				$control.push("<a class=\"group ir active\" title=\"\">1</a>");
				for(var i=1; i < groupCount; i+=1){
					$control.push("<a class=\"group ir\" title=\"\">"+ (i+1) +"</a>");
				}
				$control.push("</div>");
				$control.push("<div class=\"paging\">");
					$control.push("<a class=\"prev ir\" title=\"\">zur&uuml;ck</a>");
					$control.push("<span class=\"txt\">bl&auml;ttern</span>");
					$control.push("<a class=\"next ir\" title=\"\">weiter</a>");
				$control.push("</div>");
			$control.push("</div>");

			$control = $($control.join(""));

			// attach events to controls
			$control
				.find(".group")
				.click(function(e){
					e.preventDefault();
					var idx = $(this).text()-1;

					animate(idx);
				});

			$control
				.find(".prev")
				.click(function(e){
					e.preventDefault();
					var idx = getIndex(index-1, groupCount);
					animate(idx);
				});

			$control
				.find(".next")
				.click(function(e){
					e.preventDefault();
					var idx = getIndex(index+1, groupCount);
					animate(idx);
				});

			// attach controls
			$(that).append($control);
		});
	};



	$.fn.wazCarousselAgency = function(opts){
		var options = $.extend({
			"delay": 100,
			"duration": 300,
			"length": null,
			"lnk": true,
			"url": null,
			"urlLayer": null
		}, opts);

		return this.each(function(){
			log("$.fn.wazCarousselAgency", this);
			var that = this;

			var $mods = $(".mod", that);
			var $control;

			var index = 0;
			var modCount = $mods.size();

			$.ajax({
				"url": options.url,
				"dataType": "html"
			})
			.success(function(data, textStatus, jqXHR){
				var $data = $(".mod", data);
				var totalCount = $data.size();
				var groupCount = Math.ceil(totalCount / modCount);

				if(totalCount <= modCount || modCount === 0){ return; }

				// build groups
				var groups = [];
				for(var i=0; i < groupCount-1; i+=1){

					var group = [];
					for(var j=0, k=i*modCount; j < modCount; j+=1, k+=1){
						group.push($($data.eq(k).html()));
					}
					groups.push(group);
				}
				// add last group and fill with last mods
				var group = [];
				for(var i=0, j=totalCount-1; i < modCount; i+=1, j-=1){
					//log(i, j);
					group.unshift($($data.eq(j).html()));
				}
				groups.push(group);


				// animation
				var animate = function(idx){
					$control
						.find(".group")
						.removeClass("active")
						.eq(idx)
						.addClass("active");

					for(var i=0, delay=0; i<modCount; i+=1, delay+=options.delay){

						(function(groupIndex, modIndex){
							window.setTimeout(function(){

								$(".mod", that)
									.eq(modIndex)
									.stop(false, true)
									.fadeOut(options.duration, function(){
										$(this)
											.html(groups[groupIndex][modIndex])
											.fadeIn(options.duration);

										if(options.lnk) {
											$(this).wazLink();
										}
									});

							}, delay);
						})(idx, i);
					}
					index=idx;
				};


				// build controls
				$control = [];
				$control.push("<div class=\"control\">");
					$control.push("<div class=\"groups\">");
					$control.push("<a class=\"group ir active\" title=\"\">1</a>");
					for(var i=1; i < groupCount; i+=1){
						$control.push("<a class=\"group ir\" title=\"\">"+ (i+1) +"</a>");
					}
					$control.push("</div>");
					$control.push("<div class=\"paging\">");
						$control.push("<a class=\"prev ir\" title=\"\">zur&uuml;ck</a>");
						$control.push("<span class=\"txt\">bl&auml;ttern</span>");
						$control.push("<a class=\"next ir\" title=\"\">weiter</a>");
					$control.push("</div>");
				$control.push("</div>");

				$control = $($control.join(""));

				// attach events to controls
				$control
					.find(".group")
					.click(function(e){
						e.preventDefault();
						var idx = $(this).text()-1;

						animate(idx);
					});

				$control
					.find(".prev")
					.click(function(e){
						e.preventDefault();
						var idx = getIndex(index-1, groupCount);

						// TODO: Zählpixel

						animate(idx);
					});

				$control
					.find(".next")
					.click(function(e){
						e.preventDefault();
						var idx = getIndex(index+1, groupCount);

						// TODO: Zählpixel

						animate(idx);
					});

				// attach controls
				$(".mod_columns", that).append($control);

			})
			.error(function(jqXHR, textStatus, errorThrown){
				log("error", jqXHR, textStatus, errorThrown);
			});
		});
	};



	$.fn.wazSlideShowInlineAgency = function(opts){

		var options = $.extend({
			activeIndex: 0,
			container: null,
			imgFadeDuration: 200,
			length: null,
			sliderDelay: 100,
			sliderDuration: 200,
			triggerIdx: null,
			type: "agency",
			urlLayer: null,
			zoom: false
		}, opts);

		return this.each(function(){
			log("$.fn.wazSlideShowInlineAgency", this);

			var that = this;
			var $previews = $(".mod_columns .img" , this);
			var $mainImg = $("> .img img", that);
			var $mainTxt = $("> .txt", that);
			var $zoom = $(".zoom", that);

			var index = 0;

			options.container = this;

			$.ajax({
				url: options.url,
				beforeSend: function(xhr){
					if (xhr.overrideMimeType) {
						xhr.overrideMimeType("application/json");
					}
				},
				dataType: "json"
			})
			.success(function(data, textStatus, jqXHR){
				var json = data;

				$previews
					.die("click")
					.live("click", function(e) {
						e.preventDefault();

						var idxImg = $(".mod_columns .img" , that).index(this);
						var idxGroup = $(".control .groups a.active", that).index() > 0 ? $(".control .groups a.active", that).index() : 0;
						var tail = ((idxGroup+1) * 4) - options.length > 0 ? ((idxGroup+1) * 4) - options.length : 0;
						index  = getIndex( ((idxGroup * 4) + idxImg) - tail, options.length );


						$mainImg
							.attr("src", json.slides[index].img_m.src)
							.attr("alt", json.slides[index].img_m.alt)
							.attr("height", json.slides[index].img_m.height)
							.attr("width", json.slides[index].img_m.width);
						$mainTxt
							.html(json.slides[index].img_m.text);


						return false;
					});

				$mainImg
					.click(function(e){
						e.preventDefault();
						buildLayer(index);
					});
				$zoom
					.click(function(e){
						e.preventDefault();
						buildLayer(index);
					});

				function buildLayer(idx) {
					options.activeIndex = idx;
					options.triggerIdx = null;

					var layer = [];
					layer.push("<div class='layer'>");
						layer.push("<div class='close'><span>schlie&szlig;en</span><span class='icon'></span></div>");
					layer.push("</div>");

					var $layer = $(layer.join(""));

					$layer
						.find(".close")
						.click(function(){
							$layer.remove();

							if($("html").hasClass("ie7")) {
								$(".article").css("z-index", "auto");
							}
						});

					$.ajax({
						url: options.urlLayer
					})
					.success(function(data, textStatus, jqXHR){
						var $data = $(data);

						$layer
							.append($data)
							.wazSlideShowAgency(options)
							.show();

					})
					.error(function(jqXHR, textStatus, errorThrown){
						log(jqXHR, textStatus, errorThrown);
					});


					if($("html").hasClass("ie7")) {
						$(".article").css("z-index", "200");
					}

					$(that)
						.append($layer);

				};

				if(options.triggerIdx !== null) {
					buildLayer(options.triggerIdx);
					return false;
				}


			})
			.error(function(jqXHR, textStatus, errorThrown){
				log(jqXHR, textStatus, errorThrown);
			});

		});
	};


	$.fn.wazSlideShowAgency = function(opts){

		var options = $.extend({
			imgFadeDuration: 200,
			lastPageUrl: null,
			length: null,
			sliderDelay: 100,
			sliderDuration: 200,
			type: null,
			url: null,
			zoom: false
		}, opts);

		return this.each(function(){
			log("$.fn.wazSlideShow", this);

			var that = this;
			var init = true;
			var json = null;
			var length = options.length;
			var index = options.activeIndex;
			var sliderIndex = 0;
			var adPos = [];
			var adVisible = false;
			var $img = $(".img img", this);
			var $txt = $(".txt", this);

			function preload( idx ) {
				var start = -1; // start at index -1
				var count = 3; // load 3 images

				idx += start;

				for(var i=0; i < count; i += 1) {
					var $img = $("<img />");
					$img.attr("src", json.slides[getIndex(idx+i, length)].img_l.src);
				}
			}


			function slideTo( idx ) {

				if( idx < 0 || idx === length ) {
					if(options.type == "agency") {
						idx < 0 ? idx = length-1 : idx = 0;
						slideTo( idx );
					}
					else if(options.type !== "inline") {
						window.location = options.lastPageUrl;
					}
					else {
						$.ajax({
							url: options.lastPageUrl
						})
						.success(function(data, textStatus, jqXHR){
							$(".slideshow_c", that).remove();
							$(that).append(data);

							$(".prev_wrapper", that).click(function(){
								$(that).remove();
								options.triggerIdx = options.length - 1;
								$(options.container)
									.wazSlideShowInline(options);
								options.triggerIdx = null;
								return false;
							});
							$(".next_wrapper", that).click(function(){
								$(that).remove();
								options.triggerIdx = 0;
								$(options.container)
									.wazSlideShowInline(options);
								options.triggerIdx = null;
								return false;
							});
						})
						.error(function(jqXHR, textStatus, errorThrown){
							log( textStatus );
						});
					}
					return;
				}

				// check for ads and build if not already built
				var adIdx;
				if( (adIdx = $.inArray(idx, adPos )) !== -1 && adVisible === false) {
					var $iframe = $("<div class='iframe' />");
					var $slideshow = $(".slideshow_wrapper", that);
					$iframe.append(json.ads[adIdx].iframe);

					var height = $iframe.find("iframe").attr("height");
					var width = $iframe.find("iframe").attr("width");

					var wrapperHeight = $slideshow.outerHeight(true);
					var wrapperWidth = $slideshow.outerWidth(true);

					var top = (wrapperHeight / 2) - (height / 2);
					var left = (wrapperWidth / 2) - (width / 2);

					$iframe.css({
						"left": left,
						"top": top
					});

					$slideshow.append($iframe);
					adVisible = true;

					$(".img", that).hide();
					$(".txt", that).addClass("invisible");
				}
				else if( adVisible ) {
					$(".slideshow_wrapper .iframe", that).remove();
					adVisible = false;

					$(".img", that).show();
					$(".txt", that).removeClass("invisible");
					return;
				}


				index = idx;
				$counter.text("Bild " + ( index + 1 ) + " von " + (length + 1));

				$(".slider li.active .shadow", that)
					.remove();

				$(".slider li", that)
					.removeClass("active")
					.eq(index-sliderIndex)
					.addClass("active")
					.append("<div class=\"shadow\" />");

				if( init ) {
					$img
						.attr("src", json.slides[index].img_l.src)
						.attr("alt", json.slides[index].img_l.alt)
						.attr("height", json.slides[index].img_l.height)
						.attr("width", json.slides[index].img_l.width)
						.css("padding-top", ($(".slideshow_wrapper", that).height() - json.slides[index].img_l.height) / 2);

					$txt
						.html(json.slides[index].img_l.txt)
						.fadeIn(options.imgFadeDuration);

					init = false;
				}
				else {
					$img
						.stop( false, true )
						.fadeOut(
								options.imgFadeDuration,
								function(){
									$img
									.one("load", function() {
										$(this).fadeIn(options.imgFadeDuration);
									})
									.attr("src", json.slides[index].img_l.src)
									.attr("alt", json.slides[index].img_l.alt)
									.attr("height", json.slides[index].img_l.height)
									.attr("width", json.slides[index].img_l.width)
									.css("padding-top", ($(".slideshow_wrapper", that).height() - json.slides[index].img_l.height) / 2);

								});

					$txt
						.stop( false, true )
						.fadeOut(
								options.imgFadeDuration,
								function(){
									$txt
									.html(json.slides[index].img_l.txt)
									.fadeIn(options.imgFadeDuration);
								});
				}

				preload( index );
			}


			$(".img", this).wrap("<div class='slideshow_wrapper' />");

			var $prev_wrapper = $("<div class='prev_wrapper'><div class='prev' /></div>");
			var $prev = $prev_wrapper.find(".prev");

			var $next_wrapper = $("<div class='next_wrapper'><div class='next' /></div>");
			var $next = $next_wrapper.find(".next");

			$prev_wrapper
				.hover(
						function(){
							$prev.fadeIn(); $next.fadeIn();
						},
						function(){
							$prev.fadeOut(); $next.fadeOut();
						}
				)
				.click(function(){
					reIVW();
					slideTo( index - 1 );
				});
			$next_wrapper
				.hover(
						function(){
							$prev.fadeIn(); $next.fadeIn();
						},
						function(){
							$prev.fadeOut(); $next.fadeOut();
						}
					)
				.click(function(){
					reIVW();
					slideTo( index + 1 );
				});

			if(options.length > 1) {
				$(".slideshow_wrapper", this).append($prev_wrapper);
				$(".slideshow_wrapper", this).append($next_wrapper);
			}


			if(options.zoom) {
				var $zoom = $("<div class='zoom' />");
				$zoom
					.click(function(){
						window.location = json.slides[index].img_l.zoom;
					});
				$(".slideshow_wrapper", this).append($zoom);
			}


			var $counter = $("<div class='counter' />");
			if($(this).hasClass("img_top")){
				$(this).append($counter);
			}
			else {
				$(".img_top", this).append($counter);
			}

			function buildSlider() {

				var html = [];
				html.push("<div class='slider_wrapper'>");
					html.push("<div class='slider'>");
						html.push("<div class='control prev'></div>");
						html.push("<div class='list_wrapper'>");
							html.push("<ul class='no_ls list clearfix'>");
								for(var i=0; i < length; i+=1) {
									html.push( index === i ? "<li class='active'>" : "<li>");
										var img = "<img src='" + json.slides[i].img_s.src +"' alt='" + json.slides[i].img_s.alt + "' height='" + json.slides[i].img_s.height + "' width='" + json.slides[i].img_s.width + "' />";
										html.push( img );
										if(index === i) {
											html.push("<div class=\"shadow\" />");
										}
									html.push("</li>");
								}
							html.push("</ul>");
						html.push("</div>");
						html.push("<div class='control next'></div>");
					html.push("</div>");
				html.push("</div>");


				var $slider = $(html.join(""));

				$(".slideshow_wrapper", that).append( $slider );

				$slider
					.hover(
						function(){
							$slider.find(".slider").stop(true, true).fadeIn();
						},
						function(){
							$slider.find(".slider").stop(true, true).fadeOut();
						}
					);

				var $listItemsClone = $slider.find("li").clone( true );

				var count = $listItemsClone.size();
				var countVisible = 0;
				var width = $slider.find(".list_wrapper").width();
				var liWidth = $slider.find("li").outerWidth(true);

				countVisible = Math.floor( width / liWidth );

				var $listItems = $slider.find("li");

				var rotate = function( idx ) {
					$listItems.removeClass("active");

					var length = $listItemsClone.size();

					for(var i = 0, delay = 0; i < countVisible+1; i += 1, delay += options.sliderDelay){
						(function(idx, i){
							window.setTimeout(function(){
								$listItems
									.eq(i)
									.stop(false, true)
									.fadeOut(options.sliderDuration, function(){
										$(this)
											.html( $listItemsClone.eq( getIndex(idx+i, length) ).html() )
											.fadeIn(options.sliderDuration);
										if( getIndex( idx + i, length ) === index ) {
											$(this)
												.addClass("active")
												.append("<div class=\"shadow\" />");
										}
									});

							}, delay);
						})(idx, i);
					}
					sliderIndex=getIndex(idx, length);
				};


				// only show controls if enough items
				if( length > countVisible ) {
					$slider
						.find(".prev")
						.show()
						.click(function(){
							// TODO: Zählpixel
							rotate( sliderIndex - countVisible );
						});

					$slider
						.find(".next")
						.show()
						.click(function(){
							// TODO: Zählpixel
							rotate( sliderIndex + countVisible );
						});
				}

				// add events listeners
				$slider
					.find("li")
					.click(function(){

						var idx = $slider
							.find("li")
							.index( this );

						reIVW();
						slideTo( getIndex(sliderIndex + idx, length) );
					});

				$slider
					.find(".slider")
					.css({
						"display": "none",
						"visibility": "visible"
					});
			};

			$.ajax({
				url: options.url,
				beforeSend: function(xhr){
					if (xhr.overrideMimeType) {
						xhr.overrideMimeType("application/json");
					}
				},
				dataType: "json"
			})
			.success(function(data, textStatus, jqXHR){
				json = data;

				for(var ad in json.ads){
					adPos.push(json.ads[ad].pos);
				}

				preload(index);
				slideTo(index);

				if( options.length > 1) {
					buildSlider();
				}
			})
			.error(function(jqXHR, textStatus, errorThrown){
				log( textStatus );
			});
		});
	};



	$.fn.wazCeleb = function() {

		return this.each(function(){
			var $that = $(this);

			$(".prev, .next", this).live("click", function() {

				$.ajax({
					url: $(this).attr("href")
				})
				.success(function(data, textStatus, jqXHR){
					$that
						.html(data);
				})
				.error(function(jqXHR, textStatus, errorThrown){
					log(jqXHR, textStatus, errorThrown);
				});

				return false;

			});

		});
	};



	$.fn.wazCollection = function(opts){
		return this.each(function(){
			var $containers = $(".cont", this);
			var $prev = $(".prev", this);
			var $next = $(".next", this);

			var length = $containers.size();
			var index = 0;

			$prev.click(function(){
				index = getIndex(index-1, length);
				$containers
					.removeClass("active")
					.eq(index)
					.addClass("active");

				// TODO: Zählpixel
				return false;
			});

			$next.click(function(){
				index = getIndex(index+1, length);
				$containers
					.removeClass("active")
					.eq(index)
					.addClass("active");

				// TODO: Zählpixel
				return false;
			});

		});
	};


	// TODO Revision by Bastian (written by Oleksii, unitb consulting)////////////////////////////////////////////
	$.fn.wazComment = function(opts){
		return this.each(function(){
			var options = $.extend({
				"cookieName": "",
				"layer": "",
                "count": "",
				"repliesSlideDuration": 500
			}, opts);

			var that = this;
			var user = wazGetUserLogin( options.cookieName );

			// toggle replies
			var $comments = $(".mod_cmnt", this);
			$(".count", that)
				.live("click",
					function(){
						var idx = $(".count", that).index(this);
						$(".replies", that)
							.eq(idx)
							.is(":visible") ?
								$(".replies", that).eq(idx).slideUp(options.repliesSlideDuration) :
								$(".replies", that).eq(idx).slideDown(options.repliesSlideDuration);
						return false;
					});

			// define top and bottom forms
			var $commentTop = $(".comment_top a", this);
			var $commentTopForm = $("#cmnt_form_top", this);
			var $commentBottom = $(".comment_bottom a", this);
			var $commentBottomForm = $("#cmnt_form_bottom", this);

            // toggle reply comment form
			$(".comments .replyto", that)
				.live("click", function() {
					var idx = $(".comments .replyto", that).index(this);
                    if(user === null) {		// not logged in
						log("not logged in.");
						$.ajax({
							url: options.layer
						})
						.success(function(data, textStatus, jqXHR){
							var $layer = $(data);

							$layer
								.find(".close")
								.click(function(){
									$layer.remove();
								});

							$(".comments .mod_cmnt", that).eq(idx).append( $layer );
							$layer.show();
						})
						.error(function(jqXHR, textStatus, errorThrown){
							log(jqXHR, textStatus, errorThrown);
						});
						return false;

					} else {
       					$.ajax({
       						url: $(this).attr("href"),
       						context: document.body,
       						type: "POST"
       					}).success(
       						function (data, textStatus, jqXHR) {
       							// hide other reply forms
       							$(".comments .cmnt_form").each(function(){
       								$(this).slideUp();
       							});
       							// hide top comment form
       							$commentTopForm.slideUp();
								$commentTop.show();
								// hide bottom comment form
       							$commentBottomForm.slideUp();
								$commentBottom.show();

       							// show reply form
       							$(".comments .cmnt_form", that).eq(idx).html(data);
       							$(".comments .cmnt_form", that).eq(idx).slideDown();
       							$(".comments .cmnt_form", that).eq(idx).find("button[type=reset]")
	       							.click(function() {
	       								$(".comments .cmnt_form", that)
	       								.eq(idx)
	       								.slideUp();
	       							});
       						}
       					).error(
       						function (jqXHR, textStatus, errorThrown) {
       							$(".comments .cmnt_form", that)
       							.eq(idx)
       							.html("<p>Kommunikationsfehler ist aufgetreten.</p>");
       							$(".comments .cmnt_form", that)
       							.eq(idx)
       							.slideDown();
       						}
       					);
       					return false;
                    }
				});

			// toggle bottom comment form
			$commentBottom
				.click(function(){
                if(user === null) {		// not logged in
						log("not logged in.");
						$.ajax({
							url: options.layer
						})
						.success(function(data, textStatus, jqXHR){
							var $layer = $(data);

							$layer
								.find(".close")
								.click(function(){
									$layer.remove();
								});

							$commentBottom.after( $layer );
							$layer.show();
						})
						.error(function(jqXHR, textStatus, errorThrown){
							log(jqXHR, textStatus, errorThrown);
						});
						return false;

					} else {
      					$.ajax({
      						url: $(this).attr("href"),
      						context: document.body,
      						type: "POST"
      					}).success(
      						function (data, textStatus, jqXHR) {
      							// hide other reply forms
       							$(".comments .cmnt_form").each(function(){
       								$(this).slideUp();
       							});
       							// hide top comment form
       							$commentTopForm.slideUp();
								$commentTop.show();

       							// show bottom comment form
      							$commentBottomForm.html(data);
      							$commentBottomForm.slideDown();
                                if(data.indexOf("form") >= 0){
      						   	  $commentBottom.hide();
      							}
      							$commentBottomForm
      								.find("button[type=reset]")
      								.click(function() {
      									$commentBottomForm.slideUp();
      									$commentBottom.show();
      								});
      						}
      					).error(
      						function (jqXHR, textStatus, errorThrown) {
      							$commentBottomForm.html("<p>Kommunikationsfehler ist aufgetreten.</p>");
      							$commentBottomForm.slideDown();
      						}
      					);
      					return false;
                    }
				});


			// toggle top comment form
			$commentTop
				.click(function(){
                    if(user === null) {		// not logged in
						log("not logged in.");
						$.ajax({
							url: options.layer
						})
						.success(function(data, textStatus, jqXHR){
							var $layer = $(data);

							$layer
								.find(".close")
								.click(function(){
									$layer.remove();
								});

							$commentTop.after( $layer );
							$layer.show();
						})
						.error(function(jqXHR, textStatus, errorThrown){
							log(jqXHR, textStatus, errorThrown);
						});
						return false;

					} else {
    					$.ajax({
    						url: $(this).attr("href"),
    						context: document.body,
    						type: "POST"
    					}).success(
    						function (data, textStatus, jqXHR) {
    							// hide other reply forms
       							$(".comments .cmnt_form").each(function(){
       								$(this).slideUp();
       							});
       							// hide bottom comment form
       							$commentBottomForm.slideUp();
								$commentBottom.show();

       							// show top comment form
    							$commentTopForm.html(data);
    							$commentTopForm.slideDown();
                                if(data.indexOf("form") >= 0){
    								$commentTop.hide();
    							}
    							$commentTopForm
    								.find("button[type=reset]")
    								.click(function() {
    									$commentTopForm.slideUp();
    									$commentTop.show();
    								});
    						}
    					).error(
    						function (jqXHR, textStatus, errorThrown) {
    							$commentTopForm.html("<p>Kommunikationsfehler ist aufgetreten.</p>");
    							$commentTopForm.slideDown();
    						}
    					);
    					return false;
                    }
				});


			// show more
			var $more = $(".more a", this);
			$more.click(function(){
				$.ajax({
					url: $(this).attr("href"),
					data: {
						count: $comments.size()
					}
				})
				.success(function(data, textStatus, jqXHR){
					$(".comments", that)
						.append(data);
					$comments = $(".mod_cmnt", that);
                    if($comments.size() == options.count){
						$(".more").hide();
					}
				})
				.error(function(jqXHR, textStatus, errorThrown){
					log(jqXHR, textStatus, errorThrown);
				});
				return false;
			});


		});

	};



	//TODO Revision by Bastian (written by Ingo Kleinert, unitb consulting)////////////////////////////////////////////
	//reads last user search texts from cookie
	$.fn.wazGetSearch = function(opts){
		var options = $.extend({
			url : null,
			maxResults: 10
		}, opts);

		return this.each(function(){
			var $list = $(".list", this);
			var searches = $.cookie("mysearches").split(",");
			$(document).ready(function(){
				for(var search in searches){
					if(search < parseInt(options.maxResults))
						$list.append("<li><a title='' href='"+options.url+"?q="+searches[search]+"'><span>»</span> "+searches[search]+"</a></li>");
				}

			});
		});
	};

	$.fn.wazImgZoom = function( opts ) {
		var options = $.extend({
			format: "landscape"
		}, opts);
		return this.each(function(){
			var that = this;
			var $offsetParent = $(this).offsetParent();

			function isVisible() {
				return $(".layer", that).size() > 0;
			}

			$("a", this)
				.click(function() {
					if(isVisible()) return false;
					var link = this;
					var img = new Image();

					function onLoad() {
						var layer = [];
						layer.push("<div class='layer " + options.format + "'>");
							layer.push("<div class='close'>schlie&szlig;en<span class='icon'></span></div>");
							layer.push("<img src='" + $(link).attr("href") + "' alt='' />");
							layer.push("<div class='txt'>" + ($(".txt", that).html() == null ? "" : $(".txt", that).html()) + "</div>");
						layer.push("</div>");

						var $layer = $(layer.join(""));

						/*
						$layer
							.css("top", $(document).scrollTop()+10);
						 */



						//(viewportHeight - layerHeight) / 2 - offsetParent.position().top

						$layer
							.find(".txt")
							.css("width", img.width);

						$layer
							.find(".close")
							.click(function() {
								$layer.remove();
							});

							$(that).append($layer);

							var viewPortHeight = $(window).height();
							var viewPortOffsetTop = $(window).scrollTop();
							var layerHeight = $layer.outerHeight();
							var offsetParentTop = $offsetParent.position().top;

							log(viewPortHeight, layerHeight, offsetParentTop, viewPortOffsetTop);

							log(((viewPortHeight - layerHeight) / 2) + $offsetParent.position().top);

							$layer
								.css("top", viewPortOffsetTop - offsetParentTop + ((viewPortHeight - layerHeight) / 2));
					};


					img.src = $(this).attr("href");
					if(img.complete) {
						onLoad();
					}
					else {
						img.onload = onLoad;
					}

					return false;
				});
		});
	};


    //target of a link will be evaluated in js too
	$.fn.wazLink = function(){
		return this.each(function(){
			if( $(".hl a", this).size() === 0 ) {
				return;
			}

			var href = $(".hl a", this).attr("href");
            if($(".hl a", this).attr("target") !== undefined){
                var target = $(".hl a", this).attr("target");
            }
			var title =  $(".hl a", this).attr("title") || "";

			$(".img, .kckr, .txt", this)
				.attr("title", title)
				.addClass("cp")
				.click(function(){
					if(target === "_blank"){
						window.open(href);
					} else {
						window.location.href = href;
					}
				});
		});
	};


    $.fn.wazLinkAuthorProfile = function(){
		return this.each(function(){
			if( $(".infos .name a", this).size() === 0 && $(".author a", this).size() === 0 ) {
				return;
			}

			var href = $(".infos .name a", this).attr("href") || $(".author a", this).attr("href");
			if($(".infos .name a", this).attr("target") !== undefined || $(".author a", this).attr("target") !== undefined){
				var target = $(".infos .name a", this).attr("target") || $(".author a", this).attr("target");
			}
			var title =  $(".infos .name a", this).attr("title") || $(".author a", this).attr("title") || "";

			$(".img, .kckr, .txt", this)
				.attr("title", title)
				.addClass("cp")
				.click(function(){
					if(target === "_blank"){
						window.open(href);
					} else {
						window.location.href = href;
					}
				});
		});
	};


	$.fn.wazLogin = function( opts ) {

		var options = $.extend({
			cookieName: "",
			layerUrl: "_ajax/login.html",
			redirectUrl: null,
			url: null
		}, opts);

		return this.each(function() {
			var that = this;
			var user = wazGetUserLogin( options.cookieName );
			var $login = $(".log", this);

			log(this);

			if(user === null) {		// not logged in

				log("not logged in.");

				$login
					.unbind("click")
					.click(function() {
						/*$.ajax({
							url: options.layerUrl
						})
						.success(function(data, textStatus, jqXHR){
							var $layer = $(data);

							$layer
								.find(".close")
								.click(function(){
									$layer.remove();
								});

							$(that).append( $layer );
							$layer.show();
						})
						.error(function(jqXHR, textStatus, errorThrown){
							log(jqXHR, textStatus, errorThrown);
						});*/

                        $(".layer",that).show();
						$(".layer",that).find(".close").click(function(){	$(".layer",that).hide();});
						return false;
					});

			}
			else {		// logged in

				log("logged in.");

				var $layer = null;

				var logout = $(".log", this);
				$(logout).html("Logout");
				$(logout)
				.attr("title", "Abmelden")
				.attr("href", options.url + "?action=logout&redirectUrl=" + options.redirectUrl);

				var userLink = $(".reg", this);
				var username = (user.l).length > 20 ? (user.l).substr(0, 19) + "..." : user.l;
				$(userLink).html(username);
				$(userLink)
					.attr("title", "zum Benutzerkonto")
					.attr("href", options.url );

			}
		});
	};

    $.fn.wazDatepicker = function(opts) {
		var options = $.extend({
			url: null,
			section_url: null,
			current_date: ""
		}, opts);

		var that = $(this);

		$(".years a", this).live("click", function(){
			var year = $(this).text();
			var idx = $(".years a", that).index(this);

			$.ajax({
				data: {
					year: year,
					current_date: options.current_date,
					section_url: options.section_url
				},
				type: "GET",
				url: options.url
			})
			.success(function(data, textStatus, jqXHR){
				$(".months").html( data );
				$(".years a", that).removeClass("active").eq(idx).addClass("active");
			})
			.error(function(jqXHR, textStatus, errorThrown){
				log(jqXHR, textStatus, errorThrown);
			});

			return false;
		})

	}

	$.fn.wazMyCity = function(opts) {

		var options = $.extend({
			cities: null,
			url: null,
			id: null,
			fwId: null,
			maxCities: 5
		}, opts);

		var that = this;

		var cities = options.cities.split(",");
		// init if no cookie found
		if( !$.cookie("mycities_"+options.id) ) {
			$.cookie("mycities_"+options.id, options.cities, { expires: 3650, path: "/" });
		}
		else {
			cities = $.cookie("mycities_"+options.id).split(",");
		}

		$.fn.wazLoadCity = function(option) {
			var container = $(this);
			var city = option.city;

			$.ajax({
				data: {
					city: city
				},
				type: "GET",
				url: option.url,
				id: options.id
			})
			.success(function(data, textStatus, jqXHR){
				$(".mod", "#mod_mycities_"+option.fwId).hide(); // 'that' points here to wrong div container
				container.show().html( data );
			})
			.error(function(jqXHR, textStatus, errorThrown){
				log(jqXHR, textStatus, errorThrown);
			});
		}

		//load cities
		for(var i=0; i <= options.maxCities-1; i+=1){
			$(".nav > a", that).eq(i).html(cities[i]);
			$(".nav > a", that).eq(i).attr("title", "Zur Stadt "+cities[i])
			$(".nav > a", that).eq(i).attr("href", "#" + cities[i]);
		}

		$("#mod_mycities_"+options.fwId+"_1").wazLoadCity({"city": cities[0],"url":options.url,"fwId":options.fwId});

		/* bind events */
		// city nav
		$(".nav > a", this).live("click", function(){
			var idx = $(".nav > a", that).index(this);
			$(".nav > a", that).removeClass("active");
			$(".nav > a", that).eq(idx).addClass("active");

			var cityContent = $(".mod", that).eq(idx);

			//ajax request only if city content not loaded already
			if($("ul", cityContent).length <= 0) {
				$(".mod", that).eq(idx).wazLoadCity({"city": cities[idx],"url":options.url,"fwId":options.fwId});
			}

			cityContent = $(".mod", that).eq(idx);
			if($("ul", cityContent).length > 0) {
				$(".mod", that).hide();
				$(".mod", that).eq(idx).show();
			}

			return false;
		});

		// show layer
		$(".choose a", this).live("click", function(){
			$(".cities_layer", that).show();
			return false;
		});

		// close layer
		$(".cities_layer .close", this).live("click", function(){
			$(".cities_layer", that).hide();
			return false;
		});

		// choose city
		$(".cities_layer .list a", this).live("click", function(){
			var cities = $.cookie("mycities_"+options.id).split(",");
			var text = $(this).attr("title");
			var pos = $.inArray(text,cities);
			

			if(pos !== 0) {
				//load new city
				$("#mod_mycities_"+options.fwId+"_1").wazLoadCity({"city": text,"url":options.url,"fwId":options.fwId});

				// save cookie and rearrange cities
				if(pos > -1) {
					cities.splice(pos, 1);
				}

				for(var i=(pos < 0? options.maxCities-1 : (pos)); i > 0 ; i-=1){
					$("#mod_mycities_"+options.fwId+"_"+(i+1)).html($("#mod_mycities_"+options.fwId+"_"+i).html());
				}

				cities.unshift(text);

				if(cities.length > options.maxCities) {
					cities.splice(options.maxCities, cities.length - options.maxCities);
				}

				//rewrite cities names
				for(var i=0; i <= options.maxCities-1; i+=1){
					$(".nav > a", that).eq(i).html(cities[i]);
					$(".nav > a", that).eq(i).attr("title", "Zur Stadt "+cities[i])
					$(".nav > a", that).eq(i).attr("href", "#" + cities[i]);
				}

				// write new cookie
				log("writing new cookie: ", cities);
				$.cookie("mycities_"+options.id, cities.join(","), { expires: 3650, path: "/" });
			}

			$(".nav > a", that).removeClass("active");
			$(".nav > a", that).eq(0).addClass("active");
			$("#mod_mycities_"+options.fwId+"_1").show();
			for(var i=2; i <= options.maxCities; i+=1){
				$("#mod_mycities_"+options.fwId+"_"+i).hide();
			}

			$(".cities_layer", that).hide();
			return false;
		});
	}

	//deprecated
	$.fn.wazMyCities = function(opts){

		var options = $.extend({
			maxCities: 5,
			id: null,
			url: null
		}, opts);

		return this.each(function(){
			var that = this;

			var initCities = [];
			$(".nav > a", that).each(function(){
				initCities.push($(this).text());
			});
			log("init cities: ", initCities);


			// init if no cookie found
			if( !$.cookie("mycities_"+options.id) ) {
				$.cookie("mycities_"+options.id, initCities.join(","), { expires: 3650, path: "/" });
			}
			//refreshHTML();

			function refreshHTML() {
				$.ajax({
					data: {
						cities: $.cookie("mycities_"+options.id)
					},
					type: "GET",
					url: options.url,
					id: options.id
				})
				.success(function(data, textStatus, jqXHR){
					$(that).html( data );
				})
				.error(function(jqXHR, textStatus, errorThrown){
					log(jqXHR, textStatus, errorThrown);
				});
			}

			/* bind events */
			// city nav
			//TODO Revision by Bastian (written by Ingo Kleinert, unitb consulting): change from "> .nav a" to ".nav > a" /////////////////////////
			$(".nav > a", this).live("click", function(){
				var idx = $(".nav > a", that).index(this);
				$(".nav > a", that)
					.removeClass("active")
					.eq(idx)
					.addClass("active");

				$(".mod", that)
					.hide()
					.eq(idx)
					.show();

				return false;
			});

			// show layer
			$(".choose a", this).live("click", function(){
				$(".cities_layer", that).show();
				return false;
			});

			// close layer
			$(".cities_layer .close", this).live("click", function(){
				$(".cities_layer", that).hide();
				return false;
			});

			// choose city (changed by Ingo Kleinert, unitb consulting)
			$(".cities_layer .list a", this).live("click", function(){
				var cities = $.cookie("mycities_"+options.id).split(",");
				var pos = $.inArray($(this).text(),cities);

				if(pos !== 0) {
					if(pos > -1) {
						cities.splice(pos, 1);
					}

					cities.unshift($(this).text());

					if(cities.length > options.maxCities) {
						cities.splice(options.maxCities, cities.length - options.maxCities);
					}

					// write new cookie
					log("writing new cookie: ", cities);
					$.cookie("mycities_"+options.id, cities.join(","), { expires: 3650, path: "/" });
				}

				refreshHTML();

				$(".cities_layer", that).hide();
				return false;
			});
		});
	};


	$.fn.wazNavigation = function(){
		return this.each(function(){
			var that = this;

			var $firstLvl = $("> li", this);
			var $firstLvlA = $("> li .bg a", this);
			var $firstLvlActive = $("> li.active", this);


			$firstLvlActive.css("position", "static");
			$("> li.active .nav_sec", this).addClass("nav_sec_show");
			$("> li.active .nav_sec_w", this).addClass("nav_sec_w_show");

			$(this)
				.mouseleave(function(){
					$firstLvl
						.removeClass("active");
					$firstLvlActive
						.addClass("active");
				});

			$firstLvl
				.hover(function(e){
					$firstLvl
						.removeClass("active");
				});


			var $secondLvl = $(".nav_sec > li", this);
			$secondLvl
				.each(function(){
					if($(".nav_thi", this).size() !== 0){
						$(this).addClass("sub");
					}
				});
		});
	};


	$.fn.wazNavigationFooter = function(){
		return this.each(function(){
			var that = this;

			var $navLi = $(".nav li", this);
			var $navLiA = $(".nav li .bg a", this);
			var $navLiActive = $(".nav li.active", this);
			var $linkList = $(".link_list", this);

			$navLiA
				.hover(function(){
					var index = $navLiA.index(this);
					$navLiActive
						.removeClass("active");
					$navLiActive = $navLi.eq(index);
					$navLiActive
						.addClass("active");

					$linkList
						.removeClass("active")
						.eq(index)
						.addClass("active");
					return false;
				});
		});
	};



	$.fn.wazNewsTicker = function(opts){
		var options = $.extend({
			"show": 5,
			"steps": 5
		}, opts);

		return this.each(function(){

			// links
			$(".list li", this).each(function(){
				var href = $("a", this).attr("href");

				$(".kckr, .time", this)
					.addClass("cp")
					.click(function(){
						window.location.href = href;
					});
			});


			// tab navigation
			var $nav = $(".nav", this);
			if($nav.size() !== 0) {
				var $navs = $(".nav a", this);
				var $mods = $(".mod", this);

				$navs.click(function(e){
					var idx = $navs.index(this);

					$mods
						.addClass("hidden")
						.eq(idx)
						.removeClass("hidden");

					$navs
						.removeClass("active")
						.eq(idx)
						.addClass("active");

					// TODO: Zählpixel

					return false;
				});
			}

			// paging
			var $controls = $(".control", this);
			if($controls.size() !== 0){
				var that = this;
				var $prev = $(".prev", this);
				var $next = $(".next", this);
				var $li = $(".list li", this);

				var index = 0;
				var length = $li.size();

				var rotate = function(dir){
					$li.addClass("hidden");
					var idx = index;

					if(dir === "prev"){
						for(var i=options.steps-1; i >= 0; i-=1){
							idx = getIndex(index - options.steps + i, length);

							$li
								.eq(idx)
								.removeClass("hidden");
						}
						index = getIndex(index - options.steps, length);
					}
					else {
						for(var i=0; i < options.show; i+=1){
							idx = getIndex(index + options.steps + i, length);

							$li
								.eq(idx)
								.removeClass("hidden");
						}
						index = getIndex(index + options.steps, length);
					}

				};

				$prev.click(function(){
					rotate("prev");
					// TODO: Zählpixel
					return false;
				});

				$next.click(function(){
					rotate("next");
					// TODO: Zählpixel
					return false;
				});

			}
		});
	};


	$.fn.wazPanel = function(opts){
		var options = $.extend({
			"interval": 15 // move every 15ms 1px to the left
		}, opts);

		return this.each(function(){
			var that = this;
			var $list = $(".list", this);
			var $li = $("li", this);

			var interval = null;
			var liCount = $li.size();
			var offsetLeft = 0;
			var width = 0;


			$li.each(function() {
				width += $(this).outerWidth(true);
			});
			$li.clone().appendTo($list);


			var animate = function(){
				if(offsetLeft === width*-1){
					offsetLeft = 0;
				}
				offsetLeft -= 1;
				$list.attr("style", "left: " + offsetLeft + "px; top: 0px;");
			};
			interval = window.setInterval(animate, options.interval);

			$list.hover(
					function(){
						window.clearInterval(interval);
					},
					function(){
						interval = window.setInterval(animate, options.interval);
					});
		});
	};


	$.fn.wazPic = function(opts){
		var options = $.extend({
			"width": 0.5
		}, opts);

		return this.each(function(){
			var $outer = $(".outer", this);
			var $inner = $(".inner", this);
			var outerWidth = $outer.width();

			$inner.width(outerWidth * options.width);

			var outerHeight = $outer.height();
			var innerHeight = $inner.outerHeight();

			if($outer.hasClass("center")){
				var offsetTop = outerHeight/2 - innerHeight/2;
				$inner.css("top", offsetTop);
			}

			$outer.css("visibility", "visible");
		});
	};



	$.fn.wazPoll = function(opts) {

		var options = $.extend({
		}, opts);

		return this.each(function() {
			var $that = $(this);
			var $form = $("form", this);

			$form.live("submit", function(){

				$.ajax({
					data: $(this).serializeArray(),
					type: "POST",
					url: $(this).attr("action")
				})
				.success(function(data, textStatus, jqXHR){
					$that
						.html(data);

					// TODO: Zählpixel?

					$that
						.find(".btn")
						.click(function() {

							$.ajax({
								url: $(this).attr("href")
							})
							.success(function(data, textStatus, jqXHR){
								$that
									.html(data);
							})
							.error(function(jqXHR, textStatus, errorThrown){
								log(jqXHR, textStatus, errorThrown);
							});

							return false;
						});

					return false;
				})
				.error(function(jqXHR, textStatus, errorThrown){
					log(jqXHR, textStatus, errorThrown);
				});

				return false;
			});
		});
	};


	$.fn.wazPollLayer = function(opts) {

		var options = $.extend({
		}, opts);

		return this.each(function() {
			var $that = $(this);
			var $form = $("form", this);
			var $layer = $(".layer", this);
			var $btns = $("a.btn.show_result, .show_result a", this);
			var $nxtBtns = $("a.btn.next_voting, .next_voting a", this);
			$nxtBtns.hide();

			$btns.live("click", function(){
				var url = $(this).attr("href");
				$.ajax({
					url: url
				})
				.success(function(data, textStatus, jqXHR){
					$layer
						.html(data)
						.show();
					$layer
						.find(".close")
						.live("click", function(){
							$layer.hide();
							// TODO: Zählpixel?
						});
				})
				.error(function(jqXHR, textStatus, errorThrown){
					log(jqXHR, textStatus, errorThrown);
				});

				return false;
			});

            $nxtBtns.live("click", function(){
				var url = $(this).attr("href");
				$.ajax({
					url: url
				}).success(function(data, textStatus, jqXHR){
					$that.html(data);
					$that.wazPollLayer();
				}).error(function(jqXHR, textStatus, errorThrown){
					log(jqXHR, textStatus, errorThrown);
				});
				return false;
			});

			$form.live("submit", function(){

				$.ajax({
					data: $(this).serializeArray(),
					type: "POST",
					url: $(this).attr("action")
				})
				.success(function(data, textStatus, jqXHR){
					$layer
						.html(data)
						.show();
                    $nxtBtns.show();

					// TODO: Zählpixel?

					$layer
						.find(".close")
						.live("click", function(){
							$layer.hide();
							// TODO: Zählpixel?
						});

					return false;
				})
				.error(function(jqXHR, textStatus, errorThrown){
					log(jqXHR, textStatus, errorThrown);
				});

				return false;
			});
		});
	};


	$.fn.wazPopTab = function(opts){
		var options = $.extend({
			"duration": 300
		}, opts);

		return this.each(function(){
			var that = this;
			var $tabs = $(".nav li", this);
			var $cont = $(".cont", this);

			$tabs
				.click(function(e){
					e.preventDefault();
					if($(this).hasClass("active")) return false;

					$tabs.removeClass("active");
					$(this).addClass("active");

					var idx = $tabs.index(this);

					$cont
						.eq(getIndex(idx-1, 2))
						.hide()
						.end()
						.eq(idx)
						.show();

					// TODO: Zählpixel?
					return false;
				});
		});
	};


	$.fn.wazRab = function(opts){
		var options = $.extend({
			"duration": 750,
			"interval": 5000
		}, opts);

		return this.each(function(){
			var $nav = $(".nav li", this);
			var $mods = $(".mod", this);
			var index = 0;
			var int = null;
			var length = $mods.size();
			var stopped = false;

			$(".nav", this).css("z-index", length + 1);

			$mods.each(function(index, data){
				$(this).css({
					"left": 0,
					"position": "absolute",
					"top": 0,
					"z-index": length - index
				});
				if( index > 0 ) {
					$(this).hide();
				}

				var href = $("a", this).attr("href");
				$("*", this)
					.addClass("cp")
					.click(function(){
						window.location.href = href;
					});
			});

			var animate = function(idx){
				$nav
					.removeClass("active")
					.eq(idx)
					.addClass("active");

				$mods
					.fadeOut(options.duration)
					.eq(idx)
					.fadeIn(options.duration);
			};

			var interval = function(){
				index = getIndex(index += 1, length);
				animate(index);
			};

			$nav.click(function(){
				window.clearInterval(int);
				stopped = true;
				var idx = $nav.index(this);
				// TODO: Zählpixel
				animate(idx);
				return false;
			});

			if( length > 1 ) {
				// start autmatic rotation
				int = window.setInterval(function() {
					interval();
				}, options.interval);
			}

		});
	};



	$.fn.wazRabCaroussel = function(opts){
		var options = $.extend({
			"contentDuration": 200,
			"duration": 1000,
			"interval": 5000,
			"sliderDelay": 100,
			"sliderDuration": 200,
			"thumbsHover": false
		}, opts);

		return this.each(function(){
			var $that = $(this);
			var $nav = $(".nav li", this);
			var $mods = $(".mod", this);
			var index = 0;
			var int = null;
			var length = $mods.size();

			$(".nav", this).css("z-index", length + 1);

			$mods.each(function(index, data){
				$(this).css({
					"left": 0,
					"position": "absolute",
					"top": 0,
					"z-index": length - index
				});
				if( index > 0 ) {
					$(this).css("visibility", "hidden");
				}

				var that = this;

				$("*", this)
					.eq(0)
					.not(".slider, .slider *", this)
					.addClass("cp")
					.click(function(){
						var href = $("a.img", that).attr("href");
						window.location.href = href;
					});
			});

			var animate = function(idx){
				$nav
					.removeClass("active")
					.eq(idx)
					.addClass("active");

				$mods
					.fadeOut(options.duration)
					.eq(idx)
					.css({
						"display": "none",
						"visibility": "visible"
					})
					.fadeIn(options.duration);
			};



			$nav.click(function(){
				window.clearInterval(int);
				var idx = $nav.index(this);
				// TODO: Zählpixel
				animate(idx);
				return false;
			});


			// slider navigation/animation
			$mods.each(function( modIndex ){
				var that = this;
				var $content = $(".pic_wrapper", this);
				var $prev = $(".prev", this);
				var $next = $(".next", this);
				var $listItemsClone = $("li", this).clone( true );
				var $slider = $(".slider", this);

				var slideArray = [];

				var sliderIndex = 0;
				var count = $listItemsClone.size();
				var countVisible = 0;
				var activeLiIndex = 0;

				if( $(".slider", this).hasClass("slider_bottom") ) {
					var width = $(".list_wrapper", this).width();
					var liWidth = $("li", this).outerWidth(true);

					countVisible = Math.floor( width / liWidth );
				}
				else {
					var height = $(".list_wrapper", this).height();
					var liHeight = $("li", this).outerHeight(true);

					countVisible = Math.floor( height / liHeight );
				}

				var $listItems = $("li", this);


				function changeImage( that ) {
					var idx = $listItems.index(that);
					activeLiIndex = idx;

					$slider
						.find(".shadow")
						.remove();

					$listItems
						.removeClass("active")
						.eq(getIndex(idx, countVisible))
						.addClass("active")
						.find("a img")
						.after("<span class=\"shadow\" />");

					if( typeof slideArray[idx] == "undefined" ) {

						var url = $("a", that).attr("href");
						$.ajax({
							"url": url
						})
						.success(function(data, textStatus, jqXHR){
							$content
								.fadeOut(function() {
									$content
										.html($(data).html())
										.fadeIn(options.contentDuration);

									slideArray[idx] = $(data).html();
									//Hyphenator.run();
									//text = $(data).find(".txt_wrapper");
									//log($(text).html());
									//log(Hyphenator.hyphenate($(text).html(), 'de'));
									//$(data).find(".txt_wrapper").html(Hyphenator.hyphenate($(text).html(), 'de'));
						            //log($content);
									if((!$.browser.msie) || ($.browser.msie && $.browser.version.slice(0,3) >= "9.0")){
										Hyphenator.hyphenate(this, 'de');
									}
								});
						})
						.error(function(jqXHR, textStatus, errorThrown){
							log("error", jqXHR, textStatus, errorThrown);
							if($("html").hasClass("ie7") || $("html").hasClass("ie8")) {
								$content
									.show();
							}
							else {
								$content
									.fadeIn(options.contentDuration);
							}
						});
					}
					else {
						$content
							.fadeOut(function(){
								$content
									.html(slideArray[idx])
									.fadeIn(options.contentDuration);
								
								if((!$.browser.msie) || ($.browser.msie && $.browser.version.slice(0,3) >= "9.0")){
									Hyphenator.hyphenate(this, 'de');
								}
							});
					}
				};

				if( modIndex === 0 ) {
					int = window.setInterval(function(){
						activeLiIndex = getIndex( activeLiIndex+1, count );

						if(!(activeLiIndex >= sliderIndex && activeLiIndex < sliderIndex + countVisible)) {
							rotate(activeLiIndex);
						}

						var $li = $("li", that).eq(activeLiIndex);

						changeImage( $li );
					}, options.interval);

				}

				// thumbnail actions
				$listItems
					.click(function(){
						window.clearInterval(int);
						changeImage(this);
						return false;
					});

				// break if not enough items for rotation
				if( count <= countVisible ) {
					return;
				}

				var rotate = function( idx ) {
					$listItems.removeClass("active");

					for(var i = 0, delay = 0; i < countVisible; i += 1, delay += options.sliderDelay){
						(function(idx, i, callback){
							window.setTimeout(function(){

								$listItems
									.eq(i)
									.stop(false, true)
									.fadeOut(options.sliderDuration, function(){
										$(this)
											.html( $listItemsClone.eq( getIndex(idx+i, count) ).html() )
											.fadeIn(options.sliderDuration);
										if( getIndex( idx + i, count ) === activeLiIndex ) {
											$(this)
												.addClass("active")
												.find("a img")
												.after("<span class=\"shadow\" />");
										}
										if((!$.browser.msie) || ($.browser.msie && $.browser.version.slice(0,3) >= "9.0")){
											Hyphenator.hyphenate(this, 'de');
										}
									});

							}, delay);
						})(idx, i);
					}
					sliderIndex=idx;
				};


				$prev
					.show()
					.click(function(){
						// TODO: Zählpixel
						window.clearInterval(int);
						rotate( sliderIndex - countVisible );
					});

				$next
					.show()
					.click(function(){
						// TODO: Zählpixel
						window.clearInterval(int);
						rotate( sliderIndex + countVisible );
					});
			});


			// hover thumbs
			if( options.thumbsHover ) {
				var $slider = $(".slider", this);

				$slider.each(function( index, item ){
					var height = $(this).outerHeight( true );
					var width = $(this).outerWidth( true );
					var hover = false;
					var position = $(this).position();

					$(this).hide();

					$mods
						.eq( index )
						.mousemove(function(e){

							var x = e.pageX - $(this).offset().left;
					        var y = e.pageY - $(this).offset().top;

							if(x >= position.left && x <= position.left + width && y >= position.top && y <= position.top + height) {
								$slider
									.eq(index)
									.show();
							}
							else if(true) {
								$slider
									.eq(index)
									.hide();
							}
						});

				});
			}
		});
	};


	$.fn.wazResize = function() {
		return this.each(function(){
			var $smaller = $(".resize .smaller, #resize_bottom .smaller", this),
				$bigger = $(".resize .bigger, #resize_bottom .bigger", this),
				$text = $(".article > *, .content > *").not(".art_aside").not(".content");

			function resize( value ) {
				$text
					.each(function() {
						var fontSize = parseInt($(this).css("font-size")) + value + "px",
							lineHeight = parseInt($(this).css("line-height")) + value + "px";

						$(this)
							.css({
								"font-size": fontSize,
								"line-height": lineHeight
							});
					});

			};

			$smaller
				.addClass("cp")
				.click(function(e) {
					e.preventDefault();
					resize( -1 );

				});

			$bigger
				.addClass("cp")
				.click(function(e) {
					e.preventDefault();
					resize( +1 );
				});
		});
	};


	$.fn.wazShoutbox = function(opts){
		var options = $.extend({
			url: null
		}, opts);
		return this.each(function(){
			var that = this;

			$.ajax({
				url: options.url
			})
			.success(function(data, textStatus, jqXHR){
				var $img = $("img", data);
				var $txt = $(".txt", data);
				var $prev = $(".prev", data);
				var $next = $(".next", data);
				var $counter = $(".counter", data);

				var indexImg = 0;
				var indexTxt = 0;

				function slide(idxImg, idxTxt){

					$("img", that)
						.attr("alt", $img.eq(idxImg).attr("alt"))
						.attr("src", $img.eq(idxImg).attr("src"));

					$(".txt", that).remove();
					$(that).append($txt.eq(idxTxt));

					var offset = ($txt.eq(idxTxt).outerHeight() - $prev.outerHeight()) / 2;

					$(".ctrl", that).css("bottom", 40 + offset);

					$counter.text((idxTxt+1) + " von " + ($txt.size()));

					indexImg = idxImg;
					indexTxt = idxTxt;
				};

				$prev
					.click(function(){
						reIVW();
						var idxImg = getIndex(indexImg-1, $img.size());
						var idxTxt = getIndex(indexTxt-1, $txt.size());

						slide(idxImg, idxTxt);
					});
				$(that).append($prev);

				$next
					.click(function(){
						reIVW();
						var idxImg = getIndex(indexImg+1, $img.size());
						var idxTxt = getIndex(indexTxt+1, $txt.size());

						slide(idxImg, idxTxt);
					});
				$(that).append($next);

				$(that).append($counter);

				slide(indexImg, indexTxt);
			})
			.error(function(jqXHR, textStatus, errorThrown){
				log( textStatus );
			});

		});
	};


	$.fn.wazSlideShow = function(opts){

		var options = $.extend({
			imgFadeDuration: 200,
			lastPageUrl: null,
			length: null,
			sliderDelay: 100,
			sliderDuration: 200,
			type: null,
			url: null,
			zoom: false
		}, opts);

		return this.each(function(){
			log("$.fn.wazSlideShow", this);

			var that = this;
			var init = true;
			var json = null;
			var length = options.length;
			var index = options.activeIndex;
			var sliderIndex = 0;
			var adPos = [];
			var adVisible = false;
			var $img = $(".img img", this);
			var $txt = $(".txt", this);

			function preload( idx ) {
				var start = -1; // start at index -1
				var count = 3; // load 3 images

				idx += start;

				for(var i=0; i < count; i += 1) {
					var $img = $("<img />");
					$img.attr("src", json.slides[getIndex(idx+i, length)].img_l.src);
				}
			}


			function slideTo( idx ) {

				if( idx < 0 || idx === length ) {
					if(options.type == "agency") {
						// ignore
					}
					else if(options.type !== "inline") {
						window.location = options.lastPageUrl;
					}
					else {
						$.ajax({
							url: options.lastPageUrl
						})
						.success(function(data, textStatus, jqXHR){
							$(".slideshow_c", that).remove();
							$(that).append(data);

							$(".prev_wrapper", that).click(function(){
								$(that).remove();
								options.triggerIdx = options.length - 1;
								$(options.container)
									.wazSlideShowInline(options);
								options.triggerIdx = null;
								return false;
							});
							$(".next_wrapper", that).click(function(){
								$(that).remove();
								options.triggerIdx = 0;
								$(options.container)
									.wazSlideShowInline(options);
								options.triggerIdx = null;
								return false;
							});
						})
						.error(function(jqXHR, textStatus, errorThrown){
							log( textStatus );
						});
					}
					return;
				}

				// check for ads and build if not already built
				var adIdx;
				if( (adIdx = $.inArray(idx, adPos )) !== -1 && adVisible === false) {
					var $iframe = $("<div class='iframe' />");
					var $slideshow = $(".slideshow_wrapper", that);
					$iframe.append(json.ads[adIdx].iframe);

					var height = $iframe.find("iframe").attr("height");
					var width = $iframe.find("iframe").attr("width");

					var wrapperHeight = $slideshow.outerHeight(true);
					var wrapperWidth = $slideshow.outerWidth(true);

					var top = (wrapperHeight / 2) - (height / 2);
					var left = (wrapperWidth / 2) - (width / 2);

					$iframe.css({
						"left": left,
						"top": top
					});

					$slideshow.append($iframe);
					adVisible = true;

					$(".img", that).hide();
					$(".txt", that).addClass("invisible");
				}
				else if( adVisible ) {
					$(".slideshow_wrapper .iframe", that).remove();
					adVisible = false;

					$(".img", that).show();
					$(".txt", that).removeClass("invisible");
					return;
				}


				index = idx;
				$counter.text("Bild " + ( index + 1 ) + " von " + (length + 1));

				$(".slider li.active .shadow", that)
					.remove();

				$(".slider li", that)
					.removeClass("active")
					.eq(index-sliderIndex)
					.addClass("active")
					.append("<div class=\"shadow\" />");

				if( init ) {
					$img
						.attr("src", json.slides[index].img_l.src)
						.attr("alt", json.slides[index].img_l.alt)
						.attr("height", json.slides[index].img_l.height)
						.attr("width", json.slides[index].img_l.width)
						.css("padding-top", ($(".slideshow_wrapper", that).height() - json.slides[index].img_l.height) / 2);

					$txt
						.html(json.slides[index].img_l.txt)
						.fadeIn(options.imgFadeDuration);

					init = false;
				}
				else {
					$img
						.stop( false, true )
						.fadeOut(
								options.imgFadeDuration,
								function(){
									$img
									.one("load", function() {
										$(this).fadeIn(options.imgFadeDuration);
									})
									.attr("src", json.slides[index].img_l.src)
									.attr("alt", json.slides[index].img_l.alt)
									.attr("height", json.slides[index].img_l.height)
									.attr("width", json.slides[index].img_l.width)
									.css("padding-top", ($(".slideshow_wrapper", that).height() - json.slides[index].img_l.height) / 2);

								});

					$txt
						.stop( false, true )
						.fadeOut(
								options.imgFadeDuration,
								function(){
									$txt
									.html(json.slides[index].img_l.txt)
									.fadeIn(options.imgFadeDuration);
								});
				}

				preload( index );
			}


			$(".img", this).wrap("<div class='slideshow_wrapper' />");

			var $prev_wrapper = $("<div class='prev_wrapper'><div class='prev' /></div>");
			var $prev = $prev_wrapper.find(".prev");

			var $next_wrapper = $("<div class='next_wrapper'><div class='next' /></div>");
			var $next = $next_wrapper.find(".next");

			$prev_wrapper
				.hover(
						function(){
							$prev.fadeIn(); $next.fadeIn();
						},
						function(){
							$prev.fadeOut(); $next.fadeOut();
						}
				)
				.click(function(){
					reIVW();
					slideTo( index - 1 );
				});
			$next_wrapper
				.hover(
						function(){
							$prev.fadeIn(); $next.fadeIn();
						},
						function(){
							$prev.fadeOut(); $next.fadeOut();
						}
					)
				.click(function(){
					reIVW();
					slideTo( index + 1 );
				});

			if(options.length > 1) {
				$(".slideshow_wrapper", this).append($prev_wrapper);
				$(".slideshow_wrapper", this).append($next_wrapper);
			}


			if(options.zoom) {
				var $zoom = $("<div class='zoom' />");
				$zoom
					.click(function(){
						window.location = json.slides[index].img_l.zoom;
					});
				$(".slideshow_wrapper", this).append($zoom);
			}


			var $counter = $("<div class='counter' />");
			if($(this).hasClass("img_top")){
				$(this).append($counter);
			}
			else {
				$(".img_top", this).append($counter);
			}

			function buildSlider() {

				var html = [];
				html.push("<div class='slider_wrapper'>");
					html.push("<div class='slider'>");
						html.push("<div class='control prev'></div>");
						html.push("<div class='list_wrapper'>");
							html.push("<ul class='no_ls list clearfix'>");
								for(var i=0; i < length; i+=1) {
									html.push( index === i ? "<li class='active'>" : "<li>");
										var img = "<img src='" + json.slides[i].img_s.src +"' alt='" + json.slides[i].img_s.alt + "' height='" + json.slides[i].img_s.height + "' width='" + json.slides[i].img_s.width + "' />";
										html.push( img );
										if(index === i) {
											html.push("<div class=\"shadow\" />");
										}
									html.push("</li>");
								}
							html.push("</ul>");
						html.push("</div>");
						html.push("<div class='control next'></div>");
					html.push("</div>");
				html.push("</div>");


				var $slider = $(html.join(""));

				$(".slideshow_wrapper", that).append( $slider );

				$slider
					.hover(
						function(){
							$slider.find(".slider").stop(true, true).fadeIn();
						},
						function(){
							$slider.find(".slider").stop(true, true).fadeOut();
						}
					);

				var $listItemsClone = $slider.find("li").clone( true );

				var count = $listItemsClone.size();
				var countVisible = 0;
				var width = $slider.find(".list_wrapper").width();
				var liWidth = $slider.find("li").outerWidth(true);

				countVisible = Math.floor( width / liWidth );

				// break if not enough items for rotation
				if( length <= countVisible ) {
					return;
				}

				var $listItems = $slider.find("li");

				var rotate = function( idx ) {
					$listItems.removeClass("active");

					var length = $listItemsClone.size();

					for(var i = 0, delay = 0; i < countVisible+1; i += 1, delay += options.sliderDelay){
						(function(idx, i){
							window.setTimeout(function(){
								$listItems
									.eq(i)
									.stop(false, true)
									.fadeOut(options.sliderDuration, function(){
										$(this)
											.html( $listItemsClone.eq( getIndex(idx+i, length) ).html() )
											.fadeIn(options.sliderDuration);
										if( getIndex( idx + i, length ) === index ) {
											$(this)
												.addClass("active")
												.append("<div class=\"shadow\" />");
										}
									});

							}, delay);
						})(idx, i);
					}
					sliderIndex=getIndex(idx, length);
				};


				$slider
					.find(".prev")
					.show()
					.click(function(){
						// TODO: Zählpixel
						rotate( sliderIndex - countVisible );
					});

				$slider
					.find(".next")
					.show()
					.click(function(){
						// TODO: Zählpixel
						rotate( sliderIndex + countVisible );
					});

				// add events listeners
				$slider
					.find("li")
					.click(function(){

						var idx = $slider
							.find("li")
							.index( this );

						reIVW();
						slideTo( getIndex(sliderIndex + idx, length) );
					});

				$slider
					.find(".slider")
					.css({
						"display": "none",
						"visibility": "visible"
					});
			};

			$.ajax({
				url: options.url,
				beforeSend: function(xhr){
					if (xhr.overrideMimeType) {
						xhr.overrideMimeType("application/json");
					}
				},
				dataType: "json"
			})
			.success(function(data, textStatus, jqXHR){
				json = data;

				for(var ad in json.ads){
					adPos.push(json.ads[ad].pos);
				}

				preload(index);
				slideTo(index);
				buildSlider();
			})
			.error(function(jqXHR, textStatus, errorThrown){
				log( textStatus );
			});
		});
	};


	$.fn.wazSlideShowInline = function(opts){

		var options = $.extend({
			activeIndex: 0,
			container: null,
			imgFadeDuration: 200,
			lastPageUrl: null,
			length: null,
			sliderDelay: 100,
			sliderDuration: 200,
			triggerIdx: null,
			type: "inline",
			url: null,
			zoomUrl: ""
		}, opts);

		return this.each(function(){
			log("$.fn.wazSlideShowInline", this);

			var that = this;
			var $previews = $(".img" , this);

			options.container = this;

			$previews
				.die("click")
				.live("click", function(e) {
					var idxImg = $(".img" , that).index(this);
					var idxGroup = $(".control .groups a.active", that).index() > 0 ? $(".control .groups a.active", that).index() : 0;
					var tail = ((idxGroup+1) * 4) - options.length > 0 ? ((idxGroup+1) * 4) - options.length : 0;
					var idx = getIndex( ((idxGroup * 4) + idxImg) - tail, options.length );
					buildLayer(idx);
					return false;
				});

			function buildLayer(idx) {
				options.activeIndex = idx;
				options.triggerIdx = null;

				var layer = [];
				layer.push("<div class='layer'>");
					layer.push("<div class='close'><span>schlie&szlig;en</span><span class='icon'></span></div>");
				layer.push("</div>");

				var $layer = $(layer.join(""));

				$layer
					.find(".close")
					.click(function(){
						$layer.remove();

						if($("html").hasClass("ie7")) {
							$(".article").css("z-index", "auto");
						}
					});

				$.ajax({
					url: options.urlLayer
				})
				.success(function(data, textStatus, jqXHR){
					var $data = $(data);

					$layer
						.append($data)
						.wazSlideShow(options)
						.show();

				})
				.error(function(jqXHR, textStatus, errorThrown){
					log(jqXHR, textStatus, errorThrown);
				});


				if($("html").hasClass("ie7")) {
					$(".article").css("z-index", "200");
				}

				$(that)
					.append($layer);

			};

			if(options.triggerIdx !== null) {
				buildLayer(options.triggerIdx);
				return false;
			}

		});
	};



	$.fn.wazSlideShowVoting = function( opts ) {
		var options = $.extend({
			imgFadeDuration: 200,
			lastPageUrl: null,
			length: null,
			sliderDelay: 100,
			sliderDuration: 200,
			url: null
		}, opts);

		return this.each(function(){
			log("$.fn.wazSlideShow", this);

			var that = this;
			var json = null;
			var length = options.length;
			var index = options.activeIndex;
			var sliderIndex = 0;
			var adPos = [];
			var adVisible = false;
			var $img = $(".img img", this);
			var $txt = $(".txt", this);
			var $vote = $(".vote", this);

			function preload( idx ) {
				var start = -1; // start at index -1
				var count = 3; // load 3 images

				idx += start;

				for(var i=0; i < count; i += 1) {
					var $img = $("<img />");
					$img.attr("src", json.slides[getIndex(idx+i, length)].img_l.src);
				}
			}


			function slideTo( idx ) {

				if( idx < 0 || idx === length ) {
					if(options.type !== "inline") {
						window.location = options.lastPageUrl;
					}
					else {
						$.ajax({
							url: options.lastPageUrl
						})
						.success(function(data, textStatus, jqXHR){
							$(".slideshow_c", that).remove();
							$(that).append(data);

							$(".prev_wrapper", that).click(function(){
								$(that).remove();
								options.triggerIdx = options.length - 1;
								$(options.container)
									.wazSlideShowInline(options);
								options.triggerIdx = null;
								return false;
							});
							$(".next_wrapper", that).click(function(){
								$(that).remove();
								options.triggerIdx = 0;
								$(options.container)
									.wazSlideShowInline(options);
								options.triggerIdx = null;
								return false;
							});
						})
						.error(function(jqXHR, textStatus, errorThrown){
							log( textStatus );
						});
					}
					return;
				}

				// check for ads and build if not already built
				var adIdx;
				if( (adIdx = $.inArray(idx, adPos )) !== -1 && adVisible === false) {
					var $iframe = $("<div class='iframe' />");
					$iframe.append(json.ads[adIdx].iframe);
					$(".slideshow_wrapper", that).append($iframe);

					adVisible = true;
				}
				else if( adVisible ) {
					$(".slideshow_wrapper .iframe", that).remove();
					adVisible = false;

					return;
				}


				index = idx;
				$counter.text("Bild " + ( index + 1 ) + " von " + (length + 1));

				$(".slider li", that)
					.removeClass("active")
					.eq(index-sliderIndex)
					.addClass("active");

				$img
					.stop( false, true )
					.fadeOut(
							options.imgFadeDuration,
							function(){
								$img
									.attr("src", json.slides[index].img_l.src)
									.attr("alt", json.slides[index].img_l.alt)
									.attr("height", json.slides[index].img_l.height)
									.attr("width", json.slides[index].img_l.width)
									.css("margin-top", ($(".slideshow_wrapper", that).height() - json.slides[index].img_l.height) / 2)
									.fadeIn(options.imgFadeDuration);
							});

				$txt
					.stop( false, true )
					.fadeOut(
							options.imgFadeDuration,
							function(){
								$txt
									.html(json.slides[index].img_l.txt)
									.fadeIn(options.imgFadeDuration);
							});

				$.ajax({
					"url": json.slides[index].vote.url
				})
				.success(function(data, textStatus, jqXHR){
					log(data);
					$vote
						.html(data)
						.find("form")
						.submit(function(){
							$.ajax({
                                "type": "POST",
								data: $(this).serializeArray(),
								url: $("form", $vote).attr("action")
							})
							.success(function(data, textStatus, jqXHR){
								$vote
									.html(data);
							})
							.error(function(jqXHR, textStatus, errorThrown){
								log( textStatus );
							});
							return false;
						});
				})
				.error(function(jqXHR, textStatus, errorThrown){
					log( textStatus );
				});


				preload( index );
			}


			$(".img", this).wrap("<div class='slideshow_wrapper' />");

			var $prev_wrapper = $("<div class='prev_wrapper'><div class='prev' /></div>");
			var $prev = $prev_wrapper.find(".prev");
			$prev_wrapper
				.hover(
						function(){ $prev.fadeIn(); },
						function(){ $prev.fadeOut();}
					)
				.click(function(){
					reIVW();
					slideTo( index - 1 );
				});
			$(".slideshow_wrapper", this).append($prev_wrapper);

			var $next_wrapper = $("<div class='next_wrapper'><div class='next' /></div>");
			var $next = $next_wrapper.find(".next");
			$next_wrapper
				.hover(
						function(){ $next.fadeIn(); },
						function(){ $next.fadeOut();}
					)
				.click(function(){
					reIVW();
					slideTo( index + 1 );
				});
			$(".slideshow_wrapper", this).append($next_wrapper);


			if(options.zoom) {
				var $zoom = $("<div class='zoom' />");
				$zoom
					.click(function(){
						window.location = json.slides[index].img_l.zoom;
					});
				$(".slideshow_wrapper", this).append($zoom);
			}


			var $counter = $("<div class='counter' />");
			if($(this).hasClass("img_top")){
				$(this).append($counter);
			}
			else {
				$(".img_top", this).append($counter);
			}

			function buildSlider() {

				var html = [];
				html.push("<div class='slider_wrapper'>");
					html.push("<div class='slider'>");
						html.push("<div class='control prev'></div>");
						html.push("<div class='list_wrapper'>");
							html.push("<ul class='no_ls list clearfix'>");
								for(var i=0; i < length; i+=1) {
									html.push( index === i ? "<li class='active'>" : "<li>");
										var img = "<img src='" + json.slides[i].img_s.src +"' alt='" + json.slides[i].img_s.alt + "' height='" + json.slides[i].img_s.height + "' width='" + json.slides[i].img_s.width + "' />";
										html.push( img );
									html.push("</li>");
								}
							html.push("</ul>");
						html.push("</div>");
						html.push("<div class='control next'></div>");
					html.push("</div>");
				html.push("</div>");


				var $slider = $(html.join(""));

				$(".slideshow_wrapper", that).append( $slider );

				$slider
					.hover(
						function(){
							$slider.find(".slider").stop(true, true).fadeIn();
						},
						function(){
							$slider.find(".slider").stop(true, true).fadeOut();
						}
					);

				var $listItemsClone = $slider.find("li").clone( true );

				var count = $listItemsClone.size();
				var countVisible = 0;
				var width = $slider.find(".list_wrapper").width();
				var liWidth = $slider.find("li").outerWidth(true);

				countVisible = Math.floor( width / liWidth );

				// break if not enough items for rotation
				if( length <= countVisible ) {
					return;
				}

				var $listItems = $slider.find("li");

				var rotate = function( idx ) {
					$listItems.removeClass("active");

					var length = $listItemsClone.size();

					for(var i = 0, delay = 0; i < countVisible+1; i += 1, delay += options.sliderDelay){
						(function(idx, i){
							window.setTimeout(function(){
								$listItems
									.eq(i)
									.stop(false, true)
									.fadeOut(options.sliderDuration, function(){
										$(this)
											.html( $listItemsClone.eq( getIndex(idx+i, length) ).html() )
											.fadeIn(options.sliderDuration);
										if( getIndex( idx + i, length ) === index ) {
											$(this).addClass("active");
										}
									});

							}, delay);
						})(idx, i);
					}
					sliderIndex=getIndex(idx, length);
				};


				$slider
					.find(".prev")
					.show()
					.click(function(){
						rotate( sliderIndex - countVisible );
					});

				$slider
					.find(".next")
					.show()
					.click(function(){
						rotate( sliderIndex + countVisible );
					});

				// add events listeners
				$slider
					.find("li")
					.click(function(){

						var idx = $slider
							.find("li")
							.index( this );

						reIVW();
						slideTo( getIndex(sliderIndex + idx, length) );
					});

				$slider
					.find(".slider")
					.css({
						"display": "none",
						"visibility": "visible"
					});
			};

			$.ajax({
				url: options.url,
				beforeSend: function(xhr){
					if (xhr.overrideMimeType) {
						xhr.overrideMimeType("application/json");
					}
				},
				dataType: "json"
			})
			.success(function(data, textStatus, jqXHR){
				json = data;

				for(var ad in json.ads){
					adPos.push(json.ads[ad].pos);
				}

				preload(index);
				slideTo(index);
				buildSlider();
			})
			.error(function(jqXHR, textStatus, errorThrown){
				log( textStatus );
			});
		});
	};



	$.fn.wazSocial = function(opts){
		var options = $.extend({}, opts);

		return this.each(function(){
			var $box = $(".inner", this);

			$(document).ready(function(){
				for(var button in options.button){
					$box.append("<div class=\"line\">" + options.button[button] + "</div>");
				}
				$box.show();
			});
		});
	};


	$.fn.wazTable = function(opts){
		return this.each(function(){
			var that = this;
			var $nav = $(".nav li", this);
			var $tables = $("table", this);

			$nav.click(function(){
				var idx = $nav.index(this);
				$nav
					.removeClass("active");
				$(this)
					.addClass("active");

				$("table:visible", that)
					.hide();

				$tables
					.eq(idx)
					.removeClass("hidden")
					.show();

				return false;
			});
		});
	};


	$.fn.wazTextGallery = function(opts) {
		return this.each(function(){
			var $toggle = $(".toggle", this);
			var $hl = $(".hl", this);
			var $txt = $(".txt", this);

			function toggle(idx) {
				if($txt.eq(idx).is(":visible")) {
					$txt.eq(idx).slideUp();
					$toggle.eq(idx).addClass("toggle_c");
					$hl.eq(idx).removeClass("active");
				}
				else {
					$txt.eq(idx).slideDown();
					$toggle.eq(idx).removeClass("toggle_c");
					$hl.eq(idx).addClass("active");
				}
			};

			$toggle
				.click(function() {
					var idx = $toggle.index(this);
					toggle(idx);
				});
			$hl
				.click(function() {
					var idx = $hl.index(this);
					toggle(idx);
				});
		});
	};


	$.fn.wazTextSlide = function(){
		return this.each(function(){
			var $li = $("li", this);
			var $prev = $(".prev", this);
			var $next = $(".next", this);
			var $counter = $(".counter", this);
			var index = 0;
			var length = $li.size();

			function rotate(idx) {
				$li
					.eq(index)
					.fadeOut(function(){
						$li
							.eq(idx)
							.fadeIn();
					});
				$counter.text( (idx + 1) + " von " + length );
				index = idx;
			}

			$prev
				.show()
				.click(function() {
					rotate( getIndex(index - 1, length) );
					// TODO: Zählpixel
				});
			$next
				.show()
				.click(function() {
					rotate( getIndex(index + 1, length) );
					// TODO: Zählpixel

				});


		});
	};


	$.fn.wazVotingLayer = function(opts) {

		return this.each(function() {
			var that = this;
			var $form = $("form", this);
			var $close = $(".layer .close", this);


			$form.submit(function(){


				return false;
			});

			$close.live("click", function(){
				$(".layer", that).remove();

				return false;
			});



		});
	};


})(jQuery);


