$timer = null;

$(document).ready(function()
{
    initGalleryTeasers();
});

function initGalleryTeasers()
{
    var $galleryTeasers = $('.gallery-teasers');
        $galleryTeasers.children('.gallery-teaser').each(function()
        {
            var $gallery = $(this);
                $gallery.click(function()
                {
                    var galleryId = $gallery.find('div.metadata .gallery-id').text();
                    popup.open(galleryId);
                });
        });
}

function setupGalleryPopup()
{
    var $popup = $('#popup-wrapper');
    var $image = $popup.find('#preview-image');
        $image.find('img').load(function()
        {
            fixSlideArrowsHeight();
            popup.showBackground();
        });
        
    var $arrowRight = $popup.find('#arrow-right');
    var $slideshow = $popup.find('.slideshow');
    var $arrowLeft = $popup.find('#arrow-left');
        
    var $thumbnails = $popup.find('#thumbnails .thumbnail');
        $thumbnails.click(function()
        {
            $selectedImage = $(this);
            showThumbnail($selectedImage);
        });
        
    var $imageInfo = $popup.find('#image-info');
    var $imageCounter = $popup.find('#image-counter');
    var $selectedImage = $thumbnails.eq(0);

    $arrowRight.click(nextImage);
    $slideshow.click(slideshowPlayStop);

    $arrowLeft.click(function()
    {
        $selectedImage = $selectedImage.prev('.thumbnail');
        if ($selectedImage.length < 1)
        {
            $selectedImage = $thumbnails.filter(':last');
        }

        showThumbnail($selectedImage);
    });

    function showThumbnail($thumbnail)
    {
        var fullsize = $thumbnail.find('.metadata .fullsize').text();
        var photographer = $thumbnail.find('.metadata .photographer').text();
        var description = $thumbnail.find('.metadata .description').text();

        var position = parseInt($thumbnail.prevAll('.thumbnail').length) + 1;
        $imageCounter.text(position);
        $imageInfo.find('.description').text(description);
        $imageInfo.find('.photographer').text(photographer);
        $image.find('img').attr('src', fullsize);
    }

    function fixSlideArrowsHeight()
    {
        var imageHeight = $image.height();
        $arrowRight.parent().height(imageHeight);
        $arrowLeft.parent().height(imageHeight);
    }
	
	function nextImage()
	{
		$selectedImage = $selectedImage.next('.thumbnail');
		if ($selectedImage.length < 1)
		{
			$selectedImage = $thumbnails.filter(':first');
		}
		showThumbnail($selectedImage);
	}
	
	function slideshowPlayStop()
	{
		if ($timer==null)
		{
			slideshowNext();
			$slideshow.html('Stop slideshow');
		}
		else
		{
			clearTimeout($timer);
			$timer = null;
			$slideshow.html('Afspil som slideshow');
		}
	}

	function slideshowNext()
	{
		nextImage();
		$timer = setTimeout(slideshowNext, 3000);
	}

    fixSlideArrowsHeight();
}


