
/**************************************************

wbMember Dynamic Cart Module

**************************************************/

var wbQuickCart = function( elm, params ){

  // ------------------------------------------------
  this.container = $(elm);
  if( !this.container ){ wbDebug.log('Element Not Found - Abort'); return;
  } else wbDebug.log('Found Element: '+this.container.identify());
  this.container._control = this;

  // ------------------------------------------------
  this.elm = {
    };
  this.config = $H({
    'toggle':     this.container.identify()+'_toggle',
    'basket':     this.container.identify()+'_basket',
    'checkout':   this.container.identify()+'_checkout',
    'totalbtn':   this.container.identify()+'_total',
    'open':       0,
    'cart_qty':   0,
    'cart_items': 0,
    'cart_total': 0
  }).merge( params );
  this.timers = {
    'autoclose': null
    };
  this.system = {
  };

  // ------------------------------------------------
  this.elm.item_list = this.container.select('div[class=item_list]');
  if( this.elm.item_list && this.elm.item_list.length )
    this.elm.item_list = this.elm.item_list.shift();
  if( !Object.isElement(this.elm.item_list) ){
    alert('Failed to Initalize Item List');
    return;
  }

  // ------------------------------------------------
  this.checkout = function(mo){
    if( mo && mo.href )
      wbWindow.load( mo.href );
    else
      wbWindow.load( wbPack.script+'?option=com_member&task=cart.view&Itemid='+wbPack.Itemid );
  }

  // ------------------------------------------------
  this.clearList = function(){
    this.elm.item_list.update('');
  }

  // ------------------------------------------------
  this.update = function(transport){
    if( typeof transport == 'object' ){
      var resData = unescape(transport.responseText);
      if( resData.isJSON() ){
        resData = resData.evalJSON();
        if( resData.status != 200 ){
          alert( resData.message ); return; }
        else if( resData.cart ){
          this.loadCapture(transport);
          return;
        } else if( resData.message != null )
          alert( 'Message: ' + resData.message );
      }
    }
    wbAjax.post(wbPack.script+'?option=com_member&task=cart.query&no_html=1',null,null,"$('"+this.container.id+"')._control.loadCapture(transport);");
  }

  // ------------------------------------------------
  this.loadCapture = function(transport){
    if( typeof transport == 'object' ){
      var resData = unescape(transport.responseText), cartRows = [];
      this.clearList();
      if( resData.isJSON() ){
        resData = resData.evalJSON();
        if( resData.status != 200 ){
          alert( resData.message );
          return;
        } else if( resData.message != null )
          alert( 'Message: ' + resData.message );
        cartRows = resData.cart;
        if( cartRows != 'null' )
          for(var cKey in cartRows){
            cartRows[ cKey ][ 'key' ] = cKey;
            this.addItem( cartRows[ cKey ] );
          }
        this.config.set('cart_qty', resData.qty);
        this.config.set('cart_total', resData.total);
      }
      this.toggle.down('a').update('Cart: '+this.config.get('cart_qty')+' Items');
      this.basket.down('div[class^=total]').down('span').update(
        formatPrice( this.config.get('cart_total'), 1 ) );
      if( this.totalbtn )
        this.totalbtn.down('a').update(
          'Total: '+formatPrice( this.config.get('cart_total'), 1 ) );
    } else {
      alert( 'Cart Load Error...' );
      return;
    };
    this.activateItems();
    if( this.config.get('cart_qty') > 0 ){
      if( this.config.get('open') == 0 )
        this.toggle.fire('wbQuickCart:toggle');
    } else
      if( this.config.get('open') == 1 )
        this.toggle.fire('wbQuickCart:toggle');
  }

  // ------------------------------------------------
  this.emptyCart = function(){
    this.deleteCartItem( this.elm.item_list );
  }
  this.deleteCartItem = function( elm ){
    if( !Object.isElement(elm) ) return;
    var keySet = [];
    if( elm.hasClassName('item_list') ){
      var iNodes = elm.select('div[class^=item]');
      if( iNodes.length ){
        for(var i=0;i<iNodes.length;i++)
          if( iNodes[i].identify() )
            keySet.push( iNodes[i].identify().replace(/^cart_/,'') );
      } else {
        alert( 'No Items to Delete' );
        return;
      }
    } else {
      var itemid = elm.up('div[class^=item]').identify().replace(/^cart_/,'');
      if( itemid )
        keySet.push( itemid );
      else {
        alert( 'Invalid Item ID: '+itemid );
        return;
      }
    }
    wbAjax.post(wbPack.script+'?option=com_member&task=cart.add&no_html=1&quick=1&cart_del[]='+keySet.join('&cart_del[]=')
      ,null,null,"$('"+this.container.id+"')._control.loadCapture(transport);");
  }

  // ------------------------------------------------
  this.addItem = function( cRow ){
    var tRow = cRow;
    tRow['unit'] = formatPrice(tRow['unit']);
    tRow['total'] = formatPrice(tRow['total']);
    for(var dKey in tRow.details)
      tRow['details.'+dKey] = tRow.details[dKey];
    for(var dKey in tRow.options)
      tRow['options.'+dKey] = tRow.options[dKey];
    // Qty Detail
    if( cRow.fixed )
      cRow.qty_msg = ' <em class="fixed">fixed</em> ';
      else cRow.qty_msg = '';
    switch( cRow.details.qty_unit ){
      case '12':  cRow.qty_msg += ' Dozen'; break;
      case '6':   cRow.qty_msg += ' Half Dozen'; break;
      case '1':   cRow.qty_msg += ' Each'; break;
      default:    cRow.qty_msg += ' x '+cRow.details.qty_unit; break;
    }
    // Interpolate
    var tmpl = this.config.get('tmpl_item').interpolate( cRow );
    this.elm.item_list.insert( tmpl );
  }

  // ------------------------------------------------
  this.activateItems = function(){
    this.items = this.elm.item_list.select('div[class=item]');
    this.config.set('cart_items', this.items.length);
    if( !this.items.length ){
      this.elm.item_list.update(
        this.config.get('tmpl_empty')
        );
    } else {
      var elm, alnk, elmLnks;
      for(var iNum=0;iNum<this.items.length;iNum++){
        elm = this.items[ iNum ];
        elm._control = this;
        try{
          elmLnks = elm.select('a');
          for(var lnkNum=0;lnkNum<elmLnks.length;lnkNum++){
            alnk = elmLnks[ lnkNum ];
            alnk._control = alnk.up('div[class=item]')._control;
            alnk.href="javascript:void(0);"
            if(alnk.hasClassName('delete'))
              alnk.observe('click',function(){ this._control.deleteCartItem(this); });
          };
        } catch(e) {
          // alert( 'Cart Error:\n'+e+'\n'+elm.innerHTML );
        }
      }
    }
  }

  // ------------------------------------------------
  this.toggle = $( this.config.get('toggle') );
  if( !this.toggle ){ wbDebug.log('Toggle Not Found - Abort'); return;
  } else wbDebug.log('Found Toggle: '+this.toggle.identify());
  this.toggle._control = this;

  // ------------------------------------------------
  this.toggle.down('a').update('Cart: '+this.config.get('cart_qty')+' Items');

  // ------------------------------------------------
  this.totalbtn = $( this.config.get('totalbtn') );
  if( this.totalbtn ){
    if( this.config.get('cart_total') > 0 )
      this.totalbtn.down('a').update(
        'Total: '+formatPrice( this.config.get('cart_total'), 1 ) );
    else
      this.totalbtn.down('a').update('');
  }

  // ------------------------------------------------
  this.basket = $( this.config.get('basket') );
  if( !this.basket ){ wbDebug.log('Basket Not Found - Abort'); return;
  } else wbDebug.log('Found Basket: '+this.basket.identify());
  this.basket._control = this;

  // ------------------------------------------------
  this.basket.down('div[class^=total]').down('span').update(
    formatPrice( this.config.get('cart_total'), 1 ) );

  // ------------------------------------------------
  this.elm.checkout = $( this.config.get('checkout') );
  if( !this.elm.checkout ){ wbDebug.log('Toggle Not Found - Abort'); return;
  } else wbDebug.log('Found Checkout: '+this.elm.checkout.identify());
  this.elm.checkout._control = this;
  // this.elm.checkout.select('a').pop().href="javascript:void(0);";
  this.elm.checkout.observe('click',function(){ this._control.checkout(this); });

  // ------------------------------------------------
  var btn_close = this.container.select('a[class=close]').pop(); btn_close._control = this;
    btn_close.observe('click',function(){ this._control.toggle.fire('wbQuickCart:toggle'); });
    btn_close.href='javascript:void(0);';

  // ------------------------------------------------
  var btn_clear = this.container.select('a[class=clear]').pop(); btn_clear._control = this;
    btn_clear.observe('wbQuickCart:empty',function(){ this._control.emptyCart(); });
    btn_clear.observe('click',function(){ this.fire('wbQuickCart:empty'); });
    btn_clear.href='javascript:void(0);';

  // ------------------------------------------------
  this.toggle.select('a').pop().href="javascript:void(0);";
  this.toggle.observe('wbQuickCart:clearTimer',function(){
    window.clearTimeout(this._control.timers.autoclose);
    });
  this.toggle.observe('wbQuickCart:resetTimer',function(){
    window.clearTimeout(this._control.timers.autoclose);
    if( this._control.config.get('open') == 1 )
      this._control.timers.autoclose =
        Element.fire.delay(10,$(this),'wbQuickCart:toggle');
    wbDebug.log('wbQuickCart:resetTimer');
    });
  this.toggle.observe('wbQuickCart:toggle',function(){
    this.fire('wbQuickCart:clearTimer');
    if( this._control.config.get('open') == 1 ){
      new Effect.Parallel([
        new Effect.BlindUp(this._control.basket,{sync:true}),
        new Effect.Opacity(this._control.basket,{sync:true,from:1,to:0})
      ], {duration:1,delay:0});
      this._control.config.set('open', 0);
    } else {
      wbQuickCart_scrollTop();
      new Effect.Parallel([
        new Effect.BlindDown(this._control.basket,{sync:true}),
        new Effect.Opacity(this._control.basket,{sync:true,from:0,to:1})
      ], {duration:.5,delay:0});
      this._control.config.set('open', 1);
    }
    });
  this.toggle.observe('click',function(){
    this.fire('wbQuickCart:toggle');
    });
  this.basket.observe('mouseover',function(){
    this._control.toggle.fire('wbQuickCart:clearTimer');
    });
  this.basket.observe('mouseout',function(){
    this._control.toggle.fire('wbQuickCart:resetTimer');
    });

  // ------------------------------------------------
  this.activateItems();

};

function wbQuickCart_scrollTop(){
  var wO = document.viewport.getScrollOffsets();
  if( wO.top > 10 ) window.scrollTo(wO.left,wO.top - parseInt(wO.top/2));
    else return window.scrollTo(wO.left,0);
  setTimeout(wbQuickCart_scrollTop,100);
}