var cartURL = '/index.php?id=55';
var checkoutURL = '/index.php?id=57';

/* Adapted from Slimbox by Joao Paulo Magalhaes */
/*
  Slimbox v1.41 - The ultimate lightweight Lightbox clone
  by Christophe Beyls (http://www.digitalia.be) - MIT-style license.
  Inspired by the original Lightbox v2 by Lokesh Dhakar.
*/

var Cart = {

  init: function(options){
    this.options = $extend({
      resizeDuration: 200,
      resizeTransition: false,  // default transition
      initialWidth: 550,
      initialHeight: 350,
      animateCaption: true,
      showCounter: false
    }, options || {});

/*--    $each(document.links, function(el){
      if (el.rel && el.rel.test(/^cart/i)){
        el.onclick = this.click.pass(el, this);
      }
    }, this);--*/

    this.eventKeyDown = this.keyboardListener.bindAsEventListener(this);
    this.eventPosition = this.position.bind(this);

    this.overlay = new Element('div', {
      'id': 'cartOverlay'
    }).injectInside(document.body);

    this.center = new Element('div', {
      'id': 'cartCenter',
      'styles': {
        'width': this.options.initialWidth,
        'height': this.options.initialHeight,
        'marginLeft': -(this.options.initialWidth/2),
        'display': 'none'
      }
    }).injectInside(document.body);

    this.image = new Element('div', {
      'id': 'cartImage'
    }).injectInside(this.center);

    new Element('img',{
      'id': 'cartLogo',
      'src':'assets/templates/bacibaby-logo-56x50.jpg',
      'alt':''
    }).injectInside(this.image);
    new Element('a', {
      'id': 'cartCloseLink',
      'href': '#'
    }).setHTML('<img src="assets/templates/first/images/closelabel-crossonly.gif" alt="Fechar" title="Fechar" width="11"/>')
      .injectInside(this.image)
      .onclick = this.overlay.onclick = this.close.bind(this);

    this.title = new Element('h2')
        .setHTML('Carrinho de compras')
        .injectInside(this.image);

    this.cart = new Element('div', {
      'id': 'cart'
    }).injectInside(this.image);

    this.cartOptions = new Element('div',{
      'id':'cartOptions'
    }).injectInside(this.image);

    new Element('a', {
      'href': '#',
      'style': 'float:left;'
    }).setHTML('Voltar').injectInside(this.cartOptions)
      .onclick = this.close.bind(this);

    new Element('a', {
      'href': checkoutURL,
      'style': 'float:right;'
    }).setHTML('Ver o carrinho').injectInside(this.cartOptions)
      .onclick = this.close.bind(this); //--function(){this.close.bind(this); return true;};

    var nextEffect = this.nextEffect.bind(this);

    this.fx = {
      overlay: this.overlay.effect('opacity',{duration: 500}).hide(),

      resize: this.center.effects($extend({
        duration: this.options.resizeDuration,
        onComplete: nextEffect
      }, this.options.resizeTransition ? {transition: this.options.resizeTransition} : {})),

      image: this.image.effect('opacity', {
        duration: 500, onComplete: nextEffect
      })

/*      bottom: this.bottom.effect('margin-top', {
        duration: 400, onComplete: nextEffect
      })*/
    };

  },

  click: function(link){
    // hide the tip
    $$('.dica-tip').each(function(item){
      item.setStyle('visibility','hidden');
    });
    // add the item to the cart
    AjaxCart.add(link);
    // show the popup
    return this.show(link.href, link.title);
  },

  show: function(url, title){
    this.position();
    this.setup(true);
    this.top = window.getScrollTop() + (window.getHeight() / 15);
    this.center.setStyles({top: this.top, display: ''});
    this.fx.overlay.start(0.8);

    this.step = 1;
//    this.activeImage = imageNum;

//    this.bottomContainer.style.display = 'none';
    this.fx.image.hide();
    this.center.className = 'cartLoading';

    this.preload = this.image;//new Image();
    this.preload.onload = this.nextEffect.bind(this);
//    this.preload.src = this.images[imageNum][0];
    this.nextEffect();
    return false;
  },

  position: function(){
    this.overlay.setStyles({
      'top': window.getScrollTop(),
      'height': window.getHeight()
    });
  },

  setup: function(open){
    var elements = $A(document.getElementsByTagName('object'));
    elements.extend(document.getElementsByTagName(window.ie ? 'select' : 'embed'));
    elements.each(function(el){
      if (open) el.lbBackupStyle = el.style.visibility;
      el.style.visibility = open ? 'hidden' : el.lbBackupStyle;
    });
    var fn = open ? 'addEvent' : 'removeEvent';
    window[fn]('scroll', this.eventPosition)[fn]('resize', this.eventPosition);
    document[fn]('keydown', this.eventKeyDown);
    this.step = 0;
  },

  keyboardListener: function(event){
    switch (event.keyCode){
      case 27: case 88: case 67: this.close(); break;
    }
  },

  nextEffect: function(){
    switch (this.step++){
    case 1:
      this.center.className = '';
/*      var size = {x:0, y:0};// = $(this.preload).getSize();
      $(this.preload).getChildren().each(function(chil){
        s = chil.getSize();
        size.x += s.x;
        size.y += s.y;
      })
      this.image.style.width =  size.x + 'px';
      this.image.style.height = size.y + 'px';
*/
      this.image.style.width =  '600px';
      this.image.style.height = '320px';

      if (this.center.clientHeight != this.image.offsetHeight){
        this.fx.resize.start({height: this.image.offsetHeight});
        break;
      }
      this.step++;
    case 2:
      if (this.center.clientWidth != this.image.offsetWidth){
        this.fx.resize.start({
          width: this.image.offsetWidth,
          marginLeft: -this.image.offsetWidth/2
        });
        break;
      }
      this.step++;
    case 3:
/*      this.bottomContainer.setStyles({
        top: this.top + this.center.clientHeight,
        height: 0,
        marginLeft: this.center.style.marginLeft,
        display: ''
      });*/
      this.fx.image.start(1);
      break;
    case 4:
/*      if (this.options.animateCaption){
        this.fx.bottom.set(-this.bottom.offsetHeight);
        this.bottomContainer.style.height = '';
        this.fx.bottom.start(0);
        break;
      }
      this.bottomContainer.style.height = '';*/
    case 5:
//      if (this.activeImage) this.prevLink.style.display = '';
//      if (this.activeImage != (this.images.length - 1)) this.nextLink.style.display = '';
      this.step = 0;
    }
  },

  close: function(){
    if (this.step < 0) return;
    this.step = -1;
    if (this.preload){
      this.preload.onload = Class.empty;
      this.preload = null;
    }
    for (var f in this.fx) this.fx[f].stop();
    this.center.style.display = 'none';
    this.fx.overlay.chain(this.setup.pass(false, this)).start(0);
//--    return false;
  }
};

var AjaxCart = {

  init: function(url, elm){
    this.ajax = new Ajax(url, {update:elm, evalResponse:false});
  },

  show: function(){
    this.ajax.request({action:'print'});
  },

  empty: function(){
    this.ajax.request({action:'empty'});
  },

  add: function(link){
    var tipo = link.getProperty('tipo');
    if(tipo == 1){//sling pronto
      var obj = {
        action:'add',
        tipo:tipo,
        id_sling_pronto:link.getProperty('pid'),
        tamanho:link.getProperty('tamanho').toUpperCase(),
        qtdd:1
      }
    } else if(tipo == 2){//sling por encomenda
      var medida = 0;
      var obj = {
        action:'add',
        tipo:tipo,
        tecido1:link.getProperty('id1'),
        tecido2:link.getProperty('id2'),
//        medida:medida,
        qtdd:1
      };
    }
    this.ajax.request(obj);
  },

  remove: function(id){
    this.ajax.request({action:'remove',itemID:id});
  },

  closeXHR: function(){
    this.ajax = null;
  }
}

window.addEvent('domready', function(){
  Cart.init();
  AjaxCart.init(cartURL, Cart.cart);
});
