jQuery.noConflict();

var $bg, $imageContainer, $content, $info, $mCols, $navL, $navR;
var preColWidth = 230, preColHeight = 110, preColPad = 10, minContLP = 65, minContRP = 400, mColsV = 1, mPos = 0;
var timerHandle, $gbImg, kbIn = true, kbStep = 0;
var $homenews, $newsimages, $teasertext;

//var DEF_COLUMN_COUNT = (function() {
//  var docEl = document.documentElement, s;
//  if (docEl && (s = docEl.style)) {
//    if (typeof s.columnCount == 'string') {
//      return 'native';
//    } else if (typeof s.MozColumnCount == 'string') {
//      return 'mozilla';
//    } else if (typeof s.WebkitColumnCount == 'string') {
//      return 'webkit';
//    }
//  }
//  return null;
//})();

jQuery(document).ready(function () {

	$bg = jQuery('#bg');
	$imageContainer = jQuery('#imageContainer');
	$container = jQuery('#container');
	$content = jQuery('#content');
	$teasertext = jQuery('#teasertext');
	$navL = jQuery('#contentnav .navleft');
	$navR = jQuery('#contentnav .navright');
	$navL.click(mContentNavL);
	$navR.click(mContentNavR);
	
	/*
	var imgNr = $imageContainer.children().length;
	if (imgNr >= 2) {
		$imageContainer.children().each(function(){
			jQuery(this).hide();
		});
	}
	*/

	$info = jQuery('#infocontent');
	$info.height(0);
	jQuery('#info').hover(function(){
		$info.stop().animate({
			'height':370
		}, 'fast');
	}, function(){
		$info.delay(200).stop().animate({
			'height':0
		}, 'fast');
	});
	$homeinfo = jQuery('#homeinfo');
	$homeinfobutton = jQuery('#homeinfobutton');
	$homeinfobutton.css('backgroundPosition', '0px 0px'); //initalize (FF bug)
	if ($homeinfo.length > 0) {
		//$homeinfo.height(46);
		$homeinfobutton.toggle(function(){
		//$homeinfo.hover(function(){
			$homeinfo.stop().animate({
				'height':221
			}, 'fast');
			setBackgroundX($homeinfobutton, '-180px');
		}, function(){
			$homeinfo.delay(200).stop().animate({
				'height':51      //46
			}, 'fast');
			setBackgroundX($homeinfobutton, '0px');
		});
	}
	$homeinfobutton.hover(function(){
		setBackgroundY($homeinfobutton, '-36px');
	}, function(){
		setBackgroundY($homeinfobutton, '0px');
	});

	// Home News
	$homenews = jQuery('#homeinfocontent .news-latest-container');
	
	var newsCounter = 0;
//	var newsNavCounter = 1;
	var newsStep = -150;
	var newsTicker = setInterval(function(){
		if( newsCounter < 2 ){
			newsCounter = newsCounter + 1;
			newsNavCounter = newsCounter + 1;
			$homenews.animate({'margin-top': (newsStep*newsCounter)+'px'}, 'fast');
//			console.log(newsStep*newsCounter);
			jQuery('#homeinfocontent .squarenav').removeClass('active');
			jQuery('#homeinfocontent .newsnav'+newsNavCounter).addClass('active');
		}else{
			newsCounter = 0;
			newsNavCounter = 1;
//			console.log(newsStep*newsCounter);
			$homenews.animate({'margin-top': (newsStep*newsCounter)+'px'}, 'fast');
			jQuery('#homeinfocontent .squarenav').removeClass('active');
			jQuery('#homeinfocontent .newsnav'+newsNavCounter).addClass('active');
		}		
	},6000);
	
	
	jQuery('#homeinfocontent .newsnav1').click(function(event) {
		event.preventDefault();
		jQuery('#homeinfocontent .newsnav1').addClass('active');
		$homenews.stop().animate({'margin-top': '0px'}, 'fast');
		jQuery('#homeinfocontent .newsnav2').removeClass('active');
		jQuery('#homeinfocontent .newsnav3').removeClass('active');
		window.clearInterval(newsTicker);
	});
	jQuery('#homeinfocontent .newsnav2').click(function(event) {
		event.preventDefault();
		jQuery('#homeinfocontent .newsnav2').addClass('active');
		$homenews.animate({'margin-top': '-150px'}, 'fast');
		jQuery('#homeinfocontent .newsnav1').removeClass('active');
		jQuery('#homeinfocontent .newsnav3').removeClass('active');
		window.clearInterval(newsTicker);
	});
	jQuery('#homeinfocontent .newsnav3').click(function(event) {
		event.preventDefault();
		jQuery('#homeinfocontent .newsnav3').addClass('active');
		$homenews.animate({'margin-top': '-300px'}, 'fast');
		jQuery('#homeinfocontent .newsnav1').removeClass('active');
		jQuery('#homeinfocontent .newsnav2').removeClass('active');
		window.clearInterval(newsTicker);
	});
	
	

	//menu
	jQuery('#menu .ulmain a, #homemenu .ulmain a').each(function() {
		if (jQuery(this).siblings('ul').length > 0) {
			jQuery(this).click(function(event) {
				event.preventDefault();
				var $ul = jQuery(this).next('ul');
				if ($ul.css('display') == 'none') {
					jQuery(this).closest('li').siblings().children('ul').slideUp();
					$ul.slideDown();
				} else {
					$ul.slideUp();
				}
				return false; //prevent selection?
			});
		}
	});

	// standbild für presse???
	$infobox = jQuery(this).find('#infobox').children('img').length;

	//NEWS & REF IMAGES
//	$newsimages = $content.find('.news-single-img img');
	$newsimages = $content.find('#news-single-image img');
	if ($newsimages.length > 0) {
		$imageContainer.empty();
		$newsimages.each(function() {
			$imageContainer.append(jQuery(this));
		});
	} else {
		$newsimages = $content.find('#ref-single-image img');
		if ($newsimages.length > 0) {
			if ($newsimages.length > 1) {$imageContainer.empty();}
			$newsimages.each(function(index) {
				if (index == 0) {
					$teasertext.append(jQuery(this));
					$teasertext.find('img').css({'max-width': '270px', 'max-height': '110px', 'width': 'auto', 'height': 'auto'});
				} else {
					$imageContainer.append(jQuery(this));
				}
			});
		}
	}

	function mApplyFunctions() {
		mContentInit();
	}

	bgFaderInit('#bg');
	jQuery(window).bind('resize', mResize);
	mResize();
	jQuery('body').bind('mContentChanged', mApplyFunctions);
	jQuery('body').trigger('mContentChanged');
});

