jQuery(function($){

	// Accordion Team
	$(".acc").click(function(){
		var wid = this.id.split("_");
		var layerDisplay = $(this).parent().parent().parent().find('.teamsub').css("display");

		if (layerDisplay === "none") {
			$('.acc').removeClass('on');
			$(this).addClass('on');
			$('.teamsub').hide();
			$(this).parent().parent().parent().find('.teamsub').show();
	    } else {
			$('.teamsub').hide();
			$('.acc').removeClass('on');
	    }
	});

	// weiterlesen stipendien 
	$(".more-link a").click(function() {
		$(this).parent().hide();
		$(this).parent().parent().find(".more-details").show(10);
		return false;
	});

	// RADAR This is fuckin' random without...
	function equalHeight($$, margin) {
		var maxHeight = margin * 1;

		$$.each(function() {
			var height = $(this).height() + margin;
			if (height > maxHeight) maxHeight = height;
		});

		$$.height(maxHeight);
	}

	// ... Timeout, cheers!
	setTimeout(function() { equalHeight(copyText, 20); }, 250);
	var copyText = $(".teasercat .item .content .copy");

});



(function($) {
	
	
	$.fn.blank = function() {
		return this.click(function(e) {
			window.open(this.href);
			e.preventDefault();
			e.stopPropagation();
		});
	};
	// shows & hides children on hover
	$.fn.revealing = function() {
		return this.hover(
			function() { $('.hidden', this).show(); },
			function() { $('.hidden', this).hide(); }
		);
	};
	// add & removes .hover class of .hovers on hover
	$.fn.hovers = function() {
		return this.hover(
			function() { $('.hovers', this).addClass('hover'); },
			function() { $('.hovers', this).removeClass('hover'); }
		);
	};
	// blurs element on click
	$.fn.blurry = function() {
		return this.click(function() { $(this).blur(); });
	};
	$.fn.addLink = function() {
		var link = $('a', this).attr('href');
		this.click(
			function() { self.location.href = link; }
		);
	};
	$.fn.textCut = function() {
		$(this).each(function () {
			if( $(this).children(".content").children("h3").html() != null ){
				$fC = $(this).children(".content").children("h3");   
				if($(this).text().length > 78) {
					$fC.html($fC.html().substring(0,78) + '...');
				}
			}
			if( $(this).children(".content").children(".head").children("h3").html() != null ){
				$fC = $(this).children(".content").children(".head").children("h3");
				if($(this).children(".content").children(".head").text().length > 78) {
					$fC.html($fC.html().substring(0,76) + ' ...');
				}
			}
			if( $(this).children(".content").children(".text").children("h2").html() != null ){            
				$fC = $(this).children(".content").children(".text").children("h2");     
				$(this).children(".content").children(".text").textBoxsize();    
				if($(this).children(".content").children(".text").text().length > 90) {
					$fC.html($fC.html().substring(0,82) + ' ...');
				}
			}
		});
	};
	$.fn.displaySubnavigation = function() {
		return this.hover( 
			function() {
					//don't show subnav/arrow if no subnav children
					if ($(this).children('ul').length == 0) {
						$(this).children('a.hovers').height(32);
						if ($('body').hasClass('home')) return;
					}
					$(this).children('.subnav').show(); 
					$(this).children('ul').show();
					$('#header .navigation .folder.active a.hovers').height(32);
					$('#header .navigation .folder.active').children('ul').hide();
					//$(this).children('.subnav').find('.hidden').hide(); 
					
				},
			function() { 
					$(this).children('ul').hide();
					$(this).children('.subnav').hide(); 
		
			$('#header .navigation .folder.active a.hovers').height(48);
					$('#header .navigation .folder.active').children('ul').show();
					$(this).children('.subnav').find('.hidden').hide(); 
				}
		);
	};
	$.fn.displaySubnavigationTeaser = function() {
		$(this).hover(
			function() { $(this).siblings('.subnav').find('.hidden').show(10); }
		);
	};
$.fn.addHighlight = function() {
	var slices = location.pathname.split('/'),
		path   = slices.slice(0, slices.length - 1).join('/'),
		anchor = this.find('li > a[href="' + path + '/"]');
		
		if (document.body.className != 'home'){
			
			anchor.addClass('active')
			.parents('.folder').addClass('active').removeClass('hoverable');

			return this;
		}
};
$.fn.addQuotes = function() {
	var text = this.children('p');
		
		if(text != ''){
			text.wrapInner('<span class="new" />');
			$('<span class="last"></span>').appendTo(text);
			$('<span class="first"></span>').prependTo(text);
		}
};
$.fn.stripTitle = function() {
	var titleextract = document.title;
	$(this).html(titleextract);
};

$.fn.addListingSwitch = function() {
	var ul = $(this),
		projects = ul.parent().children('.project'),
		links = ul.find('li.orderlike a'),
		active = links.filter('.on');
	
	if(active.hasClass('trg-detail'))
		projects.find('div.listing').hide();
	else
		projects.find('div.detail').hide();
		
	links.click(function() {
		links.removeClass('on');
		$(this).addClass('on');
		if($(this).hasClass('trg-detail')) {
			projects.find('div.listing').hide();
			projects.find('div.detail').show();
		} else {
			projects.find('div.detail').hide();
			projects.find('div.listing').show();
		}
	});
};

function projectItemsBeforeDate(items, date) {
	return items.filter(function() {
		var dateRange = $('.date', this).html().split('-'),
			to = dateRange[1],
			toDate = new Date(to.replace('.', '/01/'));
		return toDate < date;
	});
}
function projectItemsNotInYear(items, year) {
	return items.filter(function() {
		var dateRange = $('.date', this).html().split('-'),
			from = dateRange[0], to = dateRange[1],
			fromYear = new Date(from.replace('.', '/01/')).getFullYear(),
			toYear = new Date(to.replace('.', '/01/')).getFullYear();
		return year > toYear || year < fromYear;
	});
}
$.fn.addDateSwitch = function() {
	var dateSwitch = $(this),
		now = new Date(),
		year = now.getFullYear(),
		ul = dateSwitch.find('ul.dropdown'),
		span = dateSwitch.find('span.trg'),
		dates = ul.children(),
		sixMonths = $(dates.get(0)),
		twelveMonths = $(dates.get(1)),
		lastYear = $(dates.get(2)).text(year - 1),
		lastLastYear = $(dates.get(3)).text(year - 2),
		items = dateSwitch.parent().parent().children(':not(.pagination, .teasermenu)');

	dates.click(function(e) {
		var selected = $(this),
			current = new Date();
		ul.hide();
		items.show().removeClass('date-deselect');
		span.html(selected.html()).removeClass('on');

		switch (selected.get(0)) {
			case sixMonths.get(0):
				var past = new Date(current.setMonth(current.getMonth() - 6));
				projectItemsBeforeDate(items, past).hide().addClass('date-deselect');
				break;
			case twelveMonths.get(0):
				var past = new Date(current.setMonth(current.getMonth() - 12));
				projectItemsBeforeDate(items, past).hide().addClass('date-deselect');
				break;
			case lastYear.get(0):
				projectItemsNotInYear(items, year - 1).hide().addClass('date-deselect');
				break;
			case lastLastYear.get(0):
				projectItemsNotInYear(items, year - 2).hide().addClass('date-deselect');
				break;
		}

		// update pagination
		$('div.teamlist div.pagination, div.teaserlist div.pagination').addPagination();
	});
	dateSwitch.hover(function() {}, function(){	
		dropdown.hide(10);
		span.removeClass('on');
	});
	span.click(function() {
		ul.show().css('zIndex', 3000);
		span.addClass('on');
	});
};

function bubbleSort(teasers) {
	var teaserCount = teasers.length,
		i, j, tmpTeaser, end;

	for (i = 0; i < teaserCount; i++){
		for (j = 0, end = teaserCount - i; j < end; j++){
			if ($(teasers[j]).data('fromDate') < $(teasers[j + 1]).data('fromDate')){
				tmpTeaser = teasers[j];
				teasers[j] = teasers[j + 1];
				teasers[j + 1] = tmpTeaser;
			}
		}
	}
	return teasers;
}

$.fn.sortTeaser = function() {

	if($(this).length == 0) return;

	var currentSortedItems = [],
		currentSortedFeaturedItems = [],
		expiredSortedItems = [],
		sortedItems = [],
		today = new Date(),
		pagination = $('.pagination');

	$(this).each(function () {
		var teaser = $(this),
		dateRange = teaser.find('div.date:first').html().split('-'),
		from = dateRange[0], fromDate = new Date(from.replace('.', '/01/')),
		to = dateRange[1], toDate = new Date(to.replace('.', '/01/')),
		featured = teaser.hasClass('featured');
		teaser.data('fromDate', fromDate);
		if(toDate < today) {
			expiredSortedItems.push(teaser);
		} else if(featured) {
			currentSortedFeaturedItems.push(teaser);
		} else {
			currentSortedItems.push(teaser);
		}
	});
	sortedItems = bubbleSort(currentSortedFeaturedItems).
		concat(bubbleSort(currentSortedItems).
		concat(bubbleSort(expiredSortedItems)
		)
	);
	$.map( sortedItems, function(item){
	   pagination.before(item.get(0));
	 });
};


$.fn.addPagination = function() {
	// CHANGE ITEMS PER PAGE HERE
	var itemsPerPage = 7,
		pagination = $(this).hide(),
		items = pagination.parent().children(':not(.pagination, .teasermenu, .date-deselect)'),
		count = items.length,
		startIndex = 0,
		currentPage = 1,
		endIndex = itemsPerPage,
		pages = Math.ceil(count / itemsPerPage),
		prev = $('<a class="prev" href="#">←</a>'),
		next = $('<a class="next" href="#">→</a>');

	if(count <= itemsPerPage) return;

	items.hide();
	items.filter(':lt('+endIndex+')').show();
	
	pagination.children().remove();
	prev.appendTo(pagination).hide();
	
	for (var i = 1; i <= pages; i++){
		var className = 'page';
		if (i == 1) className = className + ' on';
		pagination.append('<a class="'+className+'" href="#">'+i+'</a>');
	}
	pagination.append(next).show().children().click(function(e) {
		e.preventDefault();
		var link = $(e.target);

		link.siblings().removeClass('on');
		if (link.hasClass('page')) {
			currentPage = parseInt(link.text(), 10);
			link.addClass('on');
		} else if (link.hasClass('prev')) {
			currentPage--;
			link.siblings('.page:eq('+(currentPage-1)+')').addClass('on');
		} else {
			link.siblings('.page:eq('+currentPage+')').addClass('on');
			currentPage++;
		}

		if (currentPage == 1) { prev.hide(); next.show(); }
		else if (currentPage == pages) { next.hide(); prev.show(); }
		else {prev.show(); next.show();}

		startIndex = (currentPage - 1) * itemsPerPage;
		endIndex = startIndex + itemsPerPage;
		items.hide();
		items.slice(startIndex, endIndex).show();
	});
};

var changeInterval;
$.fn.themeChange = function () {
	var id = 0,
		count = 0,
		animated_gallery = $(this),
		themes = animated_gallery.children('.theme'),
		pagetitle = animated_gallery.find('.pagetitleplus'),
		pagination = animated_gallery.find('.pagination'),
		currentTheme = themes.filter('.show').length > 0 ? themes.filter('.show') : themes.first();

	var currentLink = pagination.find('a.current').length > 0 ? pagination.find('a.current') : pagination.find('a:first').addClass('current');

	themes.css({opacity: 0.0});
	currentTheme.css({opacity: 1.0}).addClass('show');
	pagetitle.css({opacity: 0.9});

	pagetitle.html(currentTheme.find('div').html())
		.animate({opacity: 1.0}, 1000);

	changeInterval = setInterval(function gallery() {

			var current = animated_gallery.find('.theme.show') ? animated_gallery.find('.theme.show') : animated_gallery.find('.theme:first');
			currentLink = pagination.find('a.current') ? pagination.find('a.current') : pagination.find('a:first');

			var next = ((current.next().length) ? ((current.next().hasClass('caption'))? animated_gallery.find('theme:first') : current.next()) : animated_gallery.find('.theme:first'));
			var nextLink = ((currentLink.next().length) ? ((currentLink.next().hasClass('caption'))? pagination.find('a:first') :currentLink.next()) : pagination.find('a:first'));
			var caption = next.find('div').html();
			//Set the fade in effect for the next image, show class has higher z-index
				next.css({opacity: 0.0})
				.addClass('show')
				.animate({opacity: 1.0},900);
				
				nextLink.addClass('current');
				
				//Hide the current image
				current.animate({opacity: 0.0}, 900)
				.removeClass('show');
				
				currentLink.removeClass('current');
				//Set the opacity to 0 and height to 1px
				pagetitle.animate({opacity: 0.5}, { queue:false, duration:100 }).animate({height: '50px'}, { queue:true, duration:300 }, function(){
					pagetitle.empty();
				});	

				//Animate the caption, opacity to 0.7 and heigth to 100px, a slide up effect
				pagetitle.animate({opacity: 1 }, 50 ).animate({height: '50px'}, 100, function(){
					pagetitle.html(caption);
				} );
				//pagination.find('a.show').css('background-color', 'red');
			
		}, 6000);
};
$.fn.themeSwitch = function () {

	$(this).click(function(e){
		clearInterval(changeInterval);
		var link = $(e.target),
			animated_gallery = link.parent().parent(),
			index = link.index(),
			theme = animated_gallery.children('.theme:eq('+index+')');
			
		e.preventDefault();
		link.siblings().removeClass('current');
		link.addClass('current');

		animated_gallery.children('.theme').removeClass('show');
		theme.addClass('show');
		animated_gallery.themeChange();	
	});
};
$.fn.cutHeight = function () {
  if($(this).html() == ""){ $(this).height(0);}
};
})(jQuery);

