var IPExchange = { util: {}, anim: {} };

IPExchange.util.Cart = function( id )
{
  if ( id )
  {
    this.init( id );
  }
}

IPExchange.util.Form = function( id )
{
  if ( id )
  {
    this.init( id );
  }
}

IPExchange.anim.blobOut = function()
{
  this.init();
}

IPExchange.anim.blobOut.prototype = {
  blobEl: false,
  anim: false,
  onComplete: new YAHOO.util.CustomEvent( 'onComplete', this ),
  
  attributes:
  {
    width:   { from: 0, to: 800 },
    height:  { from: 0, to: 800 },
    opacity: { from: 1, to: 0 }
  },
  
  duration: 0.3,

  init: function()
  {
    this.blobEl = document.createElement('div');
    this.blobEl.id = 'bod_' + $D.generateId;
    this.blobEl.className='blobOut'
    this.blobEl.style.position='absolute';
    this.blobEl.style.width  ='0px';
    this.blobEl.style.height ='0px';
    this.blobEl.style.top  ='0px';
    this.blobEl.style.left ='0px';
    this.blobEl.style.zIndex='10000';
    document.body.appendChild(this.blobEl);

    this.anim = new YAHOO.util.Anim( this.blobEl, this.attributes, this.duration );
  },

  animate: function( event, obj )
  {
    if ( ! event )
    {
      event=$E.getEvent();

      if ( ! event )
      {
        event={ clientX: 0, clientY: 0 };
      }
    }

    this.attributes.left = { from: event.clientX, to: event.clientX-( parseInt( parseInt( this.attributes.width.to) /2 ) ) };
    this.attributes.top =  { from: event.clientY, to: event.clientY-( parseInt( parseInt( this.attributes.height.to) /2 ) ) };
    this.anim.onComplete.unsubscribeAll();
    this.anim.onComplete.subscribe( this._animateEnd, obj, this );
    this.anim.animate();
  },

  _animateEnd: function( e, anim, obj )
  {
    this.blobEl.style.width  ='0px';
    this.blobEl.style.height ='0px';
    this.blobEl.style.top  ='0px';
    this.blobEl.style.left ='0px';
    this.onComplete.fire( obj );
  }
};

IPExchange.util.Form.prototype = {
  id: false,
  formEl: false,
  formElements: false,
  ajaxURL: '/fileadmin/cart/ajax.php',

  init: function( id )
  {
    if ( id && $D.get(id) )
    {
      this.id = id;
      this.formEl = $D.get(id);
      this.formElements = $D.getElementsBy( this._getFormFields , null, id );

      for( var t in this.formElements )
      {
        this._addAjaxEvent(this.formElements[t]);
      }

      $E.on( window, 'unload', this.unload, null, this );
      this.loadSessionValues();
    }
  },

  _getFormFields: function( el )
  {
    var tag = el.tagName.toLowerCase();

    if ( tag )
    {
      if ( tag == 'input'  || tag == 'select' || tag == 'textarea' )  return el;
    }

    return false;
  },

  _addAjaxEvent: function( el )
  {
    $E.on( el, 'blur', this.sendValue, el ,this );
  },

  sendValue: function( event, element )
  {
    var value=false;

    if ( element && element.id )
    {
      value = element.value;
      if ( element.className )
      {
        element.className=element.className.replace(/Error$/, "");
      }
      this._ajaxCallback.scope = this;
      var parameter = 'screen=setFormField';
      parameter += '&form='  + this.id ;
      parameter += '&field=' + element.name;
      parameter += '&value=' + element.value;
      return YAHOO.util.Connect.asyncRequest( 'POST', this.ajaxURL, this._ajaxCallback, parameter );
    }
  },

  loadSessionValues: function()
  {
    this._ajaxCallback.scope = this;
    this._ajaxCallback.success = this.setSessionValues;
    var parameter = 'screen=getFormFields';
    parameter += '&form='  + this.id ;

    return YAHOO.util.Connect.asyncRequest( 'POST', this.ajaxURL, this._ajaxCallback, parameter );
  },

  setSessionValues: function( obj )
  {
    if ( obj && obj.responseText )
    {
      var values=$T.JSONParse( obj.responseText );

      for( var t in this.formElements )
      {
        if ( this.formElements[t].id && values )
        {
          switch ( this.formElements[t].type )
          {
            case 'radio':
              if ( values[this.formElements[t].name] )
              {
                if ( values[this.formElements[t].name] == this.formElements[t].value )
                {
                  this.formElements[t].checked = true;
                }
                else
                {
                  this.formElements[t].checked = false;
                }
              }
              break;
            default:
              if ( values[this.formElements[t].id] != undefined )
              {
                this.formElements[t].value = values[this.formElements[t].id];
              }
              break;
          }
        }
      }
    }

    this._ajaxCallback.scope = null;
    this._ajaxCallback.success = this._ajaxCallBackDefault;
  },

  _ajaxCallBackDefault: function ( obj )
  {
    this.scope=null;
  },

  _ajaxCallback:
  {
    success: function( obj ) { this.scope=null },
    failure: function( obj ) { this.scope=null },
    timeout: 5000,
    scope:   null
  },

  unload: function()
  {
    this.id = null;
    this.formEl = null;
    this.formElements = null;
    this.ajaxUrl = null;
  },

  checkForm: function( checkObj )
  {
    for( var t in this.formElements )
    {
      if ( this.formElements[t].id )
      {
        var id    = this.formElements[t].id;
        var value = this.formElements[t].value;

        if ( checkObj[id] )
        {
          if ( checkObj[id].checkOnly )
          {
            var chObjId = checkObj[id].checkOnly.field;
            var chObjValue = false;

            for ( var s in this.formElements )
            {
              if ( this.formElements[s].id == chObjId ) chObjValue=this.formElements[s].value;
            }

            if ( chObjValue && this._checkFormFieldType( chObjValue, 'values' ,checkObj[id].checkOnly['values'] ) )
            {
              if ( checkObj[id].check )
              {
                if ( ! this._checkFormField( checkObj[id], value ) ) return this.formElements[t];
              }
            }
          }
          else
          {
            if ( checkObj[id].check )
            {
              if ( ! this._checkFormField( checkObj[id], value ) ) return this.formElements[t];
            }
          }
        }
      }
    }

    return true;
  },

  _checkFormField: function( field, value )
  {
    for ( var t in field.check )
    {
      var options;
      if ( field['check'+field.check[t]] ) options=field['check'+field.check[t]];
      if ( ! this._checkFormFieldType( value, field.check[t], options ) ) return false;
      return true;
    }
  },

  _checkFormFieldType: function( value, type, options )
  {
    if ( ! type ) return true;

    switch ( type )
    {
      case 'notEmpty':
        if ( String(value) !== '' ) return true;
      break;
      case 'values':
        if ( options )
        {
          for ( var t in options )
          {
            if ( value == options[t] ) return true;
          }
        }
      break;
    }

    return false;
  },

  send: function()
  {
    this._ajaxCallback.scope = this;
    this._ajaxCallback.success = function( obj ) { this._ajaxCallback.scope = null };
    var parameter = 'screen=sendForm&form=' + this.id;
    return YAHOO.util.Connect.asyncRequest( 'POST', this.ajaxURL, this._ajaxCallback, parameter );
  }
};

