/**
 * @author RMachel
 */

var HTTP_GET_VARS = new Array();

$(document).ready(function() {

	// Media Overview
	if($('div.mediaOverview').length>0)
	{ 
		initSplash();
	}


	// View Switch Hover
	if($('div.viewSwitch').length>0)
	{
		$("div.viewSwitch a img").mouseover(function() {
			src = $(this).attr("src").replace("aktiv","inaktiv");
			$(this).attr("src",src);
		});

		$("div.viewSwitch a img").mouseout(function() {
			src = $(this).attr("src").replace("inaktiv","aktiv");
			$(this).attr("src",src);
		});
	}
	
	// View Switch Hover
	if($('table.medialist').length>0)
	{
		$("table.medialist th a img").mouseover(function() {
			src = $(this).attr("src").replace("Selected","Deselected");
			$(this).attr("src",src);
		});

		$("table.medialist th a img").mouseout(function() {
			src = $(this).attr("src").replace("Deselected","Selected");
			$(this).attr("src",src);
		});
	}

	// Image List
	if($('div.imageList').length>0)
	{
		// parse Get Parameters
		parseGetParameters();
		
		var activeImgID = 0;
		var imgSum = $(".imageList ul li").length;
		var imgArray = new Array();

		if (GET('item')!="undefined" && GET('item')!=1 && GET('item')!=0) activeImgID = parseInt(GET('item')-1); 
		
		$(".imageView .passepartout a").removeClass("hidden");
		
		$(".imageView a.prev").hide(); // hide prev button
		$(".imageList ul li:last").css("padding-right","5px");

		/* Build Image Array from Mediathek Carousel */
		$(".imageList .passepartout img").each(function(i){
			
			var curImg = $(this);
			var imgSrc = $(this).attr('src');
			//var imgAlt = $(this).parent().parent().text();
			var imgAlt = $(this).attr('alt');
			var imgCopyright = $(this).parent().parent().text();
			var imgTitle = $(this).parent().attr('title');
			
			imgArray[i] = new Array();
			imgArray[i]["src"] = imgSrc;
			imgArray[i]["alt"] = imgAlt;
			imgArray[i]["title"] = imgTitle;
			imgArray[i]["copyright"] = imgCopyright;
			imgArray[i]["jQueryRef"] = $(this);
			
			$(this).parent().click(function(){
				activeImgID = i;
				//determine image format
				var imgFormat = getFormat(imgArray[i]["jQueryRef"]);
				swapImage(i,imgSrc,imgAlt,imgTitle,imgCopyright,imgSum,imgFormat);
				return false;
			})
		});
		
		/* Arrow Navigation */
		$(".imageView a.prev").click(function(){
			
			if(activeImgID==0) return false;

			activeImgID--;
			//determine image format
			var imgFormat = getFormat(imgArray[activeImgID]["jQueryRef"]);
			swapImage(activeImgID,imgArray[activeImgID]["src"],imgArray[activeImgID]["alt"],imgArray[activeImgID]["title"],imgArray[activeImgID]["copyright"],imgSum,imgFormat);
			return false;
		});

		$(".imageView a.next").click(function(){

			if(activeImgID>=(imgSum-1)) return false;

			activeImgID++;
			//determine image format
			var imgFormat = getFormat(imgArray[activeImgID]["jQueryRef"]);
			swapImage(activeImgID,imgArray[activeImgID]["src"],imgArray[activeImgID]["alt"],imgArray[activeImgID]["title"],imgArray[activeImgID]["copyright"],imgSum,imgFormat);
			return false;
		});


		/* Zoom/Lightbox Button */
		$('.imageView span.bu a').click(function(){
			//call lightbox			
			return false;
		});
		
		$(window).bind('load', function() { //bind this to onLoad event due to images not fully loaded
			//determine image format
			var imgFormat = getFormat(imgArray[activeImgID]["jQueryRef"]);
			swapImage(activeImgID,imgArray[activeImgID]["src"],imgArray[activeImgID]["alt"],imgArray[activeImgID]["title"],imgArray[activeImgID]["copyright"],imgSum,imgFormat);
			// check id for display of buttons
			if (activeImgID!=1) {
				updateArrowBtns(activeImgID,imgSum);
			}
		});

	}

	// Media Overview
	if($('#mediathekCarousel').length>0)
	{
		/* Init JCarousel for Mediathek */
	    $('#mediathekCarousel').jcarousel({
			scroll: 5
	    });
	}
	
	
	/* Thickbox-Links auf Dokumente durch Links auf Bilder ersetzen */ 
	if( $('.imageView.single').length > 0  ) {
		var linkTag = $('.imageView.single .passepartout a.thickbox');
		var imgSrc = linkTag.find('img').attr('src');
		var linkHref = linkTag.attr('href');
		var daLength = linkHref.length;
		var copyrightText = $('.imageView.single span.bu').text();
		if(linkHref.substring(daLength-5,daLength) == '.html') {
			var newImgSrc = imgSrc.replace(',lead=width,templateId=scale,width=320','');
			linkTag.attr('href', newImgSrc);
			linkTag.attr('alt', copyrightText);
			$('.imageView.single a.thickbox.zoom').attr('href', newImgSrc);
			$('.imageView.single a.thickbox.zoom').attr('alt', copyrightText);
		}
	}
});



