$().ready(function() {

    /*
     * interval identifier
     */
    var intGalleryPlay;
    
    /*
     * mouseover on thumbnail
     */
    $('ul.thumbnails > li:not(#gallery_play)').mouseover(function(e){ 
        showImage($(this), e, false)
    });
    
    /*
     * hover on play button
     */
    $('#gallery_play').hover(
        function(e) {
			var current = $('.image > img:first').attr('src'); 
			var next = $('ul.thumbnails > li').children('img[src='+current+']:not(#gallery_play)').parent().next();
			showImage($(next), e);
			// $(this).children('img:first').animate({'opacity' : 0}, 'slow');
			$(this).children('img:first').css('visibility', 'hidden');
            intGalleryPlay = setInterval(function() {
	
	            var current = $('.image > img:first').attr('src'); 
	            var next = $('ul.thumbnails > li').children('img[src='+current+']:not(#gallery_play)').parent().next();
	               
	            if($(next).html() == null)
	            next =  $('ul.thumbnails > li:not(#gallery_play):first');
                    
                showImage($(next), e);
            }, 1500);
       },
       function(e) {
           clearInterval(intGalleryPlay);
		   //$(this).children('img:first').animate({'opacity' : 1}, 'slow');
		   $(this).children('img:first').css('visibility', 'visible');
       }
    );
    
    /*
     * shows an image
     */
    function showImage(thumbnail, e, animation)
    {
        var self = thumbnail;
        
        var img_text = self.children('span:first').html();
        var img_src = self.children('img:first').attr('src');
        var img_title = self.children('img:first').attr('alt');
        
        if (animation == true || img_src != $('div.image').children('img:first').attr('src')) {
        
            $('div.image').stop().hoverFlow(
                e.type, 
				{
                    opacity: 0.0001
                }, 
				{
	                duration: 300,
	                complete: function(){
	                    self = $(this);
						//self.prepend('<img src="'+img_src+'" />');
						//self.remove('img:first');
	                    self.children('img:first').attr('src', img_src);
						//.load(function() {
							self.find('p.title').html(img_title);
                            self.find('p.caption').html(img_text);
                            self.hoverFlow(e.type, {
                                opacity: 1.0
                            }, 300);
						//});
	                }
                }
			);
        }
    }
    
});