jQuery(window).load(function() {
//	var infobox = jQuery(this).find('#infobox').children('img').length;
	var imgNr = $imageContainer.children().length;
	if (imgNr < 2) {
		if ($newsimages.length == 0 ) { //stand still on news and 404
			//KEN BURNS
//			console.log('still '+infobox);
			$kbImg = $imageContainer.children().first();
			if( $infobox == 1 ){
				mKenBurns(false);
			}else{
				mKenBurns(true);
			}
		}
	} else {
		var rndStart = Math.floor(Math.random() * imgNr);
		$imageContainer.children().each(function(){
			jQuery(this).hide();
		});
		$imageContainer.nivoSlider({
			effect:'boxRain', // sliceDown/sliceDownLeft/sliceUp/sliceUpLeft/sliceUpDown/sliceUpDownLeft/fold/fade/random/slideInRight/slideInLeft/boxRandom/boxRain/boxRainReverse
			slices:15, // For slice animations
			boxCols: 6, // For box animations
			boxRows: 4, // For box animations
			animSpeed:500, // Slide transition speed
			pauseTime:5000, // How long each slide will show
			startSlide: rndStart, // Set starting Slide (0 index)
			directionNav:false, // Next & Prev navigation
			directionNavHide:true, // Only show on hover
			controlNav:true, // 1,2,3... navigation
			controlNavThumbs:false, // Use thumbnails for Control Nav
			controlNavThumbsFromRel:false, // Use image rel for thumbs
			controlNavThumbsSearch: '.jpg', // Replace this with...
			controlNavThumbsReplace: '_thumb.jpg', // ...this in thumb Image src
			keyboardNav:false, // Use left & right arrows
			pauseOnHover:false, // Stop animation while hovering
			manualAdvance:false, // Force manual transitions
			captionOpacity:0.8, // Universal caption opacity
			prevText: 'Prev', // Prev directionNav text
			nextText: 'Next', // Next directionNav text
			beforeChange: function(){}, // Triggers before a slide transition
			afterChange: function(){}, // Triggers after a slide transition
			slideshowEnd: function(){}, // Triggers after all slides have been shown
			lastSlide: function(){}, // Triggers when last slide is shown
			afterLoad: function(){} // Triggers when slider has loaded
		});
	}
});