IPExchange.util.Cart.prototype = {
  el: {},
  id: false,

  ajaxURL: '/fileadmin/cart/ajax.php',
  locations: [{ id: 195, name: 'Nürnberg' },{ id: 196, name: 'München' }],
  locationSelected: 0,
  durations: [ 3, 12, 24, 36 ],
  contractLocation: 7,
  lang: { id: 'en', floatPoint: '.' },

  structure: false,
  contracts: false,
  groups: false,
  items: false,
  content: false,

  cartTree: false,
  cartTreeRoot: false,
  infoPanel: false,

  visible: false,

  addItemAnim: false,

  onAddItem:    false,
  onDeleteItem: false,
  onLoaded:     false,

  loadComplete: false,

  init: function( id )
  {
    this.id = id;
    if ( $D.get(id) )
    {
      this.el = $D.get(id);
    }
    else
    {
      this.createDivElement(id);
    }

    $E.on( window, 'unload', this.unload, null, this );

    this.id = id;
    $D.get(id).innerHTML = '<div class="cartPleaseWait">' + this.text[this.lang.id]['pleaseWaitLoading'] + '</div>';

    this.getStructure();
    this.onAddItem    = new YAHOO.util.CustomEvent( 'onAddItem', this );
    this.onDeleteItem = new YAHOO.util.CustomEvent( 'onDeleteItem', this );
    this.onLoaded     = new YAHOO.util.CustomEvent( 'onLoaded', this );

    this.addItemAnim  = new IPExchange.anim.blobOut();
  },

  unload: function()
  {
    this.locations=null;
    this.locationSelected=null;
    this.ajaxURL=null;
    this.structure=null;
    this.contract=null;
    this.groups=null;
    this.items=null;
    this.content=null;
    this.cartTree=null;
    this.infoPanel=null;
    this.el=null;
    this.visible=null;
    if ( $D.get(this.id) ) $D.get(this.id).innerHTML='';
  },

  createDivElement: function( id ) {
    this.el = document.createElement('div');
    this.el.id = id;
    this.el.style.position = 'absolute';
    this.el.style.top    = '10px';
    this.el.style.left   = '10px';
    this.el.style.width  = 'auto';
    this.el.style.height = 'auto';
    this.el.style.visibility = 'visible';
    this.el.style.backgroundColor = 'transparent';
    document.body.appendChild( this.el );
  },

  createTree: function() {
    this.cartTree = new YAHOO.widget.TreeView( this.id );
    this.cartTreeRoot = this.cartTree.getRoot();
    this._createTreeContracts();
    this.cartTree.draw();
    this.cartTree.expandAll();
    this.cartTree.collapseAll();
  },

  _createTreeContracts: function()
  {
    for ( var t in this.structure )
    {
      var contract = this.contracts[this.structure[t].contract_id];
      var HTML = this.getCartContractHTML( contract );
      var el = new YCartTree( HTML, this.cartTreeRoot );
      el.setBGStyle( 'cartTreeContract' + contract.id );
      el.labelStyle = 'cartTreeContract' + contract.id + 'Label';
      el.contractId = contract.id;
      el.type = 'contract';
      if ( this.structure[t].childs.length > 0 )
      {
        this._createTreeGroups( el, this.structure[t].childs );
      }
    }
  },

  _createTreeGroups: function( parentEl, structure )
  {
    for ( var t in structure )
    {
      var group = this.groups[structure[t].group_id];
      var HTML = this.getCartGroupHTML( group );
      var el = new YCartTree( HTML, parentEl, false );
      el.setBGStyle(  'cartTreeContractGroup' );
      el.labelStyle = 'cartTreeContractGroupLabel';
      el.groupId    = group.id;
      el.contractId = group.contractId;
      el.type = 'group';

      if ( structure[t].items && structure[t].items.length > 0 )
      {
        this._createTreeItems( el, structure[t] );
      }
      if ( structure[t].childs.length )
      {
        this._createTreeGroups( el, structure[t].childs );
      }
    }
  },

  _createTreeItems: function( parentEl, structure )
  {
    if ( structure.itemSelected  )
    {
      var HTML = this.getCartItemHTML( this.getItem( 'id', structure.itemSelected ) );
    }
    else
    {
      var HTML = this.getCartItemEmptyHTML( this.groups[parentEl.groupId] );
    }
    var el = new YCartTree( HTML, parentEl );
    el.setBGStyle(  'cartTreeContractItem' );
    el.labelStyle = 'cartTreeContractItemLabel';
    el.type = 'item';
    el.itemId     = structure.itemSelected;
    el.groupId    = parentEl.groupId;
    el.contractId = parentEl.contractId;
  },

  getItem: function( type, value )
  {
    switch ( type )
    {
      case 'id':
      case 'number':
        for ( var t in this.items )
        {
          if (  this.items[t] && this.items[t][type] == value ) return this.items[t];
        }
        break;
      case 'groupId':
        for ( var t in this.contect )
        {
          if ( this.content[t] && this.content[t].groupId == value ) return this.content[t];
        }
        break;
      default:
        break;
    }
    return false;
  },

  getGroup: function( type, value )
  {
    switch ( type )
    {
      case 'id':
        if ( this.groups[value] ) return this.groups[value];
        break;
      case 'itemId':
        if ( this.items[value] ) return this.groups[this.items[value].groupId];
        break;
      default:
        break;
    }
    return false;
  },

  getContract: function( id )
  {
    if ( this.contracts[id] ) return this.contracts[id];
    return false;
  },

  getTreeEl: function( type, value )
  {
    switch ( type )
    {
      case 'itemId':
        var groupId = this.getItem( 'id', value ).groupId;
        return this._getTreeElGroup( groupId, this.tree.root );
        break;
      case 'itemNumber':
        var groupId = this.getItem( 'number', value ).groupId;
        return this._getTreeElGroup( groupId, this.tree.root );
        break;
      case 'groupId':
        return this._getTreeElGroup( value, this.tree.root );
        break;
      case 'contractId':
        return this._getTreeElContract( contractId );
        break;
      default:
        return false;
        break;
    }
    return false;
  },

  _getTreeElContract: function( contractId )
  {
    for ( var t in this.tree.root.children )
    {
      if ( this.tree.root.children[t].type == 'contract' && this.tree.root.children[t].contractId == contractId )
      {
        return this.tree.root.children[t];
      }
    }
    return false;
  },

  _getTreeElGroup: function( groupId, treeRoot )
  {
    for ( var t in treeRoot.children )
    {
      if ( treeRoot.children[t].type == 'group' && treeRoot.children[t].groupId == groupId )
      {
        return treeRoot.children[t];
      }
      if ( treeRoot.children[t].children && treeRoot.children[t].children > 0 )
      {
        var el = this._getTreeElGroup( groupId, treeRoot.children[t] );
        if ( el ) return el;
      }
    }
    return false;
  },

  getStructure: function()
  {
    this.structure = false;
    this._ajaxCallback.scope = this;
    this._ajaxCallback.success = this._getStructureSuccess;
    var parameter = 'screen=getAll';
    return YAHOO.util.Connect.asyncRequest( 'POST', this.ajaxURL, this._ajaxCallback, parameter );
  },

  _getStructureSuccess: function ( obj )
  {
    this.structure = $T.JSONParse( obj.responseText );
    this.createStructure();
    this._ajaxCallback.scope   = null;
    this._ajaxCallback.success = function( obj ) {};
    this.createTree();
    this.loadComplete = true;
    this.onLoaded.fire();
    // raus hier
    if ( $D.get('cartCounter') ) $D.get('cartCounter').innerHTML= '(' + this.countItems() +  ')';
  },

  _ajaxCallback:
  {
    success: function( obj ) {},
    failure: function( obj ) {},
    timeout: 5000,
    scope:   false
  },

  _infoPanelCreate: function()
  {
    if ( ! this.infoPanel )
    {
      var pos = [0,0];
      this.infoPanel = new YAHOO.widget.Panel( this.id + 'InfoPanel', { modal: true, draggable: true, visible:false, width: '300px', zIndex: 500, underlay: 'none', xy: pos, constraintoviewport: true } );
      this.infoPanel.setBody('');
      this.infoPanel.setHeader('');
      this.infoPanel.render( document.body );
    }
    this.infoPanel.hide();
  },

  infoPanelShow: function( event, options )
  {
    if ( ! this.infoPanel ) this._infoPanelCreate();
    
    if ( event )
    {
      if ( event.clientX )
      {
        var width=$D.getViewportWidth();
        var height=$D.getViewportHeight();
        var x=event.clientX;
        var y=event.clientY;
        if ( x > width )  x=width;
        if ( y > height ) y=height;
        if ( options && options.width  && x+parseInt(options.width)  > width  )  x=width-parseInt(options.width);
        if ( options && options.height && y+parseInt(options.height) > height )  y=height-parseInt(options.height);
        if ( x<0 ) x=0;
        if ( y<0 ) y=0;
        this.infoPanel.cfg.setProperty( 'xy', [ x,y ] );
      }
    }

    if ( options )
    {
      if ( options.width )     this.infoPanel.cfg.setProperty( 'width', options.width );
      if ( options.height )    this.infoPanel.cfg.setProperty( 'height', options.height );
      if ( options.xy )        this.infoPanel.cfg.setProperty( 'xy', options.xy );
      if ( options.modal )     this.infoPanel.cfg.setProperty( 'width', options.modal );
      if ( options.draggable ) this.infoPanel.cfg.setProperty( 'width', options.draggable );
      if ( options.title )     this.infoPanel.setHeader( options.title );
      if ( options.body )      this.infoPanel.setBody( options.body );

      if ( options.type )
      {
        switch ( options.type )
        {
          case 'duration':
            this._infoPanelDuration( options.contract );
            this.infoPanel.show();
            break;
          case 'item':
            this._infoPanelItem( options.group );
            this.infoPanel.show();
            break;
        }
      }
    }
  },

  infoPanelHide: function()
  {
    this.infoPanel.hide();
    this.infoPanel.setBody( '' );
    this.infoPanel.setHeader( '' );
  },

  _infoPanelDuration: function ( contract )
  {
    this.infoPanel.setBody( '' );
    this.infoPanel.setHeader( contract.name + ' ' + this.text[this.lang.id]['laufzeitWaehlen'] );
    var HTML = '';
    HTML += '<table cellpadding="0" cellspacing="0">';
    HTML += '<tr><th class="cartInfoPanelDuration">'+ this.text[this.lang.id]['laufzeit'] + '</th></tr>';
    var selectedDurationId = contract.durationId;
    for ( var t in this.durations )
    {
      var className='cartInfoPanelDuration';
      if ( t == selectedDurationId ) className += 'Selected';
      var obj = { contractId: contract.id, durationId: t };
      var id = this.id + 'DurationSelect' + t;
      HTML += '<tr id="' + id + '">';
      HTML += '<td class="' + className + '" onmouseover="this.className=\''+className+'Over'+'\'" onmouseout="this.className=\''+className +  '\'"><div class="cartInfoPanelDurationText" >' + this.durations[t] + ' ' + this.text[this.lang.id]['monat'] + '</div></td>';
      HTML += '</tr>';
      $E.addListener( id, 'click', this.setDuration, obj, this );
    }
    HTML += '</table>';
    this.infoPanel.setBody( HTML );
  },

  _infoPanelItem: function( group )
  {
    this.infoPanel.setBody( '' );
    this.infoPanel.setHeader( '' );
    var HTML = '';

    var contract = this.contracts[group.contractId];
    var durationId = contract.durationId;

    var itemSelected=false;
    for ( var t in this.content )
    {
      if ( this.content[t].groupId == group.id )
      {
        itemSelected=this.content[t].id;
      }
    }

    HTML += '<div class="cartInfoPanelItem' + contract.name + '">';
    HTML += '<table cellpadding="0" cellspacing="0">';
    if ( group.contractId == this.contractLocation )
    {
      this.infoPanel.setHeader( this.text[this.lang.id]['bitteRechenzentrumWaehlen'] );
      HTML += '<tr>';
      HTML += '<th class="cartInfoPanelItemText' + contract.name + '">' + this.text[this.lang.id]['rechenzentrum'] + '</td>';
      HTML += '</tr>';
      for ( var t in this.items )
      {
        if ( ! this.items[t] || this.items[t].groupId != group.id ) continue;
        var id=this.id+'cartInfoPanelItem'+this.items[t].id;
        var className="cartInfoPanelItemRow";
        if ( this.items[t].id == itemSelected ) className += " selected";
        HTML += '<tr id="'+id+'" class="'+className+'" onmouseover="this.className=\''+className+' over\'" onmouseout="this.className=\''+className+'\'">';
        HTML += '<td class="cartInfoPanelItemText' + contract.name + '">' +this.items[t].name+'</td>';
        HTML += '</tr>';
        $E.on( id, 'click', this.addItem, this.items[t], this );
      }
    }
    else
    {
      this.infoPanel.setHeader( this.text[this.lang.id]['bitteArtikelWaehlen'] );
      HTML += '<tr>';
      HTML += '<th class="cartInfoPanelItemText' + contract.name + '">'+this.text[this.lang.id]['artikel']+'</td>';
      HTML += '<th class="cartInfoPanelItemPrice' + contract.name + '">'+this.text[this.lang.id]['preisInstall']+'</td>';
      HTML += '<th class="cartInfoPanelItemPrice' + contract.name + '">'+this.text[this.lang.id]['preisMonat']+'</td>';
      HTML += '</tr>';

      for ( var t in this.items )
      {
        if ( ! this.items[t] || this.items[t].groupId != group.id ) continue;
        var id=this.id+'cartInfoPanelItem'+this.items[t].id;
        var className="cartInfoPanelItemRow";
        if ( this.items[t].id == itemSelected ) className += " selected";
        HTML += '<tr id="'+id+'" class="'+className+'" onmouseover="this.className=\''+className+' over\'" onmouseout="this.className=\''+className+'\'">';
        HTML += '<td class="cartInfoPanelItemText' + contract.name + '">' +this.items[t].name+'</td>';
        if ( this.items[t].prices && this.items[t].prices[durationId] )
        {

          var _price = this.items[t].prices[durationId];
          if ( parseInt(_price.price_once) >= 0 )
          {
            HTML += '<td class="cartInfoPanelItemPrice' + contract.name + '">'+this.formatFloat(_price.price_once)+' &euro;</td>';
          }
          else
          {
            HTML += '<td class="cartInfoPanelItemPrice' + contract.name + '">' + this.text[this.lang.id]['aufAnfrage'] + '</td>';
          }
          if ( parseInt(_price.price_interval) >= 0 )
          {
            HTML += '<td class="cartInfoPanelItemPrice' + contract.name + '">'+this.formatFloat(_price.price_interval)+' &euro;</td>';
          }
          else
          {
            HTML += '<td class="cartInfoPanelItemPrice' + contract.name + '">' + this.text[this.lang.id]['aufAnfrage'] + '</td>';
          }
        }
        else
        {
          HTML += '<td class="cartInfoPanelItemPrice' + contract.name + '">' + this.text[this.lang.id]['aufAnfrage'] + '</td>';
          HTML += '<td class="cartInfoPanelItemPrice' + contract.name + '">' + this.text[this.lang.id]['aufAnfrage'] + '</td>';
        }
        HTML += '</tr>';
        $E.on( id, 'click', this.addItem, this.items[t], this );
      }
    }
    HTML += '</table>';
    HTML += '</div>';

    if ( contract.id != this.contractLocation )
    {
      HTML += '<div class="cartInfoPanelItemTax">' + this.text[this.lang.id]['preiseNetto']+ '</div>';
    }
    this.infoPanel.setBody( HTML );
  },

  setDuration: function ( e, durationObj )
  {
    if ( this.infoPanel ) this.infoPanel.hide();

    this._ajaxCallback.scope = this;
    this._ajaxCallback.success = this._setDurationSuccess;
    this._ajaxCallback.argument = [ durationObj ];

    var parameter = 'screen=setDuration&contractId=' + durationObj['contractId'] + '&durationId=' + durationObj['durationId'];
    return YAHOO.util.Connect.asyncRequest( 'POST', this.ajaxURL, this._ajaxCallback, parameter );
  },

  _setDurationSuccess: function ( obj )
  {
    var durationObj = obj.argument[0];
    this.contracts[durationObj['contractId']].durationId = durationObj['durationId'];
    this.contractUpdate( this.contracts[durationObj['contractId']] );
    this._ajaxCallback.scope = null;
    this._ajaxCallback.success = function( obj ) {};
    this._ajaxCallback.argument = [];
  },

  contractUpdate: function( contract )
  {
    var priceInstall=0.00;
    var priceMonth=0.00;
    var location = false;
    for ( var t in this.content )
    {
      if ( ! contract ) return;
      if ( contract.id == this.contractLocation && this.content[t].contractId == contract.id )
      {
        location=this.content[t];
        break;
      }
      else
      {
        if ( this.content[t].contractId == contract.id )
        {
          var id = this.id + 'TreeItemGroup' + this.content[t].groupId;
          if ( this.content[t].prices && this.content[t].prices[contract.durationId] )
          {
            var _price=this.content[t].prices[contract.durationId];
            if ( parseInt(_price.price_once) >= 0)
            {
              $D.get(id+'PriceInstall').innerHTML = this.formatFloat(_price.price_once) + ' &euro;';
              priceInstall += parseFloat( _price.price_once);
            }
            else
            {
              $D.get(id+'PriceInstall').innerHTML = this.text[this.lang.id]['aufAnfrage'];
            }
            if ( parseInt(_price.price_interval) >= 0)
            {
              $D.get(id+'PriceMonth').innerHTML   = this.formatFloat(_price.price_interval) + ' &euro;';
              priceMonth   += parseFloat( _price.price_interval);
            }
            else
            {
              $D.get(id+'PriceInstall').innerHTML = this.text[this.lang.id]['aufAnfrage'];
              $D.get(id+'PriceMonth').innerHTML   = this.text[this.lang.id]['aufAnfrage'];
            }
          }
          else
          {
            $D.get(id+'PriceInstall').innerHTML = this.text[this.lang.id]['aufAnfrage'];
            $D.get(id+'PriceMonth').innerHTML   = this.text[this.lang.id]['aufAnfrage'];
          }
        }
      }
    }

    var id = this.id + 'TreeContract' + contract.id;
    if ( $D.get(id+'PriceInstall') ) $D.get(id+'PriceInstall').innerHTML = this.formatFloat(priceInstall,2) + ' &euro;';
    if ( $D.get(id+'PriceMonth') )   $D.get(id+'PriceMonth').innerHTML   = this.formatFloat(priceMonth,2) + ' &euro;';
    if ( $D.get(id+'Duration') )     $D.get(id+'Duration').innerHTML     = this.durations[contract.durationId] + ' ' + this.text[this.lang.id]['monat'] ;
    if ( $D.get(id+'ItemCount') )    $D.get(id+'ItemCount').innerHTML    = this.countItems(contract) + ' ' + this.text[this.lang.id]['artikel'] ;
    if ( $D.get(id+'DeleteContract') )
    {
      if ( this.countItems(contract)>0 ) $D.get(id+'DeleteContract').style.display='';
      else $D.get(id+'DeleteContract').style.display='none';
    }
    if ( $D.get(id+'Location') )  $D.get(id+'Location').innerHTML = location.name;
    if ( $D.get('cartCounter') ) $D.get('cartCounter').innerHTML= '(' + this.countItems() +  ')';
    var preisImgs = $D.getElementsByClassName('preis');
    if ( preisImgs )
    {
      for ( var t in preisImgs )
      {
        if ( preisImgs[t].src && preisImgs[t].src.match(/ajax.php/) )
        {
          preisImgs[t].src=preisImgs[t].src+'#';
        }
      }
    }

  },

  getPrice: function( contract )
  {
    var price = { price_once: 0.00, price_interval: 0.00 };
    for ( var t in this.content )
    {
      if ( contract )
      {
        if ( this.content[t].prices && this.content[t].contractId == contract.id  )
        {
          price.price_once     += parseFloat(this.content[t].prices[contract.durationId].price_once);
          price.price_interval += parseFloat(this.content[t].prices[contract.durationId].price_interval);
        }
      }
      else
      {
        if ( this.content[t].prices && this.content[t].prices[this.contracts[this.content[t].contractId].durationId] )
        {
          price.price_once     += parseFloat(this.content[t].prices[this.contracts[this.content[t].contractId].durationId].price_once);
          price.price_interval += parseFloat(this.content[t].prices[this.contracts[this.content[t].contractId].durationId].price_interval);
        }
      }
    }
    return price;
  },

  createStructure: function()
  {
    this.contracts = [];
    this.groups  = [];
    this.items   = [];
    this.content = [];
    for ( var t in this.structure )
    {
      this._createStructure( this.structure[t] );
    }
  },

  _createStructure: function( obj )
  {
    switch ( obj.type )
    {
      case 'contract':
        this.contracts[obj.contract_id] = { id:         obj.contract_id,
                                            name:       obj.name,
                                            durationId: obj.durationId };
        break;
      case 'group':
        this.groups[obj.group_id] = { id:         obj.group_id,
                                      name:       obj.name,
                                      parentId:   obj.parentId,
                                      contractId: obj.contract_id,
                              items:      [] };
        if ( obj.items  )
        {
          for ( var t in obj.items )
          {
            var prices = this._createStructurePrices( obj.items[t].prices );
            var _itemsLength = this.items.length;
            this.items[_itemsLength] = { id:         obj.items[t].id,
                                         number:     obj.items[t].number,
                                         name:       obj.items[t].name,
                                         prices:     obj.items[t].prices,
                                         groupId:    obj.group_id,
                                         contractId: obj.contract_id };
            if ( obj.items[t].id == obj.itemSelected )
            {
              this.content[this.content.length] = this.items[_itemsLength];
              if ( obj.contract_id == this.contractLocation )
              {
                for ( var s in this.locations )
                {
                  if ( this.locations[s].id == obj.items[t].id )
                  {
                    this.locationSelected=s;
                  }
                }
              }
            }
            this.groups[obj.group_id].items[this.groups[obj.group_id].items.length] = obj.items[t].id;
          }
        }
        break;
      default:
        break;
    }
    if ( obj.childs && obj.childs.length>0 )
    {
      for ( var t in obj.childs )
      {
        this._createStructure( obj.childs[t] );
      }
    }
  },

  _createStructurePrices: function( prices )
  {
    if ( ! prices ) prices = [];
    for ( var t in this.durations )
    {
      if ( ! prices[t] )
      {
        prices[t] = { price_once: 'a.A.', price_interval: 'a.A.' };
        continue;
      }
      if ( prices[t].price_once == '' )     prices[t].price_once = 'a.A.';
      //else prices[t].price_once += ' €';
      if ( prices[t].price_interval == '' ) prices[t].price_interval = 'a.A.';
      //else prices[t].price_interval += ' €';
    }
  },

  addItemNr: function(e, itemNr)
  {
    if ( ! e || ! e.clientX ) e=$E.getEvent();
    for ( var t in this.items )
    {
      if ( this.items[t] && this.items[t].number == itemNr )
      {
        this.addItem(e,this.items[t]);
        break;
      }
    }
  },

  addItemId: function(e, itemId )
  {
    if ( ! e || ! e.clientX ) e=$E.getEvent();
    var item = this.getItem( 'id', itemId );
    if ( item ) this.addItem( e, itemId );
  },

  addItem: function( e, item )
  {
    if ( ! e || ! e.clientX ) e=$E.getEvent();
    if ( item && item.id && item.contractId )
    {
      if (this.infoPanel) this.infoPanel.hide();
      if ( this.addItemAnim.onComplete.subscribers.length == 0 )
      {
        this.addItemAnim.onComplete.subscribe( this._addItemStartRequest, item, this );
      }
      this.addItemAnim.blobEl.className='myCartBlobOut' + item.contractId;
      this.addItemAnim.animate(e, item );
    }
  },

  _addItemStartRequest: function( e, item )
  {
    item=item[0];
    this._ajaxCallback.scope = this;
    this._ajaxCallback.success = this._addItemSuccess;
    this._ajaxCallback.argument = [ item ];
    var parameter = 'screen=addItem&itemId=' + item.id + '&groupId=' + item.groupId;
    return YAHOO.util.Connect.asyncRequest( 'POST', this.ajaxURL, this._ajaxCallback, parameter );
  },

  _addItemSuccess: function( obj )
  {
    var item = obj.argument[0];
    var HTML = '';
    HTML += '<div class="cartTreeItemNumber">' + item.number + '</div>';
    HTML += '<div class="cartTreeItemName">' + item.name + '</div>';
    var id=this.id + 'TreeItemGroup'+item.groupId;
    if ( $D.get(id) ) $D.get(id).innerHTML=HTML;
    if ( $D.get(id+'ChangeItem') ) $D.get(id+'ChangeItem').style.display='';
    if ( $D.get(id+'AddItem') ) $D.get(id+'AddItem').style.display='none';

    if ( item.contractId != this.contractLocation )
    {
      if ( $D.get(id+'DeleteItem') )
      {
        $D.get(id+'DeleteItem').style.display='';
        $E.on( id+'DeleteItem', 'click', this.delItem, item, this );
      }
    }

    var found=false;
    for ( var t in this.content )
    {
      if ( this.content[t].groupId == item.groupId )
      {
        this.content[t] = item;
        found=true;
        break;
      }
    }
    if ( ! found )
    {
      this.content[this.content.length] = item;
    }

    this.contractUpdate( this.contracts[item.contractId] );

    this._ajaxCallback.scope = null;
    this._ajaxCallback.success = function( obj ) {};
    this._ajaxCallback.argument = [];

    this.onAddItem.fire();
  },

  delItemNr: function(e, itemNr )
  {
    for ( var t in this.items )
    {
      if ( this.items[t] && this.items[t].number == itemNr )
      {
        this.delItem(e,this.items[t]);
        break;
      }
    }
  },

  delItemId: function(e, itemId )
  {
    var item = this.getItem( 'id', itemId );
    if ( item ) this.delItem( e, item );
  },

  delItem: function( e, item )
  {
    if ( item )
    {
      if (this.infoPanel) this.infoPanel.hide();

      this._ajaxCallback.scope = this;
      this._ajaxCallback.success = this._delItemSuccess;
      this._ajaxCallback.argument = [ item ];

      var parameter = 'screen=delItem&itemId=' + item.id + '&groupId=' + item.groupId;
      return YAHOO.util.Connect.asyncRequest( 'POST', this.ajaxURL, this._ajaxCallback, parameter );
    }
  },

  delContract: function( e, contract )
  {
    if ( contract && contract.id )
    {
      if (this.infoPanel) this.infoPanel.hide();

      this._ajaxCallback.scope = this;
      this._ajaxCallback.success = this._delContractSuccess;
      this._ajaxCallback.argument = [ contract ];

      var parameter = 'screen=delContract&contractId=' + contract.id;
      return YAHOO.util.Connect.asyncRequest( 'POST', this.ajaxURL, this._ajaxCallback, parameter );
    }
  },

  _delContractSuccess: function( obj )
  {
    var contract=obj.argument[0];
    if ( contract && contract.id )
    {
      for ( var t in this.content )
      {
        if ( this.content[t].contractId == contract.id ) this._delItemSuccessDelItem( this.content[t] );
      }
      var newContent = [];
      for ( var t in this.content )
      {
        if ( this.content[t].contractId != contract.id )
        {
          newContent[newContent.length] = this.content[t];
        }
      }
      this.content = newContent;
      this.contractUpdate( contract );
    }
    this._ajaxCallback.scope = null;
    this._ajaxCallback.success = function( obj ) {};
    this._ajaxCallback.argument = [];
  },

  _delItemSuccessDelItem: function( item )
  {
    var HTML = '';
    HTML += '<div class="cartTreeItemNumber"></div>';
    HTML += '<div class="cartTreeItemEmpty">'+this.text[this.lang.id]['keinArtikelGewaehlt']+'</div>';
    var id=this.id + 'TreeItemGroup'+item.groupId;
    if ( $D.get(id) ) $D.get(id).innerHTML=HTML;
    if ( $D.get(id+'PriceInstall') ) $D.get(id+'PriceInstall').innerHTML = '';
    if ( $D.get(id+'PriceMonth') )   $D.get(id+'PriceMonth').innerHTML = '';
    if ( $D.get(id+'ChangeItem') )   $D.get(id+'ChangeItem').style.display='none';
    if ( $D.get(id+'AddItem') )      $D.get(id+'AddItem').style.display='';
    if ( $D.get(id+'DeleteItem') )
    {
      $D.get(id+'DeleteItem').style.display='none';
      $E.removeListener( id+'DeleteItem', 'click', this.delItem );
    }
    var found=false;
  },

  _delItemSuccess: function( obj )
  {
    var item = obj.argument[0];
    this._delItemSuccessDelItem(item);
    var newContent = [];
    for ( var t in this.content )
    {
      if ( this.content[t].groupId != item.groupId )
      {
        newContent[newContent.length] = this.content[t];
      }
    }
    this.content = newContent;
    this.contractUpdate( this.contracts[item.contractId] );
    this._ajaxCallback.scope = null;
    this._ajaxCallback.success = function( obj ) {};
    this._ajaxCallback.argument = [];
    this.onDeleteItem.fire();
  },

  show: function() {},
  hide: function() {},

  expandContract: function( e, contract, tree )
  {
    if ( ! tree ) tree=this.cartTree.root;
    var expand=false;
    if ( tree.children && tree.children.length>0 )
    {
      for ( var t in tree.children )
      {
        tree.collapse();
        var _expand = this.expandContract( e, contract, tree.children[t] );
        if ( _expand ) expand=true;
      }
    }
    if ( tree.groupId && tree.contractId == contract.id )
    {
      for ( var t in this.content )
      {
        if ( this.content[t].groupId == tree.groupId )
        {
          expand=true;
          break;
        }
      }
    }
    if (expand) tree.expand();
    return expand;
  },

  expandGroup: function( group ) {},
  expandItem: function( item ) {},

  collapseContract: function( contract ) {},
  collapseGroup: function( group ) {},
  collapseItem: function( item ) {},

  countItems: function( contract )
  {
    var itemCount=0;
    for ( var t in this.content )
    {
      if ( this.content[t].contractId == this.contractLocation ) continue;
      if ( contract && contract.id != this.content[t].contractId ) continue;
      itemCount++;
    }
    return itemCount;
  },

  getCartContractHTML: function( contract )
  {
    var HTML = '';
    var id = this.id + 'TreeContract' + contract.id;
    var itemCount = this.countItems( contract );

    //HTML += '<div style="position: relative;"></div>';
    HTML += '<div id="' + id + '" class="cartTreeContract ' + contract.name + '">' + contract.name + '</div>';
    HTML += '</a>';
    if ( contract.id == this.contractLocation )
    {
      HTML += '<div id="'+id+'Location" class="cartTreeContractLocation">' + this.locations[this.locationSelected].name + '</div>';
      $E.on( id+'Location', 'click', this.expandContract, contract, this );
    }
    else
    {
      HTML += '<div id="'+id+'ItemCount" class="cartTreeContractItemCount ' + contract.name + '">';
      HTML +=     this.countItems( contract ) + ' ' + this.text[this.lang.id]['artikel'];
      HTML += '</div>';
      var displayDelContract = this.countItems(contract)?'':'none';
      HTML += '<div style="display: ' + displayDelContract + ';" class="cartTreeContractDelete" id="'+id+'DeleteContract"></div>';
      $E.on( id+'DeleteContract', 'click', this.delContract, contract, this );

      HTML += '<div id="'+id+'DurationClick" class="cartTreeContractDuration ' + contract.name + '">';
      HTML += '   <span class="cartTreeContractHead ' + contract.name + '">' + this.text[this.lang.id]['laufzeit'] + '</span><br />';
      HTML += '   <span id="'+id+'Duration">' + this.durations[contract.durationId] + ' ' + this.text[this.lang.id]['monat'] + '</span>';
      HTML += '</div>';
      HTML += '<div class="cartTreeContractPriceInstall ' + contract.name + '">';
      HTML += '   <span class="cartTreeContractHead ' + contract.name + '">' + this.text[this.lang.id]['preisInstall'] + '</span><br />';
      if ( parseFloat(this.getPrice(contract).price_once) >= 0 )
      {
        HTML += '   <span id="'+id+'PriceInstall">' + this.formatFloat(this.getPrice(contract).price_once) + ' &euro;' + '</span>';
      }
      else
      {
        HTML += '   <span id="'+id+'PriceInstall">' + this.text[this.lang.id]['aufAnfrage'] + '</span>';
      }

      HTML += '</div>';
      HTML += '<div class="cartTreeContractPriceMonth ' + contract.name + '">';
      HTML += '   <span class="cartTreeContractHead ' + contract.name + '">' + this.text[this.lang.id]['preisMonat'] + '</span><br />';
      if ( parseFloat(this.getPrice(contract).price_interval) >= 0 )
      {
        HTML += '   <span id="'+id+'PriceMonth">' + this.formatFloat(this.getPrice(contract).price_interval) + ' &euro;' + '</span>';
      }
      else
      {
        HTML += '   <span id="'+id+'PriceMonth">' + this.text[this.lang.id]['aufAnfrage'] + '</span>';
      }
      HTML += '</div>';

      durationObj = { type: 'duration', width: '220px', contract: contract };
      $E.on( id+'DurationClick' , 'click', this.infoPanelShow, durationObj, this );
      $E.on( id+'ItemCount', 'click', this.expandContract, contract, this );
    }
    HTML += '<a href="#">';

    return HTML;
  },

  getCartGroupHTML: function( group )
  {
    var HTML = '';
    var id = this.id + 'TreeGroup' + group.id;

    HTML += '<div id="' + id + '" class="cartTreeGroup">';
    HTML += group.name;
    HTML += '</div>';

    return HTML;
  },

  getCartItemHTML: function( item )
  {
    var HTML = '';
    var group = this.getGroup( 'id', item.groupId );
    var contract = this.getContract( item.contractId );
    var id = this.id + 'TreeItemGroup' + item.groupId;

    HTML += '</a>';
    //HTML += '<div style="position: relative"></div>';
    HTML += '<div id="' + id + '" class="cartTreeItem">';
    HTML += '   <div class="cartTreeItemNumber">' + item.number + '</div>';
    HTML += '   <div class="cartTreeItemName">' + item.name + '</div>';
    HTML += '</div>';
    if ( item.contractId!=this.contractLocation && item.prices[contract.durationId] )
    {
      var price = item.prices[contract.durationId];
      if (  parseInt(price.price_once) >= 0 )
      {
        HTML += '<div id="' + id + 'PriceInstall" class="cartTreeItemPriceInstall">' + this.formatFloat(price.price_once) + ' &euro;' + '</div>';
      }
      else
      {
        HTML += '<div id="' + id + 'PriceInstall" class="cartTreeItemPriceInstall">' + this.text[this.lang.id]['aufAnfrage'] + '</div>';

      }
      if (  parseInt(price.price_interval) >= 0 )
      {
        HTML += '<div id="' + id + 'PriceMonth" class="cartTreeItemPriceMonth">'   + this.formatFloat(price.price_interval) + ' &euro;' + '</div>';
      }
      else
      {
        HTML += '<div id="' + id + 'PriceMonth" class="cartTreeItemPriceMonth">' + this.text[this.lang.id]['aufAnfrage'] + '</div>';
      }
      HTML += '<div class="cartTreeItemDeleteItem" id="'+id+'DeleteItem"></div>';
      $E.on( id+'DeleteItem', 'click', this.delItem, item, this );
    }
    HTML += '<div class="cartTreeItemChangeItem" id="'+id+'ChangeItem"></div>';
    HTML += '<div style="display: none;" class="cartTreeItemAddItem" id="'+id+'AddItem"></div>';
    HTML += '<a href="#">';

    var obj = { type: 'item', width: '500px', group: group };
    if ( item.contractId==this.contractLocation ) obj.width = '270px';

    $E.on( id , 'click', this.infoPanelShow, obj, this );
    $E.on( id+'ChangeItem' , 'click', this.infoPanelShow, obj, this );
    $E.on( id+'AddItem' , 'click', this.infoPanelShow, obj, this );

    return HTML;
  },

  getCartItemEmptyHTML: function( group )
  {
    var HTML = '';
    var id= this.id + 'TreeItemGroup' + group.id;

    HTML += '</a>';
    //HTML += '<div style="position: relative"></div>';
    HTML += '<div id="' + id + '" class="cartTreeItem">';
    HTML += '   <div class="cartTreeItemNumber"></div>';
    HTML += '   <div class="cartTreeItemEmpty">'
    HTML += this.text[this.lang.id]['keinArtikelGewaehlt'];
    HTML += '</div>';
    HTML += '</div>';
    HTML += '<div id="' + id + 'PriceInstall" class="cartTreeItemPriceInstall"></div>';
    HTML += '<div id="' + id + 'PriceMonth" class="cartTreeItemPriceMonth"></div>';
    HTML += '<div class="cartTreeItemAddItem" id="'+id+'AddItem"></div>';
    HTML += '<div style="display: none;" class="cartTreeItemDeleteItem" id="'+id+'DeleteItem"></div>';
    HTML += '<div style="display: none;" class="cartTreeItemChangeItem" id="'+id+'ChangeItem"></div>';
    HTML += '<a href="#">';

    var obj = { type: 'item', width: '500px', group: group };
    if ( group.contractId==this.contractLocation ) obj.width = '270px';

    $E.on( id , 'click', this.infoPanelShow, obj, this );
    $E.on( id+'AddItem' ,   'click', this.infoPanelShow, obj, this );
    $E.on( id+'ChangeItem', 'click', this.infoPanelShow, obj, this );

    return HTML;
  },

  formatFloat: function ( f, nk )
  {
    if ( ! nk ) nk=2;
    var nf;
    f += '';

    nf = parseFloat(f);
    nf = nf.toFixed(2);
    nf = nf.replace(/\./, this.lang['floatPoint']);
    
    return nf;
  },

  sendMail: function()
  {
    this._ajaxCallback.scope = this;
    this._ajaxCallback.success = function( obj ) { this._ajaxCallback.scope = null };
    var parameter = 'screen=sendForm&form=kontaktdaten';
    return YAHOO.util.Connect.asyncRequest( 'POST', this.ajaxURL, this._ajaxCallback, parameter );
  },

  getPopupItemHTML: function( item ) {},

  text:
  { en:
    { 
      keinArtikelGewaehlt: 'no Articles selected',
      artikel: 'Article',
      monat: 'Months',
      preisInstall: 'Price install',
      preisMonat: 'Month',
      laufzeit: 'Duration',
      laufzeitWaehlen: 'Select duration',
      bitteRechenzentrumWaehlen: 'Please select datacenter',
      rechenzentrum: 'Datacenter',
      bitteArtikelWaehlen: 'Please select article',
      preiseNetto: 'Alle Preise zzgl. 19% MwSt.',
      aufAnfrage: 'o.R.',
      pleaseWaitLoading: 'Bitte warten. Warenkorb wird geladen.'
    }   
  }
};

