var tabs, panels, full_sized_image;

document.observe('dom:loaded', function ()
{
  // Image zoom controls
  $$('.trigger.zoom-image').invoke('observe', 'click', function (event)
  {
    event.stop();
    if (!full_sized_image) full_sized_image = $('zoom-product').remove().show();
    broadcast.display(full_sized_image);
  });
  if ($('zoom-close')) $('zoom-close').observe('click', function (event)
  {
    event.stop();
    broadcast.dismiss();
  });
  
  // Tab behaviour
  tabs = $$('#tabbed > ul li');
  panels = $$('#tabbed > div');
  
  if (tabs) tabs.invoke('observe', 'click', function (tabs, panels, event)
  {
    var selected_index;
    
    selected_index = tabs.indexOf(event.findElement('li'));
    
    tabs.without(tabs[selected_index]).invoke('removeClassName', 'on');
    panels.without(panels[selected_index]).invoke('removeClassName', 'open');
    
    tabs[selected_index].addClassName('on');
    panels[selected_index].addClassName('open');
  }.curry(tabs, panels));
  
  // Add item to cart via Ajax, update "my bag" panel and show visual hint
  $$('.trigger.add-item-to-cart').invoke('observe', 'click', function (event)
  {
    var product;
    
    event.stop();
    
    product = event.findElement('.product');
    
    
    new Ajax.Request(event.findElement('a').getAttribute('href'),
    {
      parameters: {via_socket:true},
      onSuccess: function (transport)
      {
        var response, notification_labels, my_bag_display, bagged_items, matched_item, new_item;
        response = transport.responseJSON;
        
        notification_labels = $$('.item-added');
        my_bag_display = $('target-my-bag');
        bagged_items = my_bag_display.select('.my-bag-item');
        
        if (response.success)
        {
          notification_labels.findAll(function (product, label) {return label.hasClassName('global') || typeof product === 'undefined' || product.down('.item-added') === label;}.curry(product)).each(displayAddedToCartNotificationLabels);
          
          my_bag_display.select('.total-quantity').invoke('update', response.total_quantity);
          my_bag_display.select('.subtotal').invoke('update', response.total_value.toFixed(2));
          
          matched_item = bagged_items.find(function (product_id, variant_id, item)
          { 
            var identifier, match_string;
            identifier = item.getAttribute('id').replace(/^[a-z\-]+/i, '');
            match_string = variant_id !== null? product_id + '-' + variant_id: product_id.toString();
            return identifier === match_string;
          }.curry(response.product_id, response.variant_id));
          
          if (matched_item) matched_item.down('.variant-quantity').update('(' + response.variant_quantity + ')');
          else my_bag_display.down('ul').insert({top:constructBagItem(response.product, response.image, response.link, response.product_id, response.variant_id)});
        }
        else
        {
          if (console) console.log(response.response_code);
          if (console) console.log(response.message);
        }
      }.curry(),
      onFailure: function ()
      {
        if (console) console.log('Failure');
      },
      onError: function ()
      {
        if (console) console.log('Error');
      }
    });
  });
});

function constructBagItem (product, image, link, product_id, variant_id)
{
  var li, a, img;
  
  li = new Element('li', 
  { 
    'id':'my-bag-item-' + product_id + (variant_id !== null? '-' + variant_id: ''),
    'class':'my-bag-item'
  });
  a = new Element('a', 
  {
    'href':link,
    'title':product
  }).update('<strong><span class="variant-quantity"></span> ' + product + '</strong>');
  img = new Element('img',
  {
    'src':image,
    'alt':product
  });
  a.insert({bottom:img});li.insert({bottom:a});
  
  return li;
}

function displayAddedToCartNotificationLabels (label)
{
  var effect_duration, effect_scope, base_parameters, appear_parameters, fade_parameters, delayed_fade;
  if (typeof label.is_animating !== 'undefined' && label.is_animating) return false;
  
  effect_duration = 0.5;
  effect_scope = 'cart:display-label';
  
  base_parameters = 
  {
    duration: 0.5,
    queue: {scope:'cart:display-label'}
  };
  appear_parameters = Object.clone(base_parameters);
  appear_parameters.beforeStart = function (label) {label.is_animating = true;}.curry(label);
  label.appear(appear_parameters);
  
  fade_parameters = Object.clone(base_parameters);
  fade_parameters.afterFinish = function (label) {label.is_animating = false;}.curry(label);
  delayed_fade = function (label, fade_parameters) {label.fade(fade_parameters);}.curry(label, fade_parameters);
  delayed_fade.delay(3);
}
