$(document).ready(function() {
	$('.submenu').css('opacity', '0').hide();
	
	$('#navigation span')
		.bind({
			mouseover: function(){
				var offset	= $(this).offset();
				var width	= $(this).width();
				offset.left = offset.left + ( width - 162 )/2
				offset.top	= offset.top-20;
				
				$('.'+$(this).attr('id')).css({left: offset.left, top: offset.top-15})

				$('.'+$(this).attr('id')).stop().show().animate({opacity: "1",marginTop: "9px"}, "slow");
			},
			mouseout: function(){
				$('.'+$(this).attr('id'))
					.stop()
					.animate({opacity: "0", marginTop: 0}, "slow")
					.hide()
					.css({left: 0, top: 0});
			}
		})

	if($('img.gallery').length >= 1){
		$('img.wysiwygimg').each( function (){
			imgpos		= 0;

			matches = /[\?&_]rex_resize=([^_]+)__/.exec(this.src)
			format = './files/';
			if (matches)
				format = './index.php?rex_resize=' + matches[1] + '__'

			gallery = $(this).nextAll('img.gallery')
			gallery.each(function(){
				matches = /\/files\/(.*)$/.exec(this.src)
				this.src = format + matches[1]
				$(this).addClass('wysiwygimg');
				//this.src = this.src.replace(pattern)
			})
			imgcount		= gallery.length + 1;



			$(this).after('<a href="#" class="next"></a><a href="#" class="prev"></a>');
			//$(this).parent().append('<div class="wysiwygimgtitle"></div>');
			//$('.wysiwygimgtitle').html('Fotos ' + (imgpos+1) + ' von ' + imgcount + '</div>').css('textAlign', 'right');

			

		})
		$('.wysiwygimgtitle').hide();
		$('.wysiwygimgtitle:first').show();
		
		$('.next').bind('click', function(e){
        e.preventDefault();
        imgContainer = $(this).parent();
        imgs = $(imgContainer).children('img.wysiwygimg, img.gallery');
        imgpos = 0;
        $(imgs).each(function(i,e){
          if($(this).css('display') != 'none'){
            imgpos = i;
          }
        })
        $(imgs).hide();
        var imgcount = $(imgs).length
        imgpos++
        imgpos %= imgcount
        $(imgs[imgpos]).show()
        $(imgContainer.find('wysiwygimgtitle')[imgpos]).show();
        //$(imgContainer).find('.wysiwygimgtitle').html('Fotos ' + (imgpos+1) + ' von ' + imgcount + '</div>')

      })
      $('.prev').bind('click', function(e){
        e.preventDefault();
        imgContainer = $(this).parent();
        imgs = $(imgContainer).children('img.wysiwygimg, img.gallery');
        imgpos = 0
        $(imgs).each(function(i,e){
          if($(this).css('display') != 'none'){
            imgpos = i;
          }
        })
        $(imgs).hide();
        var imgcount = $(imgs).length
        imgpos = imgpos - 1 + imgcount
        imgpos %= imgcount
        $(imgs[imgpos]).show()
        $(imgContainer.find('wysiwygimgtitle')[imgpos]).show();
        //$(imgContainer).find('.wysiwygimgtitle').html('Fotos ' + (imgpos+1) + ' von ' + imgcount + '</div>')

      })
	}

});
