// Copyright 2008 glutrot GmbH

var pictureFrame = null;
var pictureCount = 0;
var pictureCurrent = 0;
var pictureZoomFader = null;
var pictureZoomContainer = null;
var pictureZoomCloseCounter = 0;
var pictureZoomClosed = true;

var picturesLoaded = 0;

var sgFlash = null;
var sgActiveFlashData = null;
var sgCurrentZoomedIndex = -1;
var sgThumbsLoaded = false;

function sgSetScrollArrowActive(arrow, state) {
	var elem = $("img#"+arrow+"arrow");
	if (elem.length == 0) return;
	
	var url = "/images/system/arrow_"+arrow;
	if (!state) url += "_inactive";
	url += ".gif";
	
	elem.attr("src", url);
}

function sgImagesOutsideRightBoundary(pictureLeftMost) {
	var remainingContent = 0;
	
	if (pictureLeftMost>0) {
		remainingContent += parseInt($("img#pic"+String(pictureLeftMost), pictureFrame).css('margin-right').replace('px',''));
	}
	
	for (var i=pictureLeftMost; i<pictureCount; i++) {
		var elem = $("img#pic"+String(i), pictureFrame);
		remainingContent += elem.width();
		remainingContent += parseInt(elem.css('margin-left').replace('px',''));
		if (i<(pictureCount-1)) {
			remainingContent += parseInt(elem.css('margin-right').replace('px',''));
		}
	}
	var visibleWidth = parseInt($("#outerpictureframe").css('width').replace('px',''));
	return (visibleWidth < remainingContent);
}

function sgThumbsFinishedLoading() {
	sgThumbsLoaded = true;
	sgSetScrollArrowActive('right', sgImagesOutsideRightBoundary(pictureCurrent));
	$('#pictureframeoverlay').animate( {'opacity': 0}, 750, 'swing', function(){	$(this).remove();	});
	
	sgPreloadFullImages();
}

function sgThumbLoaded() {
	picturesLoaded++;
	
	if ((pictureFrame != null) && (picturesLoaded >= pictureCount)) {
		// init was faster than loading
		sgThumbsFinishedLoading();
	}
}

function sgZoomContainerFS() {
	// resize container and fader full screen
	
	if (pictureZoomClosed) return; // don't resize if closed
	
	var windowWidth = 0;
	var windowHeight = 0;
	
	if ($.browser.msie) {
		windowWidth  = window.document.documentElement.clientWidth;
		windowHeight = window.document.documentElement.clientHeight;
		if (!windowWidth) {
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}
	} else {
		windowWidth  = window.innerWidth;
		windowHeight = window.innerHeight;
	}
	
	faderHeight = windowHeight;
	var minFaderHeight = $('#header').height() + $('#contentcontainer').height() + $('#fuss').height()
	if (faderHeight < minFaderHeight) {
		faderHeight = minFaderHeight;
	}
	
	faderWidth = windowWidth;
	var minFaderWidth = 1220; // FIXME: seems to be browser-specific; IE6: 1220px
	if (faderWidth < minFaderWidth) {
		faderWidth = minFaderWidth;
	}
	
	/*
	pictureZoomFader.css('width', windowWidth);
	pictureZoomFader.css('height', windowHeight);
	*/
	pictureZoomFader.css('width', faderWidth);
	pictureZoomFader.css('height', faderHeight);
	pictureZoomContainer.css('width', windowWidth);
	pictureZoomContainer.css('height', windowHeight);
	
	var flashContainer = $('#sgFlashContainer');
	if (flashContainer.length>0) {
		// we need to remove any header flash before we can embed the new SWF
		// else we get painting errors from Flash plugin
		// added for use outside gallery
		if ($('#headflash').length > 0) {
			$('#headflash').before('<div id="headimg" style="width: 538px; height: 138px; background-color: white;"></div>');
			swfobject.removeSWF('headflash');
			
		}
		
		// center flash
		var posx = (windowWidth - $('#sgFullImage').width()) / 2;
		//var posy = (windowHeight - $('#sgFullImage').height()) / 2;
		var posy = 80;
		
		var flashposx = posx + parseInt(sgActiveFlashData['x']);
		var flashposy = posy + parseInt(sgActiveFlashData['y']);
		
		flashContainer.css('top', String(Math.round(flashposy))+'px');
		flashContainer.css('left', String(Math.round(flashposx))+'px');
		
		var flashNotice = $('#sgFlashNotice');
		if (flashNotice.length>0) {
			flashNotice.css('position','absolute');
			flashNotice.css('top', String(Math.round(posy + $('#sgFullImage').height()))+'px');
			flashNotice.css('left', String(Math.round(posx))+'px');
			flashNotice.css('width', String(Math.round($('#sgFullImage').width()))+'px');
			flashNotice.fadeIn(750);
		}
	}
}

