var MT_CartControll = new Class({
  Implements: Events
});


/**
 * Warenkorb
 */
var Cart = {

  save: function()
  {
    Configurator.Storage.save();
  },
  
  /**
   * Speichern
   */
  remove: function(ID)
  {
    Configurator.Storage.remove(ID);
  },
  
  saveDo: function()
  {
    Configurator.Storage.saveDo();
  },
  
  /**
   * Absetzen einer Änderung
   */
  update: function(FromElement, o)
  {
    o = $pick(o, {});
    if (FromElement[0] && !FromElement.options) 
    {
      Parameters = '';
      for (ElemCount = 0; ElemCount < FromElement.length; ElemCount++) 
      {
        if (Parameters.length > 0) 
        {
          Parameters += '&';
        }
        Parameters += Cart.prepareValue(FromElement[ElemCount]);
      }
    }
    else 
    {
      Parameters = Cart.prepareValue(FromElement);
    }
    
    if (Parameters.length > 0) 
    {
      Parameters += '&';
    }
    
    var SessID = Cart.sessionId();
    
    if (SessID) 
    {
      Parameters += 'PHPSESSID=' + SessID;
    }
    
    Parameters += '&KEY=' + KEY;
    Parameters += '&FromEngine=' + document.location.href;
    
    var ReqDate = new Date();
    new Request.JSON({
       url: '/plugin/de.masstisch.ajax/Cart.php'
      ,data: Parameters
      ,onComplete: function(r)
      {
        Cart.paint(r);
  
        document.getElements('.helplink').each(function(el)
        {
          if (el.preppedHelplink) return; el.preppedHelplink = true;
          if (!el.href && !el.src) return;
          
          var JB = Jax_BrowserUtil.getInstance();
          JB.prepareTrigger(el);
        });
        
        if (this.o.onComplete)
        {
          this.o.onComplete();
        }
        
        Cart.Controll.fireEvent('updated');
        window.fireEvent('cartUpdated');
      }.bind({o: o})
    }).send();
  },
  
  
  /**
   * Neuzeichnen des Warenkorbs und ausführen weiterer Aktionen
   */
  paint: function(r)
  {
    r = $pick(r, {});
    
    if ($('the_card') && r.CartHTML) 
    {
      $('the_card').set('html', r.CartHTML);
      $('cart_side').style.display = '';
    }
    
    if (r.DeBug) 
    {
      console.log(r.DeBug);
    }
    
    if (r.Actions) 
    {
      MTJax.Action.execute(r.Actions);
    }
    
    if ($defined(Behaviour)) 
    {
      Behaviour.apply();
    }
    
    Cart.elementInits();
    Cart.fixPNG();
    window.fireEvent('reInitTips');
    
    try
    {
      Slimbox.scanPage();
    }
    catch (e) {}
  },
  
  fixPNG: function()
  {
    console.log('Trying: Cart.fixPNG();');
    if (Browser.Engine.trident && Browser.Engine.version == 4)
    {
      console.log('Doing: Cart.fixPNG();');
  
      $$('.fixpng').each(function(el)
      {
        if (el.fixedPng) return; el.fixedPng = true;
        bg = el.getStyle('background-image');
        
        if ('none' == bg) 
        {
          return;
        }
        
        el.setStyle('background-image', '');
        bg = bg.replace(/url\(/, '');
        bg = bg.replace(/\)/, '');
        filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' + bg + '\', sizingMethod=\'scale\'';
        el.setStyle('filter', filter);
      }); 
    }
  },
  
  /**
   * Auswerten von Checkboxen
   */
  prepareValue: function(Elem)
  {
    if (Elem.type == 'checkbox') 
    {
      return Elem.name + '=' + Elem.checked;
    }
    return Elem.name + '=' + encodeURIComponent(Elem.value);
  },
  
  
  /**
   * Mitlaufen des Warenkkorbs
   */
  place: function()
  {
    //        return;
    Bumper     = $('bumper');
    CartDiv    = $('cart_side');
    BumperDim  = Bumper.getCoordinates();
    CartDivDim = CartDiv.getCoordinates();
    
    if (!Bumper.Fx) 
    {
      Bumper.Fx = new Fx.Tween(Bumper, {
         property: 'height'
        ,duration: 300, wait: false
        ,transition: Fx.Transitions.linear
      });
    }
    
    if (CartDivDim.height > window.getSize().y) 
    {
      h = 0;
    }
    else
    {
      h = window.getScroll().y - BumperDim.top;
    }
    
    Bumper.Fx.start(Math.max(0, h));
  },
  
  
  /**
   * Starten des Intervals für Cart.place()
   */
  setTimeOut_place: function()
  {
    if ($('bumper') && $('cart_side')) 
    {
      window.addEvent('scroll', Cart.place);
    }
  },
  
  
  sessionId: function()
  {
    return PHPSESSID;
    //    	return getCookie('PHPSESSID');
  },
  
  
  initTips: function()
  {
    $$('.tooltip').setStyle('opacity', 0);
    
    document.getElements('.tipimg').each(function(el)
    {
      if (el.tipPrepped) return; el.tipPrepped = true;
      el.addClass('tip');el.removeClass('tipimage');
      var txt = el.title.split(/::/);
      
      var html = '';
      if (txt[1])
      {
        var w = txt[2];
        var h = txt[3];
        var p = txt[4] ? txt[4] : 'center center';
        
        html += '<div style="width: ' + w + 'px; height: ' + h + 'px; background: url(/media/Image/Icons/ajax/indicator_snake.gif) center center no-repeat;">';
        html += '<div style="width: ' + w + 'px; height: ' + h + 'px; background: url(' + txt[1] + ') ' + p + ' no-repeat;">';
        html += '</div>';
        html += '</div>';
      }
      
      el.store('tip:title', txt[0] ? txt[0] : '');
      el.store('tip:text', html);
    });
    
    document.getElements('.tip').each(function(el)
    {
      if (el.tipPrepped) return; el.tipPrepped = true;
      
      var txt = el.title.split(/::/);
      el.store('tip:title', txt[0] ? txt[0] : '');
      el.store('tip:text', txt[1] ? txt[1] : '');
    });
    
    new Tips(document.getElements('.tip'), {
         className: 'tooltip'
        ,onShow: function(tip){
            tip.fade('in');
        }
        ,onHide: function(tip){
            tip.fade('out');
        }
    });
  }
  
  ,elementInits: function()
  {
    document.getElements('.img_select').each(function(el)
    {
      new MTJax.ImgSelect(el);
    });
    document.getElements('div.tooltip').each(function(el)
    {
      el.setStyle('opacity', 0);
    });
    
    
    document.getElements('div.tisch-schema').each(function(el)
    {
      var IDs = el.id.split(/_/);
      
      IDs[0] = 'laenge';
      el.elLaenge = $(IDs.join('_'));
      
      IDs[0] = 'breite';
      el.elBreite = $(IDs.join('_'));
      
      el.makeResizable({
        limit: {
          x: [60, 300],
          y: [60, 150]
        },
        grid: 5,
        onComplete: function(el)
        {
          var Coords = el.getCoordinates();
          
          el.elLaenge.value = Coords.width;
          el.elBreite.value = Coords.height;
          
          Cart.update([el.elLaenge, el.elBreite]);
        },
        onDrag: function(el)
        {
          var Coords = el.getCoordinates();
          
          el.elLaenge.value = Coords.width;
          el.elBreite.value = Coords.height;
          
          window.fireEvent('visual-redraw');
        }
      });
    });
    
    
    document.getElements('div.cart .line').each(function(el)
    {
      if (-1 != el.id.search(/MTData_Lieferung/)) 
      {
        new Cart.Lieferung(el);
      }
    });
  }
  
  ,Controll: null
  ,init: function()
  {
    this.Controll = new MT_CartControll();
    window.fireEvent('initCart');
  }
};

