$(function(){
  $("img.valign").each(function(){
    $(this).css("margin-top", Math.floor(($(this).parent().height() - $(this).height()) / 2) + "px");
    $(this).load(function(){
      $(this).css("margin-top", Math.floor(($(this).parent().height() - $(this).height()) / 2) + "px");
    });
  });

  $('#topslides').slideshow({
    nextElem: '#slideshow .nextImage',
    prevElem: '#slideshow .prevImage',
    fadeDuration: 500,
    interval: 5000
  });


  var showProduct = $('#productSlides').slideshow({
    fadeDuration: 400,
    nextElem: '#productSlides .sright',
    prevElem: '#productSlides .sleft',
    onShow: function(elem) {
      $(elem).parent().children().each(function(i, e) {
        if (elem.get(0) == e) {
          $('#product .minis li').each(function(j, e){
            if (i == j) {
              $(this).addClass('selected');
              var top = $(this).position().top;
              var scroll = $(this).parent().scrollTop();

              if (top < 0) $(this).parent().animate({
                scrollTop: scroll+top
              });
              if (top > 230) {
                $(this).parent().animate({
                  scrollTop: scroll+top-$(this).height()-110
                });
              }
            } else {
              $(this).removeClass('selected');
            }
          })
        }
      });
    },
    interval: 0
  });

  $('#product .minis a').each(function(i, elem){
    $(elem).click(function(event){
      event.stopPropagation();
      s = $('#productSlides li').eq(i);
      showProduct(s);
      return false;
    })
  });

  function adjustPaletteHeights() {
    $('.color-palette:visible').each(function () {
      var _maxHeight = 0;
      $('b', this).each(function(){
        if (_maxHeight < $(this).height()) {
          _maxHeight = $(this).height();
        }
      });
      $('b', this).css({height: _maxHeight+'px'});
    })
  }
  if ($('.color-palette').is(":visible")) {
    adjustPaletteHeights();
  } else {
    $('#showColors').click(function(){
      adjustPaletteHeights();
    })
  }
});


