/**
 * Supports image swap with cross-fade and info text change
 */
$(function() {
  // Set active image color
  var colorDefault = $('#color_name').attr('alt');
  var preLoad = new Array();
  
  // Change the Buy now link to a form submit button
  $('#tabs .buy a, #nav_buynow a').click(function() {
    // testing if the form exists (product overview page)
    if ($('#pdapproduct_sku_form').length) {
      $('#pdapproduct_sku_form').submit();
      return false;
    }
  });
  
  // Handle color swatch hover interactions
  $('li.color-swatch').hover(function() {
    var colorName = $(this).attr('title');
    $('#color_name').html(colorName);
  }, function() {
    $('#color_name').html(colorDefault);
  });
  
  // Handle color swatch click interactions
  $('li.color-swatch').click(function() { 
    var colorValue = $(this).attr('name');
    colorDefault = $(this).attr('title');
    $('li.color-swatch').removeClass('active');
    $(this).addClass('active');
    $('#pdapproduct_sku_form #edit-color').val(colorValue);
    imageSwap(this);
  });
  
  // Handle alt view click interactions
  $('ul.alt-view li').click(function() { 
    imageSwap(this);
  });
  
  // Handle size swatch click interactions
  $('li.size-swatch').click(function() { 
    var sizeValue = $(this).attr('name');
    $('li.size-swatch').removeClass('active');
    $(this).addClass('active');
    $('#pdapproduct_sku_form #edit-size').val(sizeValue);
  });
  
  // preload all alternate images
  $('li.color-swatch, ul.alt-view li').each(function(){
    $(new Image()).attr('src', $(this).attr('src'));
  });
});

/**
 * Image crossfade
 */
function imageSwap(element) {
  colorImage = $(element).attr('src');
  $('#product-loader img').attr('src', colorImage);
  $('#product').fadeOut(500, function () {
    $('#product img').attr('src', colorImage);
    $(this).css('display', 'block');
  });

  return false;
}