var data = {};

/* German initialisation for the jQuery UI date picker plugin. */
/* Written by Milian Wolff (mail@milianw.de). */
jQuery(function($){
	$.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']);
});

$(document).ready(function() {
	// init overlay
	initOverlay();
	
	// overlay top left corner on homepage
	$('body.home #content').append($('<div id="topLeftCorner">'));
	
	// see control buttons :active state
	$('a[href^="#"]').live('click',function (event) {
		event.preventDefault();
	});
	
	// toggle topics dropdown
	$('#themen h4 span').click(function() {
		var topics = $(this).closest('#themen');
		if (topics.hasClass('opened')) {
			// hide
			topics.removeClass('opened');
			$('#head').removeClass('opened');
			hideOverlay();
		} else {
			// show
			topics.addClass('opened');
			$('#head').addClass('opened');
			showOverlay();
		}
		return false;
	});
	$('#overlay').click(function() {
		$('#themen').removeClass('opened');
		hideOverlay();
	});
	
	// make content/sidebar same height
	$('#leftWrap').css('minHeight', $('#sidebar').outerHeight() + 30);
	
	// make sure page is as heigh as browser window
	//if ($('#footer').offset().top + $('#footer').height() < $(document).height()) {
	correctHeight();
	$(window).resize(function() {
		correctHeight();
	});

	// init highlights tabs
	initHighlights();
	
	// init homepage (equal heights in top section, etc.
	initHomepage();
	
	// toggle news
	// @todo: change click target! (exclude #newsText)
	$('#news.more h2, #news.more #newsSummary, #highlights.more h2').click(function() {
		var show = $('#newsText:visible').length > 0 ? false : true;
		$('#newsText').toggle('blind');
		$('#highlights').animate({
			top: show ? $('#highlights').data('shrunkTop') : $('#highlights').data('defaultTop'),
			height: show ? $('#highlights').data('shrunkHeight') : $('#highlights').data('defaultHeight')
		});
		$('#news, #highlights').addClass(show ? 'open' : 'closed').removeClass(show ? 'closed' : 'open');
		$('#highlights').addClass('more').addClass(show ? 'closed' : 'open').removeClass(show ? 'open' : 'closed');
	});
	
	// init latest videos carousel
	carouselInit($('#latest'));
	
	// init categories carousel
	carouselInit($('#categories'));
	
	/**
	 * video list 
	 */
	
	// check title lengths
	listTitleLengths();
	
	// ie nth-child replacement styles
	listAddClasses();
	
	// toggle video list grid/expanded style
	$('#viewBtn').click(function (event) {
		$(this).toggleClass('grid list');
		$('ul.videos').toggleClass('grid list');
		document.cookie = 'listStyle=' + $(this).attr('class');
		
		listTitleLengths();
		
		return false;
	});
	
	// load more items (ajax)
	$('a.load.videos').click(function() {
		var clickedElement = $(this);
		var url = $(this).attr('href');
		var list = $('ul.videos');
		var action = $(this).hasClass('more') ? 'append' : 'replace';
		
		// determine current video page
		if (!data.videopage) {
			data.videopage = 2;
		} else {
			data.videopage++;
		}
		if (action == 'replace') {
			data.videopage = 1;
		}
		
		// add active indicator
		if (clickedElement.parent().is('li')) {
			clickedElement.closest('ul').find('li').removeClass('active');
			clickedElement.closest('li').addClass('active');
		}
		
		// add loading indicator
		clickedElement.addClass('loading');
		list.addClass('loading');
		
		$.get(url, {page:data.videopage,ajax:true}, function(response) {
			// hide loading indicator
			clickedElement.removeClass('loading');
			list.removeClass('loading');
			
			if ($.trim(response).length == 0) {
				// empty result
				clickedElement.replaceWith('Keine weiteren Videos vorhanden.');
			} else {
				$('a.load.videos[href="'+clickedElement.attr('href')+'"]').attr('href', clickedElement.attr('href').replace('page='+(data.videopage), 'page='+(data.videopage + 1)));
				
				if (action == 'replace') {
					list.empty();
				}
				list.append(response);
				//list.find('._new').hide().slideToggle();
				
				listTitleLengths();
				listAddClasses();
			}
		});
		
		return false;
	});
	
	/**
	 * forms
	 */
	
	// input labels
	if (!Modernizr.input.placeholder) {
		$('input,textarea').each(function() {
			if ($(this).val() == '') {
				$(this).val($(this).attr('placeholder')).addClass('labeled');
			}
		});
		$('input,textarea').focus(function() {
			if ($(this).val() == $(this).attr('placeholder')) {
				$(this).val('').removeClass('labeled');
			}
		});
		$('input,textarea').bind('change, blur', function() {
			if ($(this).val() == '') {
				$(this).val($(this).attr('placeholder')).addClass('labeled');
			} else {
				$(this).removeClass('labeled');
			}
		});
	}
	
	// submit comment form via ajax
	$('#commentForm').submit(function() {
		var form = $(this);
		// remove placeholder texts
		form.find('input.labeled, textarea.labeled').val('');
		// show loading indicator
		form.find(':submit').hide().after($('<span class="loading">'));
		// post comment
		$.post(form.attr('action'), form.serialize(), function(response) {
			// hide loading indicator
			form.find(':submit').show();
			form.find('span.loading').remove();
			// add comment
			$('#comments ol').append(response);
			// reset form
			form.find('textarea').val('').blur();
			
			// debug
			/*
			console.log(response);
			console.log($(response));
			console.log($(response).find('li').hasClass('error') ? 'error' : 'alright');
			*/
		});
		return false;
	});
	
	// get embed code
	$('#embed, #embedClose').click(function() {
		$('#embed, #embedClose').toggle();
		$('#share').toggleClass('default open');
		$('#embedCode').toggle().focus().select();
	});
	$('#embedCode').bind('focus, click', function() {
		$(this).select();
	});
	
	// datepicker
	if (typeof $.datepicker != 'undefined') {
		$('.datepicker').datepicker({
			firstDay:1,
			maxDate:0,
			dateFormat:'yy-mm-dd'
		});
	}
	
	$('#listdate').change(function() {
		var url = $(this).data('url');
		url = url.replace('XXXX', $(this).val());
		location.href = url;
	});
	
	/**
	 * mobile
	 */
	
	$('.mobile .videos li').live('click', function() {
		document.location = $(this).find(':header a').first().attr('href');
	});
	
	$('.mobile #topicsSelect').change(function() {
		document.location = $(this).attr('value');
	});
	
	$('.mobile #search').click(function() {
		if ($('#searchWrapper').is(':visible')) {
			$('#searchForm').submit();
		} else {
			$('#searchWrapper').show();
			$('#searchString').focus();
		}
	});
	$('.mobile #searchString').blur(function() {
		$('#searchWrapper').slideUp();
	});
	
	$('.mobile a.toggle').click(function() {
		$('.toggle:not(a)').slideToggle();
		$(this).remove();
	});
	
	$('.mobile #switch').click(function() {
		document.cookie = 'nomobile=1; path=/';
	});

});

