(function($) {
	$.fn.overlay = function() {
		return this.each(function() {
			// Cache some stuff
			var overlay = $("<div id='lean_overlay'></div>"),
				overlay_id = $(this).attr("href"),
				$overlay = $(overlay_id),
				overlay_height = $overlay.outerHeight()+20,
				overlay_width = $overlay.outerWidth(),
				stripHeight = '124px',
				offset = $(this).offset(),
				targetOffset = $(this).closest('.sections').offset(),
				$overlayContent = $(this).html();

			$overlay.css({
				'left': '-' + overlay_width + 'px',
				'top': offset.top-1,
				'height': stripHeight
			});
			// Semi hack to avoid using min-height in the css which dont play nice with jquery's animation
			$('#erhverv .left').height(177);
			
			if ($(this).parent().hasClass('special')) {
				
				$(this).parent().click(function(e) {

					e.preventDefault();

					$('.scroller').append(overlay);
					$('#lean_overlay').css({ 'display' : 'block', 'opacity' : '0' });
					$('#lean_overlay').fadeTo(200, 0.5);

					$overlay.css({'display': 'block', 'height': stripHeight}).animate({ left: ['0', 'easeInCubic'] }, function (){
						$(this).animate({ height: [overlay_height, 'easeInCubic'], top: [targetOffset.top-1, 'easeInCubic'] }, function(){
							$('.left, .right', this).css({opacity: 0, visibility: "visible"}).animate({opacity: 1});
						});
					});

					$("#lean_overlay").click(function() {

						$(this).fadeOut(200, function(){
							$(this).remove();
						});
						$('.left, .right', $overlay).animate({opacity: 0}, function(){
							$overlay.animate({ height: [stripHeight, 'easeInCubic'], top: [offset.top-1, 'easeInCubic'] }, function (){
								$(this).animate({ left: ['-' + overlay_width, 'easeOutCubic'] }, function(){
									$(this).css('display', 'none');
									$overlay.height(overlay_height);
								});
							});
						});
					});
				});
				$('.overlay .close').click(function(e){
					e.preventDefault();
					$('#lean_overlay').trigger('click');
				});
				$('.menu-popup .close').click(function(e){
					e.preventDefault();
					$(this).parent().trigger('mouseleave');
				});
				$(document).keyup(function(e) {
				  if (e.keyCode == 27) { $('#lean_overlay').trigger('click'); }   // esc
				});
			} else {
				$(this).parent().click(function(e) {
					e.preventDefault();
					window.location = $(this).data('link');
				});
			}
		});
	};
}(jQuery));
