
// jQuery selectors
var $window;
var $container;
var $objects;
var $overlayContainer;
var $overlays;
var $clickerContainer;
var $previous;
var $next;
var $sliderLine;
var $slider;
var $navigationArea;
var $navigation;
var $menu;
var $handle;
var $label;
var $branding;
var $info;
var $link;

// Variables
var windowWidth;
var containerWidth;
var objectCount;
var widths; // Image widths
var cumulativeWidths = [ 0 ]; // Cumulative image widths
var leftOffsets; // Position offsets for clicker and anchor
var position = 0; // Container position
var offset = 0; // Image offsets from the left edge of the canvas
var sliderPosition; // In pixels.
var sliderMax;
var previousSliderIndex;
var sliderFlipPosition;
var menuWidth;
var category;
var timeout;
var speed;
var labelMarginLeft;
var slideOffset = 3; // 1
var picIndex = 0; // current pic
var touchStart;
var touchEnd;

// Timers
var autoSlideTimeout;
var autoSlideInterval;

// Constants
var objectVisibleClassName = "visible";
var navigationDisallowHideClassName = "disallow";
var menuFlippedClassName = "flipped";
var labelFlippedClassName = "labelFlipped";
var containerBuffer = 512; // Buffer to avoid image wrap. Don't worry won't be visible since the slider won't allow it. :-)
var infoWidth = 432;
var navigationOffset = 61; // Value for the correct location of the slider position.
var ua;

function showImpressum() {
	$('#info').show();
	$('#navigation_mobile').hide();
	$('#info').css('width', '330px').css('height', window.innerHeight - 40).css('font-size','18px');
}

// define resize handler
$.fn.resizeHandler = function() {
	windowWidth = window.innerWidth; //$window.width();
	sliderFlipPosition = windowWidth - infoWidth;
	containerWidth = cumulativeWidths[objectCount] + containerBuffer;

	$.each(widths, function(i, width) {
		$objects.eq(i).css("width", width).css("left", cumulativeWidths[i]);
        $overlays.eq(i).css("width", width).css("left", cumulativeWidths[i]);
	});

	position = -cumulativeWidths[picIndex] + $.fn.calcImagePos();
	if (position > 0) {
		position = 0;
	}
	sliderMax = cumulativeWidths[objectCount] - windowWidth;
	if (position < -sliderMax) {
		position = -sliderMax;
	}

	$container.css("width", containerWidth).css("left", position);
    $overlayContainer.css("width", containerWidth).css("left", position);

	$slider.slider("destroy").append($navigation).css("width",
			windowWidth - infoWidth).slider( {
		animate : false,
		min : 0,
		value : -position,
		max : sliderMax,
		step : 1,
		slide : function(event, ui) {
			position = -ui.value;
			sliderPosition = event.pageX;
			$.fn.slideHandler();
		}
	});

	// Rebind
	$navigationArea.mouseenter(function() {
		$menu.show();
		$sliderLine.show();
		$slider.removeClass("hidden");
	}).mouseleave(function(event) {
		if (!$(event.relatedTarget).hasClass(navigationDisallowHideClassName)) {
			$menu.hide();
			$sliderLine.hide();
			$slider.addClass("hidden");
		}
	});

	$link.mousedown(function() {
		window.location.href = $(this).attr("href");
	});

	$navigation.mousedown(function(event) {
		$.fn.setOpacity(false);
	});

	$navigation.mouseup(function(event) {
		$.fn.setOpacity(true);
	});

	sliderPosition = $navigation.position().left + navigationOffset;

	return $container;
};

// define slide handler
$.fn.slideHandler = function(callback) {
	$container.css("left", position);
    $overlayContainer.css("left", position);

	for (var i = 0; (cumulativeWidths[i] + position) <= windowWidth; i++) {
		offset = cumulativeWidths[i] + position;
		var center = document.body.clientWidth / 2;
		if (offset < center && (offset + $objects.eq(i).innerWidth()) > center) {
			$.fn.setPicIndex(i);
			break;
		}
	}

	if ($menu.hasClass(menuFlippedClassName)
			&& (sliderPosition <= sliderFlipPosition)) {
		$menu.removeClass(menuFlippedClassName).css("margin-left", -2);
		$label.removeClass(labelFlippedClassName);
	} else if (!$menu.hasClass(menuFlippedClassName)
			&& (sliderPosition > sliderFlipPosition)) {
		$menu.addClass(menuFlippedClassName).css("margin-left", -	 - 1);
		$label.addClass(labelFlippedClassName);
	}

	if ($label.hasClass(labelFlippedClassName)) {
		$label.width(windowWidth - (windowWidth - sliderPosition));
		$label.css("margin-left", -$label.width());
	} else {
		$label.width(windowWidth - sliderPosition);
		if ($label.css("margin-left") != labelMarginLeft) {
			$label.css("margin-left", labelMarginLeft);
		}
	}

	if (callback != undefined) {
		callback();
	}

	return $container;
};

