// aggancio la richiesta via ajax sui link del carrello
window.addEvent('domready', function(){
  // carrello ajax solo se abbiamo il carrello visuale in colonna

  if (!$('sidebar-cart'))
    return;

  $$('.butt-compra').each(function(el){
    el.addEvent('click', function(e){
      e = new Event(e);
      e.preventDefault();

      var request_url = this.getProperty('href')+'&'+$time();

      var xrequest = new Request.HTML({
        url : request_url,
        method : 'post',
        encoding : 'iso-8859-1',
        headers: {'X-Request': 'Ajax'},
        onRequest : function(){
          overlay.show();
        },
        onComplete : function(responseTree, responseElements, responseHTML, responseJavaScript){
          // se esiste il blocco carrello lo sostituisco
          var cart_wrapper = $('sidebar-cart');
          var col_wrapper = $('blocco-dx');
          var tot_articoli = 0;
          var extra_msg = '';

          if (cart_wrapper){
            cart_wrapper.destroy();
            old_content = col_wrapper.get('html');
            col_wrapper.set('html', responseHTML, old_content);

            $$('#sidebar-cart .sub-totale').each(function(el){
              var str = el.get('text');
              tot_articoli += str.substring(0, str.indexOf(' ')).toInt();
            });
          }

          if (tot_articoli > 0)
            {
            extra_msg += '<p class="small"><strong>Hai un totale di '+ tot_articoli + ' prodott';
            extra_msg += (tot_articoli == 1) ? 'o' : 'i';
            extra_msg += ' nel carrello</strong></p>';
            }

          overlay.msg('<p>Prodotto aggiunto</p>'+ extra_msg+'<a href="javascript:overlay.msg_hide();">Scegli altri prodotti</a> | <a href="' + window.site_url +'cart.php">Completa l\'ordine</a></p>');
        }
      }).send();
    });
  });
});

var overlay = new Hash({
  show : function(){
    if (!this.o)
      this.o = new Element('div', {'id': 'overlay'}).injectInside(document.body);

    this.o.setStyles({'display': 'block', 'opacity': 0.9, 'top': (window.getScrollTop() + (window.getHeight() / 3))});
  },

  hide : function(){
    this.o.setStyle('display', 'none');
  },

  msg : function(message){
    if (!this.m)
      this.m = new Element('div', {'id': 'overlay-msg'}).injectInside(document.body);

    this.hide();
    this.m.setStyles({'opacity': 0.9, 'top': (window.getScrollTop() + (window.getHeight() / 3))});
    this.m.set('html', '<br />' + message);
    (function(){ this.msg_hide() }).bind(this).delay(5000)
  },

  msg_hide : function(){
    this.m.fade('out');
  }

});
