// (C) noebl.com 2010

// globals PAGE, ITEM, CIRCLE_TYPES, IMAGE_REPLACEMENT_PRELOAD
// globals COLORS, PRODUCT_IMAGE_PATH, TOOLTIP_FILE on product detail pages

jQuery.extend( jQuery.easing,
{
	easeOutExpo: function (x, t, b, c, d) {
		return (t==d) ? b+c : c * (-Math.pow(Math.E, -10 * t/d) + 1) + b;
	}
});


(function($){
	var duration = 200;
    $.fn.extend({
        fadeOutCustom: function (callback) {
    		if ( ! $.isFunction(callback)) callback = $.noop;
            return this.each(function() {
            	$(this).animate({
            		opacity: 0
            	}, {duration: duration, complete: function(){$(this).css({display: 'none'}); callback();}});
            });  
        },
        fadeInCustom: function (callback) {
    		if ( ! $.isFunction(callback)) callback = $.noop;
            return this.each(function() {
            	$(this).show().animate({
            		opacity: 1
            	}, {duration: duration, complete: callback});
            });  
        },
        replace: function (newElement, callback) {
        	var self = $(this);
        	$(newElement).css({opacity: 0}).appendTo($(this).parent()).fadeInCustom(function () {
        		self.remove();
        	});
            return this;
        },
    	disableSelection: function() {
    		return this
    			.attr('unselectable', 'on')
    			.css('MozUserSelect', 'none')
    			.bind('selectstart', function() { return false; });
    	}
    });
}(jQuery));







function ProductDetailPage() {

	new ColorPicker();

	$('#image-container').hover(
		function() {
			$(this).find('.title').stop().fadeOutCustom();
		},
		function() {
			$(this).find('.title').stop().fadeInCustom();
		}
	);
}







function ColorPicker() {

	var spriteWidth = 300;
	var tooltipOffset = {x: 15, y: 25};
	var tooltipHeight = 20;
	var tooltipWidth = 171;
	
	var activateColors = function () {
		var colors = $('.color');
		colors.css({cursor: 'pointer'});
		colors.mouseover(function () {
			var nr = colors.index(this);
			new Preloader(image(nr));
			showThumb(nr);
		});
		colors.click(function () {
			var nr = colors.index(this);
			new Preloader(image(nr), function () {
				show(nr);
			});
		});
	};
	
	var activateTooltips = function () {
		new Preloader(TOOLTIP_FILE);
		var colors = $('.color');
		colors
			.hover(function(e) {
				var nr = colors.index(this);
				var tooltip = $('#tooltip');
				if ( ! tooltip.get(0)) {
					tooltip = $('<div/>', {
						id: 'tooltip',
						css: {
							position: 'absolute',
							overflow: 'hidden',
							height: tooltipHeight,
							width: tooltipWidth,
							top: e.pageY - tooltipOffset.y,
							left: e.pageX + tooltipOffset.x,
							zIndex: 100,
							display: 'none'
						}
					}).appendTo($('#wrapper'));
					$('<img/>', {
						src: TOOLTIP_FILE,
						css: {
							position: 'absolute'
						}
					}).appendTo(tooltip);
				}
				tooltip.find('img').css({top: - nr * tooltipHeight});
				tooltip.show();
			}, function() {
				$('#tooltip').hide();
			})
			.mousemove(function(e) {
				$('#tooltip').css({
					top: e.pageY - tooltipOffset.y,
					left: e.pageX + tooltipOffset.x
				});
			});
	};
	
	var showThumb = function (nr) {
		// Replace whole container instead of image to prevent IE7+8 overflow hidden bug
		oldImage = $('.sprite-container');
		newImage = oldImage.first().clone();
		newImage.find('img').removeClass().addClass('sprite'+nr);
		oldImage.replace(newImage);
	};
	
	var show = function (nr) {
		oldImage = $('#image-container img');
		newImage = oldImage.first().clone().attr({src: image(nr)});
		oldImage.replace(newImage);
	};
	
	var image = function (nr) {
		return PRODUCT_IMAGE_PATH+ITEM+'-'+COLORS[nr]+'.jpg';
	};
	
	activateColors();
	activateTooltips();
};