YCartTree = function( oData, oParent, expanded )
{
  if (oData)
  {
    this.init(oData, oParent, expanded);
    this.setUpLabel(oData);
  }

  this.multiExpand = true;
  this.type = false;
  this.groupId = false;
  this.contractId = false;
  this.durationId = false;
  this.expandedAll = false;
};

YAHOO.extend( YCartTree, YAHOO.widget.MenuNode );

YCartTree.prototype.BGClassName = 'ygtvitem';

YCartTree.prototype.getHtml = function()
{
  var html;

  html  = '<div style="position: relative" class="' + this.BGClassName  + '" id="ygtv' + this.index + '">';
  html += this.getNodeHtml();
  html += '<div class="ygtvchildren" id="ygtvc' + this.index + '" style="display:none;"></div>';
  html += '</div>';

  return html;
};

YCartTree.prototype.setBGStyle = function( className )
{
  this.BGClassName = className + ' ygtvitem';
};

YCartTree.prototype.toggle = function()
{
  if (!this.tree.locked && ( this.hasChildren(true) || this.isDynamic()) )
  {
    if (this.expanded) { this.collapse(); }
    else
    {
      if ( this.parent.isRoot() )
      {
        for ( var t in this.parent.children )
        {
          this.parent.children[t].collapse();
        }
        //this.expandAll();
        //$( this.tree.id + 'InfoPanel_c').style.visibility = 'hidden';
      }
      this.expand();
      $E._tryPreloadAttach();
    }
  }

};

YCartTree.prototype.draw = function()
{
  var html = this.root.getHtml();
  this.getEl().innerHTML = html;
  this.firstDraw = false;
  $E._tryPreloadAttach();
};
