(function ($) {
  $.fn.carousel = function (opt) {
    var defaults = {
        dir         :'horizontal',
        imgWidth    :'80',
        imgHeight   :'80'
    };
    var opt = $.extend(defaults, opt);

    //nice little function that makes an array(n) and joins it to a string with (str) as limitator
    function repeat(str, n) {
        return new Array(n+1).join(str);
    }
    return this.each(function (){
        var $parent=$(this),
            $wrapper=$('<div class="wrapper"></div>').appendTo($parent),
            $carousel=$('<ul></ul>').appendTo($wrapper);

        $.each(opt.images,function (){
            $item=$('<li></li>').appendTo($carousel);
            $item.css({'float':(opt.dir=='horizontal'?'left':'clear')});
        });


        $items = $carousel.find('> li');
        $single = $items.filter(':first');
        itemWidth = $single.outerWidth();
        var currentPage=1,
        itemsVisible=Math.ceil($wrapper.innerWidth()/itemWidth),
        pages=Math.ceil($items.length/itemsVisible);

        console.log(itemsVisible)
        console.log(itemWidth)
        console.log($wrapper.innerWidth())

        if (($items.length % itemsVisible) != 0) {
            $carousel.append(repeat('<li style="float:'+(opt.dir=='horizontal'?'left':'clear')+'"/>', itemsVisible - ($items.length % itemsVisible)));
            $items = $carousel.find('> li');
        }
        $carousel.width(itemWidth*$items.length);
        var i=0;
        $.each(opt.images,function (){
            if($item.imageLoad)
                $($items[i++]).imageLoad({'images':[this]});
            else
                $($items[i++]).append('<img src="'+this.src+'" '+(this.alt?'alt="'+this.alt+'"':'')+' width="'+opt.imgWidth+'" height="'+opt.imgHeight+'">');
        });
        if($.fn.imageLoad){
              $.imageLoadAllLoadedCallback=(function(){
                  $items.filter(':first').before($items.slice(- itemsVisible).clone().addClass('cloned'));
                  $items.filter(':last').after($items.slice(0, itemsVisible).clone().addClass('cloned'));
                  $items = $carousel.find('> li');
                  $carousel.width(itemWidth*$items.length);
                  $wrapper.scrollLeft(itemWidth*itemsVisible);
              });
         }else{
            $items.filter(':first').before($items.slice(- itemsVisible).clone().addClass('cloned'));
            $items.filter(':last').after($items.slice(0, itemsVisible).clone().addClass('cloned'));
            $items = $carousel.find('> li');
            $items.mouseenter(function(){
                if($(this).children().length>0){
                    var newImage=$(this).children().clone().css({width:425,height:392,display:'none'}),
                        oldImage=$('#viewport').children('img')
                    $('#viewport').prepend(newImage)
                    newImage.fadeIn(400).addClass('productImage')
                    oldImage.fadeOut(400)
                }
            })
            $carousel.width(itemWidth*$items.length);
            $wrapper.scrollLeft(itemWidth*itemsVisible);
        }
        
        function gotoPage(page) {
            var dir = page < currentPage ? -1 : 1,
                n = Math.abs(currentPage - page),
                left = itemWidth * dir * itemsVisible * n;


            $wrapper.filter(':not(:animated)').animate({
                scrollLeft : '+=' + left
            }, 500, function () {
                if (page == 0) {
                    $wrapper.scrollLeft(itemWidth * itemsVisible * pages);
                    page = pages;
                } else if (page > pages) {
                    $wrapper.scrollLeft(itemWidth * itemsVisible);
                    page = 1;
                }
                $('.pageNavi > div').css({'background-image':'url(images/icons/pageNavi.png)'})
                $('.pageNavi > #'+page).css({'background-image':'url(images/icons/pageNaviActive.png)'})
                currentPage = page;
            });
        }

        $pageNavi=$('<div class="pageNavi"></div>')
        $pageNavi.width(pages*20)
        $wrapper.after($pageNavi);
        for(var x=1;x<pages+1;x++){
            $pageNavi.append('<div id="'+x+'"></div>')
        }
        $('.pageNavi > #1').css({'background-image':'url(images/icons/pageNaviActive.png)'})

        $('.pageNavi > div', this).click(function () {
              $('.pageNavi > div').css({'background-image':'url(images/icons/pageNavi.png)'})
              $('.pageNavi > #'+$(this).attr('id')).css({'background-image':'url(images/icons/pageNaviActive.png)'})
              gotoPage(parseInt($(this).attr('id')));
        });

        $wrapper.before('<a class="arrow back"></a>');
        $wrapper.after('<a class="arrow forward"></a>');

        $('a.back', this).click(function () {
            gotoPage(currentPage-1);
        });

        $('a.forward', this).click(function () {
            gotoPage(currentPage+1);
        });

        $(this).bind('goto', function (event, page) {
            gotoPage(page);
        });

    });
  };
})(jQuery);
