;(function($){
    var $imageList = $('ul', '#background');
    	preloadedImages = [],
        numberOfImages  = backgrounds.length,
		previousImageID = numberOfImages;
        currentIndex = 0,
        delay = 7000,
        duration = 3000;

    function preloadBackgrounds()
    {
        var initialized = false;

        // loop through the defined backgrounds
        $.each(backgrounds, function(i, backgroundSrc) {

            // create and preload a new image element
            var img = new Image();
            $(img).load(function(){

                // store the image in an array for use in the animations
                var newImage = {
                    image:  $(img),
                    width:  img.width,
                    height: img.height,
                    id: i
                };
                preloadedImages.push(newImage);

                // create a new list item
                var $newListItem    = $('<li />').css({opacity: 0, position: 'absolute', left: 0, top: 0}),
                    imageDemensions = calculateOptimalDimenstions(newImage);

                // add the newly created image and set the optimal dimensions
                $(img)
                    .attr('width', imageDemensions.width)
                    .attr('height', imageDemensions.height)
                    .attr('id', newImage.id)
                    .appendTo($newListItem);

                $newListItem.appendTo($imageList);

                // if the animation wasn't yet initialized, initialize it
                if (!initialized) {
                    init();
                    initialized = true;
                }

            })
            .attr('src', backgroundSrc);
        });
    }

    /**
     * returns the image dimensions so the image will
     * fill the screen withouth distorting the image ratio
     *
     * @param object { width: [original image width], height: [original image height] }
     * @return object { width: [optimal image width], height: [optimal image height] }
     */
    function calculateOptimalDimenstions($image)
    {
        // calculate window ratio
        var windowRatio = $(window).width() / $(window).height();

        // calculate image dimensions
        var imageRatio = $image.width/$image.height;

        if (imageRatio < windowRatio) {
            // resize by width
            var imageWidth  = $(window).width();
            var imageHeight = imageWidth / imageRatio;
        } else {
            // resize by height
            var imageHeight = $(window).height();
            var imageWidth  = imageHeight * imageRatio;
        }

        // return optional dimensions
        return {
            width: imageWidth,
            height: imageHeight
        };
    }

    // start animation loop
    function init()
    {
        animate();
        if ($.browser.msie && $.browser.version < 8) {
        	return;
        }
        var timer = window.setInterval(animate, delay);
    }

    /**
     * animates to the next image by increasing zIndex
     * and animates the opacity to 1
     * after the animation, the previous image is hidden and
     * the old image's zIndex is lowered
     */
    function animate()
    {
        // determine currentIndex
        if (currentIndex == numberOfImages) {
            currentIndex = 0;
        }

        // determin previousIndex
        if (currentIndex == 0) {
            oldIndex = numberOfImages - 1;
        } else {
            oldIndex = currentIndex -1;
        }

        // check for preloaded images
        if (preloadedImages.length > 0 && typeof(preloadedImages[currentIndex]) == 'object') {
        
            // get the required dom elements
            var $newItem = $('#background').find('li:eq(' + currentIndex + ')'),
                $oldItem = $('#background').find('li:eq(' + oldIndex + ')'),
                $image   = $newItem.find('img');

			// store id of preloadedImage
			newImageID = preloadedImages[currentIndex].id;

            // recalculate optimal image dimensions
            imageDemensions = calculateOptimalDimenstions(preloadedImages[currentIndex]);

            $image
                .attr('width', imageDemensions.width)
                .attr('height', imageDemensions.height);

				$('.home #header-title').addClass('werk'+newImageID);

	        // change z-index and animate opacity
            $newItem
                .css('z-index', 10)
                .animate({opacity: 1}, duration, function(){
                    $(this).css('z-index', 0);
                    $oldItem.css('opacity', 0);
                });

			$('.home #header-title').removeClass('werk'+previousImageID);

	        previousImageID = preloadedImages[currentIndex].id;
        }

        currentIndex++;

    }

    // start preloading images
    preloadBackgrounds();

})(jQuery);