$(function() { 
	$('a[href^="http://"]').blank();
	$('#print').click(function() { window.print(); });
	document.title = "Joachim Herz Stiftung - "+document.title;
	$('div.teamlist div.pagination, div.teaserlist div.pagination').parent().children(':not(.pagination, .teasermenu, .date-deselect)').sortTeaser();
	$('div.teamlist div.pagination, div.teaserlist div.pagination').addPagination();
	$('div.teamlist ul.teasermenu, div.teaserlist ul.teasermenu').addListingSwitch();
	$('ul.teasermenu .date').addDateSwitch();
	$('a').blurry();
	$('.animated-gallery').themeChange();
	$('.animated-gallery .pagination a').themeSwitch();
	$('.hoverable').hovers();
	$('#header .navigation .folder').addHighlight();
	$('#header .navigation .folder.hoverable').displaySubnavigation();
	$('.teasers .hoverable').addLink();
	$('.home #header .navigation .folder.hoverable ul').displaySubnavigationTeaser();
	$('.quote').addQuotes(); 
	//don't put pagetitle before headline
        //$('.page .pagetitle').stripTitle();
	$('#infobox').cutHeight();
	//better let them handle it. google cant read it if added via js...
	//if($('.page')) $('head title').text('Joachim-Herz-Stiftung - ' + document.title);
});