/**
 * general
 */

function correctHeight() {
	if ($(document).height() <= $(window).height()) {
		$('#footer').css('min-height', $(window).height() - $('#footer').position().top);
	}
}

/**
 * overlay
 */

function initOverlay() {
	$('<div id="overlay">').appendTo('body').hide();
}

function showOverlay() {
	$('#overlay').fadeIn('fast');
}

function hideOverlay() {
	$('#overlay').fadeOut('fast');
}

/**
 * init homepage
 */
function initHomepage() {
	// equal heights on homepage
	
	// change css styles for animation
	$('#news').css({
		float:null,
		position:'absolute',
		right:0
	});
	$('#highlights').css({
		float:null,
		position:'absolute',
		top:$('#news').outerHeight(),
		right:0,
		overflow:'hidden'
	});
	
	// extend height of latest videos
	var totalHeight = $('#featured').height() + $('#latest').height();
	if ($('#news').length) {
		$('#highlights').height(totalHeight - $('#news').outerHeight(true));
		$('#highlights').data('defaultHeight', $('#highlights').height());
		$('#highlights').data('defaultTop', $('#news').outerHeight(true));
		$('#highlights').data('shrunkHeight', $('#highlights h2').innerHeight() + 20);
		$('#highlights').data('shrunkTop', totalHeight - $('#highlights').data('shrunkHeight'));
	} else {
		$('#highlights').height(totalHeight);
	}
	if ($('#highlights').length) {
		$('#highlights').css({
			overflow:'hidden'
		})
		var maxTop = $('#highlights').offset().top + $('#highlights').outerHeight();
		$('#highlights li').each(function() {
			if ($(this).offset().top + $(this).innerHeight() - 25 > maxTop) {
				$(this).remove();
			}
		});
	}
	
	/*
	var topHeight = Math.max($('#news').outerHeight() + $('#highlights').outerHeight(), $('#featured').outerHeight() + $('#latest').outerHeight()); // height of top 4 panels
	var latestOuterHeight = topHeight - $('#featured').outerHeight();
	var latestPadding = $('#latest').outerHeight() - $('#latest').height();
	$('#latest').css('min-height', latestOuterHeight - latestPadding);
	
	// calculate different heights for top clips
	$('#highlights').data('defaultHeight', $('#highlights').height());
	$('#highlights').data('defaultTop', $('#news').outerHeight(true));
	$('#highlights').data('shrunkHeight', $('#highlights h2').innerHeight() + 15);
	$('#highlights').data('shrunkTop', topHeight - $('#highlights h2').innerHeight() - ($('#highlights').innerHeight() - $('#highlights').height()) - 15);
	*/
	// set max height of newsText
	$('#newsText').css('height', $('#highlights').data('defaultHeight') - $('#highlights').data('shrunkHeight') - 6);
	
}

