/*(function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
})(jQuery)

$.preLoadImages(
		"images/menu/balkonowe.jpg",
		"images/menu/drzwi-tarasowe.jpg",
		"images/menu/zewnetrzne.jpg",
		"images/menu/wewnetrzne.jpg",
		"images/menu/parapety.jpg",
		"images/menu/okiennice.jpg",
		"images/menu/drzwi-garazowe.jpg",
		"images/menu/podlogi.jpg",
		"images/menu/realizacje.jpg",
		"images/menu/okna.jpg",
		"images/menu/drzwi.jpg",
);*/

$(document).ready(function() {

	$(".menu-dynamic").each(function() {
		var id = $(this).attr('id');
		var aID = id;
		aID = aID.replace(/-menu/g, "");
		
		var position = $("#"+aID).position();
		$(this).css('left', position.left + 54).css('top', position.top - $(this).height() - 6);
		$(this).data('pos', $(this).position()).data('height', $(this).height()).hide();
		$('#'+aID).data('shown', false);
	});

	$("#menu a.mnu").mouseenter(function() {
		//console.log('enter #' + $(this).attr('id'));
		if (!$(this).data('shown'))
		{
			var myID = $(this).attr('id');
			var top = $(this).position().top;
			var selector = "#"+myID+"-menu";
			var pos = $(selector).data('pos');
			var height = $(selector).data('height');
			$(selector).show();
			$(selector).queue(function() {$(this).height(0).css('top', top); $(this).dequeue(); });
			$(selector).animate({ 'height' : height, 'top' : pos.top }, 500);
			$(this).data('shown', true);
		}
		//else console.log('enter, skipping: #' + $(this).attr('id'));
	});
	
	$(".menu-dynamic").mouseenter(function() {
		$(this).data('mouse', true);
	}).mouseleave(function() {
		//console.log('mouseleave');
		$(this).data('mouse', false);
		var id = $(this).attr('id');
		var aID = id;
		aID = aID.replace(/-menu/g, "");
		$(this).clearQueue().animate({ 'height' : '0px', 'top' : $("#"+aID).position().top }, 500, function () { $(this).hide(); $("#"+aID).data('shown', false); });
	});
	
	$("#menu a.mnu").mouseleave(function() {
		if ($(this).data('shown'))
		{
			var myID = $(this).attr('id');
			var top = $(this).position().top;
			var selector = "#"+myID+"-menu";
			$(selector).clearQueue();
			$(selector).delay(100).queue(function() 
				{
					if ($(this).data('mouse'))
					{
						//console.log('mouse detected, not hiding');
						$(this).clearQueue();
					}
					else
					{
						$(this).animate({ 'height' : '0px', 'top' : top }, 500, function () { $(this).hide(); $("#"+myID).data('shown', false); });
					}
					$(this).dequeue();
				});
		}
		//else console.log('leave, skipping: #' + $(this).attr('id')); 
	});
	
});