$.fn.showHandler = function() {
	$branding.css("visibility", "visible");
	$sliderLine.css("visibility", "visible");

	return $container;
}

$.fn.calculate = function(callback) {
	//alert(window.innerHeight + " : " + window.innerWidth);
	$.getJSON("index.php", {
		rq : "calculate",
		width : window.innerWidth, //$(window).width(),
		height : window.innerHeight, //$(window).height(),
		category : category
	}, function(data) {
		widths = data.widths;
		cumulativeWidths = data.cumulativeWidths;
		leftOffsets = data.leftOffsets;
		menuWidth = $menu.width();
		$.fn.resizeHandler();
		if (callback != null) {
			callback();
		}
	});
}

// sets opacity on all pics but the one with clickIndex
$.fn.setOpacity = function(value) {
    if (!$.browser.msie) {
        if (value) {
            for ( var i = 0; i < picIndex; i++) {
                $overlays.eq(i).show().fadeTo(0, 0.88);
            }
            $overlays.eq(picIndex).show().fadeTo(0, 0);
            for ( var i = picIndex + 1; i < $overlays.length; i++) {
                $overlays.eq(i).show().fadeTo(0, 0.88);
            }
        } else {
            for ( var i = 0; i < $overlays.length; i++) {
                $overlays.eq(i).show().fadeTo(0, 0);
            }
        }
    } else {
        //$overlays.hide();
        $clickerContainer.css("opacity", 0); // DON'T ASK.. IE NEEDS THAT   
        if (value) {
            for ( var i = 0; i < picIndex; i++) {
                $overlays.eq(i).css("filter", "alpha(opacity=88)");
            }
           $overlays.eq(picIndex).css("filter", "alpha(opacity=0)");
            for ( var i = picIndex + 1; i < $overlays.length; i++) {
                $overlays.eq(i).css("filter", "alpha(opacity=88)");
            }
        } else {
            for ( var i = 0; i < $overlays.length; i++) {
                $overlays.eq(i).css("filter", "alpha(opacity=0)");
            }
        }
        
    }
    
}

//calculate image position
$.fn.calcImagePos = function() {
	var pos = (document.body.clientWidth - $objects.eq(picIndex).innerWidth()) / 2;
	return pos;
}

//set mouse cursor
$.fn.setMouseCursor = function() {
	if (picIndex >= $objects.length - 1) {
		$previous.css("cursor", "url(../gfx/back.gif), w-resize");
		$next.css("cursor", "auto");
	} else if (picIndex == 0) {
		$previous.css("cursor", "auto");
		$next.css("cursor", "url(../gfx/forward.gif), e-resize");
	} else {
		$previous.css("cursor", "url(../gfx/back.gif), w-resize");
		$next.css("cursor", "url(../gfx/forward.gif), e-resize");
	}
}

//set pic index
$.fn.setPicIndex = function(index) {
	picIndex = index;
	$handle.empty().append(index + 1);
	//$label.empty().append('<h2>' + $objects.eq(index).attr("title") + '</h2>');
	if (!$.browser.msie) {
		window.location.hash = "#" + (index + 1);
	}
}

slide = function() {
	position = position - slideOffset;
	if (position < -sliderMax) {
		position = -sliderMax;
		clearInterval(autoSlideInterval);
	}
	$slider.slider("value", -position);
	sliderPosition = $navigation.position().left + navigationOffset;
	$.fn.slideHandler();
};

autoSlide = function() {
	autoSlideInterval = setInterval(slide, speed);
};

$(window).ready(function() {
	category = $(document).getUrlParam("category");
	if (category == null) {
		category = startcategory;
	}
	// Autoslide start timeout and speed
	timeout = $(document).getUrlParam("timeout");
	if (timeout <= 0) {
		timeout = 0; //5000
	}
	speed = $(document).getUrlParam("speed");
	if (speed <= 0) {
		speed = 25; //26
	}
	// Anchor
	if (window.location.hash != "") {
		picIndex = parseInt(window.location.hash.substr(1,
				window.location.hash.length - 1)) - 1;             
	}
	// Callback make sure that images are visible if the fading code was executed. Avoids pictures flashing onload
	$.fn.calculate(function() {
		$("div#imageContainer").children().css("visibility", "visible");
	});
}).resize(function() {
	clearTimeout(autoSlideTimeout);
	clearInterval(autoSlideInterval);
	//if (ua.search('ipad') != -1) {
	//	$.fn.resizeHandler();
	//} else {
		$.fn.calculate();
	//}
}).load(function() {
	$loader.fadeOut("slow");
});