/**
 * carousel stuff
 */

function carouselInit(element) {
	// get dimensions
	var child = $(element).find('.slideContainer > *:first');
	if (child.length > 0) {
		$(element).data({
			left:child.position().left,
			width:$(element).innerWidth()
		});
	}
	
	// set styles
	$(element).css({
		position:'relative',
		overflow:'hidden',
		minHeight:$(element).height()
	});
	
	// number slides/pages
	var n = 1;
	$(element).find('.slideContainer > *').each(function() {
		$(this).addClass('page'+n).data('page', n);
		n++;
	});
	
	// indicators
	var max = Math.max(2, $(element).data('max'));
	for (var i = 1; i <= max; i++) {
		$(element).children('.indicators').append('<a href="#' + i + '"' + (i == 1 ? 'class="active"' : '') + '>' + i + '</a>');
	}
	
	// event listeners
	$(element).find('.indicators a').live('click', function() {
		carouselGoTo(element, $(this).text());
	});
	$(element).find('.controls .next').click(function() {
		carouselNext(element);
	});
	$(element).find('.controls .prev').click(function() {
		carouselPrev(element);
	});
	
	carouselRefresh(element);
}
function carouselRefresh(element) {
	// style corrections for sucking browsers (IE!)
	$(element).find('li:nth-child(3n)').addClass('noBorder');
}

function carouselAni(direction, current, next, left, width) {
	var aniLeft = direction == 'left' ? true : false;
	
	// animate current out
	current.css({
		position:'absolute'
	});
	current.animate({
		left:aniLeft ? -width : width
	}, null, null, function() {
		current.css({
			display:'none'
		});
	});
	
	// animate next in
	next.css({
		position:'absolute',
		left:aniLeft ? width : -width,
		display:'block'
	});
	next.animate({
		left:left
	});
}

function carouselToLeft(current, next, left, width) {
	carouselAni('left', current, next, left, width);
}

function carouselToRight(current, next, left, width) {
	carouselAni('right', current, next, left, width);
}

function carouselNext(container) {
	var current = $(container).find('.slideContainer > :visible');
	return carouselGoTo(container, current.data('page') * 1 + 1);
}

function carouselPrev(container) {
	var current = $(container).find('.slideContainer > :visible');
	return carouselGoTo(container, Math.max(1, current.data('page') * 1 - 1));
}

function carouselGoTo(container, page) {
	container = $(container);
	var data = container.data();
	var slideContainer = container.find('.slideContainer');
	var current = slideContainer.children(':visible');
	//var next = slideContainer.children(':nth-child(' + (page) + ')');
	var next = slideContainer.children('.page' + page);
	
	var count = slideContainer.children().length;
	var currentIndex = current.index() + 1;
	var max = $(container).data('max') ? $(container).data('max') : count + 1;
	
	if (page <= max && next.index() != current.index()) {
		while (container.find('.indicators a').length < page) {
			var i = container.find('.indicators a').length + 1;
			container.find('.indicators').append('<a href="#'+i+'">'+i+'</a>');
		}
		
		// set indicator
		container.find('.indicators a').removeClass('active');
		container.find('.indicators a:nth-child(' + (page) + ')').addClass('active');
		
		// enable both arrows
		container.find('.controls .next').removeClass('disabled');
		container.find('.controls .prev').removeClass('disabled');
		
		// first element? -> disable left arrow
		if (next.index() == 0) {
			container.find('.controls .prev').addClass('disabled');
		}
		
		// last element? -> disable right arrow
		if (page == data.max) {
			container.find('.controls .next').addClass('disabled');
		}
		
		// load more content?
		if (next.length == 0 && page <= max) {
			// show loading indicator
			container.find('.indicators a:nth-child(' + (page) + ')').addClass('loading');
			
			// get content and show it
			$.get(data.url, {page:page, ajax:1}, function(response) {
				// hide loading indicator
				container.find('.indicators a:nth-child(' + (page) + ')').removeClass('loading');
				
				// add page number to content
				next = $(response).addClass('page'+page).data('page', page);
				
				// add html to dom
				var previousPage;
				var previousPageIndex = page - 1;
				var previousPageFound = false;
				while (!previousPageFound && previousPageIndex > 0) {
					previousPage = slideContainer.find('.page'+previousPageIndex)
					previousPageFound = previousPage.length;
					previousPageIndex--;
				}
				if (!previousPageFound) {
					previousPage = current;
				}
				previousPage.after(next);
				
				// init new element!
				// @todo does this still make sense?!
				carouselRefresh(container);
				
				// go to next
				//carouselToLeft(current, next, data.left, data.width);
				if (current.index() > next.index()) {
					carouselToRight(current, next, data.left, data.width);
				} else {
					carouselToLeft(current, next, data.left, data.width);
				}
			});
		} else {
			if (current.index() > next.index()) {
				carouselToRight(current, next, data.left, data.width);
			} else {
				carouselToLeft(current, next, data.left, data.width);
			}
		}
	}
	
	return false;
}

