(function($) {
	/* offset fix for mobile safari */
	if ( /webkit.*mobile/i.test(navigator.userAgent)) {
		(function($) {
			$.fn.offsetOld = $.fn.offset;
			$.fn.offset = function() {
				var result = this.offsetOld();
				result.top -= window.scrollY;
				result.left -= window.scrollX;
				return result;
			};
		})(jQuery);
	}

	/* German initialisation for the jQuery UI date picker plugin. */
	/* Written by Milian Wolff (mail@milianw.de). */
	$.datepicker.regional['de'] = {
		closeText: 'schließen',
		prevText: '&#x3c;zurück',
		nextText: 'Vor&#x3e;',
		currentText: 'heute',
		monthNames: ['Januar','Februar','März','April','Mai','Juni',
		'Juli','August','September','Oktober','November','Dezember'],
		monthNamesShort: ['Jan','Feb','Mär','Apr','Mai','Jun',
		'Jul','Aug','Sep','Okt','Nov','Dez'],
		dayNames: ['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag'],
		dayNamesShort: ['So','Mo','Di','Mi','Do','Fr','Sa'],
		dayNamesMin: ['So','Mo','Di','Mi','Do','Fr','Sa'],
		weekHeader: 'Wo',
		dateFormat: 'dd.mm.yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['de']);

	/* styleswitch js/nojs */
	document.write(
		"<style>"+
		".foldable{height:15px;overflow: hidden;}"+
		".groupcontentdesc{display: block;}"+
		".foldable .grouptitle{background-position: -10px -10px}"+
		".dateinputwrapepr .nojs {display: none;}"+
		".dateinputwrapepr .js {display: inline;}"+
		"<\/style>"
	);

	/* list hover */
	$('#main_content .listview .itemd,#main_content .listview tr[class!=label]').live(
		'mouseover',function(e){
			$(this).addClass('itemhover');
		}
	).live(
		'mouseout',function(e){
			$(this).removeClass('itemhover');
		}
	).live(
		'click',function(e){
			if (e.target.nodeName.toLowerCase() == "a") {
				return true;
			}
			e.preventDefault();
			$(this).find('.previewmore a, .last a').each(function(){
				location.href = $(this).attr('href');
			});
		}
	);

	/* folding */
	var getFoldConf = function(s) {
		var conf = $(s).data('xwk.fold');
		if (!conf) {
			var c = $(s).height();
			$(s).find('.groupcontentdesc').css({marginTop: -30});
			var h = $(s).css({height: 'auto'}).height();
			conf = {inited:true,h:h,isfolded:true};
			$(s).find('.groupcontentdesc').css({marginTop: 0});
			$(s).height(c).data('xwk.fold',conf);
		}
		return conf;
	}

	var ua = navigator.userAgent,
    event = (ua.match(/iPad/i)) ? "touchstart" : "click";

	$('#main_content .foldable .grouptitle').live(
		event,function(e){
			var conf = getFoldConf($(this).parents('.foldable'));
			conf.isfolded = !conf.isfolded;
			$(this).css({backgroundPosition: conf.isfolded ? "-10px -40px" : "-10px -70px"});
			$(this).parents('.foldable').animate({height: conf.isfolded ? 15 : conf.h});
			$(this).parents('.foldable').find('.groupcontentdesc').animate({marginTop: conf.isfolded ? 0 : -30});
		}
	).live(
		'mouseover',function(e){
			var conf = getFoldConf($(this).parents('.foldable'));
			$(this).css({cursor: 'pointer', backgroundPosition: conf.isfolded ? "-10px -40px" : "-10px -70px"});
		}
	).live(
		'mouseout',function(e){
			var conf = getFoldConf($(this).parents('.foldable'));
			$(this).css({backgroundPosition: conf.isfolded ? "-10px -10px" : "-10px -70px"});
		}
	);/*
	$('#main_content .foldable').live(
		'mouseover',function(e){
			var conf = getFoldConf(this);
			conf.isfolded = false;
			$(this).stop().animate({height: conf.isfolded ? 15 : conf.h});
		}
	).live(
		'mouseout',function(e){
			var conf = getFoldConf(this);
			conf.isfolded = true;
			$(this).stop().animate({height: conf.isfolded ? 15 : conf.h});
		}
	);*/
})(jQuery);

jQuery(function($) {

	/* von/bis datepickers */
	var datepicker = function(wrapper,name,cb) {
		var dp = wrapper.find('.js input');
		var valid = true;
		var start = new Date();
		wrapper.find("select").each(function() {
			if (this.name == name+'[d]') {
				if ($(this).val() == "") valid=false;
				start.setDate(parseInt($(this).val()));
			}
			if (this.name == name+'[m]') {
				if ($(this).val() == "") valid=false;
				start.setMonth(parseInt($(this).val())-1);
			}
			if (this.name == name+'[Y]') {
				if ($(this).val() == "") valid=false;
				start.setFullYear(parseInt($(this).val()));
			}
		});
		var onSelectDate = function(text) {
			var date=null;
			try{
				var date=$.datepicker.parseDate("yy-mm-dd",text);
			}catch(e){
			}
			if (date) {
				wrapper.find("select").each(function() {
					if (this.name == name+'[d]') {
						$(this).val(date.getDate());
					}
					if (this.name == name+'[m]') {
						$(this).val(date.getMonth()+1);
					}
					if (this.name == name+'[Y]') {
						$(this).val(date.getFullYear());
					}
				});
			} else {
				wrapper.find("select").val("");
			}
			var o = "";
			if (null == date)  {
				o = "beliebig";
			} else {
				o = ($.datepicker.formatDate('yy-mm-dd',new Date())==text)
					? 'heute' : $.datepicker.formatDate('dd.mm.yy',date);
			}
			wrapper.find('.js span').text(o);
			cb(date);
		};
		var lastclose = new Date();
		dp.datepicker({
			minDate: 0,
			dateFormat: "yy-mm-dd",
			onSelect: function(text) {
				onSelectDate(text);
				$('#datereset .js').show();
			},
			onClose: function() {
				lastclose = new Date();
			}
		});
		if (valid)
			dp.datepicker('setDate',start);
		onSelectDate(dp.val());
		wrapper.find('.js').click(function() {
			if ((new Date()-lastclose) > 250) {
				dp.focus();
			} else {
			//	dp.blur();
			}
		})
		return dp;
	}

	var vondp = null;
	var bisdp = null;
	bisdp = datepicker($("#bisdate"),"bis",function(date){
	});
	vondp = datepicker($("#vondate"),"von",function(date){
		bisdp.datepicker('option','minDate',date);
	});

	// reset datepicker
	$('#datereset .js').click(function() {
		$('#vondate .js span').text('heute');
		$('#bisdate .js span').text('beliebig');
		var date = new Date();
		$('#vondate').find("select").each(function() {
			if (this.name == 'von[d]') {
				$(this).val(date.getDate());
			}
			if (this.name == 'von[m]') {
				$(this).val(date.getMonth()+1);
			}
			if (this.name == 'von[Y]') {
				$(this).val(date.getFullYear());
			}
		});
		$('#bisdate').find('select').each(function() {
			if (this.name == 'bis[d]') {
				$(this).val("");
			}
			if (this.name == 'bis[m]') {
				$(this).val("");
			}
			if (this.name == 'bis[Y]') {
				$(this).val("");
			}
		});
		$('#datereset .js').hide();
	});

	/* autosuggest queryfield */

	function split(val) {
		return val.split(/,\s*/);
	}
	function extractLast(term) {
		return split(term).pop();
	}
	$("input[name=query]").autocomplete({
		minLength: 0,
		source: function(request, response) {
			$.getJSON(XWK.host+'XooWebKit/bin/suggest.php?m='
					+ $('#suggest_class').val() + '&p='
					+ $('#suggest_modules').val(), {
				q: extractLast(request.term),
				limit: 15
			}, response);
		},
		focus: function() {
			// prevent value inserted on focus
			return false;
		},
		select: function(event, ui) {
			var terms = split( this.value );
			// remove the current input
			terms.pop();
			// add the selected item
			terms.push( ui.item.value );
			// add placeholder to get the comma-and-space at the end
			terms.push("");
			this.value = terms.join(", ");
			return false;
		}
	});

	/* inputtooltip */
	$('input.inputtooltip[alt]').each(function() {
		var i = $(this);
		var text = i.attr('alt');
		var dummy = $('<input type="text">');
		dummy.attr('class', i.attr('class'));
		dummy.attr('style', i.attr('style'));
		dummy.attr('name', i.attr('name') + '_tooltipdummy');
		dummy.val(text);
		i.after(dummy);
		dummy.hide();

		dummy.focus(function() {
			i.show();
			dummy.hide();
			i.focus();
		});

		i.blur(function() {
			if (i.val() == "") {
				i.hide();
				dummy.show();
			}
		});

		i.blur();

	});

	/* slidegallery */
	$('.images').css( {
		position : 'relative'
	});

	var min = 0;
	var max = 0;
	var center = 0;
	var current = 0;
	var div = $('.images').width() - $('.images div').width();

	$('.slider').css('marginLeft', 0)
	var pos = function(x) {
		current = Math.max(0, Math.min(max, x));
		$('.slider').css('marginLeft', current);
		$('.images div').css('marginLeft', div * current / max);
	};
	var posAbs = function(x) {
		pos(x - min - center);
	};

	var holdtimer;
	var want = 0;
	var force = 0;
	var ac = 10;
	var lastX;

	max = $('.slidebar').width() - $('.slider').width();
	$('.slidebar').draggable( {
		distance : 0,
		helper : false,
		start : function(a) {
			lastX = a.pageX;
			// console.log(a);
			min = $(this).offset().left;
			center = a.pageX - min - current;
			if (center < 0 || center > $('.slider').width()) {
				center = $('.slider').width() / 2;
			}
			posAbs(a.pageX);
		},
		drag : function(a) {
			posAbs(a.pageX);
		},
		stop : function(a) {
			posAbs(a.pageX);
		}
	}).bind('touchmove',function(a){
		min = $(this).offset().left;
		a.originalEvent.preventDefault();
		if (a.originalEvent.changedTouches.length) {
			posAbs(a.originalEvent.changedTouches[0].pageX);
		}
	});
	var wasdraged = false;
	var startx = 0;
	$('.images a').draggable( {
		distance : 0,
		helper : false,
		start : function(a) {
		min = $(this).offset().left;
		startx = a.pageX;
		starty = a.pageY;
		startstate = div * current / max;
		wasdraged = false;
	},
	drag : function(a) {
		var d  = a.pageX-startx;
		state =  startstate+d;
		pos(state/div*max);
		wasdraged = true;
		if (state > 0 || state < div) {
			startx = a.pageX;
			startstate = div * current / max;
		}
	},
	stop : function(a) {
		if (!wasdraged) {
			$(this).nyroModalManual();
		}
	}
	}).bind('touchstart',function(a){
		a = a.originalEvent.changedTouches[0];
		min = $(this).offset().left;
		starty = a.pageY;
		startx = a.pageX;
		startstate = div * current / max;
	}).bind('touchmove',function(e){
		var a = e.originalEvent.changedTouches[0];
		if (Math.abs(starty-a.pageY)-Math.abs(startx-a.pageX)<0) {
			var d  = a.pageX-startx;
			state =  startstate+d;
			pos(state/div*max);
			if (!(state > 0 || state < div)) {
				e.originalEvent.preventDefault();
			}
		} else {
			startx = a.pageX;
			startstate = div * current / max;
		}
	});
	var btstart = function(bt) {
		force = 0;
		ac = 10;
		want = bt.hasClass('lbt') ? -10 : 10;
		window.clearInterval(holdtimer);
		holdtimer = window.setInterval(function() {
			force += (want - force) / ac;
			pos(current + (force))
			if (Math.abs(force) < .1 && want == 0) {
				window.clearInterval(holdtimer);
			}
		}, 40);
	};
	var btstop = function(bt) {
		ac = 5;
		want = 0;
	};

	$('.rbt,.lbt').draggable( {
		distance : 0,
		helper : false,
		start : function() {
		btstart($(this));
	},
	stop : function() {
		btstop($(this));
	}
	}).bind('touchstart',function(a){
		a.originalEvent.preventDefault();
		btstart($(this));
	}).bind('touchend',function(a){
		a.originalEvent.preventDefault();
		btstop($(this));
	});
	/* end slidegallery */

	$('form input[name=__offsetx]').each(function() {
		var f = $(this.form);
		var o = $(this);
		if (o.val() != "") {
			$(window).scrollTop(o.val());
		}
		f.submit(function(e) {
			o.val($(window).scrollTop());
		});
	});


});
