jQuery(document).ready(function ($) {
	
	// Menu tweaks for lightbox
	setLightboxImageCount();
	$('#item4').attr('rel','0');

  /* menu */
  function fadeMenuIn(items, minDelay) {
  	var step = 100;
  	var fadeDuration = 250;
  	for (var i = 0; i < items.length; i++) {
  		$(items[i]).hide().delay(minDelay + (i * step)).fadeIn(fadeDuration);
  	}
  }

	// fade in menu
	var hasNoMenuSelection = $('ul#site_menu li.menu-text').length == 0;
	if (hasNoMenuSelection) {
		fadeMenuIn($('ul#site_menu').children(), 800);
	}

	// fade in submenu
	if($('body').attr('id') != 'p1') {
	  var hasNoSubmenuSelection = $('ul#site_submenu li.menu-text').length == 0;
	  if (hasNoSubmenuSelection) {
		  fadeMenuIn($('ul#site_submenu').children(), 800);
	  }
	} else {
	  // Homepage: Hide submenu
	  $('#item3 a').click(function(event) {
      event.preventDefault();
      console.log($(this));
      $(this).parent('li').removeClass('menu-text-gray').addClass('menu-text');
      fadeMenuIn($('ul#site_submenu').children(), 0);
    });
	}
	
	/* Bilder in der Lightbox*/
	function setLightboxImageCount() {
		$.ajax({
			type:'POST',
			url: '/?eID=lightbox',
			data: {
				eID: "lightbox",
				countImage: true
			},
			dataType: 'json',
			success: function(result) {
				if (result.countImage >= 0) {
					$('#item4').attr('rel',result.countImage);
					$('#item4 a').html('LIGHTBOX (' + result.countImage+')');
				}
			}
		});
	}
});

(function($) {
    $.fn.smartBackgroundImage = function(url){
            var t = this;
            $('body').prepend('<div id="bgoverlay" style="width:100%; height:100%; position:absolute; background-color:#595959;"></div>');
            $('<img />')
            .attr('src', url)
            .load(function(){ //attach onload to set background-image
                    t.each(function(){ 
                            $(this).css('backgroundImage', 'url('+url+')' );
                            $('#bgoverlay').fadeOut(1000, function(){
                                    $(this).remove() 
                            });
                    });
            });
            return this;
    }

    $.fn.scaleImage = function(options) {
        var opts = $.extend({parent: false, scale: 'fill', center: true, fade: 0}, options); // merge default options with user's

        return this.each(function() {
            var $img = $(this);
            var $parent = opts.parent ? $img.parents(opts.parent) : $img.parent(); // if not supplied, use default direct parent
            $parent.css({opacity: 0, overflow: 'hidden'}); // keep the img inside boundaries
            
            if ($parent.length > 0) {
                $img.removeAttr('height').removeAttr('width');
                if (this.complete) { // img already loaded/cached
                    scale($img, $parent);
                } else {
                    $img.load(function() {
                        scale($img, $parent);
                    });
                }
            }
        });
        
        function scale($img, $parent) {
            var imgSize = getOriginalImgSize($img),
                imgW = imgSize.width,
                imgH = imgSize.height,
                destW = $parent.width(),
                destH = $parent.height(),
                borderW = parseInt($img.css("borderLeftWidth"), 10) + parseInt($img.css("borderRightWidth"), 10),
                borderH = parseInt($img.css("borderTopWidth"), 10) + parseInt($img.css("borderBottomWidth"), 10),
                ratioX, ratioY, ratio, newWidth, newHeight;
            
            if (destH === 0 || destW === 0) { // parent is invisible, eg. display: none
                var parentSize = getHiddenElemSize($parent);
                destW = parentSize.width;
                destH = parentSize.height;
            }
            
            // check for valid border values. IE takes in account border size when calculating width/height so just set to 0
            borderW = isNaN(borderW) ? 0 : borderW;
            borderH = isNaN(borderH) ? 0 : borderH;
            
            // calculate scale ratios
            ratioX = destW / imgW;
            ratioY = destH / imgH;

            // Determine which algorithm to use
            if (opts.scale === "fit") {
                ratio = ratioX < ratioY ? ratioX : ratioY;
            } else if (opts.scale === "fill") {
                ratio = ratioX > ratioY ? ratioX : ratioY;
            }

            // calculate our new image dimensions
            newWidth = parseInt(imgW * ratio, 10) - borderW;
            newHeight = parseInt(imgH * ratio, 10) - borderH;
            
            // Set new dimensions to both css and img's attributes
            $img.css({
                "width": newWidth,
                "height": newHeight
            }).attr({
                "width": newWidth,
                "height": newHeight
            });
            
            if (opts.center) { // set offset if center is true
                $img.css("margin-left", Math.floor((destW - newWidth) / 2));
                $img.css("margin-top", Math.floor((destH - newHeight) / 2));
            }
        
            if (opts.fade > 0) { // fade-in effect
                $parent.animate({opacity: 1}, opts.fade);
            } else {
                $parent.css("opacity", 1);
            }
        }

        /**
         * To calculate the correct scale ratio, we need the image's original size rather than some preset values,
         * which were set either manually in code or automatically by browser.
         * Thanks FDisk for the solution:
         * http://stackoverflow.com/questions/318630/get-real-image-width-and-height-with-javascript-in-safari-chrome
         */
        function getOriginalImgSize($img) {
            var t = new Image();
            t.src = $img.attr("src");
            return {width: t.width, height: t.height};
        }
        
        /**
         * If the element is invisible, jQeury .height() and .width() return 0 in IE.
         * This function returns the hidden element's correct width and height.
         * Thanks elliotlarson for the solution:
         * http://stackoverflow.com/questions/2345784/jquery-get-height-of-hidden-element-in-jquery-1-4-2
         */
        function getHiddenElemSize(element) {
            var copy = element.clone().css({visibility: 'hidden', display: 'block', position: 'absolute'});
            $("body").append(copy);
            var size = {width: copy.width(), height: copy.height()};
            copy.remove();
            return size;
        }
    };
})(jQuery);