function Slider() {
	
	var slider = $('#slider');
	var slideContainer = $('#slide-container');
	var width = slideContainer.width();
	var duration = 2000;
	var numberOfImages;
	var sliderOffset = 0;
	var initialOffset = - 2 * width;
	
	var initialSetup = function () {
		$('#slide-container, #slide-container *').disableSelection();
		children = slider.children();
		numberOfImages = children.length;
		children.clone().appendTo(slider);
		slider.css({left: initialOffset});
		rearrangeItems();
	};
	
	var rearrangeItems = function () {
		sliderOffset = (parseInt(slider.css('left')) % width + width) % width;
		slider.children().each(function (i) {
			$(this).css({left: i * width});
		});
	};
	
	var activateButton = function () {
		slideContainer.find('.next')
			.css({display: 'block', zIndex: 2})
			.click(slide);
	};
	
	var slide = function () {
		slider.stop();
		slider.children(':first').detach().appendTo(slider);
		rearrangeItems();
		slider.css({left: initialOffset + width + sliderOffset}).animate({
			left: initialOffset
		}, {
			duration: duration,
			easing: 'easeOutExpo'
		});
	};
	
	initialSetup();
	activateButton();
	
}



function Scroller() {
	
	var duration = 60000;
	var scrollContainer = $('#scroll-container');
	var scroller;
	var scrollItems = scrollContainer.children();
	var width = scrollItems.eq(0).width();
	var self = this;
	
	var initialSetup = function () {
		scrollItems.clone().appendTo(scrollContainer);
		scrollContainer.children().wrapAll($('<div/>', {
			id: 'scroller',
			css: {
				position: 'absolute',
				left: 0,
				overflow: 'visible'
			}
		})).each(function (i) {
			$(this).css({left: i * width});
			for (var j in CIRCLE_TYPES) {
				if ($(this).hasClass(CIRCLE_TYPES[j])) {
					$(this).data('type', CIRCLE_TYPES[j]);
				};
			}
		});
		scroller = $('#scroller');
		scrollContainer.find('a').attr({tabIndex: -1}).css({outline: 'none'});
	};
	
	var activateSubtitles = function() {
		scrollContainer.find('.name').hide();
		scroller.children().hover(function (event, delegated) {
			$(this).find('.name').show();
			// Show corresponding circle (if event is not already delegated by circles, which would cause infinite loop)
			delegated || $('.circle.'+$(this).data('type')).trigger('mouseover', [true]);
		}, function (event, delegated) {
			$(this).find('.name').hide();
			// Hide corresponding circle
			delegated || $('.circle.'+$(this).data('type')).trigger('mouseout', [true]);
		});
	};
	
	this.scroll = function () {
		scroller.animate({
			left: - (width * scrollItems.length)
		}, {
			duration: duration,
			complete: function () {
				scroller.css({left: 0});
				self.scroll();
			},
			easing: 'linear'
		});
	};
	
	initialSetup();
	activateSubtitles();
	
}



function Preloader(urls, callback){

	var images = [];
	var howManyLoaded = 0;

	var loadedHandler = function () {
		howManyLoaded++;
		if (howManyLoaded == urls.length) callback();
	};

	if (typeof(urls) == 'string') urls = [urls];
	if ( ! $.isFunction(callback)) {
		callback = $.noop;
	}
	
	for (i = 0; i < urls.length; i++) {
		images[i] = $('<img/>').load(loadedHandler).attr('src', urls[i]);
	}
}


	
function Intro() {
	var intro = $('#intro').css({zIndex: 10});
	var black = intro.find('.frame:first');
	var frames;
	
	var getFrames = function () {
		return intro.find('.frame:not(":first")');
	};
	
	var start = function () {
		black.fadeOut(1000).delay(1000).fadeIn(1000, function () {
			frames = getFrames();
			frames.first().remove();
			if (frames.get(1)) {
				start();
			}
			else {
				end();
			}
		});
	};
	
	var end = function () {
		SCROLLER.scroll();
		// IE8 won't fade pngs inside containers, so apply fade to the images directly
		// Also, there seems to be a problem with $.fadeIn() in this context
		$('#scroll-container img').css({opacity: 0}).animate({opacity: 1}, 1000);
		$('#scroll-container').show();
		black.fadeOut(1000, function () {
			intro.remove();
			CIRCLES.initialSetup();
		});
	};
	
	frames = getFrames();
	frames.hide();
	$('#slide-container, #scroll-container').hide();
	black.show();
	new Preloader(black.attr('src'), function () {
		frames.show();
		$('#slide-container').show();
		new Preloader(frames.map(function (i, frame) {return $(frame).attr('src');}), start);
	});

}