$(function() {
	// jQuery Selectors
	$window = $(window);
	$container = $("div#imageContainer");
	$objects = $container.children();
	$overlayContainer = $("div#overlayContainer");
	$overlays = $overlayContainer.children();
	$clickerContainer = $("div#clickerContainer");
	$previous = $clickerContainer.children("div#previous");
	$next = $clickerContainer.children("div#next");
	$sliderLine = $("div#sliderLine");
	$slider = $("div#slider");
	$navigationArea = $("div.navigationArea");
	$navigation = $("div#navigation");
	$menu = $navigation.children("div.navigation");
	$handle = $navigation.children("div.handle");
	$loader = $("#loader");
	$label = $("div#label");
	$branding = $("div#branding");
	$info = $("div#info");
	$infoBranding = $("img#infoBranding");
	$link = $("a.link");
    
	// Event handlers
	$("a.mail").click(function(event) {
		event.preventDefault();
		var s = $(this).attr("href");
		var n = 0;
		var r = "";
		for ( var i = 0; i < s.length; i++) {
			n = s.charCodeAt(i);
			if (n >= 8364) {
				n = 128;
			}
			r += String.fromCharCode(n - 1);
		}
		window.location.href = r;
	});
	
	objectCount = $objects.length;
	labelMarginLeft = $label.css("margin-left");
	
	// get user agent
	ua = navigator.userAgent.toLowerCase();
	
	// check for smartphones
	iphone = (ua.search('iphone') != -1) ? true : false;
	ipod = (ua.search('ipod') != -1) ? true : false;
	ipad = (ua.search('ipad') != -1) ? true : false;
	android = (ua.search('android') != -1) ? true : false;
	opera_mobi = (ua.search('opera mobi') != -1) ? true : false;
	
	//console.log(ua);
	//alert(ua);
		
	if (iphone || ipod || ipad || android || opera_mobi) {
	
		//alert(window.innerHeight + " : " + window.innerWidth);
		
		$('div#clickerContainer div').remove();

		document.getElementById('clickerContainer').addEventListener('touchstart', function(event) {
			//alert(event.touches[0].screenX);
			event.preventDefault();
			touchStart = event.touches[0].screenX;
			//alert('touchStart');
			$info.hide();
			$menu.hide();
		}, false);
		
		/*
		document.getElementById('previous').addEventListener('touchstart', function(event) {
			event.preventDefault();
			touchStart = event.touches[0].screenX;
			//alert(touchStart);
		}, false);
		*/
		
				
		window.addEventListener('touchend', function(event) {
			event.preventDefault();
			//alert('touchEnd');
			//alert(touchStart + ":" + touchEnd);
			clearTimeout(autoSlideTimeout);
			clearInterval(autoSlideInterval);
			if (touchEnd < touchStart) {
				if (picIndex < (objectCount - 1)) {
					position = -cumulativeWidths[++picIndex] + $.fn.calcImagePos();
					if (position < -sliderMax) {
						position = -sliderMax;
					}
					$container.css("left", position);
					$overlayContainer.css("left", position);
					$.fn.setPicIndex(picIndex);
		
					$slider.slider("value", -position);
					sliderPosition = $navigation.position().left + navigationOffset;
					if ($.browser.msie) {
						window.location.hash = "#" + picIndex;
					}
				}
			} else {
				if (picIndex > 0) {
					position = -cumulativeWidths[--picIndex] + $.fn.calcImagePos();
					if (position > 0) {
						position = 0;
					}
					$container.css("left", position);
					$overlayContainer.css("left", position);
					$.fn.setPicIndex(picIndex);
		
					$slider.slider("value", -position);
					sliderPosition = $navigation.position().left + navigationOffset;
					if ($.browser.msie) {
						window.location.hash = "#" + picIndex;
					}
				}
			}
			$.fn.setOpacity(true);
			$.fn.setMouseCursor();
		}, false);
	
		window.addEventListener('touchmove', function(event) {
			event.preventDefault();
			touchEnd = event.touches[0].screenX;
	    	//alert('touchmove');
		}, false);
		
		$info.hide();
		$slider.hide();
		$sliderLine.hide();
		$navigation.hide();
		$navigationArea.hide();
		
		$menu = $('#navigation_mobile');
		$menu.css("opacity", 0.75);
		
		$info.css('padding','20px');
		$info.css('opacity',0.75);
		$info.css('width','200px');
		$info.css('height','320px');
		
		$branding.click(function() {
			$menu.show();
		});
					
		if (category == startcategory) {
	        autoSlideTimeout = setTimeout(autoSlide, timeout); // start auto slide when in start category
			$.fn.setOpacity(false); 
			$menu.show(); // show menu at startup
		} else {
			$.fn.setOpacity(true);
			$menu.hide();
		}
		
	} else {
	
		$('#navigation_mobile').hide();

		$branding.hover(function() {
			$info.fadeIn();
			$infoBranding.fadeIn();
		}, function(event) {
			if (!$(event.relatedTarget).is("div#info")
					&& !$(event.relatedTarget).is("div#info *")
					&& !$(event.relatedTarget).is("img#infoBranding")) {
				$info.fadeOut();
				$infoBranding.fadeOut();
			}
		});
	
		$info.css("opacity", 0.75).mouseleave(
				function(event) {
					if (!$(event.relatedTarget).is("div#info *")
							&& !$(event.relatedTarget).is("img#infoBranding")) {
						$info.fadeOut();
						$infoBranding.fadeOut();
					}
				});
	
		$infoBranding.mouseleave(function(event) {
			if (!$(event.relatedTarget).is("div#info")
					&& !$(event.relatedTarget).is("div#info *")) {
				$info.fadeOut();
				$infoBranding.fadeOut();
			}
		});
	
		
			
		// Clicker handlers
		$clickerContainer.click(function() {
			$.fn.setOpacity(true);
			$.fn.setMouseCursor();
		});
	
		$previous.click(function() {
			clearTimeout(autoSlideTimeout);
			clearInterval(autoSlideInterval);
			if (picIndex > 0) {
				position = -cumulativeWidths[--picIndex] + $.fn.calcImagePos();
				if (position > 0) {
					position = 0;
				}
	
				//$.fn.slideHandler(); // We actually just need the sliderIndex calculation.. kinda performance hog
				$container.css("left", position);
				$overlayContainer.css("left", position);
				$.fn.setPicIndex(picIndex);
	
				$slider.slider("value", -position);
				sliderPosition = $navigation.position().left + navigationOffset;
				//$.fn.slideHandler();
				if ($.browser.msie) {
					window.location.hash = "#" + picIndex;
				}
			}
		});
	
		$next.click(function() {
			clearTimeout(autoSlideTimeout);
			clearInterval(autoSlideInterval);
			if (picIndex < (objectCount - 1)) {
				position = -cumulativeWidths[++picIndex] + $.fn.calcImagePos();
				if (position < -sliderMax) {
					position = -sliderMax;
				}
	
				//$.fn.slideHandler(); // We actually just need the sliderIndex calculation.. kinda performance hog
				$container.css("left", position);
				$overlayContainer.css("left", position);
				$.fn.setPicIndex(picIndex);
	
				$slider.slider("value", -position);
				sliderPosition = $navigation.position().left + navigationOffset;
				//$.fn.slideHandler();
				if ($.browser.msie) {
					window.location.hash = "#" + picIndex;
				}
			}
		});
	
		$navigationArea.mouseenter(function() {
			$menu.show();
			$sliderLine.show();
			$slider.removeClass("hidden");
		}).mouseleave(function(event) {
			if (!$(event.relatedTarget).hasClass(navigationDisallowHideClassName)) {
				$menu.hide();
				$sliderLine.hide();
				$slider.addClass("hidden");
			}
		});
	
		$navigation.mouseleave(function(event) {
			if (!$(event.relatedTarget).hasClass(navigationDisallowHideClassName)) {
				$menu.hide();
				$sliderLine.hide();
				$slider.addClass("hidden");
			}
		});
	
		$navigation.mousedown(function(event) {
			$.fn.setOpacity(false);
		});
	
		$navigation.mouseup(function(event) {
			clearTimeout(autoSlideTimeout);
			clearInterval(autoSlideInterval);
			$.fn.setOpacity(true);
		});
		
		if (category == startcategory) {
	        autoSlideTimeout = setTimeout(autoSlide, timeout); // start auto slide when in start category
			$.fn.setOpacity(false); 
			$menu.show(); // show menu at startup
			$sliderLine.show();
			$slider.removeClass("hidden");
		} else {
			$.fn.setMouseCursor();
			$.fn.setOpacity(true);
		}

	}
	
	$link.mousedown(function() {
		window.location.href = $(this).attr("href");
	});
     	
    $.fn.setPicIndex(picIndex); // set inital pic index
    
});