function sgZoomCloseCounter() {
	pictureZoomCloseCounter++;
	if (pictureZoomCloseCounter>=2) {
		pictureZoomCloseCounter = 0;
		pictureZoomClosed = true;
		pictureZoomFader.css('width', '0px');
		pictureZoomFader.css('height', '0px');
		pictureZoomContainer.css('width', '0px');
		pictureZoomContainer.css('height', '0px');
		
		swfobject.removeSWF('sgFlashMovie');
		$('*',pictureZoomContainer).remove();
		$('#sgFlashContainer').css('display','none');
		$('#sgFlashContainer').remove();
		
		// we need to reactivate any previously removed flash header
		// added for use outside gallery
		activateFlashHeader();
	}
}

function sgZoomOff() {
	pictureZoomFader.animate( {'opacity': 0}, 750, 'swing', sgZoomCloseCounter);
	pictureZoomContainer.animate( {'opacity': 0}, 750, 'swing', sgZoomCloseCounter);
}

function sgZoom() {
	sgZoomReal(this);
	return false;
}

function sgZoomReal(obj) {
	var fullID = $(obj).attr('name').replace('fullpicid','');
	var arrayIndex = $(obj).attr('id').replace('pic','');
	
	if ((fullID == '') || (fullID == '0')) return;

	sgCurrentZoomedIndex = parseInt(arrayIndex); // remember array index for zoom controls
	
	if (pictureZoomContainer == null) {
		$("body").append('<div id="sgZoomFader" style="position: absolute; left: 0px; top: 0px; background-color: black; overflow: hidden; z-index: 998; display: none;">&nbsp;</div>');
		$("body").append('<div id="sgZoomContainer" style="position: absolute; left: 0px; top: 0px; overflow: hidden; z-index: 999; display:none; overflow: visible;">&nbsp;</div>');
		pictureZoomFader = $('#sgZoomFader');
		pictureZoomContainer = $('#sgZoomContainer');
		pictureZoomFader.css('opacity',0);
		pictureZoomContainer.css('opacity',0);
		pictureZoomFader.css('display','block');
		pictureZoomContainer.css('display','block');
		$(window).resize(sgZoomContainerFS);
	}
	
	if (pictureZoomClosed) {
		// only fade if not already open
		pictureZoomFader.animate( {'opacity': 0.75}, 750);
		pictureZoomContainer.animate( {'opacity': 1}, 750);
	}
	pictureZoomClosed = false;
	sgZoomContainerFS();
	
	pictureZoomContainer.html('<img src="/innolino/image.php?id='+fullID+'" style="margin-top: 80px;" id="sgFullImage" /><img src="/images/system/close.gif" class="closeButton" style="cursor: pointer;" onclick="sgZoomOff();" />');
	
	// handle flash movies
	if (typeof sgFlash[arrayIndex] != 'undefined') {
		sgActiveFlashData = sgFlash[arrayIndex];
		
		$('#sgFullImage').load(function(){
			if ($('div#sgFlashContainer').length == 0) {
				pictureZoomContainer.append('<div id="sgFlashContainer"><div id="sgFlashTemp"></div></div>');
			}
			
			flashURL = '/innolino/datei.php?id='+sgActiveFlashData['flash'];
			if ((typeof sgActiveFlashData['alternative_path'] != 'undefined') && (sgActiveFlashData['alternative_path'] != '')) {
				flashURL = sgActiveFlashData['alternative_path'];
			}
			
			var flashvars = {/*
			  name1: "hello",
			  name2: "world",
			  name3: "foobar"*/
			};
			
			var params = {/*
			  menu: "false"*/
			  wmode: "window"
			};
			
			var attributes = {
			  id: "sgFlashMovie" /*,
			  name: "myDynamicContent"*/
			};
			
			if (swfobject.getFlashPlayerVersion().major <= 0) {
				// no player installed
				pictureZoomContainer.append('<div id="sgFlashNotice" style="display: none;">Der Flash-Film kann nicht abgespielt werden, da Sie den <a href="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" target="_blank">Adobe Flash Player</a> nicht installiert oder deaktiviert haben.</div>');
			} else if (!swfobject.hasFlashPlayerVersion(sgActiveFlashData['player_version'])) {
				// player too old
				pictureZoomContainer.append('<div id="sgFlashNotice" style="display: none;">Die installierte Version des <a href="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" target="_blank">Adobe Flash Player</a> ist zu alt um diesen Film darzustellen.</div>');
			}
			swfobject.embedSWF(flashURL, "sgFlashTemp", sgActiveFlashData['width'], sgActiveFlashData['height'], sgActiveFlashData['player_version'],"/additions/swfobject/expressInstall.swf", flashvars, params, attributes);
			
			flashContainer = $('#sgFlashContainer');
			flashContainer.css('position', 'absolute');
			flashContainer.css('z-index', '999');
			
			sgZoomContainerFS();
		});
	}
	
	// buttons for next/previous item
	if ($('#sgZoomedSelectionControls').length==0) {
		pictureZoomContainer.prepend('<div id="sgZoomedSelectionControls"><img src="/images/system/arrow_left_inactive.gif" id="sgZoomedPrev" /><img src="/images/system/arrow_right_inactive.gif" id="sgZoomedNext" /></div>');
		
		$('#sgZoomedNext').click(sgZoomControls);
		$('#sgZoomedPrev').click(sgZoomControls);
		
		$('#sgZoomedSelectionControls img').mouseover(function(){$(this).css("cursor","pointer");});
		$('#sgZoomedSelectionControls img').mouseout(function(){$(this).css("cursor","default");});
	}
	sgZoomControlsUpdate();
}