/**
 * Functions
 */


function initSplash(){
	
	// Insert HTML for Image Splash Box
	$('<div id="mediaSplash" class="mediathek"><div class="wrap"><div class="centering"><div class="passepartout"><span></span><img src="" width="188" alt="" title="" /></div></div><p>&nbsp;</p></div></div>').insertAfter($('#body'));
	
	// Set easier Identifiers
	var base = $('div.mediaOverview');
	var splash = $('#mediaSplash');
	
	// Set size,positions for Container and Splash into static variables
	var dimensions = new Array();
	dimensions['height'] = base.innerHeight();
	dimensions['width'] = base.innerWidth();
	dimensions['left'] = base.offset().left;
	dimensions['top'] = base.offset().top;
	dimensions['splashHeight'] = splash.height();
	dimensions['splashWidth'] = splash.width();
	dimensions['splashInnerHeight'] = splash.innerHeight();
	dimensions['splashInnerWidth'] = splash.innerWidth();
	
	// Set margin, tween time
	var windowOpen = false;
	var margin = 8;
	var tweenInTime = 0;
	var tweenOutTime = 10;

	$('.mediaOverview .articleTeaser').hover(function(){

		// recalculate height, no height on images cause of passepartout gives height without images in safari and chrome
		dimensions['height'] = base.innerHeight();
		
		// get and set image and text in splash screen
		var boxLink = $(this).find(".artikeltext h3 a").attr("href"); //get Link
		var imgSrc = $(this).find(".artikelimg img").attr("src"); //get Image Source
		imgSrc = imgSrc.replace(",width=116","");
		imgSrc = imgSrc.replace(",templateId=scale","");
		var imgParaShort = $(this).find(".artikeltext h3").html(); // get short Text
		imgParaShort = imgParaShort.replace(new RegExp("\\n","g"), ""); // strip line breaks
		
		var imgParaLong = $(this).find(".artikelimg img").attr("title"); // get long Text
		imgParaLong = imgParaShort.replace(/(<a href=".*?"><img src=".*?" alt=".*?">).*?(<\/a>)/img, "$1"+imgParaLong+"$2"); // swap short text with long text without touching the image or the link
		
		var imgWidth = 188;
		//if(getFormat($(this).find(".artikelimg img").height(),$(this).find(".artikelimg img").width()) == "portrait") imgWidth = 145;
		if(getFormat($(this).find(".artikelimg img")) == "portrait") imgWidth = 145;

		$("#mediaSplash").click(function(){
			window.location.href = boxLink;
		});
		$("#mediaSplash img").attr("src",imgSrc);
		$("#mediaSplash img").attr("width",imgWidth);
		
		// set text
		$("#mediaSplash p").html(imgParaLong);

	 
		// calculate offset
		var offset = $(this).offset();
		offset.top = Math.round(offset.top	- (dimensions['splashHeight']-$(this).height())/2);
		offset.left = Math.round(offset.left - (dimensions['splashWidth']-$(this).width())/2);

		// check if offset is still in container, otherwise set to container bounds
		if(offset.top <= dimensions['top']) offset.top = dimensions['top']+margin;
		else if((offset.top+dimensions['splashInnerHeight']) >= (dimensions['top']+dimensions['height'])) offset.top = dimensions['top']+dimensions['height']-dimensions['splashInnerHeight']-margin;
		
		if(offset.left <= dimensions['left']) offset.left = dimensions['left']+(margin/2);
		else if((offset.left+dimensions['splashInnerWidth']) >= (dimensions['left']+dimensions['width'])) offset.left = dimensions['left']+dimensions['width']-dimensions['splashInnerWidth']-margin;
		
		// position and show splash screen
		splash.css("top", (offset.top));
		splash.css("left", (offset.left));
		
	  	if(!windowOpen){
			splash.toggle();
			windowOpen = true;
		} 
	  
	},function(){
		return null;
	});
	
		
	$("body").mousemove(function(e)
	{
		if(windowOpen==true)
		{
			if( (e.pageX<=dimensions['left']) || (e.pageX>=(dimensions['left']+dimensions['width'])) || (e.pageY<=dimensions['top']) || (e.pageY>=(dimensions['top']+dimensions['height'])))
			{
			  splash.toggle();
			  windowOpen=false;
			}
		}
	});
		
}
	

