(function($) {
	// FIXME don't ignore me! [http://planetsmilies.net/angry-smiley-1497.gif]
	// Move iconWidth & upperMargin into CSS class, but check $.fn.spots
	// before!
	var upperMargin =  25;

	$.fn.spots = function() {
		var iconWidth = 40;

		return this.each(function() {
			var clicked       = false,
			    $spot         = $('.spot', this),
			    $excerpt      = $spot.find('.content'),
			    $content      = $spot.find('.content1'),
			    $close        = $content.find('.close'),
			    $bodyContent  = $('#body .content'),
			    $description  = $bodyContent.find('.desc'),
			    $container    = $('#hotspots'),
			    position      = $spot.parent().position(),
			    excerptWidth  = $excerpt.find('h3').innerWidth() + iconWidth,
			    contentWidth  = $content.find('h3').innerWidth() + (iconWidth / 2),
			    excerptHeight = $excerpt.find('h3').innerHeight(),
			    contentHeight = $content.find('h3').innerHeight() + $content.find('p').innerHeight() + upperMargin;

			$spot.css({ width: excerptWidth, height: excerptHeight });
			$excerpt.css({ width: excerptWidth, height: excerptHeight });
			$content.css({ left: contentWidth * -1, opacity: 0 });

			var tooFat  = position.left + contentWidth > $container.width(),
			    tooTall = position.top + contentHeight > $container.height(),
			    tooBig  = tooFat || tooTall;

			function itsTooBig(dimensions) {
				$spot.parent().animate(dimensions, 800);
			}
			function putHimBack() {
				$spot.parent().animate({
					left: position.left,
					top: position.top
				}, 800);
			}
			function unfoldExcerpt() {
				$excerpt.animate({ left: contentWidth, top: 0, opacity: 0 }, {
					queue:    false,
					duration: 300,
					complete: unfoldContent
				});
			}
			function foldContent() {
				$content.animate({ left: contentWidth * -1, top: 0, opacity: 0 }, {
					queue:    false,
					duration: 300,
					complete: foldSpotAndExcerpt
				});
			}
			function foldSpotAndExcerpt() {
				$spot.animate({ width: excerptWidth, height: excerptHeight }, 400);
				$excerpt.animate({ left: 0, width: excerptWidth, height: excerptHeight, opacity: 1 }, {
					queue:    false,
					duration: 400
				});
			}
			function unfoldContent() {
				$spot.animate({ width: contentWidth, height: contentHeight }, 800);
				$content.animate({ left: contentWidth, width: contentWidth, opacity: 1 }, {
					queue:    false,
					duration: 300
				});
			}
			function unfoldSpot() {
				$spot.animate({ width: contentWidth, height: contentHeight }, 800);
			}
			$(this).click(function() {
				var $siblings = $(this).siblings('.spotable'), set = '#productset' + this.id;
				clicked = !clicked;

				if (clicked) {
					unfoldExcerpt();
					if (tooBig) {
						var dim = {};
						if (tooTall)
							dim['top'] = position.top - contentHeight + excerptHeight;
						if (tooFat)
							dim['left'] = position.left - contentWidth + excerptWidth;
						itsTooBig(dim);
					}
					$description.fadeOut(300);
					$bodyContent.find(set).fadeIn(1000);
					$siblings.hide();
				} else {
					$siblings.show();
					$bodyContent.find(set).fadeOut(300);
					$description.fadeIn(1000);
					foldContent();
					if (tooBig)
						putHimBack();
				}
			});
		});
	};

	$.fn.slotsizing = function() {
		var maxHeight = 0;

		return this.
		each(function() {
			var height = $(this).height();
			if (height > maxHeight) maxHeight = height;
		}).
		height(maxHeight);
	};

	$.fn.descslotsizing = function() {
		var height, container = $('.topteasers .teaser');
		height  = container.find('.slot .generic').height() + 17;
		height += container.find('img:first').height();

		return this.css('height', height);
	};
	$.fn.clearShades = function() {
		var teasershade = this.find('.teasersbg .teaserbox');
		var awardiconset = this.find('.award.iconset');
		if(teasershade.html() != ""){
			teasershade.css('margin-top',10);
		}
		if(awardiconset.children().size() == 0){
			awardiconset.css({'background' : 'none','margin': '0'});
		}
	};
	// FIXME use $(...).revealing()
	$.fn.help = function() {
		this.hover(
			function() { $('#help', this).show(); },
			function() { $('#help', this).hide(); }
		);
	};

	function showTooltip(e) { $(this).data('tooltip').show(); }
	function hideTooltip(e) { $(this).data('tooltip').hide(); }
	$.fn.tooltip = function() {
		return this.
		each(function() {

			var tool = $(this),
			parentcontainer = $('.simpleproduct'),
			$P   = $('<P>').html(tool.attr('alt')),
			$DIV = $('<DIV CLASS="tooltip">').append($P);

			if (tool.data('tooltip') || tool.attr('alt') == '') return;

			$('#body').append($DIV);

			var offset = tool.offset(),
			parentoffset = parentcontainer.offset(),
			height = tool.height(),
			width  = tool.width(),
			parenttop = parentoffset.top,
			parentleft = parentoffset.left,
			top    = offset.top + height - parenttop,
			left   = offset.left + width / 2 - $DIV.width() / 2 - parentleft;
			$DIV.css({left: left, top: top + 10}).hide();

			tool.data('tooltip', $DIV);
		}).
		hover(showTooltip, hideTooltip);
	};


	function falseFn() { return false; }
	$.fn.wall = function(selector) {
		var wall   = $(selector),
		    first  = $(this).children('img:first'),
		    hovers = $(this).find('.hovers');

		hovers.click(function(e) {
			var $$ = $(this);

			$$.parent().addClass('hover').siblings().removeClass('hover');
			wall.attr('src', $$.prev().attr('src'));
		}).hover(falseFn).
		first().click();

		return this;
	};
	$.fn.addlink = function() {
		return this.click(function(e) {
			if (e.target.tagName != 'A') {
				window.location.href = $('a:first', this).attr('href');
			}
		});
	};
	$.fn.addbgheight = function() {
		var bgheight = $('.nobg').innerHeight();
		return this.css({height:bgheight});
	};
	$.fn.lotto = function() {
		return this.each(function() {
			var container = $(this), limit, anchors, countdown;

			limit     = container.attr('class').match(/limit-\d+/).pop();
			limit     = limit.match(/\d+/).pop() * 1;
			anchors   = $('.tabs a[href^="/"]');
			countdown = anchors.length;

			anchors.each(function(e) {
				var anchor = $(this), href = anchor.attr('href'), scenes;

				anchor.click(function() {
					anchors.removeClass('.active');
					anchor.addClass('.active');
					container.html(scenes);

					return false;
				});

				$.get(href, function(html) {
					scenes = $('.slot', html).filter(function() {
						return $('a', this).attr('href') != href;
					});
					while (scenes.length > limit) {
						n = Math.floor(Math.random() * scenes.length);
						scenes = scenes.filter(':not(:eq(' + n + '))');
					}

					if (!--countdown) { anchors.first().click(); }
				});
			});
		});
	};
	$.fn.searchFilter = function() {
		return this.click(function(e) {
			e.preventDefault();
			var li = $(this),
			    section = li.find('a').attr('rel');

			$('.left .excerpt.' + section).toggle();
			li.toggleClass('active');
		});
	};

	$(function() {
		// <hack>
		function activateTab(href) {
			this.filter(function() { return this.href == href; }).
			parents('li').addClass('active').siblings().removeClass('active');
		}
		var pageClass = '.generate-product_system_swep ';
		var toptabs = $(pageClass + '.systoptabs a[href^="#"]').
		click(function() {
			activateTab.call(toptabs, this.href);
			activateTab.call(bottomtabs, this.href);
		});
		var bottomtabs = $(pageClass + '.sysbottomtabs a[href^="#"]').
		click(function() {
			activateTab.call(toptabs, this.href);
			activateTab.call(bottomtabs, this.href);
		});
		// </hack>

		var reveal = $('.reveal').show(), blocks = $();
		var anchors = reveal.find('a[href^="#"]').each(function() {
			var anchor   = $(this),
			    parent   = anchor.parents('li'),
			    selector = anchor.attr('href');

			if (selector === '#') { return; } // fix content-entry

		    var block = $(selector);
			blocks = blocks.add(block);

			anchor.click(function() {

				var visible = blocks.filter(':visible').get() == block.get();
				if (visible) { return false; }

				parent.addClass('active').siblings().removeClass('active');

				var y1 = $(window).scrollTop(),
				    y2 = anchor.parents('.reveal').offset().top;

				block.fadeIn(100, function() {
					var y3 = anchor.parents('.reveal').offset().top;
					$(window).scrollTop(y1 - y2 + y3);
				});
				blocks.not(block).hide();

				return false;
			});
		});
		anchors.parent().removeClass('active');

		var nonEmpty = 0, firstContent = 0;
		blocks.each(function(i) {
			var isBlank = $(this).html().replace(/\s/g, '') == '';
			if (!isBlank) {
				nonEmpty++;
			} else if (nonEmpty == 0) {
				firstContent++;
			}
			return nonEmpty < 2;
		});
		if (nonEmpty < 2) {
			reveal.hide();
		} else {
			anchors.eq(firstContent).click();
		}

		$('.transbg, .whitetransbg').addbgheight();

		var blanks = $('a[href^="http://"]');
		// see #119
		var assets = ['pdf', 'zip', 'doc', 'xls', 'ppt', 'txt', 'jpg', 'gif', 'png', 'tiff', 'bmp'];
		$.each(assets, function() {
			blanks = blanks.add('a[href$="' + this + '"]');
		});
		blanks.blank();

		$('.selected:first').selected();
		$('.hoverable').hovers();
		// WTFF!?!
		$('.centercol.coloured').addClass('centercol-col');
		// WTFF!?!
		$('.centercol.topshade').addClass('centercol-ts');
		$('.info').help();
		$('ul.preview-box li').wall('#product-image img');
		// need to wait for loading to get image sizes...
		$(window).load(function() { $('img.tooltips').tooltip(); });
		$('.teaser .slot .generic', this).slotsizing();
		$('.teaser .descslot').descslotsizing();
		$('.spotable').spots();
		$('#homepageTeaser').loopedSlider({
			autoStart: 8000,
			restart: 9100,
			startTimer: 0
		});
		$('.random.collection').lotto();
		$('.products #body').clearShades();
		$('.clickable', this).addlink();
		// WTFF!?!
		$('#breadcrumbs').children().first().css('background','none');
		$('a').blurry(); // FIXME use * :focus { outline: 0; } instead
		$('body.search #more ul.inline-a li').searchFilter();
	});
})(jQuery);

