// ==========================================================================
// AFTER DOCUMENT IS LOADED, DO...
// ==========================================================================

document.observe("dom:loaded", function() {
  // On the product page
    if ($('product')) {
      $('zoomBtn').observe('click', function(event) {
        $$("#gallery div a")[0].simulate("click");
      });
      
      $('print').observe('click', function(event) {
        window.print();
        Event.stop(event);
      });
            
      $('zoomBtn').observe('click', function(event) {
        enlargeImage();
        Event.stop(event);
      });  
      
      arrangeTheseThumbs();
    }
  
  // If there's a Product list..
    if ($$('ul.collection').length > 0) {
      resizeCollection();
    }
});

// ==========================================================================
// COLLECTION RESIZE
// Resizes each element of the same row to make them all the same height.
// ==========================================================================

function resizeCollection() {
  var numberInRow = 4;
  
  var items = $$('ul.collection li');
  var rows = Math.ceil(items.length / numberInRow);
  
  for (r = 1; r < rows; r++) {
    var highest = 0;
    
    // Loops through all the items to find the highest 
      for (i = 1; i < numberInRow; i++) {
        var item = items[(r * numberInRow) - i];
        var newHeight = item.getHeight();
        
        if (newHeight > highest) highest = newHeight;
      }
    
    // Loops through all the items to find the highest 
      for (i = 1; i <= numberInRow; i++) {
        var item = items[(r * numberInRow) - i];
        item.setStyle({
          height: highest + 'px'
        });
      }
  }
}

// ==========================================================================
// ARRANGE THESE THUMBS!
// Vertically centers product thumbnails into its container.
// ==========================================================================

function arrangeTheseThumbs() {
  var thumbnails = $$('#thumbnails li a img');
  
  thumbnails.each(function(thumb) {
    var parentHeight = thumb.parentNode.clientHeight;
    var thumbHeight = thumb.getHeight();
    var offsetY = (parentHeight - thumbHeight) / 2;
    
    thumb.setStyle({ marginTop: offsetY + 'px' });
  });
}

// ==========================================================================
// ENLARGE IMAGE
// Enlarges the displayed thumbnail.
// ==========================================================================

function enlargeImage() {
  var containers = $$('#gallery div');
  
  containers.each(function(container) {
    if (container.getStyle('display') != 'none') {
      container.firstDescendant().simulate('click');
    }
  });
}