(function () {
    $.fn.infiniteCarousel = function () {
        function repeat(str, n) {
            return new Array( n + 1 ).join(str);
        }
        
        return this.each(function () {
            // magic!
            var $wrapper = $('> div', this).css('overflow', 'hidden'),
                $slider = $wrapper.find('> ul').width(99999),
                $items = $slider.find('> li'),
                $single = $items.filter(':first')
                
                singleWidth = $single.outerWidth(),
                visible = Math.ceil($wrapper.innerWidth() / singleWidth),
                currentPage = 1,
                pages = Math.ceil($items.length / visible);
            
            // 1. pad the pages with empty element if required
            if ($items.length % visible != 0) {
                // pad
                $slider.append(repeat('<li class="empty" />', visible - ($items.length % visible)));
                $items = $slider.find('> li');
            }
            
            // 2. create the carousel padding on left and right (cloned)
            $items.filter(':first').before($items.slice(-visible).clone().addClass('cloned'));
            $items.filter(':last').after($items.slice(0, visible).clone().addClass('cloned'));
            $items = $slider.find('> li');
            
            // 3. reset scroll
            $wrapper.scrollLeft(singleWidth * visible);
            
            // 4. paging function
            function gotoPage(page) {
                var dir = page < currentPage ? -1 : 1,
                    n = Math.abs(currentPage - page),
                    left = singleWidth * dir * visible * n;

                navpage = page;
                if (page > pages) {
                    navpage = 1;
                } else if (page == 0) {
                    navpage = pages;
                }
                
                $('.dots a.on').removeClass('on');
                $('#carousel-'+navpage).addClass('on'); 

                $wrapper.filter(':not(:animated)').animate({
                    scrollLeft : '+=' + left
                }, 500, function () {
                    // if page == last page - then reset position
                    if (page > pages) {
                        $wrapper.scrollLeft(singleWidth * visible);
                        page = 1;
                    } else if (page == 0) {
                        page = pages;
                        $wrapper.scrollLeft(singleWidth * visible * pages);
                    }
                    currentPage = page;                   
                });               
            }
            
            // 5. bind the back and forward links
            
            $(this).bind('goto', function (event, page) {
                gotoPage(page);
            });
            
            
            $(this).bind('next', function () {
                gotoPage(parseInt(currentPage) + 1);
            });
            
            $(this).bind('prev', function() {
                gotoPage(parseInt(currentPage) - 1);
            });
        });
    };
})(jQuery);

$(document).ready(function () {

    var autoscrolling = true;

    $('.infiniteCarousel').not('.no-carousel').infiniteCarousel().mouseover(function () {
        autoscrolling = false;
    }).mouseout(function () {
        autoscrolling = true;
    });

    $('.dots li a').click(function(){
        autoscrolling = false;
        $('.dots li a.on').removeClass('on');
        $(this).addClass('on');
        $('.infiniteCarousel').trigger('goto', $(this).text());
        return false;
    });

    setInterval(function () {
        if (autoscrolling) {
            $('.infiniteCarousel').trigger('next');
        }
    }, 8000);


    $('#dwelling-thumbs, #dwelling-thumbs .wrapper').css('height', '93px');

    $('#dwelling-thumbs .wrapper').css({
        'overflow' : 'hidden',
        'position' : 'absolute'
    });
    
    $('#dwelling-thumbs .wrapper ul').css({
        'position' : 'absolute',
        'height' : '93px'
    });
    
    $('#dwelling-thumbs , #dwelling-thumbs .wrapper, #dwelling-thumbs .wrapper ul').css('width', '608px');


    $('#dwelling-thumbs').infiniteCarousel();
    $('.next').click(function(){
        $('#dwelling-thumbs').trigger('next');
        return false;
    });
    $('.prev').click(function(){
        $('#dwelling-thumbs').trigger('prev');
        return false;
    });
    
    $('#dwelling-thumbs li a').click(function(){
        
        var alt = $('img', this).attr('alt');
        
        $('<div class="thumb-loader"></div>').appendTo($(this));
        
        var img = new Image();
        
        $(img).load(function(){
        
            $('.dwelling-photo-image').addClass('remove');
            
            $newPhoto = $('<div></div>')
            .appendTo($('#dwelling-photo'))
            .addClass('dwelling-photo-image')
            .hide();
            
            $(img).appendTo($newPhoto);
            
            $newPhoto.fadeIn();
            
            $('#caption').text(alt);
            
            $('.dwelling-photo-image.remove').fadeOut(function(){ 
                $(this).remove();
                $('.thumb-loader').remove();         
            });

        });
        img.src = $(this).attr('href');        
        return false;
    });
    
    if($('.js.next').length > 0) {
        var i = 1;
        setInterval(function(){
            if(autoscrolling) {
                var $list = $('#dwelling-thumbs ul li:visible').not('.cloned').not('.empty');
                
                if(i >= $list.length) {
                    i = 0;
                }
                
                $item = $list[i];
                
                $item = $($item);
                
                if($item.length > 0) {
                    $('a', $item).click();
                }
                
                if(i%5 == 0 && i > 0 || i == $list.length-1) {
                    $('.js.next').click();
                }            
                i++;
            }
        },5000);
        
        $('#dwelling-thumbs').mouseover(function () {
            autoscrolling = false;
        }).mouseout(function () {
            autoscrolling = true;
        });
            
    }  

});

