$(document).ready(function(){

	/* Backlink */
	$('#link_back').click(function(){
		var $loc = location.href.split('/').reverse().slice(2).reverse();
		$loc.push('');

		if(document.referrer && location.href != document.referrer)
			location.href = document.referrer;
		else if($loc.length > 2)
			location.href =  $loc.join('/');

		return false;
	});

	/* Menü bottom active */
	$('#bottom_menu:has(.active)').addClass('active');

	/* Background image */
	var $pagebackground = $('#border img');
	if($pagebackground.length)	{
		$('#container').css('background-image', 'url('+$pagebackground[0].src+')').children().css('background-color', 'transparent');
		$pagebackground.remove();
	}

	/* Custom Checkboxes */
	$('input[type=checkbox]').each(function(){
		var $input = $(this);
		var $fake = $('<a href="#" class="fakecheck"></a>');
		var $name = $input.attr('name');

		$input.hide();
		$fake.insertAfter($input);
		$fake.parent().append('<div class="clear" />');

		$fake.click(function(){ $input.trigger('click'); return false; });
		if($input[0].checked) $fake.addClass('checked'); else  $fake.removeClass('checked');
		$input.change(function(){ $fake.toggleClass('checked'); });

		// toggle other checked fakechecks (akt like radiobuttons) with same prefix
		if($name.split('_').length > 1)
		{
			var $segment = $name.split('_')[0];
			$fake.click(function(){
				$('input[type=checkbox]:checked[name^='+$segment+'][name!='+$name+']')
				.trigger('click').next('.fakecheck').toggleClass('checked');
			});
		}
	});



	/* Bildmatrix */
	var $imageBlockCount = 0;
	var $MatrixImageItems = $('body.layout3 #content > .csc-default:has(.csc-textpic)');
	if($MatrixImageItems.length)
	{
		while(($MatrixImageItems = $('body.layout3 #content > .csc-default:has(.csc-textpic):lt(18)')).length)
		{
			var $otherItems = $('body.layout3 #content > .csc-default > p');
			var $imageBlock = $('<div class="imageBlock" />').attr('page', ($imageBlockCount+1))/*.height(6*63)*/.insertBefore($MatrixImageItems[0]);

			if($imageBlockCount)
				$imageBlock.hide();
			$imageBlockCount++;

			$MatrixImageItems.each(function(){
				var $parent = $('#content');
				$(this).find('.csc-textpic-clear').remove();

				var $header =   $(this).find('.csc-header:visible').hide();
				var $imgGray	= $(this).find('.csc-textpic-imagewrap').children(':eq(1)').clone();
				var $imgColor	= $(this).find('.csc-textpic-imagewrap').children(':eq(0)').clone();
				var $text		= $(this).find('.csc-textpic-text').clone();

				$text.find('tr td:first-child, tr th:first-child').css({width:'40%'});

				$imageBlock.append($imgColor);
				if($imgGray.length)
					$imageBlock.append($imgGray);

				$('#content').append($text.hide());

				$(this).remove();

				if($imgGray.length)
				{
					$imgGray
						.css({marginLeft:'-150px', cursor:'pointer' })
						.hover(
							function(){ $(this).fadeTo(500, 0.01) },
							function(){ $(this).fadeTo(500, 1.0) }
						)
						.click(function(){
							$(this).hide().siblings('img').fadeIn();
							$otherItems.hide();
							$text.show().siblings('.csc-textpic-text').hide();
						});

					$imgGray.hover(function(){
							$otherItems.hide();
							$text.show().siblings('.csc-textpic-text').hide();
						},function(){
							$otherItems.show();
							$text.hide();
					});
				}
				else
				{
					//console.log($text.text());
					$imgColor
						//.css({cursor:'pointer' })
						.click(function(){
							$(this).siblings('img').show();
							$otherItems.hide();
							$text.show().siblings('.csc-textpic-text').hide();
						});

					$imgColor.hover(function(){
							$otherItems.hide();
							$text.show().siblings('.csc-textpic-text').hide();
						},function(){
							$otherItems.show();
							$text.hide();
					});
				}
			});
		}

		// Scroll Arrows
		var $listen = $('#content > [page]');
		if($listen.length > 1)
		{
			var updateScrollArrows = function()
			{
				//console.log('#content > [page='+($currentPage+1)+']');
				var $nextPage = $('#content > *[page='+($currentPage+1)+']');
				var $prevPage = $('#content > *[page='+($currentPage-1)+']');

				if(!$nextPage.length) $scrollerDown.hide(200); else $scrollerDown.show(200);
				if(!$prevPage.length) $scrollerUp.hide(200);   else $scrollerUp.show(200);
				// scroll links
				if(!$nextPage.length) $('#page_browse #pageNext').hide(200); else $('#page_browse #pageNext').show(200);
				if(!$prevPage.length) $('#page_browse #pagePrev').hide(200); else $('#page_browse #pagePrev').show(200);
			}
			var $currentPage = 1;
			// scroll arrows
			var $scrollerDown = $('<a href="#down" id="scrollerDown"><span>next</span></a>');
			var $scrollerUp   = $('<a href="#up"   id="scrollerUp"><span>prev</span></a>');
			/// ### Scrollarrows deaktivated
			//$('#page_menu').append($scrollerDown.hide()).append($scrollerUp.hide());

			// scroll links
			$('#page_browse #pageNext').click(function(){ $scrollerDown.click(); return false; });
			$('#page_browse #pagePrev').click(function(){ $scrollerUp.click();   return false; });
			$('#page_browse').css({
				top:$('#page_browse').position().top,
				left:$('#page_browse').position().left,
				width:$('#page_browse').width(),
				position:'absolute'
			});

			updateScrollArrows();

			$scrollerDown.click(function(){
				var $nextPage = $('#content > [page='+($currentPage+1)+']');
				var $currPage = $('#content > [page='+$currentPage+']');
				if($nextPage.length)
				{
					$currPage.slideUp(350);	$nextPage.slideDown(350);
					//$currPage.hide(); $nextPage.show();
					$currentPage++;
					updateScrollArrows();
				}
				return false;
			});
			$scrollerUp.click(function(){
				var $nextPage = $('#content > [page='+($currentPage-1)+']');
				var $currPage = $('#content > [page='+$currentPage+']');
				if($nextPage.length)
				{
					$currPage.slideUp(350);	$nextPage.slideDown(350);
					//$currPage.hide(); $nextPage.show();
					$currentPage--;
					updateScrollArrows();
				}
				return false;
			});

		}
		else
		{
			$('#page_browse #pageNext[href*=\\#down], #page_browse #pagePrev[href*=\\#up]').hide();
		}
	}




	/* gutefilmesindkeinzufall */
	var $scrollImagesCont = $('body[id^="seite-gute"] #content .csc-textpic-equalheight:first .csc-textpic-imagewrap:first');
	if($scrollImagesCont.length)
	{
		var $img = $scrollImagesCont.find('.csc-textpic-image a, .csc-textpic-image img:not(a img)').clone();
		$scrollImagesCont
			.empty()
			.css({ whiteSpace:'nowrap', width:'auto' })
			// fist batch is incomplete
			.append($img.slice(Math.floor(Math.random() * $img.length)).clone())
			.append($img.clone())
			.append($img.clone())
			.append($img.clone())
			.append($img.clone())
			.append($img.clone())
			.append($img.clone())
			.append($img);

		// scroll a random amount
		$scrollImagesCont.parent()[0].scrollLeft = Math.random() * $img.eq(0).width();

		$scrollFunc1 = function(){ $scrollImagesCont.parent().animate({scrollLeft: $scrollImagesCont.width() -$scrollImagesCont.parent().width() }, $img.length*8*12*1000, "linear", function() { $scrollFunc2(); }) };
		$scrollFunc2 = function(){ $scrollImagesCont.parent().animate({scrollLeft: 0}, 0, "linear", function() { $scrollFunc1(); }) };

		$scrollFunc1();
	}

	/* gutefilmesindkeinzufall - bild in menü */
	var $menuVideo = $('#content_left .csc-textpic');
	if($menuVideo.length)
	{
		$menuVideo.each(function(){
			var $pic = $(this).find('.csc-textpic-imagewrap');
			var $text = $(this).find('.csc-textpic-text, .tx_kuloplayer_pi1-player-text');

			if($pic.length || $text.length)
				$('#mn_news').empty().css({ top:0, background:'none', overflow:'' }).append($pic).append($text);

			$(this).remove();

		});
	}

	/* News Teaser Startseite */
	var $newsTeaserHeader = $('body[id^="seite-gute"] #content_right .csc-header');
   	if($newsTeaserHeader.length)
	{
		var $newsTeaser = $('<div id="news_teaser"></div>');
		$('#content').append($newsTeaser);

		$newsTeaserHeader.each(function(){
			var $head = $(this).find('h1:first');
			var $date = $(this).find('.csc-header-date:first');
			var $text = $(this).next('.csc-textpic-text');

			var $block = $('<div>')
				.append($(this)).append($text)
				.addClass($head.text()).addClass('news_teaser_block');

			$newsTeaser.append($block);

			if($block.prev('.news_teaser_block').length)
				$block.find('.csc-header-date, h1').css({cursor:'pointer'}).click(function() {
					$block.animate({ marginLeft:-252 }, 500);
				});
			$block.hover(
				function() {$block.next('.news_teaser_block').animate({ marginLeft:-50 }, 500);},
				function() {	}
			);

			if($head.find('a').length)
				$text.css({cursor:'pointer'}).click(function() {
					location.href = $head.find('a').attr('href');
				});
		});
	}



	/* Bildlaufleiste */
	var $LeisteImageItems = $('body.layout5 #content > .csc-default:has(.csc-textpic)');
	if($LeisteImageItems.length)
	{
		var $otherItems = $('body.layout5 #content > p');
		var $scrollObject = $('<div class="scrollObject" />');
		var $scrollContainer = $('<div class="scrollContainer" />').append($scrollObject).insertBefore($LeisteImageItems[0]);


		$LeisteImageItems.slice(1).hide();
		$LeisteImageItems.each(function(){
			var $parent = $('#content');
			$(this).find('.csc-textpic-clear').remove();

			var $header =   $('#content > .csc-header').hide();
			// bild für leiste
			var $img	= $(this).find('.csc-textpic-imagewrap').find('a:has(img), img').slice(1,2).clone();
			// aus text entfernen
			$(this).find('.csc-textpic-imagewrap').find('a:has(img), img').slice(1,2).closest('.csc-textpic-imagerow').remove();
			// alle restlichen elemente
			var $text		= $(this);

			$text.find('tr td:first-child, tr th:first-child').css({width:'40%'});

			$scrollObject.append($img);
			$img.css({cursor:'pointer',width:'150px'})
				.click(function(){
					$otherItems.hide();
					$text.show().siblings('.csc-default').hide();
				});
		});

		$scrollObject.css({ whiteSpace:'nowrap', width:'auto' });
		var $scrollCurrent = 0;
		var $scrollStep = 150;
		var $scrollerRight = $('<a href="#right" id="scrollerRight"></a>').insertBefore($scrollContainer[0]);
		var $scrollerLeft  = $('<a href="#left" id="scrollerLeft"></a>').insertBefore($scrollContainer[0]).hide();

		var updateScrollerButtons = function()
		{
			if($scrollCurrent >= ($scrollObject.width()-$scrollContainer.width()))
			{
				$scrollCurrent = ($scrollObject.width()-$scrollContainer.width());
				$scrollerRight.fadeOut(300);
			}
			else
				$scrollerRight.fadeIn(300);
			if($scrollCurrent <= 0)
			{
				$scrollCurrent = 0;
				$scrollerLeft.fadeOut(300);
			}
			else
				$scrollerLeft.fadeIn(300);
		}

		$scrollerRight.dblclick(function(){
			$scrollCurrent += 3*$scrollStep;
			updateScrollerButtons();
			$scrollContainer.stop().animate({scrollLeft:$scrollCurrent}, 500);
			return false;
		});
		$scrollerLeft.dblclick(function(){
			$scrollCurrent -= 3*$scrollStep;
			updateScrollerButtons();
			$scrollContainer.stop().animate({scrollLeft:$scrollCurrent}, 500);
			return false;
		});
		$scrollerRight.click(function(){
			$scrollCurrent += $scrollStep;
			updateScrollerButtons();
			$scrollContainer.stop().animate({scrollLeft:$scrollCurrent}, 500);
			$(this)[0].blur();
			return false;
		});
		$scrollerLeft.click(function(){
			$scrollCurrent -= $scrollStep;
			updateScrollerButtons();
			$scrollContainer.stop().animate({scrollLeft:$scrollCurrent}, 500);
			$(this)[0].blur();
			return false;
		});
		updateScrollerButtons();
	}


	/* video */
	var $videopage = $('body.layout2');
	if($videopage.length)
	{
		//var $fadeElems = $('#container > *:not(#content)');
		var $fadeElems = $('#top_menu');
		var $hideElems = $('#bottom_menu, #bottom_menu_right, #page_browse');
		var $closeElems = $('html');
		var $btn_close = $('<a href="#" class="video_btn_close" />').text($video_close_text).click(function() { $closeElems.click();return false; });

		$videopage.find('#content .csc-textpic:has(.csc-textpic-imagewrap)').each(function(){
			$(this).find('.csc-textpic-text:first').find('p.bodytext:first, table.contenttable tr:first td p:first-child').css('margin-top', 0);
		});

		$videopage.find('#content .csc-textpic:has(.rgmediaimages-player)').each(function(){
			var $pic = $(this).find('.csc-textpic-image:has(img):first');
			var $video = $(this).find('.csc-textpic-image:has(.rgmediaimages-player):first');
			var $videoContainer = $video.parent();
			var $text = $(this).find('.csc-textpic-text');
			var $player = document.getElementById('mpl');

			//$pic.closest('.csc-textpic-imagewrap').css('float', 'none');

			$text.find('tr td:first-child, tr th:first-child').css({width:'50%'});
			$video.append($btn_close);

			//var $playBtn = $('<div class="videoPlayBtn">');
			//$('.csc-textpic-caption:has(.videoPlayBtn)').css({ height:'100%', display:'block' });

			var $height = Math.max($video.height(), $pic.height());
			var $width = Math.max($video.width(), $pic.width());
			try {
				$player.sendEvent('STOP');
			}
			catch(err) {}

			//$pic.height($height).css({cursor:'pointer', position:'relative'}).append($playBtn);
			$pic/*.height($height)*/.css({cursor:'pointer', position:'relative'}).fadeTo(0, 0.95);
			$video.height($height).hide()//.remove();

			//$pic.find('img:first').css('width', '100%').removeAttr('height');

			//if($.browser.msie)
			$pic.click(function(e)
			{
				e.stopPropagation();
				//$fadeElems.stop().fadeTo(900, 0.5);
				$fadeElems.css('visibility', 'hidden');
				$hideElems.css('visibility', 'hidden');

				$pic.hide();
				$video
					//.insertAfter($pic)
					.show()
					.click(function(e){e.stopPropagation();});
				// get player object
				var $player = document.getElementById('mpl');

				$($player).css({
						height:"495px",
						left:"-322px",
						top:"0",
						position:"absolute",
						zIndex:10,
						width:"848px",
						zoom:'1'
					});

				$closeElems.click(function(e){
					e.stopPropagation();
					//e.preventDefault();
					try {
						$player.sendEvent('STOP');
					}
					catch(err) {}
					$video.hide();
					$pic.show();

					//$fadeElems.stop().fadeTo(900, 1.0);
					$fadeElems.css('visibility', 'visible');
					$hideElems.css('visibility', 'visible');
					$closeElems.unbind('click');
				});
				$closeElems.find('object, embed').click(function(e){ e.stopPropagation(); });

				// create closure to start player
				var $playVideo = function(){
					try {	$player.sendEvent('PLAY'); } catch(err) { }
				}
				// start player after it is hopefully in the dom
				setTimeout($playVideo, 500);
			});
		});
	}

	/* referenzliste */
	var $referenzen = $('body.layout4 #content > .csc-default > .csc-header');
	if($referenzen.length)
	{
		$('#content').append('<div id="pagerContainer">');

		var $perlist = 18;
		for(var $i = 1; $i <= Math.ceil($referenzen.length / $perlist); $i++)
		{
			var $list = $('<ul class="referenzListe" />');
			$referenzen.slice(($i-1)*$perlist, $i*$perlist).each(function(){

				var $this = $(this);
				var $name = $this.children();
				var $text = $this.next('.csc-textpic-text').clone().add($(this).next('.csc-textpic').find('.csc-textpic-text').clone());
				var $img = $this.next('.csc-textpic').clone().find('dt img');
				var $img_sidebar = $('<div class="referenzBild">').hide().css({backgroundImage:'url(' + $img.attr('src') + ')'});

				$this.next('.csc-textpic-text, .csc-textpic').remove();
				$this.closest('.csc-default').remove();

				var $li = $('<li />');
				$li.append($name);
				$name.wrap('<nobr></nobr>');
				//$li.append($img);
				if($text.text() || $img.length)
				{
					$('#sidebar_left').append($img_sidebar);
					$li.hover(function(){
							$img_sidebar.siblings().stop().fadeOut(50);
							$img_sidebar.fadeIn(300).fadeTo(100, 1);
						},function(){
							$img_sidebar.stop().fadeOut(500);
						}
					);
				}
				if($name.find('a').length)
					$li.addClass('active');

				$list.append($li);
				// next page
				if($i > 2)
					$list.hide();

				$list.attr('page', Math.ceil($i/2));
			});

			$('#pagerContainer').append($list);
		}

		// Scroll Arrows
		var $listen = $('body.layout4 #content .referenzListe');
		if($listen.length > 2)
		{
			var updateScrollArrows = function()
			{
				var $nextPage = $('#pagerContainer [page='+($currentPage+1)+']');
				var $prevPage = $('#pagerContainer [page='+($currentPage-1)+']');
				if(!$nextPage.length) $scrollerDown.hide(200); else $scrollerDown.show(200);
				if(!$prevPage.length) $scrollerUp.hide(200);   else $scrollerUp.show(200);
			}
			var $currentPage = 1;
			var $scrollerDown = $('<a href="#down" id="scrollerDown"></a>');
			var $scrollerUp   = $('<a href="#up" id="scrollerUp"></a>');
			$('#page_menu').append($scrollerDown.hide()).append($scrollerUp.hide());

			$scrollerDown.click(function(){
				var $nextPage = $('#pagerContainer [page='+($currentPage+1)+']');
				var $currPage = $('#pagerContainer [page='+$currentPage+']');
				if($nextPage.length)
				{
					//$currPage.stop().slideUp(150, function(){ $nextPage.fadeIn(150); });
					$currPage.hide(); $nextPage.show();
					$currentPage++;
					updateScrollArrows();
				}
				return false;
			});
			$scrollerUp.click(function(){
				var $nextPage = $('#pagerContainer [page='+($currentPage-1)+']');
				var $currPage = $('#pagerContainer [page='+$currentPage+']');
				if($nextPage.length)
				{
					//$currPage.stop().fadeOut(150, function(){ $nextPage.slideDown(150); });
					$currPage.hide(); $nextPage.show();
					$currentPage--;
					updateScrollArrows();
				}
				return false;
			});

			updateScrollArrows();
		}
	}




	/* Ticker */
	$('#tickertext').each(function(){
		var $ticker = $(this);

		var $scrollCont = $('<span></span>').css({ whiteSpace:'nowrap', width:'auto' });
		$scrollCont.html( $ticker.html() + $ticker.html() + $ticker.html() + $ticker.html() + $ticker.html() + $ticker.html() + $ticker.html() + $ticker.html() + $ticker.html() + $ticker.html() + $ticker.html() + $ticker.html() );

		$ticker.empty().append($scrollCont);

		var $scrollFunc1 = function(){ $ticker.animate({scrollLeft: $scrollCont.width() - $ticker.width() }, $scrollCont.width()*40, "linear", function() { $scrollFunc2(); }) };
		var $scrollFunc2 = function(){ $ticker.animate({scrollLeft: 0}, 0, "linear", function() { $scrollFunc1(); }) };

		$scrollFunc1();
	});
});


function playerReady(obj)
{
	player = document.getElementsByName(obj.id)[0];
	//console.log(obj.id);
	//console.log('PLAYPAUSE');
	player.sendEvent('PLAYPAUSE');
};
