// Kennzeichnet den Einsatz der jQuery-Bibliothek in den Dateien.
// Alle jQuery-Funktionen werden ausschließlich über "jsapi" aufgerufen.

var jsapi = $;
var config_directory = '/' + pathname;

// Lightbox für die Bilder.

/*
  jQuery lightBox plugin
  This jQuery plugin was inspired and based on Lightbox 2 by Lokesh Dhakar (http://www.huddletogether.com/projects/lightbox2/)
  and adapted to me for use like a plugin from jQuery.
  @name jquery-lightbox-0.5.js
  @author Leandro Vieira Pinho - http://leandrovieira.com
  @version 0.5
  @date April 11, 2008
  @category jQuery plugin
  @copyright (c) 2008 Leandro Vieira Pinho (leandrovieira.com)
  @license CC Attribution-No Derivative Works 2.5 Brazil - http://creativecommons.org/licenses/by-nd/2.5/br/deed.en_US
  @example Visit http://leandrovieira.com/projects/jquery/lightbox/ for more informations about this jQuery plugin
*/

var theme_dir = '/themes/kahunablog/';
(function($){$.fn.lightBox=function(settings){settings=jQuery.extend({overlayBgColor:'#858173',overlayOpacity:0.8,fixedNavigation:false,imageLoading:theme_dir+'images/layout/lightbox-ico-loading.gif',imageBtnPrev:theme_dir+'images/layout/lightbox-btn-prev.gif',imageBtnNext:theme_dir+'images/layout/lightbox-btn-next.gif',imageBtnClose:theme_dir+'images/layout/lightbox-btn-close.gif',imageBlank:theme_dir+'images/layout/lightbox-blank.gif',containerBorderSize:10,containerResizeSpeed:400,txtImage:'Bild',txtOf:'von',keyToClose:'c',keyToPrev:'p',keyToNext:'n',imageArray:[],activeImage:0},settings);var jQueryMatchedObj=this;function _initialize(){_start(this,jQueryMatchedObj);return false;}
function _start(objClicked,jQueryMatchedObj){$('embed, object, select').css({'visibility':'hidden'});_set_interface();settings.imageArray.length=0;settings.activeImage=0;if(jQueryMatchedObj.length==1){settings.imageArray.push(new Array(objClicked.getAttribute('href'),objClicked.getAttribute('title')));}else{for(var i=0;i<jQueryMatchedObj.length;i++){settings.imageArray.push(new Array(jQueryMatchedObj[i].getAttribute('href'),jQueryMatchedObj[i].getAttribute('title')));}}
while(settings.imageArray[settings.activeImage][0]!=objClicked.getAttribute('href')){settings.activeImage++;}
_set_image_to_view();}
function _set_interface(){$('body').append('<div id="jquery-overlay"></div><div id="jquery-lightbox"><div id="lightbox-container-image-box"><div id="lightbox-container-image"><img id="lightbox-image"><div style="" id="lightbox-nav"><a href="#" id="lightbox-nav-btnPrev"></a><a href="#" id="lightbox-nav-btnNext"></a></div><div id="lightbox-loading"><a href="#" id="lightbox-loading-link"><img src="'+settings.imageLoading+'"></a></div></div></div><div id="lightbox-container-image-data-box"><div id="lightbox-container-image-data"><div id="lightbox-image-details"><span id="lightbox-image-details-caption"></span><span id="lightbox-image-details-currentNumber"></span></div><div id="lightbox-secNav"><a href="#" id="lightbox-secNav-btnClose"><img src="'+settings.imageBtnClose+'"></a></div></div></div></div>');var arrPageSizes=___getPageSize();$('#jquery-overlay').css({backgroundColor:settings.overlayBgColor,opacity:settings.overlayOpacity,width:arrPageSizes[0],height:arrPageSizes[1]}).fadeIn();var arrPageScroll=___getPageScroll();$('#jquery-lightbox').css({top:arrPageScroll[1]+(arrPageSizes[3]/10),left:arrPageScroll[0]}).show();$('#jquery-overlay,#jquery-lightbox').click(function(){_finish();});$('#lightbox-loading-link,#lightbox-secNav-btnClose').click(function(){_finish();return false;});$(window).resize(function(){var arrPageSizes=___getPageSize();$('#jquery-overlay').css({width:arrPageSizes[0],height:arrPageSizes[1]});var arrPageScroll=___getPageScroll();$('#jquery-lightbox').css({top:arrPageScroll[1]+(arrPageSizes[3]/10),left:arrPageScroll[0]});});}
function _set_image_to_view(){$('#lightbox-loading').show();if(settings.fixedNavigation){$('#lightbox-image,#lightbox-container-image-data-box,#lightbox-image-details-currentNumber').hide();}else{$('#lightbox-image,#lightbox-nav,#lightbox-nav-btnPrev,#lightbox-nav-btnNext,#lightbox-container-image-data-box,#lightbox-image-details-currentNumber').hide();}
var objImagePreloader=new Image();objImagePreloader.onload=function(){$('#lightbox-image').attr('src',settings.imageArray[settings.activeImage][0]);_resize_container_image_box(objImagePreloader.width,objImagePreloader.height);objImagePreloader.onload=function(){};};objImagePreloader.src=settings.imageArray[settings.activeImage][0];};function _resize_container_image_box(intImageWidth,intImageHeight){var intCurrentWidth=$('#lightbox-container-image-box').width();var intCurrentHeight=$('#lightbox-container-image-box').height();var intWidth=(intImageWidth+(settings.containerBorderSize*2));var intHeight=(intImageHeight+(settings.containerBorderSize*2));var intDiffW=intCurrentWidth-intWidth;var intDiffH=intCurrentHeight-intHeight;$('#lightbox-container-image-box').animate({width:intWidth,height:intHeight},settings.containerResizeSpeed,function(){_show_image();});if((intDiffW==0)&&(intDiffH==0)){if($.browser.msie){___pause(250);}else{___pause(100);}}
$('#lightbox-container-image-data-box').css({width:intImageWidth});$('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({height:intImageHeight+(settings.containerBorderSize*2)});};function _show_image(){$('#lightbox-loading').hide();$('#lightbox-image').fadeIn(function(){_show_image_data();_set_navigation();});_preload_neighbor_images();};function _show_image_data(){$('#lightbox-container-image-data-box').slideDown('fast');$('#lightbox-image-details-caption').hide();if(settings.imageArray[settings.activeImage][1]){$('#lightbox-image-details-caption').html(settings.imageArray[settings.activeImage][1]).show();}
if(settings.imageArray.length>1){$('#lightbox-image-details-currentNumber').html(settings.txtImage+' '+(settings.activeImage+1)+' '+settings.txtOf+' '+settings.imageArray.length).show();}}
function _set_navigation(){$('#lightbox-nav').show();$('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({'background':'transparent url('+settings.imageBlank+') no-repeat'});if(settings.activeImage!=0){if(settings.fixedNavigation){$('#lightbox-nav-btnPrev').css({'background':'url('+settings.imageBtnPrev+') left 15% no-repeat'}).unbind().bind('click',function(){settings.activeImage=settings.activeImage-1;_set_image_to_view();return false;});}else{$('#lightbox-nav-btnPrev').unbind().hover(function(){$(this).css({'background':'url('+settings.imageBtnPrev+') left 15% no-repeat'});},function(){$(this).css({'background':'transparent url('+settings.imageBlank+') no-repeat'});}).show().bind('click',function(){settings.activeImage=settings.activeImage-1;_set_image_to_view();return false;});}}
if(settings.activeImage!=(settings.imageArray.length-1)){if(settings.fixedNavigation){$('#lightbox-nav-btnNext').css({'background':'url('+settings.imageBtnNext+') right 15% no-repeat'}).unbind().bind('click',function(){settings.activeImage=settings.activeImage+1;_set_image_to_view();return false;});}else{$('#lightbox-nav-btnNext').unbind().hover(function(){$(this).css({'background':'url('+settings.imageBtnNext+') right 15% no-repeat'});},function(){$(this).css({'background':'transparent url('+settings.imageBlank+') no-repeat'});}).show().bind('click',function(){settings.activeImage=settings.activeImage+1;_set_image_to_view();return false;});}}
_enable_keyboard_navigation();}
function _enable_keyboard_navigation(){$(document).keydown(function(objEvent){_keyboard_action(objEvent);});}
function _disable_keyboard_navigation(){$(document).unbind();}
function _keyboard_action(objEvent){if(objEvent==null){keycode=event.keyCode;escapeKey=27;}else{keycode=objEvent.keyCode;escapeKey=objEvent.DOM_VK_ESCAPE;}
key=String.fromCharCode(keycode).toLowerCase();if((key==settings.keyToClose)||(key=='x')||(keycode==escapeKey)){_finish();}
if((key==settings.keyToPrev)||(keycode==37)){if(settings.activeImage!=0){settings.activeImage=settings.activeImage-1;_set_image_to_view();_disable_keyboard_navigation();}}
if((key==settings.keyToNext)||(keycode==39)){if(settings.activeImage!=(settings.imageArray.length-1)){settings.activeImage=settings.activeImage+1;_set_image_to_view();_disable_keyboard_navigation();}}}
function _preload_neighbor_images(){if((settings.imageArray.length-1)>settings.activeImage){objNext=new Image();objNext.src=settings.imageArray[settings.activeImage+1][0];}
if(settings.activeImage>0){objPrev=new Image();objPrev.src=settings.imageArray[settings.activeImage-1][0];}}
function _finish(){$('#jquery-lightbox').remove();$('#jquery-overlay').fadeOut(function(){$('#jquery-overlay').remove();});$('embed, object, select').css({'visibility':'visible'});}
function ___getPageSize(){var xScroll,yScroll;if(window.innerHeight&&window.scrollMaxY){xScroll=window.innerWidth+window.scrollMaxX;yScroll=window.innerHeight+window.scrollMaxY;}else if(document.body.scrollHeight>document.body.offsetHeight){xScroll=document.body.scrollWidth;yScroll=document.body.scrollHeight;}else{xScroll=document.body.offsetWidth;yScroll=document.body.offsetHeight;}
var windowWidth,windowHeight;if(self.innerHeight){if(document.documentElement.clientWidth){windowWidth=document.documentElement.clientWidth;}else{windowWidth=self.innerWidth;}
windowHeight=self.innerHeight;}else if(document.documentElement&&document.documentElement.clientHeight){windowWidth=document.documentElement.clientWidth;windowHeight=document.documentElement.clientHeight;}else if(document.body){windowWidth=document.body.clientWidth;windowHeight=document.body.clientHeight;}
if(yScroll<windowHeight){pageHeight=windowHeight;}else{pageHeight=yScroll;}
if(xScroll<windowWidth){pageWidth=xScroll;}else{pageWidth=windowWidth;}
arrayPageSize=new Array(pageWidth,pageHeight,windowWidth,windowHeight);return arrayPageSize;};function ___getPageScroll(){var xScroll,yScroll;if(self.pageYOffset){yScroll=self.pageYOffset;xScroll=self.pageXOffset;}else if(document.documentElement&&document.documentElement.scrollTop){yScroll=document.documentElement.scrollTop;xScroll=document.documentElement.scrollLeft;}else if(document.body){yScroll=document.body.scrollTop;xScroll=document.body.scrollLeft;}
arrayPageScroll=new Array(xScroll,yScroll);return arrayPageScroll;};function ___pause(ms){var date=new Date();curDate=null;do{var curDate=new Date();}
while(curDate-date<ms);};return this.unbind('click').click(_initialize);};})(jQuery);

/*
 * 	Easy Slider 1.5 - jQuery plugin
 *	written by Alen Grakalic
 *	http://cssglobe.com/post/4004/easy-slider-15-the-easiest-jquery-plugin-for-sliding
 *
 *	Copyright (c) 2009 Alen Grakalic (http://cssglobe.com)
 *	Dual licensed under the MIT (MIT-LICENSE.txt)
 *	and GPL (GPL-LICENSE.txt) licenses.
 *
 *	Built for jQuery library
 *	http://jquery.com
 *
 */

(function($) {

	$.fn.easySlider = function(options){

		// default configuration properties
		var defaults = {
			auto: false,
			continuous: false,
			controlsAfter: '',
			controlsBefore: '',
			controlsFade: true,
			controlsShow:	true,
			firstId: 'firstBtn',
			firstShow: false,
			firstText: 'Erstes',
			lastId: 'lastBtn',
			lastShow: false,
			lastText: 'Letztes',
			nextId: 'layout_content_gallery_next',
			nextText: 'Next',
			pause: 2000,
			prevId: 'layout_content_gallery_prev',
			prevText: 'Previous',
			speed: 800,
			vertical:	false,
			counter: 1,
			counter_total: 10
		};

		var options = $.extend(defaults, options);

		this.each(function() {
		
			var obj = $(this);
			var s = $('li', obj).length;
			var w = $('li', obj).width();
			var h = $('li', obj).height();
			
			var image = $('#layout_content_gallery_url_' + options.counter).html();
      if (image == 'undefined') {
        image = '';
      }
      
			obj.width(w);
			obj.height(h);
			obj.css('overflow', 'hidden');
			
			var ts = s-1;
			var t = 0;
			
			$('ul', obj).css('width', s*w);
			if(!options.vertical) $('li', obj).css('float', 'left');

			if (options.controlsShow) {
			
				var html = options.controlsBefore;
				
				html += '<div id="layout_content_gallery_title">' + image + '</div>\n';
				
				html += '<div id="layout_content_gallery_options">\n';
				if (options.firstShow) { html += '<span id="'+ options.firstId +'"><a href="javascript:void(0);">'+ options.firstText +'</a></span>'; }
				html += '<span id="'+ options.prevId +'"><a href="javascript:void(0);" title="'+ options.prevText +'">&lt;&lt;</a></span> ';
				html += '<span id="layout_content_gallery_counter">Bilder laden...</span> ';
				html += '<span id="'+ options.nextId +'"><a href="javascript:void(0);" title="'+ options.nextText +'">&gt;&gt;</a></span> | ';
				if (options.lastShow) { html += ' <span id="'+ options.lastId +'"><a href="javascript:void(0);">'+ options.lastText +'</a></span>'; }
				html += jsapi('#layout_content_gallery_url').html();
        html += '</div>\n';
				
				html += options.controlsAfter;
				
				$(obj).after(html);
				
			};

			$('a', '#'+options.nextId).click(function(){
				animate('next', true);
			});
			$('a', '#'+options.prevId).click(function(){
				animate('prev', true);
			});
			$('a', '#'+options.firstId).click(function(){
				animate('first', true);
			});
			$('a', '#'+options.lastId).click(function(){
				animate('last', true);
			});

			function animate(dir,clicked){
				var ot = t;
				switch(dir){
					case 'next':
						t = (ot>=ts) ? (options.continuous ? 0 : ts) : t+1;
						break;
					case 'prev':
						t = (t<=0) ? (options.continuous ? ts : 0) : t-1;
						break;
					case 'first':
						t = 0;
						break;
					case 'last':
						t = ts;
						break;
					default:
						break;
				};

				var diff = Math.abs(ot-t);
				var speed = diff*options.speed;
				if(!options.vertical) {
					p = (t*w*-1);
					$('ul', obj).animate(
						{ marginLeft: p },
						speed
					);
				} else {
					p = (t*h*-1);
					$('ul', obj).animate(
						{ marginTop: p },
						speed
					);
				};

				if(!options.continuous && options.controlsFade){
					if(t==ts){
						$('a', '#'+options.nextId).hide();
						$('a', '#'+options.lastId).hide();
					} else {
						$('a', '#'+options.nextId).show();
						$('a', '#'+options.lastId).show();
					};
					if(t==0){
						$('a', '#'+options.prevId).hide();
						$('a', '#'+options.firstId).hide();
					} else {
						$('a', '#'+options.prevId).show();
						$('a', '#'+options.firstId).show();
					};
				};

				if(clicked) clearTimeout(timeout);
				if(options.auto && dir=='next' && !clicked){;
					timeout = setTimeout(function(){
						animate('next', false);
					},diff*options.speed+options.pause);
				};
				
				if (dir == 'prev') {
  				options.counter = options.counter-1;
				} else {
  				options.counter = options.counter+1;
        }
        if (options.counter < 1 || options.counter > options.counter_total) {
          options.counter = 1;
        }

        $('#layout_content_gallery_img_' + options.counter).attr('src', $('#layout_content_gallery_imgdata_' + options.counter).attr('rel'));
				$('#layout_content_gallery_counter').html('Bild ' + options.counter + '/' + options.counter_total);
				
				if ($('#layout_content_gallery_imgdata_' + (options.counter+1)).attr('rel') != '') {
          $('#layout_content_gallery_buffer').append('<img src="' + $('#layout_content_gallery_imgdata_' + (options.counter+1)).attr('rel') + '" border="0" alt="" />');
				}

				if ($('#layout_content_gallery_imgdata_' + (options.counter+2)).attr('rel') != '') {
          $('#layout_content_gallery_buffer').append('<img src="' + $('#layout_content_gallery_imgdata_' + (options.counter+2)).attr('rel') + '" border="0" alt="" />');
				}

				var image = $('#layout_content_gallery_url_' + options.counter).html();
				
				if (image != 'undefined') {
  				$('#layout_content_gallery_title').html(image);
        }
        
			};
			// init
			var timeout;
			if(options.auto){;
				timeout = setTimeout(function(){
					animate('next', false);
				},options.pause);
			};

			if(!options.continuous && options.controlsFade){
				$('a', '#'+options.prevId).hide();
				$('a', '#'+options.firstId).hide();
			};

		});

	};

})(jQuery);

// Autocomplete für die Suchbox oben.

/*
	jQuery Autocomplete plugin
	http://www.pengoworks.com/workshop/jquery/autocomplete.htm
*/

jQuery.autocomplete = function(input, options) {
	// Create a link to self
	var me = this;

	// Create jQuery object for input element
	var $input = $(input).attr('autocomplete', 'off');

	// Apply inputClass if necessary
	if (options.inputClass) $input.addClass(options.inputClass);

	// Create results
	var results = document.createElement('div');
	// Create jQuery object for results
	var $results = $(results);
	$results.hide().addClass(options.resultsClass).css('position', 'absolute');
	if ( options.width > 0 ) $results.css('width', options.width);

	// Add to body element
	$('body').append(results);

	input.autocompleter = me;

	var timeout = null;
	var prev = '';
	var active = -1;
	var cache = {};
	var keyb = false;
	var hasFocus = false;
	var lastKeyPressCode = null;

	// flush cache
	function flushCache() {
		cache = {};
		cache.data = {};
		cache.length = 0;
	};

	// flush cache
	flushCache();

	// if there is a data array supplied
	if ( options.data != null ) {
		var sFirstChar = '', stMatchSets = {}, row = [];

		// no url was specified, we need to adjust the cache length to make sure it fits the local data store
		if ( typeof options.url != 'string' ) options.cacheLength = 1;

		// loop through the array and create a lookup structure
		for (var i=0; i < options.data.length; i++ ) {
			// if row is a string, make an array otherwise just reference the array
			row = ((typeof options.data[i] == 'string') ? [options.data[i]] : options.data[i]);

			// if the length is zero, don't add to list
			if ( row[0].length > 0 ) {
				// get the first character
				sFirstChar = row[0].substring(0, 1).toLowerCase();
				// if no lookup array for this character exists, look it up now
				if ( !stMatchSets[sFirstChar] ) stMatchSets[sFirstChar] = [];
				// if the match is a string
				stMatchSets[sFirstChar].push(row);
			}
		}

		// add the data items to the cache
		for (var k in stMatchSets ) {
			// increase the cache size
			options.cacheLength++;
			// add to the cache
			addToCache(k, stMatchSets[k]);
		}
	}

	$input
	.keydown(function(e) {
		// track last key pressed
		lastKeyPressCode = e.keyCode;
		switch(e.keyCode) {
			case 38: // up
				e.preventDefault();
				moveSelect(-1);
				break;
			case 40: // down
				e.preventDefault();
				moveSelect(1);
				break;
			case 9:  // tab
			case 13: // return
				if ( selectCurrent() ) {
					// make sure to blur off the current field
					$input.get(0).blur();
					e.preventDefault();
				}
				break;
			default:
				active = -1;
				if (timeout) clearTimeout(timeout);
				timeout = setTimeout(function() {onChange();}, options.delay);
				break;
		}
	})
	.focus(function() {
		// track whether the field has focus, we shouldn't process any results if the field no longer has focus
		hasFocus = true;
	})
	.blur(function() {
		// track whether the field has focus
		hasFocus = false;
		hideResults();
	});

	hideResultsNow();

	function onChange() {
		// ignore if the following keys are pressed: [del] [shift] [capslock]
		if ( lastKeyPressCode == 46 || (lastKeyPressCode > 8 && lastKeyPressCode < 32) ) return $results.hide();
		var v = $input.val();
		if (v == prev) return;
		prev = v;
		if (v.length >= options.minChars) {
			$input.addClass(options.loadingClass);
			requestData(v);
		} else {
			$input.removeClass(options.loadingClass);
			$results.hide();
		}
	};

 	function moveSelect(step) {

		var lis = $('li', results);
		if (!lis) return;

		active += step;

		if (active < 0) {
			active = 0;
		} else if (active >= lis.size()) {
			active = lis.size() - 1;
		}

		lis.removeClass('layout_search_over');

		$(lis[active]).addClass('layout_search_over');

		var lis_value = $(lis[active]).html();
		var lis_value_text = $(lis_value + ' a');
		$input.val(lis_value_text.attr('title'));

		// Weird behaviour in IE
		// if (lis[active] && lis[active].scrollIntoView) {
		// 	lis[active].scrollIntoView(false);
		// }

	};

	function selectCurrent() {
		var li = $('li.layout_search_over', results)[0];
		if (!li) {
			var $li = $('li', results);
			if (options.selectOnly) {
				if ($li.length == 1) li = $li[0];
			} else if (options.selectFirst) {
				li = $li[0];
			}
		}
		if (li) {
			selectItem(li);
			return true;
		} else {
			return false;
		}
	};

	function selectItem(li) {
		if (!li) {
			li = document.createElement('li');
			li.extra = [];
			li.selectValue = '';
		}
		var v = $.trim(li.selectValue ? li.selectValue : li.innerHTML);
		input.lastSelected = v;
		prev = v;
		$results.html('');

		//var lis_value_text = $(v + ' a').text();
		//$input.val(lis_value_text);

		document.location.href = $(v + ' a').attr('href');
		return;

		hideResultsNow();
		if (options.onItemSelect) setTimeout(function() { options.onItemSelect(li) }, 1);
	};

	// selects a portion of the input string
	function createSelection(start, end) {
		// get a reference to the input element
		var field = $input.get(0);
		if ( field.createTextRange ) {
			var selRange = field.createTextRange();
			selRange.collapse(true);
			selRange.moveStart('character', start);
			selRange.moveEnd('character', end);
			selRange.select();
		} else if ( field.setSelectionRange ) {
			field.setSelectionRange(start, end);
		} else {
			if ( field.selectionStart ) {
				field.selectionStart = start;
				field.selectionEnd = end;
			}
		}
		field.focus();
	};

	// fills in the input box w/the first match (assumed to be the best match)
	function autoFill(sValue) {
		// if the last user key pressed was backspace, don't autofill
		if ( lastKeyPressCode != 8 ) {
			// fill in the value (keep the case the user has typed)
			$input.val($input.val() + sValue.substring(prev.length));
			// select the portion of the value not typed by the user (so the next character will erase)
			createSelection(prev.length, sValue.length);
		}
	};

	function showResults() {
		// get the position of the input field right now (in case the DOM is shifted)
		var pos = findPos(input);
		// either use the specified width, or autocalculate based on form element
		var iWidth = (options.width > 0) ? options.width : $input.width();
		// reposition
		$results.css({
			width: parseInt(iWidth) + 'px',
			top: (pos.y + input.offsetHeight) + 'px',
			left: pos.x + 'px'
		}).show();
	};

	function hideResults() {
		if (timeout) clearTimeout(timeout);
		timeout = setTimeout(hideResultsNow, 200);
	};

	function hideResultsNow() {
		if (timeout) clearTimeout(timeout);
		$input.removeClass(options.loadingClass);
		if ($results.is(':visible')) {
			$results.hide();
		}
		if (options.mustMatch) {
			var v = $input.val();
			if (v != input.lastSelected) {
				selectItem(null);
			}
		}
	};

	function receiveData(q, data) {
		if (data) {
			$input.removeClass(options.loadingClass);
			results.innerHTML = '';

			// if the field no longer has focus or if there are no matches, do not display the drop down
			if ( !hasFocus || data.length == 0 ) return hideResultsNow();

			if ($.browser.msie) {
				// we put a styled iframe behind the calendar so HTML SELECT elements don't show through
				$results.append(document.createElement('iframe'));
			}
			results.appendChild(dataToDom(data));
			// autofill in the complete box w/the first match as long as the user hasn't entered in more data
			if ( options.autoFill && ($input.val().toLowerCase() == q.toLowerCase()) ) autoFill(data[0][0]);
			showResults();
		} else {
			hideResultsNow();
		}
	};

	function parseData(data) {
		if (!data) return null;
		var parsed = [];
		var rows = data.split(options.lineSeparator);
		for (var i=0; i < rows.length; i++) {
			var row = $.trim(rows[i]);
			if (row) {
				parsed[parsed.length] = row.split(options.cellSeparator);
			}
		}
		return parsed;
	};

	function dataToDom(data) {
		var ul = document.createElement('ul');
		var num = data.length;

		// limited results to a max number
		if ( (options.maxItemsToShow > 0) && (options.maxItemsToShow < num) ) num = options.maxItemsToShow;

		for (var i=0; i < num; i++) {
			var row = data[i];
			if (!row) continue;
			var li = document.createElement('li');
			if (options.formatItem) {
				li.innerHTML = options.formatItem(row, i, num);
				li.selectValue = row[0];
			} else {
				li.innerHTML = row[0];
				li.selectValue = row[0];
			}
			var extra = null;
			if (row.length > 1) {
				extra = [];
				for (var j=1; j < row.length; j++) {
					extra[extra.length] = row[j];
				}
			}
			li.extra = extra;
			ul.appendChild(li);
			$(li).hover(
				function() { $('li', ul).removeClass('layout_search_over'); $(this).addClass('layout_search_over'); active = $('li', ul).indexOf($(this).get(0)); },
				function() { $(this).removeClass('layout_search_over'); }
			);
		}
		return ul;
	};

	function requestData(q) {
		if (!options.matchCase) q = q.toLowerCase();
		if ( (typeof options.url == 'string') && (options.url.length > 0) ) {
			$.get(makeUrl(q), function(data) {
				data = parseData(data);
				addToCache(q, data);
				receiveData(q, data);
			});
		// if there's been no data found, remove the loading class
		} else {
			$input.removeClass(options.loadingClass);
		}
	};

	function makeUrl(q) {
		var url = options.url + '?q=' + encodeURI(q);
		for (var i in options.extraParams) {
      if (i == 'category') {
        url += '&' + i + '=' + jsapi('#layout_search_category').val();
      } else {
        url += '&' + i + '=' + encodeURI(options.extraParams[i]);
      }
		}
		return url;
	};

	this.flushCache = function() {
		flushCache();
	};

	this.setExtraParams = function(p) {
		options.extraParams = p;
	};

	this.findValue = function() {
		var q = $input.val();

		if (!options.matchCase) q = q.toLowerCase();
		if (1==1) {
			$.get(makeUrl(q), function(data) {
				data = parseData(data)
				addToCache(q, data);
				findValueCallback(q, data);
			});
		} else {
			// no matches
			findValueCallback(q, null);
		}
	}

	function findValueCallback(q, data) {
		if (data) $input.removeClass(options.loadingClass);

		var num = (data) ? data.length : 0;
		var li = null;

		for (var i=0; i < num; i++) {
			var row = data[i];

			if ( row[0].toLowerCase() == q.toLowerCase() ) {
				li = document.createElement('li');
				if (options.formatItem) {
					li.innerHTML = options.formatItem(row, i, num);
					li.selectValue = row[0];
				} else {
					li.innerHTML = row[0];
					li.selectValue = row[0];
				}
				var extra = null;
				if ( row.length > 1 ) {
					extra = [];
					for (var j=1; j < row.length; j++) {
						extra[extra.length] = row[j];
					}
				}
				li.extra = extra;
			}
		}

		if ( options.onFindValue ) setTimeout(function() { options.onFindValue(li) }, 1);
	}

	function addToCache(q, data) {
		if (!data || !q || !options.cacheLength) return;
		if (!cache.length || cache.length > options.cacheLength) {
			flushCache();
			cache.length++;
		} else if (!cache[q]) {
			cache.length++;
		}
		cache.data[q] = data;
	};

	function findPos(obj) {
		var curleft = obj.offsetLeft || 0;
		var curtop = obj.offsetTop || 0;
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
		return {x:curleft,y:curtop};
	}
}

jQuery.fn.autocomplete = function(url, options, data) {
	// Make sure options exists
	options = options || {};
	// Set url as option
	options.url = url;
	// set some bulk local data
	options.data = ((typeof data == 'object') && (data.constructor == Array)) ? data : null;

	// Set default values for required options
	options.inputClass = options.inputClass || 'layout_search_query';
	options.resultsClass = options.resultsClass || 'layout_search_results';
	options.lineSeparator = options.lineSeparator || '\n';
	options.cellSeparator = options.cellSeparator || 'ooo';
	options.minChars = options.minChars || 1;
	options.delay = options.delay || 400;
	options.matchCase = options.matchCase || 0;
	options.matchContains = options.matchContains || 0;
	options.cacheLength = options.cacheLength || 1;
	options.mustMatch = options.mustMatch || 0;
	options.extraParams = options.extraParams || {};
	options.loadingClass = options.loadingClass || 'layout_search_loading';
	options.selectFirst = options.selectFirst || false;
	options.selectOnly = options.selectOnly || false;
	options.maxItemsToShow = options.maxItemsToShow || -1;
	options.autoFill = options.autoFill || false;
	options.width = parseInt(options.width, 10) || 0;

	this.each(function() {
		var input = this;
		new jQuery.autocomplete(input, options);
	});

	// Don't break the chain
	return this;
}

jQuery.fn.autocompleteArray = function(data, options) {
	return this.autocomplete(null, options, data);
}

jQuery.fn.indexOf = function(e) {
	for (var i=0; i<this.length; i++ ) {
		if ( this[i] == e ) return i;
	}
	return -1;
};

function autocomplete_select(li) {
	document.form_live_search.submit();
}

// Javascript-Funktionen für u.a. jQuery werden beim Aufruf der Seite ausgeführt.

jQuery(function($) {

  // Lightbox für die Bilder.

  jsapi('[rel^=lightbox]').lightBox();
  
  // Slider für die Startseite und die Blog-Beiträge.

	jsapi('#layout_content_gallery').easySlider({
		prevText: 'Vorheriges Bild',
		nextText: 'Nächstes Bild',
		auto: true,
		pause: 7000,
		firstShow: false,
		lastShow: false,
		vertical: false,
		continuous: true,
		controlsBefore: '',
		controlsAfter: '',
		counter_total: $('#layout_content_gallery li').size()
  });

  // Autocomplete für die Suchbox oben.

  jsapi('#layout_search_query').autocomplete(
		'/index.php',
		{
			delay: 200,
		  extraParams: { file: 'search', live: 'yes', clean: 'yes', category: 'all' },
			minChars: 2,
			maxItemsToShow: 15,
			onItemSelect: autocomplete_select,
			width: 314
		}
	);

  // Beim Klick auf einen Link mit der CSS-Klasse "layout_count_reisenews" wird die URL aufgerufen und die bisherige Seite neu geladen.

  jsapi('.layout_count_reisenews').live('click', function(event) {

    var url = jsapi(this).attr('href');
    var click_url = config_directory + 'index.php?file=weblog&mode=click_news_ajax&form[url]=' + escape(url) + '&clean=yes';
    
    // event.preventDefault();

    jsapi.get(click_url, function(data) {
      // document.location.href = url;
      // return;
    });
  
  });

  // Beim Klick auf einen Link mit der CSS-Klasse "layout_content_pagination" wird die Zielseite direkt per AJAX eingebunden.

  jsapi('.layout_content_pagination a').live('click', function(event) {

    var url = jsapi(this).attr('href');

    if (url.search(/file=search/) == -1 && jsapi('#layout_content_inner')) {

      showLoadingAnimation();

      if (url.search(/clean=yes/) == -1) {
        if (url.search(/index.php/) != -1) {
          url = url + '&clean=yes';
        } else {
          url = url + '?clean=yes';
        }
      }

      event.preventDefault();
      jsapi('html, body').animate({ scrollTop: 0 }, 0);
      
      jsapi.get(url, function(data) {
        jsapi('#layout_content_inner').html(data);
        jsapi('#layout_content_inner [rel^=lightbox]').lightBox();
      });
      
		}

  });

  // Beim Klick auf einen Link mit der CSS-Klasse "contentpapst_content_load" wird die Zielseite direkt per AJAX eingebunden.

  jsapi('.contentpapst_content_load').live('click', function(event) {

    var url = jsapi(this).attr('href');

    if (jsapi('#layout_content_inner')) {

      showLoadingAnimation();

      if (url.search(/clean=yes/) == -1) {
        if (url.search(/index.php/) != -1) {
          url = url + '&clean=yes';
        } else {
          url = url + '?clean=yes';
        }
      }

      event.preventDefault();
      jsapi('html, body').animate({ scrollTop: 0 }, 0);

      jsapi.get(url, function(data) {
        jsapi('#layout_content_inner').html(data);
      });

		}

  });

});

// Blendet die Lade-Animation im Inhaltsbereich ein.

function showLoadingAnimation() {

  jsapi('#layout_content_inner').prepend('<div style=\"float: right\"><img src=\"' + config_directory + 'themes/kahunablog/images/layout/ajax_loading_bar.gif\" border=\"0\" alt=\"\" /></div>');

}

// Blendet die Tabs in der linken Spalte beim Mouseover ein.

function showMiscTabs(number) {

  jsapi('.layout_content_misc_tabs').hide();
	jsapi('#layout_content_misc_tab_' + number).show();

}

// Zeigt die Karte in den Beiträgen an.

function showMap(map, country, city, zoom) {

  if (zoom == '') {
    var zoom = 13;
  }

  if (jsapi('#layout_map_' + map).is(':hidden')) {

    // Google Static Maps API
    // jsapi('#layout_map_' + map).html('<a href="http://maps.google.de/" target="_blank"><img src="http://maps.google.com/maps/api/staticmap?center=' + escape(city + ',' + country) + '&amp;zoom=' + zoom + '&amp;size=690x400&amp;format=png8&amp;maptype=terrain&amp;language=de&amp;sensor=false" border="0" alt="" /></a>');
    
    // Google Maps als iFrame
    jsapi('#layout_map_' + map).html('<iframe width="690" height="400" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://maps.google.de/maps?f=q&amp;source=s_q&amp;hl=de&amp;geocode=&amp;q=' + escape(city + ',' + country) + '&amp;ie=UTF8&amp;hq=&amp;hnear=' + encodeURI(city + ',' + country) + '&amp;z=' + zoom + '&amp;output=embed" style="border: 1px solid #ACAAA6"></iframe><br /><div style="font-size: 11px; margin-top: 4px; text-align: left"><a href="http://maps.google.de/maps?f=q&amp;source=embed&amp;hl=de&amp;geocode=&amp;q=' + escape(city + ',' + country) + '&amp;ie=UTF8&amp;hq=&amp;hnear=' + escape(city + ',' + country) + '&amp;z=' + zoom + '" target="_blank">Größere Kartenansicht bei Google Maps</a></div>');

    jsapi('#layout_map_control_' + map).text('Karte zu ' + city + ' ausblenden');
    
  } else {
  
    jsapi('#layout_map_control_' + map).text('Karte zu ' + city + ' anzeigen');
  
  }
  
  jsapi('#layout_map_' + map).slideToggle();

}

// Zeigt die Slideshow in den Galerien an.

function showSlideshow(url) {

  jsapi('.layout_content_pagination').fadeOut();

  var code = '<iframe height="920" width="100%" allowtransparency="true" src="' + url + '" scrolling="no" frameborder="0"></iframe><br />';
  jsapi('#layout_content_slideshow').html(code);

}