function sgZoomControls() {
	if (sgCurrentZoomedIndex<0) return; // assert correct initialization
	
	var goForth = false;
	var goBack = false;
	
	var myID = $(this).attr('id');
	var mode = myID.substr(myID.length-4);
	
	if (mode=='Prev') {
		goBack = true;
	} else if (mode=='Next') {
		goForth = true;
	} else {
		// unsupported control
		return;
	}
	
	var newItem = sgTraverseFullID($('img#pic'+String(sgCurrentZoomedIndex), pictureFrame), goBack);
	if (newItem.preview == null) return; // no result found
	
	sgZoomReal(newItem.preview);
}

function sgZoomControlsUpdate() {
	// back button
	var newItem = sgTraverseFullID($('img#pic'+String(sgCurrentZoomedIndex), pictureFrame), true);
	var canGoBack = (newItem.preview != null);
	$('#sgZoomedPrev').attr('src', '/images/system/arrow_left'+(canGoBack ? '' : '_inactive')+'.gif');
	
	// next button
	newItem = sgTraverseFullID($('img#pic'+String(sgCurrentZoomedIndex), pictureFrame), false);
	var canGoForth = (newItem.preview != null);
	$('#sgZoomedNext').attr('src', '/images/system/arrow_right'+(canGoForth ? '' : '_inactive')+'.gif');
	
	// show or hide controls?
	if (canGoForth || canGoBack) {
		$('#sgZoomedSelectionControls').css('visibility','visible');
	} else {
		$('#sgZoomedSelectionControls').css('visibility','hidden');
	}
}

