$(function() {
    var $currentImage = $('#intro-slider').find('img').first();
    var noImages = $('#intro-slider').find('img').length;
    $('#intro-slider').find('img').hide().each(function(i) {
        $(this).css('z-index', noImages - i);
        if (i === noImages - 1) {
            startIntroSlide();
        }
    });

    //Intro slider
    function startIntroSlide() {

        $currentImage.imagesLoaded(function() {
            $(this).fadeIn(1800, function() {
                $(this).siblings('img').show();
                cycleImages();
            });
        });
    }

    function cycleImages() {
        $currentImage.delay(4000).fadeOut(800, function() {
            $(this).css('z-index', 1).show();
            $currentImage.siblings('img').each(function() {
                $(this).css('z-index', parseInt($(this).css('z-index')) + 1);
            });
            if($(this).next().length == 0) {
                $currentImage = $('#intro-slider').find('img').first();
            } else {
                $currentImage = $currentImage.next();
            }
            cycleImages();
        });
    }

    $('#product-slider').find('img').first().imagesLoaded(function() {
        $(this).fadeIn(800, function() {
            $('#product-slider').initSlider();
        });
    });

    $('#select-month').change(function() {
        document.location.href = $(this).val();
    });

    $.fn.initSlider = function() {
        $(this).cycle({
            next: '#product-slider-nav .next',
            prev: '#product-slider-nav .prev',
            timeout: 5000
        });
    }

});

$.fn.imagesLoaded = function(callback){
    var elems = this.filter('img'),
    len   = elems.length;

    elems.bind('load',function(){
        --len;
        if (len === 0) {
            callback.call(elems, this);
        }
    }).each(function(){
        // cached images don't fire load sometimes, so we reset src.
        if (this.complete || this.complete === undefined){
            var src = this.src;
            // webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f
            // data uri bypasses webkit log warning (thx doug jones)
            this.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
            this.src = src;
        }
    });

    return this;
}