Cart.Lieferung = {
  initialize: function(el)
  {
    el.addClass('editable');
    
    var ziel = 'de';
    if ((ziel = el.getElement('.ziel')))
    {
      ziel = ziel.get('title').toLowerCase();
    }
    
    if ((aufbau = el.getElement('.aufbau'))) 
    {
      aufbau.setStyles({
        background: 'url(/media/Image/Icons/warenkorb_pfeil.gif) no-repeat right 4px',
        paddingRight: 10,
        cursor: 'pointer'
      });
      
      
      if (aufbau.getParent().get('href'))
      {
        aufbau.getParent().set('href', 'javascript:void(0);');
      }
      
      aufbau.addEvent('click', function(e)
      {
        e.stop();
        var FlowSelector = new MT_Jax.FlowSelector({
          width: 150,
          height: Configurator.devOpt.type.length * 25
        });
        Container = FlowSelector.getContainer();
        
        Configurator.devOpt.type.each(function(el)
        {
          Div = new Element('div', {
            rel: el
          });
          Div.set('html', MTJax.Lang.get(Configurator.devOpt.langKey + el));
          Div.setStyles({
            marginBottom: 4,
            background: 'url(/media/Image/Icons/arrow-a.gif) no-repeat left 5px',
            cursor: 'pointer',
            paddingLeft: 16
          });
          
          Div.addEvent('click', function(e)
          {
            var name =  Configurator.devOpt.paramKey + (/MTData_Lieferung-(.*)$/.exec(this.cartLine.id)[1]);
            var value = ((e.target.getProperty('rel') == 'x') ? 'true' : 'false');
            value = e.target.getProperty('rel');
            if (document.getElement('div.cartbig')) 
            {
              document.location.href = '?' + name + '=' + value;
            }
            else 
            {
              Cart.update({
                name:  name,
                value: value
              });
              this.container.fireEvent('hide');
            }
          }.bindWithEvent(this));
          
          Div.injectInside(this.container);
        }.bind({
          container: Container,
          cartLine: this
        }));
        
        FlowSelector.show(e);
      }.bindWithEvent(el));
    }
    if (!el.getElement('.ziel')) return;
    
    Trigger = new Element('div');
    Trigger.setStyles({
      cursor: 'pointer'
    });
    
    flag = new Element('img', {
      src: '/media/Image/Flags/16by11/' + ziel + '.png'
    });
    arrow = new Element('img', {
      src: '/media/Image/Icons/warenkorb_pfeil.gif'
    });
    
    Trigger.adopt(flag);
    Trigger.adopt(arrow);
    
    el.getElement('.the-bottom').adopt(Trigger);
    
    Trigger.addEvent('click', function(e)
    {
      var FlowSelector = new MT_Jax.FlowSelector({
        width: 150,
        height: 120
      });
      Container = FlowSelector.getContainer();
      
      Configurator.Zielland.prototype.Countries.each(function(el)
      {
        Div = new Element('div', {
          rel: el
        });
        Div.set('html', MTJax.Lang.get('.locale.land.label.' + el));
        Div.setStyles({
          marginBottom: 4,
          background: 'url(/media/Image/Flags/16by11/' + el + '.png) no-repeat left 3px',
          cursor: 'pointer',
          paddingLeft: 23
        });
        
        Div.addEvent('click', function(e)
        {
          if (document.getElement('div.cartbig')) 
          {
            document.location.href = '?Zielland' + (/MTData_Lieferung-(.*)$/.exec(this.cartLine.id)[1]) + '=' + e.target.getProperty('rel').toUpperCase();
          }
          else 
          {
            Cart.update({
              name: 'Zielland' + (/MTData_Lieferung-(.*)$/.exec(this.cartLine.id)[1]),
              value: e.target.getProperty('rel').toUpperCase()
            });
            this.container.fireEvent('hide');
          }
        }.bindWithEvent(this));
        
        Div.injectInside(this.container);
      }.bind({
        container: Container,
        cartLine: this
      }));
      
      FlowSelector.show(e);
    }.bindWithEvent(el));
    
    
    
  }
};
Cart.Lieferung = new Class(Cart.Lieferung);