function setBackgroundX(el, val) {
	el = el.get(0); //convert jQuery => DOM object
	if (el.style.backgroundPositionX !== undefined) {
		el.style.backgroundPositionX = val;
	} else {
		var tmpPos = el.style.backgroundPosition.split(' ');
		el.style.backgroundPosition = val + ' ' + tmpPos[1];
	}
}

function setBackgroundY(el, val) {
	el = el.get(0); //convert jQuery => DOM object
	if (el.style.backgroundPositionY !== undefined) {
		el.style.backgroundPositionY = val;
	} else {
		var tmpPos = el.style.backgroundPosition.split(' ');
		el.style.backgroundPosition = tmpPos[0] + ' ' + val;
	}
}

function mResize() {
	mContentNav();
}

function mContentInit() {
	 //images larger than 110px => runaway-condition || special handling tt_news?? ($content.find('.news-single-item').length > 0 || )
//	if ($content.find('.news-list-item').length > 0 || $content.find('img, iframe').length == 0) {
//		$content.width((preColWidth + preColPad) * 2 + 10); //best results with 2 columns
//		//$content.find('br').addClass('removeiffirst');
//		$content.find('h4').addClass('dontend');
//		$content.columnize({
//			width: preColWidth,
//			height: preColHeight,
//			//      lastNeverTallest: true,
//			buildOnce: true,
//			doneFunc: function() {
//				$mCols = $content.children('.column');
//				$content.width('20000px'); //wegen AGB
//				$content.css('margin-left', '0px');
//				mPos = 0;
//				$mCols.height(preColHeight + 'px');
//				$mCols.css('margin-right', preColPad + 'px');
//				mContentNav();
//			}
//		});
//	} else {
//		$mCols = $content.children('.column');
//		$content.width('20000px'); //wegen AGB
//		if ($mCols.length > 0) {
//			mContentNav();
//		}
//	}
	 if ($content.find('.ref-list-item').length > 0) {
		$mCols = $content.children('.column');
		$content.width('20000px'); //wegen AGB
		if ($mCols.length > 0) {
			mContentNav();
		}
	} else {
		$content.width((preColWidth + preColPad) * 2 + 10); //best results with 2 columns
		//$content.find('br').addClass('removeiffirst');
		$content.find('h4').addClass('dontend');
		$content.columnize({
			width: preColWidth,
			height: preColHeight,
			//      lastNeverTallest: true,
			buildOnce: true,
			doneFunc: function() {
				$mCols = $content.children('.column');
				$content.width('20000px'); //wegen AGB
				$content.css('margin-left', '0px');
				mPos = 0;
				$mCols.height(preColHeight + 'px');
				$mCols.css('margin-right', preColPad + 'px');
				mContentNav();
			}
		});
	}
}