function Circles() {
	var circles = $('.circle');
	var hoverFadeDuration = 200;
	var animationFadeDuration = 350;

	this.initialSetup = function () {
		circles.attr({tabIndex: -1}).css({opacity: 0}).show();
		// Let circles be aware of their type
		circles.each(function () {
			for (var i in CIRCLE_TYPES) {
				if ($(this).hasClass(CIRCLE_TYPES[i])) {
					$(this).data('nr', i);
				};
			}
		});
		// If there is more than one circle type, start animation
		// (test if there are 5 or more circles; there could be as much as 4 on single-circle-type pages with slider)
		circles.get(4) ? animate() : circles.fadeInCustom();
	};
	
	var activateHover = function () {
		circles.hover(function (event, delegated) {
			var type = CIRCLE_TYPES[$(this).data('nr')];
			// IE8 won't fade pngs inside containers, so apply fade to the images directly
			$(this).find('img').stop(true).animate({opacity: 1}, hoverFadeDuration);
			// Show corresponding name in scroller (if event is not already delegated by scroller, which would cause infinite loop)
			delegated || $('.scroll-item').filter('.'+type).trigger('mouseover', [true]);
		}, function (event, delegated) {
			// Hide corresponding name in scroller
			var type = CIRCLE_TYPES[$(this).data('nr')];
			$(this).find('img').stop(true).animate({opacity: 0}, hoverFadeDuration);
			delegated || $('.scroll-item').filter('.'+type).trigger('mouseout', [true]);
		});
	};
	
	var animate = function () {
		// Animate circles only on topmenu pages
		if (PAGE == 'hotspot' || PAGE == 'produkte' || PAGE == 'index') {
			new Preloader($('#image-container img').map(function (i, image) {return $(image).attr('src');}), function () {
				circles.each(function () {
					// IE8 won't fade pngs inside containers, so apply fade to the images directly
					$(this).find('img').css({opacity: 0}).delay($(this).data('nr') * animationFadeDuration * 2)
						.animate({opacity: 1}, animationFadeDuration)
						.animate({opacity: 0}, animationFadeDuration);
					$(this).css({opacity: 1}).show();
				});
				setTimeout(activateHover, CIRCLE_TYPES.length * animationFadeDuration * 2);
			});
		}
		else {
			activateHover();
		}
	};
	
	
	new Preloader($('#image-container img').map(function (i, image) {return $(image).attr('src');}));
}





function FormValidation() {
	$('input').focus(function () {
		$(this).removeClass('error');
		if ( ! $('.error').get(0)) {
			$('.submit').show();
		}
	});
	$('input').blur(function () {
		if ( ! $(this).attr('value')) {
			var label = $('label[for='+$(this).attr('id')+']');
			if (label.get(0)) {
				if (label.text().match(/[*]/)) {
					$(this).addClass('error');
					$('.submit').hide();
				}
			}
		}
	});
}





$(function() {
	function isGlobal(variable) {
		return (typeof(window[variable]) != 'undefined');
	}
	new Preloader(IMAGE_REPLACEMENT_PRELOAD);
	(PAGE == 'produkte') && ITEM && new ProductDetailPage();
	$('#slide-container').get(0) && new Slider();
	$('#scroll-container').get(0) && (window['SCROLLER'] = new Scroller());
	$('.circle').get(0) && (window['CIRCLES'] = new Circles());
	// Don't start scroller and circles immediately on intro page, let Intro handle that after the intro movie has finished
	$('#intro').get(0) && new Intro() || (isGlobal('SCROLLER') && SCROLLER.scroll() || isGlobal('CIRCLES') && CIRCLES.initialSetup());
	$('form').get(0) && new FormValidation();
	// Make external links open in new windows or tabs (don't use 'target' attribute directly, as it's forbidden in strict DOCTYPES)
	// (Also, don't use window.open instead, as there are potential problems with referrer reporting)
	$('a.external, a.pdf, a[href*="facebook"], .händler #content a, .fördergeber #content a').attr({target: '_blank'});
});
