// meh... if you want your script in the document head
$(function(){
  //name space isolating closure
  (function(){

    var delay = 6000, // image view time
        $galleryContainer = $('.gallery-container'),
        $gallery = $galleryContainer.find('.gallery'),
        $galleryImages = $gallery.find('img'),
        $thumbs, $thumbImages, $activeThumb, thumbWidth, timer;

    // ensure at least 5 items
    if ($galleryImages.length < 5){
      for (var i = 0; i < $galleryImages.length; i++){
        $gallery.append($galleryImages.eq(i).clone());
      }
      $galleryImages = $gallery.find('img');
    }

    $galleryImages.hide();

    // build thumbnail slider
    $galleryContainer.append('<div class="gallery-slider">' +
      '<div class="slider-left"></div>' +
      '<div class="slider-container"><ul class="thumbs"></ul></div>' +
      '<div class="slider-right"></div>' +
    '</div>');

    $thumbs = $galleryContainer.find('.thumbs');

    // TODO - populate scoller could check width/size and calc thumbnails
    for (i = 0; i < $galleryImages.length; i++){
      $thumbs.append('<li><img src="' + $galleryImages.eq(i).attr('rel') + '" data-idx="' + i + '"/></li>'); // thumbnail = gallery image rel attribute
    }

    $thumbImages = $thumbs.find('img');
    thumbWidth = $('.thumbs li').outerWidth(); //include padding/border

    // TODO - could check if number of thumbs requires scrolling (calc widths) and show/hide buttons
    $thumbs.find('li:first').before($thumbs.find('li:last')); // move last list item before the first item - click left will see the last item


    /* * * start * * */
    activeImage();
    startTimer();


    /* * * events - using < jQ 1.7 * * */

    $galleryImages.bind('mouseenter', function(){
      stopTimer();
    });

    $galleryImages.bind('mouseleave', function(){
      startTimer();
    });


    $galleryImages.bind('click', function(){
      window.location = $(this).attr('data-link'); // load valid link
    });


    $galleryContainer.delegate('.thumbs img', 'mouseenter', function(){
      stopTimer();
      showThumb($(this));
    });


    $galleryContainer.delegate('.thumbs', 'mouseleave', function(){
      showThumb($thumbs.find('li:eq(2) img'));
      startTimer();
    });


    $galleryContainer.delegate('.thumbs li', 'click', function(){
     var sel = $thumbs.find('li').index(this);
     if (sel != 2){
      sel > 2 ? slide('right') : slide('left');
     }
    });


    $galleryContainer.delegate('.slider-right', 'click', function(){
      slide('right');
    });


    $galleryContainer.delegate('.slider-left', 'click', function(){
      slide('left');
    });


    /* * * methods * * */

    function startTimer(){
      timer = setTimeout(slide, delay);
    }


    function stopTimer(){
      clearTimeout(timer);
    }


    function showThumb($thumb){
      if ($thumbs.not(':animated')){
        $thumbImages.css({'opacity': .5});
        $thumb.css({'opacity': 1});
      }
    }

    // Note: have to pass idx as attribute selectors [rel= ...] do not work correctly in MSIE < 8
    function showImage($thumb){
      $galleryImages.fadeOut(300).eq($thumb.attr('data-idx')).show().stop(true, true).fadeIn(400);
    }


    function activeImage(){
      $activeThumb = $thumbs.find('li:eq(2)').find('img');
      showThumb($activeThumb);
      showImage($activeThumb);
    }


    function slide(dir) {
      dir = dir || 'right';
      var offset = parseInt($('.thumbs').css('left')) + (dir == 'left' ?  thumbWidth : -thumbWidth);
      // sliding effect
      $thumbs.not(':animated').animate({'left': offset}, 500, function(){
        stopTimer();
        // when the animation finishes make illusion of infinity by changing place of last or first item
        dir == 'left' ? $thumbs.find('li:first').before($thumbs.find('li:last')) : $thumbs.find('li:last').after($thumbs.find('li:first'));
        $thumbs.css({'left': '-' + thumbWidth + 'px'});
        activeImage();
        startTimer();
      });
    }

  })();

});