function mContentNav() {
	if ($mCols) {
		//calculate visible cols => minimum 1 (+ 1 colPad == last colPad not necessary)
		mColsV = Math.max(Math.floor(($bg.width() - (minContLP + minContRP) + preColPad) / (preColWidth + preColPad)), 1);
		var completeW = $mCols.length * (preColWidth + preColPad);
		var visibleW = mColsV * (preColWidth + preColPad);
		$container.width(visibleW - preColPad);
		$container.css('margin', '0 ' + ($bg.width() - (visibleW - preColPad) - minContLP) + 'px 0 ' + minContLP + 'px');
		var tmpPos = -mPos * (preColWidth + preColPad);
		if (tmpPos + completeW > visibleW + 10) {
			$navR.css('visibility', 'visible')
			} else  {
			$navR.css('visibility', 'hidden')
			}
		if (tmpPos < 0) {
			$navL.css('visibility', 'visible')
			} else  {
			$navL.css('visibility', 'hidden')
			}
	//    var colHidden = 0, colOverflow = 0;
	//    $mCols.each(function() {
	//      var tmpPos = jQuery(this).position().top;
	//      if (tmpPos == 0) {colHidden++;}
	//      else if (tmpPos > preColHeight) {colOverflow++;}
	//    });
	//    if (colHidden > 0) {$navL.css('visibility', 'visible')} else  {$navL.css('visibility', 'hidden')}
	//    if (colOverflow > 0) {$navR.css('visibility', 'visible')} else  {$navR.css('visibility', 'hidden')}
	} else {
		$container.width($bg.width() - (minContLP + minContRP));
		$container.css('margin', '0 ' + minContRP + 'px 0 ' + minContLP + 'px');
	}
}
function mContentNavL(event){
	event.preventDefault();
	mPos = Math.max(mPos - 1, 0);
	$content.stop().animate({
		'margin-left' : -mPos * (preColWidth + preColPad)
		});
	//  $content.css('margin-left', -mPos * (preColWidth + preColPad));
	//  $mCols.each(function(index) {
	//    if (index > 0 && jQuery(this).css('display') != 'none') {
	//      jQuery(this).prev().css('display', '');
	//      return false;
	//    }
	//  });
	mContentNav();
	return false; //prevent selection?
}
function mContentNavR(event){
	event.preventDefault();
	mPos = Math.min(mPos + 1, $mCols.length - 1);
	$content.stop().animate({
		'margin-left' : -mPos * (preColWidth + preColPad)
		});
	//  $content.css('margin-left', -mPos * (preColWidth + preColPad));
	//  $mCols.each(function(index) {
	//    if (jQuery(this).css('display') != 'none') {
	//      jQuery(this).css('display', 'none');
	//      return false;
	//    }
	//  });
	mContentNav();
	return false; //prevent selection?
}

function mShowLoading() {
	bgFaderStop();
	jQuery('#content > .contentinner').html('<div class="ajax-loader"><img src="fileadmin/images/ajax-loader.gif" /></div>');
	jQuery('#content > .scrollbar').hide();
	jQuery('#content > .scrolltrack').hide();
	jQuery('#close').hide();
}

function mLoadAjax(el) {
	mShowLoading();
	var url = jQuery(el).attr('href');
	if (mcache[url] == undefined) {
		jQuery.get(url, '', function(data){
			mcache[url] = data;
			mParseAjax(data);
		});
	} else {
		mParseAjax(mcache[url]);
	}
	//make google analytics call
	if (url.substr(0, 1) == '/') {
		_gaq.push(['_trackPageview', url]);
	} else {
		_gaq.push(['_trackPageview', '/' + url]);
	}

	function mParseAjax(data) {
		//TODO: cache parsed content not plain content
		var mwidth = 620;
		var mheight = 420;
		if (jQuery(data).find('body').hasClass('smallcontent')) { //TODO: not working
			mwidth = 249
			mheight = 209;
		}
		jQuery(data).find(".contentinner").children().each(function(){ //#ID not working
			jQuery('#content > .contentinner').html(this);
		});
		mContentResize(620, 420, function(){
			jQuery('body').trigger('mContentChanged');
			jQuery('#close').show();
		//      bgFaderInit('#bg', jQuery(data).find('.helper4aj').find('img')); //#ID not working
		});
		//get title for titlebar and google analytics
		var mTitleMatches = data.match(/<title>(.*?)<\/title>/);
		var mTitle = mTitleMatches[1];
		mTitle = mTitle.replace('&nbsp;', ' ')
		document.title = mTitle;
	}
}

