jQuery.noConflict();
jQuery(document).ready(function(){
  totalWidthOfBox = 0;
  widthOfVisibleBox = jQuery("#products").width();
  
  jQuery('#products img').each(function() {
    totalWidthOfBox += jQuery(this).attr('width');
  });
  totalWidthOfBox += 215;
  jQuery('#products').css('overflow', 'hidden');
  
  if (totalWidthOfBox > widthOfVisibleBox) {
    halfWidthOfBox = totalWidthOfBox / 2;
    jQuery('#products .product').wrapAll('<div id="imageSlide_Wrapper" style="position: relative; left: 0px; width: '+totalWidthOfBox+'px"></div>');
    
    outerToInnerRelation = (totalWidthOfBox - widthOfVisibleBox) / widthOfVisibleBox;
    
    jQuery('#products').mousemove(function(event) {
    
      jQuery('#imageSlide_Wrapper').stop();
      currentMouseposition = event.clientX - jQuery('#products').offset()['left']; 
      interpolatedPosition = currentMouseposition * outerToInnerRelation;
      
      if (interpolatedPosition <= (totalWidthOfBox - widthOfVisibleBox)) {
        jQuery('#imageSlide_Wrapper').css('left', '-'+interpolatedPosition+'px');
      }
    });
    
    jQuery('#products').mouseout(function(event) { 
      if (event.clientX > currentMouseposition) {
        animateRight(totalWidthOfBox - widthOfVisibleBox);
      } else {
        animateLeft(totalWidthOfBox - widthOfVisibleBox);
      }
    });
    
    animateRight(totalWidthOfBox - widthOfVisibleBox);
  }     
  
  jQuery('.product a').click(function() {
  	 jQuery('#detailImages div').css('display', 'none');
  	 imageId = '#' + jQuery(this).attr('rel');    
  	 jQuery(imageId).fadeIn('fast');
  	 return false;
  });
});

function animateLeft(total) {
  jQuery('#imageSlide_Wrapper').animate({ left: '0px'}, calculateSeconds(-1, total), 'linear', function() { animateRight(total) });
}

function animateRight(total) {
  jQuery('#imageSlide_Wrapper').animate({ left: '-' + total + 'px'}, calculateSeconds(1, total), 'linear', function() { animateLeft(total) });
}

function calculateSeconds(direction, totalWidth) {
  currentPosition = Math.abs(Number(jQuery('#imageSlide_Wrapper').css('left').replace('px', '')));
  miliSecondsPerPixel = 20;
  
  if (direction == 1) {
    return miliSecondsPerPixel * (totalWidth - currentPosition);
  } else {
    return miliSecondsPerPixel * currentPosition;
  }
}
