jQuery(function($) {
  
	var container = $("#product-slider");
	
	var timeoutOpen, timeoutClose;
	container.not(".open").hover(function() {
		if (timeoutClose) window.clearTimeout(timeoutClose);
		if (container.hasClass("open")) return;
		// Aufklappen
		timeoutOpen = window.setTimeout(function() {
			container.animate({height:200}).addClass("open");
		}, 500);
	}, function() {
		if (timeoutOpen) window.clearTimeout(timeoutOpen);
		/*
		if (!container.hasClass("open")) return;
		// Zuklappen
		timeoutClose = window.setTimeout(function() {
			container.animate({height:60}).removeClass("open");
		}, 1000);
		*/
	});

	var productList = $("ul", container);
	
	// Scrollbars aufsetzen
	var neededWidth = 100 * $("#product-slider li").length + parseInt(productList.css("padding-left")) + parseInt(productList.css("padding-right")),
		visibleArea = container.width();
	if (neededWidth < visibleArea) return; // ausreichende Breite vorhanden => kein Scrollbar
	
	productList.width(neededWidth);
	var maxScroll = -(neededWidth - visibleArea);
	
	// Scrollbar einbinden
	var scrollbar = $('<div class="scrollbar"></div>'),
		scrollhandle = $('<div class="scrollhandle"><div class="scrollhandle-left"></div><div class="scrollhandle-middle"></div><div class="scrollhandle-right"></div></div>'),
		scrollLeft = $('<div class="scroll-left"></div>'),
		scrollRight = $('<div class="scroll-right"></div>');
	
	container.append(scrollbar.append(scrollhandle)).append(scrollLeft).append(scrollRight);
	var scrollbarWidth = scrollbar.width(),
		scrollhandleWidth = scrollbarWidth * visibleArea/neededWidth,
		maxDrag = scrollbarWidth - scrollhandleWidth;
	scrollhandle.width(scrollhandleWidth);
	
	scrollhandle.bind("mousedown", function(e) {
		var currentX = parseInt(scrollhandle.css("margin-left")),
			startX = e.pageX + this.offsetLeft - currentX;
		
		
		var onDrag = function(e) {
			var targetX = e.pageX - startX + currentX;
			targetX = Math.max(0, Math.min(maxDrag, targetX));
			scrollhandle.css("margin-left", targetX);
			
			productList.css("margin-left", targetX/maxDrag * maxScroll);
			
			return false;
		};
		$(document.body).mousemove(onDrag);
		$(document.body).bind("mouseup", function() {
			$(document.body).unbind("mousemove", onDrag);
		});
		// Selektion abbrechen
		this.blur();
		return false;
	});
	
	
	var scrollBy = function(step) {
		var currentX = parseInt(scrollhandle.css("margin-left")),
			targetX = currentX + step;
		targetX = Math.max(0, Math.min(maxDrag, targetX));
		scrollhandle.css("margin-left", targetX);
		productList.css("margin-left", targetX/maxDrag * maxScroll);
	};
	
	var scrollInterval;
	scrollLeft.hover(function() {
		scrollInterval = window.setInterval(function() {
			scrollBy(-5);
		}, 50);
	}, function() {
		window.clearInterval(scrollInterval);
	});
	scrollRight.hover(function() {
		scrollInterval = window.setInterval(function() {
			scrollBy(5);
		}, 50);
	}, function() {
		window.clearInterval(scrollInterval);
	});
});
