function touchScroll (id) {
	var el=document.getElementById(id);
	var scrollStartPos=0;

	document.getElementById(id).addEventListener("touchstart", function(event) {
		scrollStartPos=this.scrollTop+event.touches[0].pageY;
		//event.preventDefault();
	}, false);

	document.getElementById(id).addEventListener("touchmove", function(event) {
		this.scrollTop=scrollStartPos-event.touches[0].pageY;
		event.preventDefault();
	}, false);
}

(function ($) {
	
	$.extend(jQuery.browser, {
		ipad : navigator.userAgent.toLowerCase().indexOf('ipad') > -1
	});

	$.wrapperWidth = function () {
		var ww = $(window).width() - ($.browser.ipad ? 28 : 0),
			sidebar = $('aside').outerWidth(true);
		$('#wrapper').css('width', ww - sidebar);
	};
	
	function scrollbarWidth() { 
	    var div = $('<div style="width:50px;height:50px;overflow:hidden;position:absolute;top:-200px;left:-200px;"><div style="height:100px;"></div>'); 
	    // Append our div, do our calculation and then remove it 
	    $('body').append(div); 
	    var w1 = $('div', div).innerWidth(); 
	    div.css('overflow-y', 'scroll'); 
	    var w2 = $('div', div).innerWidth(); 
	    $(div).remove(); 
	    return (w1 - w2); 
	}
	
	$.fn.nlForm = function () {
		var $form = $(this);
		$('.submit', $form).click(function () {
			$form.submit();
		});
		return $(this).submit(function (e) {
			e.preventDefault();
			var url = $form.attr('action'),
				$input = $('input', $form);
			// send input data
			$.post(url, $form.serialize(), function (rsp) {
				if (rsp == 1) {
					$form.prepend('<span id="nlsucc">Erfolg!<\/span>');
					setTimeout(function () {
						$('#nlsucc').fadeOut('fast', function () { $(this).remove(); });
					}, 1500);
					// clear form
					$input.val('');
				}
			});
		});
	};
	
	$.fn.doScrollbar = function () {
		// remove old scrollbar thingy
		$('.scrollbar-handle-container').remove();
		$('.scrollbar-pane').children().unwrap();
		$(this).css('height', '100%');
		
		// add new scrollbar and remove unnecessary wrapper div
		$(this).scrollbar({
			arrows: false
		});
		
		// do some margins
		$('.scrollbar-handle-container').css('height', '-=8');
		$('.scrollbar-handle').css('height', '-=8');
		
		return this;
	};

})(jQuery);

(function ($) {
	
	$.fn.newsGallery = function () {
		
		return this.each(function () {
			
		// seperator for nav numbers
		var sep = '|',
			next = '&gt;',
			prev = '&lt;',
			// set gallery to relative
			$gal = $(this).css('position', 'relative'),
			$lis = $('li', $(this));
		
		$('li', $(this)).css('position', 'absolute').not(':first-child').css({
				/*display: 'none',*/
				visibility: 'hidden'/*,
				cursor: 'pointer'*/
			})/*.click(showNextImage)*/;
		
		// show next image
		function showNextImage() {
			var $next = $('.current', $gal).next();
			if ( ! $next.length) {
				$next = $lis.first();
			}
			setNewCurrent($next);
		}
		
		// show previous image
		function showPrevImage() {
			var $prev = $('.current', $gal).prev();
			if (!$prev.length) {
				$prev = $lis.last();
			}
			setNewCurrent($prev);
		}
		
		// show specified image on nav click
		function showThisImage() {
			var num = parseInt($(this).text()),
				$li = $lis.eq(num - 1);
			if ($li.length) {
				setNewCurrent($li);
			}
		}
		
		// set given $element to current image to show
		function setNewCurrent($element) {
			var $current = $('.current', $gal);
			// reset the height of the gallery
			$gal.css('height', $element.height());
			$current.hide()/*.fadeOut('fast')*/.removeClass('current');
			$element.css({
				display: 'none',
				visibility: 'visible'
			}).show()/*.fadeIn('fast', function () {
				//$('#wrapper').doScrollbar();
			})*/.addClass('current');
			updateGalleryNavigation();
		}
		
		// rebuild gallery navigation on every image switch
		function updateGalleryNavigation() {
			var max = $lis.length,
				curIndex = $('.current', $gal).index(),
				$navi = $('.galnav', $gal.parent());
			
			if (max == 1) {
				return;
			}
			
			if ( ! $navi.length) {
				$navi = $('<div\/>').addClass('galnav').insertAfter($gal);
			}
			// remove all children
			$navi.children().remove();
			// build the nav numbers
			for (i = 0; i < max; i++) {
				var $span = $('<span\/>').text(i + 1).addClass('num').css('cursor', 'pointer').click(showThisImage);
				// tag current image in nav
				if (curIndex == i) {
					$span.addClass('curimg');
				}
				$span.appendTo($navi);
				// add the seperator
				if (i < (max - 1)) {
					$('<span\/>').addClass('sep').html(sep).appendTo($navi);
				}
			}
			// build prev and next span
			$('<span\/>').addClass('prev').css('cursor', 'pointer').html(prev).click(showPrevImage).prependTo($navi);
			$('<span\/>').addClass('next').css('cursor', 'pointer').html(next).click(showNextImage).appendTo($navi);
		}
		
		// show galleries when everything's loaded
		$(window).bind('load.news', function () {
			// switch to first image
			showNextImage();
			if ( ! $.browser.ipad) {
				$('#wrapper').doScrollbar();
			}
		});
		
		});
		
	};
	
})(jQuery);