function updateCart(FromElement)
{
  Cart.update(FromElement);
};

window.addEvent('domready', function()
{
  Cart.setTimeOut_place();
  Cart.elementInits();
  Cart.fixPNG();
  
  document.getElements('.cartbig td.number').each(function(el)
  {
    el.textMode = true;
    el.theInput = new Element('input', {
      'type': 'text'
    });
    el.theInput.setStyles({
      width: 10
    });
    
    el.setStyles({
      'cursor': 'default'
    });
    
    el.addEvents({
      'dblclick': function()
      {
        if (true == this.textMode) 
        {
          this.textMode = false;
          this.theInput.value = this.get('text');
          this.empty();
          
          this.theInput.injectInside(this);
          this.theInput.focus();
        }
      }
.bind(el)      ,
      'keyup': function(e)
      {
        this.theInput.value = this.theInput.value.replace(/\D/g, '');
        
        if (13 == e.event.keyCode) 
        {
          document.location.href = '?Action=ItemAmount&Menge_' + this.getProperty('rel') + '=' + this.theInput.value;
        }
      }
.bindWithEvent(el)
    });
  });
});






window.addEvent('domready', Cart.init.bind(Cart));
window.addEvent('domready', Cart.initTips.bind(Cart));
window.addEvent('reInitTips', Cart.initTips.bind(Cart));
window.addEvent('layerFilled', Cart.initTips.bind(Cart));