$$('.tabs .tab').each(function(tab){
  if (tab.hasClass('reload')) {
    
    head = tab.getElement('.caption').get('text').trim().split(' ');
        
    if (tab.getElement('.caption').get('text').contains('(')) {
      head = head[0]+' '+head[head.length-1];
    }
    else {
      head = head[0];
    }
    
    var hd = new Element('a', {
      'class': 'caption',
      'text': head,
      'href': '?comments'
    });
  }
  else {
    var hd = new Element('span', {
      'class': 'caption',
      'text': tab.getElement('.caption').get('text').split(' ')[0]
    });
    hd.addEvent('click', function(){
      var actual = this.getAllPrevious('.caption').length;
      $$('.tabs .head .caption').removeClass('active');
      this.addClass('active');

      $$('.tabs .tab').setStyle('display', 'none');
      $$('.tabs .tab')[actual].setStyle('display', 'block');
    });
  }
  hd.inject($$('.tabs')[0].getElement('.head'));
});

$$('.tabs .tab').addClass('hdn');

if ($$('.tabs .tab.active').length > 0) {
  $$('.tabs .tab.active').removeClass('hdn');
  i = $$('.tabs .tab.active')[0].getAllPrevious('.tab').length;
  $$('.tabs .head .caption')[i].addClass('active');
}
else {  
  $$('.tabs .head .caption')[0].fireEvent('click', $$('.tabs .head .caption')[0]);
}


if ($$('.pcs-increase')) {
  $$('input.pcs').addEvents({
    keydown: function(event) {
      if (event.key == 'up') {
        event.preventDefault();
        this.value++;
        this.select();      
      }
      else if (event.key == 'down') {
        event.preventDefault();
        this.value--;
        if (this.value < 1) {
          this.value = 1;
        }
        this.select();
      }
    }
  });
  $$('.pcs-increase').addEvents({
    click: function(event){
      input = this.getParent('div').getElement('input.pcs');
      input.value++;
      input.select();
      input.focus();
    },
    mousedown: function(event){
      event.preventDefault();
      this.getParent('div').getElement('input.pcs').focus();
    }
  });
  $$('.pcs-decrease').addEvents({
    click: function(event){
      event.preventDefault();
      input = this.getParent('div').getElement('input.pcs');
      input.value--;
    
      if (input.value < 1) {
        input.value = 1;
      }
      input.select();
      input.focus();
    },
    mousedown: function(event){
      event.preventDefault();
      this.getParent('div').getElement('input.pcs').focus();
    }
  });
}