/*
 * jQuery hashchange event - v1.3 - 7/21/2010
 * http://benalman.com/projects/jquery-hashchange-plugin/
 * 
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function($,e,b){var c="hashchange",h=document,f,g=$.event.special,i=h.documentMode,d="on"+c in e&&(i===b||i>7);function a(j){j=j||location.href;return"#"+j.replace(/^[^#]*#?(.*)$/,"$1")}$.fn[c]=function(j){return j?this.bind(c,j):this.trigger(c)};$.fn[c].delay=50;g[c]=$.extend(g[c],{setup:function(){if(d){return false}$(f.start)},teardown:function(){if(d){return false}$(f.stop)}});f=(function(){var j={},p,m=a(),k=function(q){return q},l=k,o=k;j.start=function(){p||n()};j.stop=function(){p&&clearTimeout(p);p=b};function n(){var r=a(),q=o(m);if(r!==m){l(m=r,q);$(e).trigger(c)}else{if(q!==m){location.href=location.href.replace(/#.*/,"")+q}}p=setTimeout(n,$.fn[c].delay)}$.browser.msie&&!d&&(function(){var q,r;j.start=function(){if(!q){r=$.fn[c].src;r=r&&r+a();q=$('<iframe tabindex="-1" title="empty"/>').hide().one("load",function(){r||l(a());n()}).attr("src",r||"javascript:0").insertAfter("body")[0].contentWindow;h.onpropertychange=function(){try{if(event.propertyName==="title"){q.document.title=h.title}}catch(s){}}}};j.stop=k;o=function(){return a(q.location.href)};l=function(v,s){var u=q.document,t=$.fn[c].domain;if(v!==s){u.title=h.title;u.open();t&&u.write('<script>document.domain="'+t+'"<\/script>');u.close();q.location.hash=v}}})();return j})()})(jQuery,this);

