// Optional parameter includeMargin is used when calculating outer dimensions
(function($) {
$.fn.getHiddenDimensions = function(includeMargin) {
    var $item = this,
        props = { position: 'absolute', visibility: 'hidden', display: 'block' },
        dim = { width:0, height:0, innerWidth: 0, innerHeight: 0, outerWidth: 0, outerHeight: 0 },
        $hiddenParents = $item.parents().andSelf().not(':visible');
    includeMargin = (includeMargin == null)? false : includeMargin;

    var oldProps = [];
    $hiddenParents.each(function() {
        var old = {};

        for ( var name in props ) {
            old[ name ] = this.style[ name ];
            this.style[ name ] = props[ name ];
        }

        oldProps.push(old);
    });

    dim.width = $item.width();
    dim.outerWidth = $item.outerWidth(includeMargin);
    dim.innerWidth = $item.innerWidth();
    dim.height = $item.height();
    dim.innerHeight = $item.innerHeight();
    dim.outerHeight = $item.outerHeight(includeMargin);

    $hiddenParents.each(function(i) {
        var old = oldProps[i];
        for ( var name in props ) {
            this.style[ name ] = old[ name ];
        }
    });

    return dim;
};
}(jQuery));

jQuery(function ($) {
	
	var $win = $(window);
	var $body = $(document.body);
	var $sidebar = $('#sidebar');
	var $content = $('#content');

	// check for support of background-size
	var $background = $('#background');
	var $bgImage = $background.children('img');

	var backgroundSize = $background.css('-moz-background-size') || $background.css('-o-background-size') || $background.css('-webkit-background-size');

	if (backgroundSize == 'cover') {
		// GOOOD browser :)
		$background.css('background-image', 'url("' + $bgImage.attr('src') + '")');
		$bgImage.remove();

	} else {
		// have to fake background-size :/

		// do not use jQuerys .attr(), because it returns the computed width/height not the attribute!
		var imgWidth  = $bgImage[0].getAttribute('width');
		var imgHeight = $bgImage[0].getAttribute('height');
		var imgRatio  = imgWidth / imgHeight;
		
		var resizeBackground = function() {
			var areaWidth  = $background.width();
			var areaHeight = $background.height();
			var ratio  = areaWidth / areaHeight;

			// scale the image
			if (ratio > imgRatio) {
				width = areaWidth;
				height = width / imgRatio;
			} else {
				width = height * imgRatio;
				height = areaHeight;
			}

			// position the image centered
			var top  = Math.floor((areaHeight - height) / 2);
			var left = Math.floor((areaWidth - width) / 2);
			$bgImage.css({width: width, height: height, top: top, left: left});
		};
		
		$win.resize(function() {
			resizeBackground();
		}).resize();
	}
	
	// search box behaviour
	$('#searchbox').click(function () {
		var $searchbox = $(this);
		
		$('#searchform').fadeToggle(function() {
			$(this).find('input[type="text"]').first().focus();
			$searchbox.toggleClass('active', $(this).is(':visible'));
		});
	});
	
	// menu collision detection
	var hideSubmenu = function() {
		var $this = $(this);
		$this.find('ul.level0:first').fadeOut(50, function() {
			$this.removeClass('hover');
		});
	};
	
	$('#mainnavigation > li')
		.each(function() {
			var $this = $(this);
			
			var $page = $('#page');
			var $submenu = $this.find('ul.level0');

			if ($this.offset().left - $page.offset().left + $submenu.outerWidth() > $page.width()) {
				$this.find('li.first').append($('<span />', { 'class': 'border' }));
				$this.addClass('left');
				if ($this.hasClass('active parent')) {
					$this.addClass('active-parent-left');
				} else if ($this.hasClass('parent')) {
					$this.addClass('parent-left');
				}
			}
		}).hover(function() {
			var $this = $(this);
			$this.addClass('hover').siblings().each(hideSubmenu);
			clearTimeout($this.data('timeout'));
			$this.find('ul.level0:first').stop(true, true).fadeIn(250);
		}, function() {
			$(this).data('timeout', setTimeout($.proxy(hideSubmenu, this), 250));
		});
		
	// header navigation submenus
	$('#quickaccess li > .submenu').hide().closest('li').mouseenter(function() {
		window.clearTimeout($(this).data('timer'));
		$(this).find('.submenu').stop(true,true).fadeIn(355);
	}).mouseleave(function() {
		var _this = $(this);
		$(this).data('timer', window.setTimeout(function() {
			_this.find('.submenu').stop(true,true).fadeOut(200);
		}, 100));
		
	});
	
	// flash messages
	$flashmsgbox = $('#messages');
	$flashmsgbox.find('li.error-msg > ul > li').each(function(index) {
		var $item = $(this);
		// possibility to close it with ESC key
		$(document).bind('keydown.error-msg' + index, function(event) {
			if (event.keyCode == 27) {
				// ESC
				$item.closest('.error-msg').remove();
				$(document).unbind('keydown.error-msg' + index);
				event.preventDefault();
				event.stopPropagation();
				event.stopImmediatePropagation();
			}
		});
		$item.append($('<a />', {
			href: '#',
			'class': 'close',
			text: 'Diese Meldung schließen',
			click: function(event) {
				event.preventDefault();
				event.stopPropagation();
				
				$item.closest('.error-msg').remove();
				$(document).unbind('keydown.error-msg' + index);
			}
		}));
	});
	
	$flashmsgbox.css({
		top: ($win.height() - $flashmsgbox.height()) / 3
	})
	.show(50, function() {
		if (!$(this).find('li.error-msg').size()) {
			window.setTimeout(function() { $flashmsgbox.fadeOut(350); }, 1300);
		}
	});
	
	// product view: tabs
	$datapage = $('.product-collateral');
	$mediapage = $('.product-essential');
	
	$panels = $datapage.children('div[id].tab-panel');
	//if ($panels.size() > 1) {
	$tabs = $('<ul>', { 'class': 'tabs clearfix' });

	var $first = $panels.first();
	$first.before(function() {
		$panels.each(function() {
			$tabs.append($('<li>').append($('<a>', { href: '#' + $(this).attr('id'), text: $(this).find('h2:first').remove().text() }).after($('<span>'))));
		});
		return $tabs;
	});
	$tabs.find('span:last').remove();

	$datapage.tabs();
	$tabs.find('li:first').addClass('ui-first-tab');
	$tabs.find('li:last').addClass('ui-last-tab');
	//}
	
	// product view: column height and zoom lens height calculation
	$($datapage, $mediapage).height(function() { return Math.max($datapage.height(), $mediapage.height()); });
	$($sidebar, $content).height(function() { return Math.max($sidebar.height(), $content.height()); });
	
	/*$('').hover(function() {
		console.log($(this), 'in');
		$datapage.animate({ opacity: 0 }, 200);
	}, function() {
		console.log($(this), 'out');
		$datapage.animate({ opacity: 1 }, 200);
	});
	*/
	
	// product view: gallery images
	
	// make sure the next line runs before the CloudZoom init code
	var $productImgTemplate = $('#main-image').clone();
	
	$('.more-views a.thumbnail').click(function(e) {
		e.preventDefault();
		var imgData = $(this).metadata();
		var newImg = new Image();
		
		$(newImg).bind('load error', function() {
			var $productImage = $productImgTemplate.clone();
			$productImage
				.find('a').attr({ href: imgData.original })
				.find('img').attr({ src: $(this).attr('src') });
			
			$('#main-image').replaceWith($productImage);
			$('#main-image').find('a.cloud-zoom').CloudZoom();
		});
		
		newImg.src = imgData.image;
	});
	
	// wishlist
	$('a.wishlist-comment').click(function(e) {
		e.preventDefault();
		$(this).siblings('div:first').slideToggle();
	});

	// IE fixes
	if ($.browser.msie) {
		$(':first-child').addClass('first-child');
		$(':last-child').addClass('last-child');
		
		if ($.browser.version.substr(0,1) < 8) {
	
			$('#mainnavigation ul.level0').each(function() {
				var maxItemWidth = 0;
		
				$(this).find('li').each(function() {
					var dim = $(this).getHiddenDimensions();
			
					if (dim.width > maxItemWidth) {
						maxItemWidth = dim.width;
					}
				});

				$(this).css({ width: Math.max(maxItemWidth, $(this).closest('li.level0').width()) });
			});
		}
	}
});