function swapImage(id,imgSrc,imgAlt,imgTitle,imgCopyright,imgSum,imgFormat){
	
	var affImg = $('.imageView .passepartout img');
	var affImgTitle = $('.fotoGallery span.title');
	var affImgBU = $('.imageView span.bu');
	var affImgCount = $('.imageView span.count');
	var affZoomIcon = $('.imageView .buttons a.zoom'); // Zoom Icon
	var affZoomImg = $(".imageView .passepartout a:nth-child("+(id+1)+")");
	
	var affImgWidth = 320;
	if(imgFormat=="portrait") affImgWidth = 254;

	if(affImg) {
		
		//hide all images in imageView and display active one
		$(".imageView .passepartout a").hide();
		affZoomImg.show();
		
		//set size
		//affImg.attr("width",affImgWidth);
		affImgCount.text("Bild "+(id+1)+" von "+imgSum);
		affImgTitle.text(imgTitle);
		affImgBU.text(imgCopyright);
		
		cloneThickboxImage();
	}
	
	updateArrowBtns(id,imgSum);
	imageListHighlight(id);

	activeImgID = id;
}

function cloneThickboxImage(){

	var zoom = $('.imageView .buttons a.zoom');
	var zoomIconUrl = zoom.find("img").attr("src");
	
	var TBClone = $(".imageView .passepartout a:visible");
	
	$('.imageView .buttons a.zoom').replaceWith(TBClone.clone(true).addClass("zoom").removeClass("thickbox"));
	
	$('.imageView .buttons a.zoom').attr("title","Öffnet neues Fenster: 'Vergrößerung'");
	$('.imageView .buttons a.zoom img').attr("src",zoomIconUrl).attr("alt", "Bild vergrößern").removeAttr("width");
	
}

function updateArrowBtns(id,imgSum)
{
	if (id == 0) $(".imageView a.prev").hide();
	else $(".imageView a.prev").show();
	
	if(id>=(imgSum-1)) $(".imageView a.next").hide();
	else $(".imageView a.next").show();	
}

function getFormat(elm){
	var format = "landscape";
	var height = elm.height();
	var width = elm.width();

	if(width <= height) format = "portrait";

	return format; 
}

function imageListHighlight(id)
{
	$(".imageList .centering").removeClass("highlight");
	$(".imageList .centering").each(function(i){
		
		if(i==id) $(this).addClass("highlight");
	});
	return false;
}

function changeMediaIcon(text)
{
	return text.replace(".gif","_splash.gif");
}

function GET(v)
{
	if(!HTTP_GET_VARS[v]){return 'undefined';}
	return HTTP_GET_VARS[v];
}

function parseGetParameters()
{
	getString = document.location.search.substr(1, document.location.search.length);
	if (getString != '') {
		strArr = getString.split('&');
		for (i = 0; i < strArr.length; ++i) {
			value = '';
			valueArr = strArr[i].split('=');
			if (valueArr.length > 1) {
				value = valueArr[1];
			}
			HTTP_GET_VARS[unescape(valueArr[0])] = unescape(value);
		}
	}
}
