var Checkout = {
  _currentPanel: 'personal-information',
  _products: [],

  _panels: $H({}),

  _removeItemString: "",

  initialize: function(removeItemString){
    Checkout._removeItemString = removeItemString;
    Gucci.setOnBeforeFilling(Checkout.renderProducts.bind(Checkout));
    Checkout.render();
    Gucci.redraw();

    Gucci.scrollPanel(
      $('shopping-bag-contents'),
      $('item_list').down('div.handle'),
      $('item_list').down('div.scrollbar'),
      $('shopping-bag-contents').getHeight()
    );
  },

  registerProduct: function(product){
    this._products.push(product);
  },

  renderProducts: function(){
    var big          = this._products.length*260;
    var browser      = $('item_list').down('div.product-browser');

    $('product-images').getElementsBySelector('.thumbnail').invoke('remove');
    $('product-images').getElementsBySelector('.full').invoke('remove');
    $('item_list').setStyle({width:'260px'});

    var widths       = Gucci.projectedWidths();
    var isFull       = widths[0] >= big || (this._products.length == 1);

    if(isFull) {
      $('item_list').setStyle({width:big+260+'px'});
      browser.setStyle({width:big+'px'});
    } else {
      var width = Math.ceil(this._products.length/3)*130;
      $('item_list').setStyle({width:width+260+'px'});
      browser.setStyle({width:width+'px'});
    }

    this._products.each(function(p,i){
      var label;
      if(p.textOverlay!=null && p.textOverlay!='') {
        label = Builder.node('span', [(i+1), Builder.node('br'), p.textOverlay]);
      }
      else {
        label = (i+1);
      }
      var n = Builder.node('div',{'class': isFull ? 'full' : 'thumbnail'},[
        Builder.node('img',{src: isFull ? p.full : p.thumb }),
        Builder.node('div',{'class':'nr'},label)
      ]);
      $('product-images').appendChild(n);
    });
  },

  renderProductsList: function(){
    $('shopping-bag-product-list').update();
    this._products.each(function(p,i){
      var nodes = [
        p.description,
        Builder.node('br'),
        p.variationDescription,
        (p.size!='') ? Builder.node('br'): '',
        (p.size!='') ? p.size : '',
        Builder.node('div',{'class':'style-information'},[
          Builder.node('div',{'class':'style-number'},p.style),
          Builder.node('div',{'class':'price'}, (p.sale!='') ?
            [Builder.node('s', p.price),Builder.node('br'),p.sale] :
            [p.price]
          )
        ])
      ];
      if(!Checkout._isFinished) nodes.push(
        Builder.node('div',{'class':'functions remove-item'},[
          Builder.node('a',{'href':'#', onclick:'Checkout.removeItem('+i+',this); return false'},
            Checkout._removeItemString)])
      );
      var d = Builder.node('div',{'class':'style'},nodes);
      $('shopping-bag-product-list').appendChild(d);
    });
  },

  render: function(){
    this.renderProductsList();
    this.renderProducts();
  },

  maySubmitWhenReady: function(){
    var cb_accept_terms_checked = $('cb_accept_terms').type!='checkbox' ||
    	($('cb_accept_terms').type=='checkbox' && $('cb_accept_terms').checked);
    var cb_accept_pp_checked = $('cb_accept_pp').type!='checkbox' ||
    	($('cb_accept_pp').type=='checkbox' && $('cb_accept_pp').checked);
    var goodToGo = cb_accept_terms_checked && cb_accept_pp_checked && Checkout._shipMethod;

    $('cb_accept_terms').next().removeClassName('error');
    $('cb_accept_pp').next().removeClassName('error');
    $('shipping_options_required').hide();

    if(!$('cb_accept_terms').checked) $('cb_accept_terms').next().addClassName('error');
    if(!$('cb_accept_pp').checked) $('cb_accept_pp').next().addClassName('error');
    if(!Checkout._shipMethod) $('shipping_options_required').show();

    Checkout.toggleSubmitButton(goodToGo);
  },

  toggleSubmitButton: function(on){
    $('wait_button').hide();
    $('submit_button').show();
    if(!on){
      $('submit_button').onclick = null;
      $('submit_button').setStyle({opacity: 0.2});
      $('checkout_message').show();
    } else {
      $('submit_button').onclick = Checkout.submitOrder;
      $('submit_button').setStyle({opacity: (Prototype.Browser.WebKit ? 0.999 : 1.0)}); // bug in safari 2.0
      $('checkout_message').hide();
    }
  },

  purchase: function(){
    $('purchase-button').addClassName('busy');

    new Ajax.Updater('purchase-form-slide','form.asp',{
      evalScripts: true,
      onComplete: function() {
        Checkout.startPurchase();
      }
    });
  },

  initSubmenu: function(){
    $$('#purchase-form-slide div.form').each(function(f,i){
      Checkout._panels[f.id] = {
        position: i,
        form:     f,
        title:    f.down('h1').innerHTML.escapeHTML(),
        status:   i==0 ? 'active' : 'inactive',
        open:     !f.hasClassName('optional')
      }
    });
  },

  renderSubmenu: function(){
    var submenu = $$('#purchase-form-slide div.form').map(function(f,i){
      var klass = ['checkout-menu-item', 'menu-item-'+f.id];
      var panel = Checkout._panels[f.id];

      if(f.id == 'submission_error') return;

      klass.push(panel.status);
      if(!panel.open) klass.push('optional');
      // onclick="if(!$(this).hasClassName(\'inactive\')){Checkout.submitPanelAndContinueTo(\''+f.id+'\')}"
      return '<p class="'+ klass.join(' ') + '">' + panel.title + '</p>';
    }).join('');

    Checkout.menuPanel = submenu;
    Gucci._renderSubMenu('', submenu);
    return submenu;
  },

  refreshSubmenuPanel: function(){
    var submenu =  Checkout.renderSubmenu();
    Gucci.showMenuPanel(Gucci.SUB_MENU,submenu);
    Gucci.setCustomTimeoutMenuEvent(function(){
      var submenu = Checkout.renderSubmenu();
      Gucci.showMenuPanel(Gucci.SUB_MENU,submenu);
    });
  },

  startPurchase: function(){
    $('purchase-button').removeClassName('busy').hide();
    $('shopping-bag-headline').hide();
    $('your-order-headline').show();
    $('purchase-form').morph('width:260px',{
      transition: Gucci.cubic,
      afterUpdate: Gucci.redraw
    });

    Checkout.toggleSubmitButton(false);
    Checkout.initSubmenu();
    var submenu = Checkout.renderSubmenu();

    setTimeout(function(){ Checkout.refreshSubmenuPanel(); },1050);
  },

  hidePanel: function(step){
    if($('step'+step+'_bar').offsetWidth == 0) return;
    $('step'+step+'_bar').morph('width:0px',{
      transition: Gucci.cubic,
      afterUpdate: Gucci.redraw,
      afterFinish: function(){
        $('step'+step+'_bar').setStyle({borderLeftWidth:'0px'});
      }
    });
  },
  setComplete: function(id){
    this._panels[id].status = 'complete';
  },
  setIncomplete: function(id){
    // NOP
  },
  showPanelX: function(id){
    // internals of showPanel
    Checkout._panels[id].status = 'active';

    $('submit_functions')[ id == 'order_summary' ? 'show' : 'hide']();

    Checkout._panels.findAll(function(p){
      return p[1].position > Checkout._panels[id].position
    }).each(function(inactive){
      Checkout._panels[inactive[0]].status = 'inactive'
    });

    this.refreshSubmenuPanel();
    if(id=='order_summary') {
      $('cb_accept_terms').checked = $('cb_accept_pp').checked = false;
      $$('.shipping-details').invoke('show');
      this.maySubmitWhenReady();
    }

    $('purchase-form-slide').morph('left:-'+$(id).offsetLeft+'px',{
      transition: Gucci.cubic,
      afterUpdate: function(){
        Gucci.redraw();
      }
    });
    this._currentPanel = id;
    Checkout.hbxPanelChange(id);
  },
  reshowPanel: function(id){
    // same as showPanel, but without hbx hit
    Checkout.showPanelX(id);
  },
  showPanel: function(id){
    Checkout.showPanelX(id);
    Checkout.hbxPanelChange(id);
  },

  removeItem: function(idx,link){
    if(link) $(link).addClassName('with-indicator');
    new Ajax.Request('remove_item.asp',{parameters:'item='+idx});
  },

  finalizeRemoveItem: function(idx){
    this._products = this._products.reject(function(p,i){ return i==idx });
    this.render();
    this.recalculate();
    Gucci.redraw();
  },

  showFailure: function(){
    $('submit_button').hide();
    $('wait_button').hide();
    $('submit_functions').hide();
    $('total').hide();
    $('failure').show();
    $('restart_functions').show();
    Checkout.hbxPanelFailure();
  },

  restart: function(){
    Checkout.goBackToPanel('personal_information');
  },

  goBackToPanel: function(panelName){
    $('failure').hide();
    $('restart_functions').hide();
    $('shipping_options_container').update(
      '<input type="hidden" id="shipMethod" name="shipMethod" value=""/>'
      );
    Checkout._shipMethod = null;
    Checkout.resetShippingOptions();
    Checkout.toggleSubmitButton(0);
    $('submit_functions').hide();
    $('total').show();
    var m = $("additional_tax_message");
    if(m) {m.hide();}
    $("additional_tax_amount").up().hide();
    $("additional_tax_text").up().hide();
    m = $("tax_refund_message");
    if(m) {m.hide();}
    $("tax_refund_amount").up().hide();
    $("tax_refund_text").up().hide();
    $("total_amount").up().hide();
    $("total_text").up().hide();
    $("VAT_amount").up().hide();
    $("VAT_text").up().hide();
    Checkout.hbxPanelRevisit(panelName);
    Checkout.reshowPanel(panelName);
  },

  submitOrder: function(){
    $('submit_button').hide();
    $('wait_button').show();
    $('wait_button').setStyle({opacity: 0.4});
    $('wait_button').onclick = null;
    $$('functions').each(function(p){p.hide();});
    $('order_summary').getElementsByClassName('editInfo').each(function(p){p.hide();});
    new Ajax.Request('submit_order.asp',{parameters:Checkout.serializePanel(Checkout._currentPanel)});

  },

  finalizeSubmitOrder: function(){
    $('shopping-bag-contents').getElementsBySelector(".remove-item").invoke('hide');
    $('submit_button').hide();
    $('wait_button').hide();
    this._isFinished = true;
    this.render();
    Gucci.redraw();
  },

  enablePanel: function(id){
    Checkout._panels[id].open = true;
    $(id).addClassName('visible');
    $('purchase-form-slide').setStyle({left:-$(Checkout._currentPanel).offsetLeft+'px'});
    Checkout.refreshSubmenuPanel();
  },

  disablePanel: function(id){
    Checkout._panels[id].open = false;
    $(id).removeClassName('visible');
    $('purchase-form-slide').setStyle({left:-$(Checkout._currentPanel).offsetLeft+'px'});
    Checkout.refreshSubmenuPanel();
  },

  hbxHit: function(pageName){
    if(hbx && hbxx) {
      if(hbxx.mlc) {
        var l = hbxx.mlc.lastIndexOf('/');
        if(l != -1) {
          _hbSet('cpv.cacct',hbxCommerce);
          _hbSet('cpv.bd','Gucci');
          var mlc2 = hbxx.mlc.substring(0,l) + '/' + pageName;     
          _hbPageView(pageName,mlc2);
        }
      }
    }
  },

  hbxPanelChange: function(name) {
    Checkout.hbxHit('to_'+name);
  },

  hbxPanelError: function(name) {
    Checkout.hbxHit('error_'+name);
  },

  hbxPanelRevisit: function(name) {
    Checkout.hbxHit('backto_'+name);
  },

  hbxPanelFailure: function() {
    Checkout.hbxHit('failure');
  },

  getPanelFields: function(panel){
    return [
      $(panel).getElementsBySelector('input'),
      $(panel).getElementsBySelector('select'),
      $(panel).getElementsBySelector('textarea')
    ].flatten();
  },
  serializePanel: function(panel){
    return Form.serialize('order_form') + '&panel=' + $(panel).id;
  },
  submitPanel: function(element){
    element = $(element);
    var button = element;
    button.addClassName('busy');
    if(!element.hasClassName('form')) element = element.up('div.form');
    new Ajax.Request('validate.asp',{
      parameters:this.serializePanel(element),
      onComplete: function(){ button.removeClassName('busy') }
    });
  },
  submitPanelAndContinueTo: function(nextPanel){
    nextPanel = $(nextPanel);
    new Ajax.Request('validate.asp',{parameters:this.serializePanel(this._currentPanel)+'&to='+nextPanel.id});
  },

  markError: function(field){
    field = $(field);
    field.addClassName('error');
    field.up('.form-body').getElementsBySelector('.'+field.id).invoke('addClassName','error');
  },
  clearErrors: function(panel){
    $(panel).getElementsBySelector('*').invoke('removeClassName','error');
    $(panel).down('p.message').update();
    $('centerColumnMessage').show();
  },
  showError: function(panel, message){
    $(panel).down('p.message').update(message);
    $('centerColumnMessage').hide();
    Checkout.hbxPanelError(panel);
  },

  setSubtotal: function(subtotal){
    $('subtotal').update(subtotal);
  },

  resetShippingOptions: function() {
    $('shipping_options_required').hide();
    $('shipping_amount').update('');
    $('additional_tax_amount').update('');
    $('tax_refund_amount').update('');
    $('total_amount').update('');
    $('VAT_amount').update('');
  },

  recalculate: function(){
    if(!$('shipMethod')) return;
    if($('shipMethod').tagName == 'SELECT' && $('shipMethod').selectedIndex == 0) {
      Checkout.resetShippingOptions();
      Checkout._shipMethod = null;
      return;
    }
    var option = this._shippingOptions.find(function(o){ return o.shippingType == $F('shipMethod') });
    $('shipping_amount').update(option.shippingAmount);
    $('additional_tax_amount').update(option.additionalTaxAmount);
    $('tax_refund_amount').update(option.taxRefundAmount);
    $('total_amount').update(option.totalAmount);
    $('VAT_amount').update(option.VATAmount);

    Checkout._shipMethod = $F('shipMethod');
  },

  setShippingOptions: function(options, selectShippingText){
    Checkout.resetShippingOptions();
    var selected = $('shipMethod') ? $F('shipMethod') : null, s;
    this._shippingOptions = options;

    if(options.length>1) {
      s = '<select id="shipMethod" name="shipMethod" ' +
       'onchange="Checkout.recalculate(); Checkout.maySubmitWhenReady();" ' +
       'onkeydown="return Checkout.handleTab(event,\'shipMethod\')" ' +
       'onkeypress="return Checkout.handleTab(event,\'shipMethod\')"' +
       '>';
      if(selectShippingText) s += '<option value=\'\'>' + selectShippingText.escapeHTML() + '</option>';
      options.each(function(o){
        s += '<option value="' + o.shippingType + '"' +
          (selected == o.shippingType ? ' selected="selected"' : '') + '>' +
          o.shippingName.escapeHTML() + '</option>';
      });
      s += '</select>';
    } else {
      s = '<input type="hidden" id="shipMethod" name="shipMethod" value="'+options[0].shippingType+'"/>' +
        options[0].shippingName.escapeHTML();
    }
    $('shipping_options_container').update(s);

    if(options.length == 1) Checkout.recalculate();
    Checkout.maySubmitWhenReady();
  },

  showAdditionalTax: function(additionalTaxText){
    $("additional_tax_text").update(additionalTaxText);
    var m = $("additional_tax_message");
    if(m) {m.show();}
    $("additional_tax_amount").up().show();
    $("additional_tax_text").up().show();
  },

  showTaxRefund: function(taxRefundText){
    $("tax_refund_text").update(additionalTaxText);
    $("tax_refund_message").show();
    $("tax_refund_amount").up().show();
    $("tax_refund_text").up().show();
  },

  showTotal: function(totalText){
    $("total_text").update(totalText);
    $("total_amount").up().show();
    $("total_text").up().show();
  },

  showVAT: function(VATText){
    $("VAT_text").update(VATText);
    $("VAT_amount").up().show();
    $("VAT_text").up().show();
  },

  checkGiftMessage: function(msg){
    var msg = $(msg);
    $('gift_message_chars_left').update( msg.value.length > 0
      ? Math.round((msg.value.length/200.0)*100.0) + '%' : '' );
  },

  handleTab: function(event, id){
    if(event.keyCode == Event.KEY_TAB) {
      $(id).focus();
      Event.stop(event);
      return false;
    }
  },

  switchswitch: function(){
    var elem = $('switchsolo');
    var ct = $('cardType');

    if(ct.value == 'switch') {
      elem.show();
    }
    else {
      if (ct.value == 'solo') {
        elem.show();
      }
      else {
        elem.hide();
      }
    }
  }

}