// fire on ready
$(function () {
	$.wrapperWidth();
	$('#newsletter').nlForm();
	
	if ($.browser.ipad && $('#wrapper').length > 0) {
		touchScroll('wrapper');
	}
	
	$('#filter span').not('.filter-header').click(function () {
		$(this).toggleClass('active');
		
		var isActive = $(this).hasClass('active');
		if ( ! isActive && ! $('#filter .active').size()) {
			var found = $('#filter span').not('.filter-header').not(this).eq(0).toggleClass('active');
			if ( ! found.length) {
				$(this).toggleClass('active');
			}
		}
		
		var needle = [],
			params = [],
			isNews = $(this).parent().hasClass('news');
		$('#filter .active').each(function () {
			if (isNews) {
				var param = $(this).attr('rel').replace('group-', '');
			} else {
				var param = 'tag-' + $(this).attr('rel').split(':').pop();
				params.push('tag[]=' + $(this).attr('rel').split(':').pop());
			}
			needle.push(param);
		});

		$.post(location.href, params.join('&'));
		
		if (isNews) {
			var query = '';
			for (var i in needle) {
				if (i > 0) {
					query += '&';
				}
				query += 'group[]=' + needle[i];
			}
			$('#news').load(global.root, query, function () {
				$(window).unbind('load.news');
				
				$('.news-gallery').newsGallery();
				if ( ! $.browser.ipad) {
					$('#wrapper').doScrollbar();
				}
				
				$(window).trigger('load.news');
			});
			return false;
		}
		
		$('#content figure').each(function () {
			var classes = this.className.split(' '),
				$img = $(this);
			$.each(classes, function (i, c) {
				if ($.inArray(c, needle) != -1 || c == '') {
					$img.removeClass('hide').addClass('show');
					return false;
				}
				$img.removeClass('show').addClass('hide');
			});
		});
		$('#content figure.show').fadeIn('fast');
		$('#content figure.hide').fadeOut('fast', function () {
			$('#wrapper').doScrollbar();
		});
	});
	
	$('.news-gallery').newsGallery();
	
	if ( ! $.browser.ipad) {
		setTimeout(function () {
			$('#wrapper').doScrollbar();
		}, 50);
	}
	
	if (typeof gallery != 'undefined') {
		$(window).hashchange(function () {
			var mediaId = parseInt(location.hash.replace(/^#/, '')),
				found = false;
			for (m in gallery) {
				if (gallery[m].id == mediaId) {
					found = true;
					mediaId = m;
					break;
				}
			}
			if ( ! found) {
				mediaId = 0;
			}
			showGalleryImage(mediaId);
		});
		
		if (location.hash != '') {
			$(window).trigger('hashchange');
		} else {
			showGalleryImage(0);
		}
	}
	
	if ( ! $.browser.ipad) {
		$('#left, #right').bind('mouseenter mouseleave mousemove', function (e) {
			var text = ($(this).is('#left') ? 'PREV' : 'NEXT'),
				cursor = text.toLowerCase() + '-cursor';
			if ( ! $('#' + cursor).size()) {
				$('<span id="' + cursor + '">' + text + '<\/span>').appendTo($('body'));
			}
			
			if (e.type != 'mouseleave') {
				$('#' + cursor).css({
					top: e.pageY + 20,
					left: e.pageX + 15
				}).show();
			} else {
				$('#' + cursor).hide();
			}
		});
	}
	
	$('.add-pdf').click(function () {
		var id = this.id.replace('pic-', ''),
			isAdded = $(this).hasClass('added'),
			$link = $(this);
		$.post(global.root + '/selection/add/' + id, function (rsp) {
			if (isAdded) {
				$link.removeClass('added').text('add to pdf');
			} else {
				$link.addClass('added').text('added');
			}
			
			for (var picIndex in gallery) {
				if (gallery[picIndex].id == id) {
					gallery[picIndex].is_fav = $link.hasClass('added');
					break;
				}
			}
			
			if (rsp == '00') {
				$('#pdf-selection').hide();
			} else {
				$('#pdf-selection').show();
			}
			
			$('#pdf-selection span').text(rsp);
		});
	});
	
	$('.remove-pdf').click(function () {
		var id = this.id.replace('pic-', ''),
			$link = $(this);
		$.post(global.root + '/selection/add/' + id, function (rsp) {
			$link.parent().fadeOut('fast', function () { $(this).remove(); });
			
			if (rsp == '00') {
				$('#pdf-selection').hide();
				$('#download').remove();
			} else {
				$('#pdf-selection').show();
			}
			
			$('#pdf-selection span').text(rsp);
		});
	});
	
	$('.type-video a').each(function () {
		$(this).append('<span class="play"><\/span>');
	});
	
});

var media = {};

function resizeGalleryImage() {
	var viewport = {
			width: $(window).width() - 60,
			height: $(window).height() - 230
		};
	
	if (media.type == 'image') {
		var newImgHeight = viewport.height,
			newImgWidth = newImgHeight * (media.width / media.height);
		
		if (newImgHeight > media.height) {
			newImgHeight = media.height;
			newImgWidth = newImgHeight * (media.width / media.height);
		}
		
		if (newImgWidth > media.width) {
			newImgWidth = media.width;
			newImgHeight = newImgWidth * (media.height / media.width);
		}
		
		if (newImgWidth > viewport.width) {
			newImgWidth = viewport.width;
			newImgHeight = newImgWidth * (media.height / media.width);
		}
		
		if (newImgHeight > viewport.height) {
			newImgHeight = viewport.height;
			newImgWidth = newImgHeight * (media.width / media.height);
		}
		
		$('#media img').attr({
			width: newImgWidth,
			height: newImgHeight
		});
		
		$('#left, #right').css({
			height: newImgHeight,
			width: newImgWidth / 2
		});
		
		$('#media').css({
			marginTop: -($('#media').height() / 2),
			marginLeft: -($('#media').width() / 2)
		});
	}
}

function showGalleryImage(mediaId) {
	media = gallery[mediaId],
	
	$('#media figcaption').remove();
	
	$('#media figure').css('visibility', 'hidden').html('')
		.append(media.html);
	$('#media').append('<figcaption>' + media.title + '<\/figcaption>');
	$('#media').css({
		width: 'auto',
		height: 'auto'
	});
	
	$('.add-pdf').hide().attr('id', 'pic-' + media.id).removeClass('added').text('add to pdf');
	if (media.type == 'image') {
		resizeGalleryImage();
		$('#media img').load(function () {
			$(this).parent().css('visibility', 'visible');
			if (media.is_fav) {
				$('.add-pdf').addClass('added').text('added');
			}
			$('.add-pdf').show();
		});
	} else {
		$('#media').css({
			marginTop: -($('#media').height() / 2),
			marginLeft: -($('#media').width() / 2)
		});
		$('#left, #right').css({
			height: media.height - 35,
			width: media.width / 3
		});
		$('#media figure').css('visibility', 'visible');
	}
	
	var lastMediaId = firstMediaId = 0;
	for (firstMediaId in gallery) break;
	for (lastMediaId in gallery);
	
	var url = location.href;
	
	$('#left').unbind('click').click(function () {
		var i = 0, prev = 0, newId = 0, show = true;
		for (myId in gallery) {
			if (myId == mediaId) {
				if (i == 0) {
					//newId = lastMediaId;
					location.href = prevGal;
					show = false;
				} else {
					newId = prev;
				}
				break;
			}
			prev = myId;
			i++;
		}
		if (show) {
			showGalleryImage(newId);
			location.hash = '#' + gallery[newId].id;
		}
	});
	
	$('#right').unbind('click').click(function () {
		var i = 0, next = 0, newId = 0, show = true;
		for (myId in gallery) {
			if (myId == mediaId) {
				newId = parseInt(myId) + 1;
				if (typeof gallery[newId] == 'undefined') {
					//newId = 0;
					location.href = nextGal;
					show = false;
				}
				break;
			}
		}
		if (show) {
			showGalleryImage(newId);
			location.hash = '#' + gallery[newId].id;
		}
	});
	
}

// fire on resize
var scrollTimeout = null;
$(window).resize(function () {
	// set new wrapper width
	$.wrapperWidth();
	// re-initialize scrollbar when resizing has been finished
	if ( ! $.browser.ipad) {
		clearTimeout(scrollTimeout);
		scrollTimeout = setTimeout(function () {
			$('#wrapper').doScrollbar();
		}, 50);
	}
	resizeGalleryImage();
});

function supports_video() {
  return !!document.createElement('video').canPlayType;
}

function supports_h264_baseline_video() {
  if (!supports_video()) { return false; }
  var v = document.createElement("video");
  var canPlay = v.canPlayType('video/mp4');
  return (canPlay == 'no' || canPlay == '' || canPlay == 'maybe' ? false : true);
}