function sgTraverseFullID(origin, goBack) {
	var output = new Object();
	output.fullID = '';
	output.preview = null;
	
	var newPreview = origin;
	var newFullID = '';
	
	while (newFullID=='') {
		if (goBack) {
			newPreview = newPreview.prev();
		} else {
			newPreview = newPreview.next();
		}
		
		if (newPreview.length==0) return output; // out of items
		
		newFullID = newPreview.attr('name').replace('fullpicid','');
	};
	
	output.fullID = newFullID;
	output.preview = newPreview;
	
	return output;
}

function sgThumbOverlayShowSpinner() {
	if (sgThumbsLoaded) return; // no need to show spinner, thumbs finished loading earlier
	
	$('#pictureframeoverlay').css('background-position','center center');
	$('#pictureframeoverlay').css('background-repeat','no-repeat');
	$('#pictureframeoverlay').css('background-image','url(\'/images/system/loader.gif\')');
}

function initSlidingGallery() {
	pictureFrame = $("#pictureframe");
	if (!pictureFrame.length || (!$("img",pictureFrame).length)) return; // skip if pictureframe was not found
	
	setTimeout(sgThumbOverlayShowSpinner, 1000);
	
	$("img", pictureFrame).each(function(){this.onload = sgThumbLoaded;});
	pictureCount = parseInt($("img:last", pictureFrame).attr("id").substr(3)) + 1;
	
	if (picturesLoaded>=pictureCount) {
		// loading was faster than init
		sgThumbsFinishedLoading();
	}
	
	$("img", pictureFrame).click(sgZoom);
	$("img", pictureFrame).mouseover(function(){
		var fullID = $(this).attr('name').replace('fullpicid','');
		if ((fullID == '') || (fullID == '0')) return;
		$(this).css("cursor","pointer");
	});
	$("img", pictureFrame).mouseout(function(){$(this).css("cursor","default");});
}

function initSlidingGalleryZoomLinksOnly() {
	zoomLinks = $(".sgzoomlink");
	if (!zoomLinks.length) return; // skip if no links to zoom were not found
	
	zoomLinks.click(sgZoom);
	zoomLinks.mouseover(function(){
		var fullID = $(this).attr('name').replace('fullpicid','');
		if ((fullID == '') || (fullID == '0')) return;
	});
}

function sgHorizontalScroll(direction) {
	if (direction == 'right') {
		pictureCurrent--;
	} else {
		if (!sgImagesOutsideRightBoundary(pictureCurrent)) {
			// no need to scroll because everything is visible - ignore click
			return;
		}
		
		pictureCurrent++;
	}
	
	if (pictureCurrent>=pictureCount) {
		pictureCurrent = pictureCount - 1;
		return;
	} else if (pictureCurrent<0) {
		pictureCurrent = 0;
		return;
	}
	
	var picturePosition = 0;
	for (var i=0; i<pictureCurrent; i++) {
		var elem = $("img#pic"+String(i), pictureFrame);
		picturePosition += elem.width();
		picturePosition += parseInt(elem.css('margin-left').replace('px',''));
		picturePosition += parseInt(elem.css('margin-right').replace('px',''));
	}
	
	pictureFrame.animate( { left: String(-picturePosition)+'px' }, 750, 'swing' );
	sgSetScrollArrowActive('right', sgImagesOutsideRightBoundary(pictureCurrent));
	sgSetScrollArrowActive('left',  pictureCurrent>0);
}

function sgPreloadFullImages() {
	// should only be called after thumbs have been loaded
	$('body').append('<div style="position:absolute; top:0px; left:-1000px;" id="sgPreloadContainer"></div>');
	var preloadContainer = $('#sgPreloadContainer');
	
	var fullID;
	for (var i=0; i<pictureCount; i++) {
		fullID = $("img#pic"+String(i), pictureFrame).attr('name').replace('fullpicid','');
		if (fullID!='') {
			preloadContainer.append('<img src="/innolino/image.php?id='+fullID+'" style="position:absolute;" />');
		}
	}
}

$(document).ready(initSlidingGallery);
$(document).ready(initSlidingGalleryZoomLinksOnly);