var bgFader = new Array();
var bgFadeCont, bgFadeContW, bgFadeContH, bgFadeContR;

function bgFaderInit(bgStr) {
	jQuery(window).unbind('resize', bgFaderResize);
	bgFadeCont = jQuery(bgStr);
	bgFader = bgFadeCont.find('img');
	jQuery(bgFader).each(function () {
		jQuery(this).attr('oWidth', jQuery(this).width());
		jQuery(this).attr('oHeight', jQuery(this).height());
	});
	bgFaderResize();
	jQuery(window).bind('resize', bgFaderResize);
}

function bgFaderResize() {
	var paperChildren = 0;
	var offsetBottom;
	if(document.getElementById('paper')){
		paperChildren = document.getElementById('paper').childNodes.length;
	}
	if ( paperChildren > 0 ){
		offsetBottom = 160;
//		console.log('paper '+paperChildren);
	}else{
		offsetBottom = 0;
//		console.log('paper '+paperChildren);
	}
	bgFadeContW = jQuery(bgFadeCont).width();
	bgFadeContH = jQuery(bgFadeCont).height() - offsetBottom; //wegen paper unten
	bgFadeContR = bgFadeContW / bgFadeContH;
	jQuery(bgFader).each(function () {
		var newW, newH, newR, offL, offT;
		var oldW = jQuery(this).attr('oWidth'); //jQuery(this).width(); //prevents calculation errors on extreme resize
		var oldH = jQuery(this).attr('oHeight'); //jQuery(this).height();
		var tmpR = oldW / oldH;
		if (tmpR > bgFadeContR) {
			newR = bgFadeContH / oldH;
		} else {
			newR = bgFadeContW / oldW;
		}
		newW = Math.ceil(oldW * newR);
		newH = Math.ceil(oldH * newR);
		offL = Math.ceil((bgFadeContW - newW) / 2);
		offT = Math.ceil((bgFadeContH - newH) / 2);
		jQuery(this).css('position', 'absolute');
		//    jQuery(this).css('left', offL);
		//    jQuery(this).css('top', offT);
		jQuery(this).css('left', 0);
		jQuery(this).css('top', 0);
		jQuery(this).css('width', newW);
		jQuery(this).css('height', newH);
		jQuery(this).attr('sWidth', newW);
		jQuery(this).attr('sHeight', newH);
	//    jQuery(this).hide();
	//    jQuery(this).attr('mOffLeft', offL);
	//    jQuery(this).attr('mOffTop', offT);
	});
	mKenBurns();
}

function mKenBurns(mInit) {
	if (! timerHandle && ! mInit) {
		return;
	}
	if (timerHandle) {
		window.clearTimeout(timerHandle);
	}
	if (kbStep > 0.5) {
		kbIn = ! kbIn;
	}
	bgFadeContW = jQuery(bgFadeCont).width();
	bgFadeContH = jQuery(bgFadeCont).height() - 160; //wegen paper unten
	var tmpW = $kbImg.attr('sWidth');
	var tmpH = $kbImg.attr('sHeight');
	if (kbIn) {
		tmpW = tmpW * 1.1;
		tmpH = tmpH * 1.1;
	//    console.log(bgFadeContW + '-' + tmpW + '=' + Math.floor(bgFadeContW - tmpW));
	}
	$kbImg.stop().animate({
		width: tmpW,
		height: tmpH
	}, {
		duration: 10000,
		step: function(now, fx) {
			kbStep = fx.pos;
		}
	});
	timerHandle = window.setTimeout(mKenBurns, 14000);
}