/**
 * higlights tabs
 */
function initHighlights() {
	var highlightsHandler = $('.tabHandler li');
	var highlightsContainer = $('#highlights');
	highlightsHandler.each(function (index) {
		// store index in dataObj.
		$(this).data('index', index);
	});
	$('#tabContent ul').each(function (index) {
		// store index in dataObj.
		$(this).data('index', index);
		// .hide.not(:first-child)
		if ($(this).data('index') !== 0) {
			$(this).hide();
		}
	});
	
	highlightsHandler.click(function () {
		// reset class=""
		highlightsHandler.attr('class', '');
		// add class="active"
		$(this).addClass('active');
		// add class="active + indexOfActiveElm" on #highlights
		highlightsContainer.attr('class', 'child' + $(this).data('index'));
		
		var clickedTab = $(this);
		$('#tabContent ul').each(function () {
			// hide all lists
			$(this).hide();
			// show list = clicked = index
			if ($(this).data('index') == clickedTab.data('index')) {
				$(this).show();
			}
		});
		
	});
}

/**
 * video lists
 */

function listTitleLengths() {
	// calculate text lengths (once!)
	$('ul.videos.grid li:not(.checked)').each(function() {
		var title = $(this).find('h4 a');
		var subtitle = $(this).find('h5');
		var titleHeight = title.height();
		var subtitleHeight = subtitle.height();
		
		var titleText = title.text();
		var subtitleText = subtitle.text();
		
		if (titleHeight + subtitleHeight > 48) {
			if (titleHeight > 48 && !subtitleHeight) {
				titleText = title.text().substr(0, 44) + '...';
			} else if (titleHeight > 24) {
				titleText = title.text().substr(0, 20) + '...';
			}
			if (subtitleHeight > 24) {
				subtitleText = subtitle.text().substr(0, 22) + '...';
			}
			
			$(this).data({
				title:title.text(),
				title_short:titleText,
				subtitle:subtitle.text(),
				subtitle_short:subtitleText
			});
			$(this).addClass('textlengths');
		}
			
		$(this).addClass('checked');
	});
	
	// switch long/shortended texts
	$('ul.videos.grid li.textlengths').each(function() {
		$(this).find('h4 a').text($(this).data('title_short'));
		$(this).find('h5').text($(this).data('subtitle_short'));
	});
	$('ul.videos.list li.textlengths').each(function() {
		$(this).find('h4 a').text($(this).data('title'));
		$(this).find('h5').text($(this).data('subtitle'));
	});
}

// adds row and col classes to list elements
function listAddClasses() {
	if ($.browser.msie && Number($.browser.version.substr(0, 1)) < 9) { // if f*** browser
		var i = 0;
		var row = 1;
		var col = 1;
		$('.videolist .videos li').each(function() {
			row = Math.floor(i / 3) + 1;
			col = (i % 3) + 1;
			$(this).addClass('row-'+row).addClass('col-'+col);
			i++;
		});
		$('.videos .row-last').removeClass('row-last');
		//$('.videolist .videos li:nth-child(3n+1):nth-last-child(-n+3), .videolist .videos li:nth-child(3n+2):nth-last-child(-n+2), .videolist .videos li:nth-last-child(1)').addClass('row-last');
		$('.videos .row-'+row).addClass('row-last');
		$('.videos li:first-child').addClass('first-child');
		$('.videos li:last-child').addClass('last-child');
	}
}
