var AjaxCart = {
  closed: true,
  product: {},
  timeoutId: false,
  setProduct:function(product) {
    this.product = product;
  },
  addProduct:function() {
    if (this.timeoutId) { window.clearTimeout(this.timeoutId); this.timeoutId = false; }
    if (arguments.length > 0) this.setProduct({id:arguments[0]});
    var url = 'product_info.php?action=ajax_product';
    new Ajax.Request(url, {
      method: 'post',
      parameters: {products_id: this.product.id},
      onSuccess: function(x) {
        eval('var rObj = ' + x.responseText + ';');
        AjaxCart.processResponse(rObj);
      },
      onFailure: function(x) {
        $('cart_quantity').submit();
      }
    });
    return true;
  },
  updateProduct:function() {
    if ($('slide_product_quantity') && ($F('slide_product_quantity') >= 0)) {
      var url = 'product_info.php?action=ajax_product';
      new Ajax.Request(url, {
        method: 'post',
        parameters: {products_id: this.product.id, product_quantity: $F('slide_product_quantity')},
        onSuccess: function(x) {
          eval('var rObj = ' + x.responseText + ';');
          AjaxCart.processResponse(rObj);
        },
        onFailure: function(x) {
          $('cart_quantity').submit();
        }
      });
    }
  },
  processResponse:function(r) {
    this.setProduct(r.product);
    this.totalItems = r.total_items;
    this.totalPrice = r.total_price;
    this.buildCart();
  },
  makeWrapper:function() {
    var ele = Builder.node('div',{id:'cart_slide_outer_wrapper'});
    document.body.appendChild(ele);
  },
  buildCart:function() {
    var ele = Builder.node('div',{id:'cart_slide_wrapper',style:'display:none;'},[
      Builder.node('div',{id:'cart_slide'},[
        Builder.node('form',{id:'cart_update_form',method:'post',action:'product_info.php?products_id='+this.product.id},[
          Builder.node('div',{id:'slide_header'},[
            Builder.node('div',{id:'slide_head_main'},[
              (this.product.quantity > 0) ? 
                Builder.node('span',{id:'slide_item_added'},this.product.quantity + ' ' + this.pluralize('item', this.product.quantity) + ' added to your cart') :
                Builder.node('span',{id:'slide_item_added'},'Item removed from your cart')
            ]),
            Builder.node('div',{id:'slide_head_closer'},[
              Builder.node('a',{href:'product_info.php?products_id='+this.product.id, onClick:'AjaxCart.close();return false;', title:'close'},'close')
            ])
          ]),
          Builder.node('div',{id:'slide_main'},[
            Builder.node('p',{className:'productListing-data'},[
              Builder.node('a',{href:'product_info.php?products_id='+this.product.id},[
                Builder.node('b',{},this.product.name)
              ])
            ]),
            Builder.node('table',{id:'slide_quantity',width:'100%'},[
              Builder.node('tbody',{},[
                Builder.node('tr',{},[
                  Builder.node('td',{className:'productListing-data slide_col1'},[
                    Builder.node('span',{className:'body-bold'},'Quantity:'),
                    ' ',
                    Builder.node('input',{type:'text',size:'2',value:this.product.quantity,name:'product_quantity',name:'product_quantity',id:'slide_product_quantity'}),
                    ' ',
                    Builder.node('a',{href:'shopping_cart.php',onClick:'AjaxCart.updateProduct();return false;',title:' Update Cart '},'update')
                  ]),
                  Builder.node('td',{className:'productListing-data',className:'slide_col2'},[
                    Builder.node('span',{className:'body'},this.product.totalPrice)
                  ])
                ]),
                Builder.node('tr',{},[
                  Builder.node('td',{colSpan:'2'},[
                    Builder.node('div',{id:'slide_total_separator'})
                  ])
                ]),
                Builder.node('tr',{},[
                  Builder.node('td',{className:'slide_col1'},[
                    Builder.node('span',{className:'body-bold'},this.totalItems + ' ' + this.pluralize('item', this.totalItems) + ' in cart')
                  ]),
                  Builder.node('td',{align:'right',className:'slide_col2 body-bold'},'Total: ' + this.totalPrice)
                ]),
                Builder.node('tr',{},[
                  Builder.node('td',{className:'slide_col1 body'},[
                    Builder.node('a',{href:'shopping_cart.php',title:' View Cart '},'view cart')
                  ]),
                  Builder.node('td',{align:'right',className:'slide_col2 body'},[
                    Builder.node('a',{href:'checkout_shipping.php',id:'slide_checkout',title:' Checkout '},'checkout')
                  ])
                ])
              ])
            ])
          ])
        ])
      ])
    ]);
    var descP = ele.firstChild.firstChild.childNodes[1].firstChild;
    var descHTML = '';
    if (typeof(this.product.color)!="undefined") {
      descHTML += Builder.node('div', {}, [
          Builder.node('br'),
          Builder.node('span',{className:'body-bold'},'Color/Style:'),
          ' ',
          Builder.node('img',{src:this.product.color_img}),
          ' ',
          Builder.node('span',{className:'body'},'('+this.product.color+')')
        ]).innerHTML;
    }
    if (typeof(this.product.pairings)!="undefined") {
      descHTML += Builder.node('div', {}, [
          Builder.node('br'),
          Builder.node('span',{className:'body-bold'},'Best with:'),
          ' ',
          Builder.node('span',{className:'body'},this.product.pairings)
        ]).innerHTML;
    }
    if (typeof(this.product.region)!="undefined") {
      descHTML += Builder.node('div', {}, [
          Builder.node('br'),
          Builder.node('span',{className:'body-bold'},'Region:'),
          ' ',
          Builder.node('span',{className:'body'},this.product.region)
        ]).innerHTML;
    }
    if (typeof(this.product.grape)!="undefined") {
      descHTML += Builder.node('div', {}, [
          Builder.node('br'),
          Builder.node('span',{className:'body-bold'},'Grape:'),
          ' ',
          Builder.node('span',{className:'body'},this.product.grape)
        ]).innerHTML;
    }
    if (typeof(this.product.vintage)!="undefined") {
      descHTML += Builder.node('div', {}, [
          Builder.node('br'),
          Builder.node('span',{className:'body-bold'},'Vintage:'),
          ' ',
          Builder.node('span',{className:'body'},this.product.vintage)
        ]).innerHTML;
    }
    if (typeof(this.product.error)!="undefined") {
      descHTML += Builder.node('div', {}, [
          Builder.node('br'),
          Builder.node('span',{id:'cart_slide_error', className:'body-bold'},this.product.error)
        ]).innerHTML;
    }
    new Insertion.Bottom(descP, descHTML);
    if ($('cart_slide_wrapper')) {
      $('cart_slide_wrapper').update(ele.innerHTML);
    } else {
      document.body.appendChild(ele);
    }

    if (! $('cart_slide_wrapper').visible()) this.slideDown();
    this.slideUpDelay();

    Event.observe('slide_product_quantity', 'keypress', function(e) {
      if (e.keyCode == Event.KEY_RETURN) {
        AjaxCart.updateProduct();
        Event.stop(e);
      }
    }, true);
    Event.observe('slide_product_quantity', 'blur', function(e) {
      AjaxCart.slideUpDelay();
    });
    Event.observe('slide_product_quantity', 'focus', function(e) {
      if (AjaxCart.timeoutId) { window.clearTimeout(AjaxCart.timeoutId); AjaxCart.timeoutId = false; }
    });

    new Effect.ScrollTo(document.body);
    Element.remove($('cartImg').nextSibling);
    $('cartLink').appendChild(Builder.node('span',{className:'hilite-cartLink'},' ' + this.totalItems + ' ' + this.pluralize('item', this.totalItems) + ' in cart'));
    $('cartLink').style.color = 'white';
    $('cartLink').style.textDecoration = 'none';
  },
  close: function() {
    this.slideUp();
  },
  cleanup: function() {
    Element.remove($('cartImg').nextSibling);
    $('cartLink').appendChild(Builder.node('span',{className:''},' ' + AjaxCart.totalItems + ' ' + AjaxCart.pluralize('item', AjaxCart.totalItems) + ' in cart'));
    $('cartLink').style.color = '';
    $('cartLink').style.textDecoration = 'underline';
  },
  pluralize: function(str, num) {
    return (num==1) ? str : str + 's';
  },
  slideDown: function() {
    if (this.timeoutId) { window.clearTimeout(this.timeoutId); this.timeoutId = false; }
    new Effect.SlideDown('cart_slide_wrapper', {queue:'end', afterFinish:AjaxCart.listenForClicks});
  },
  slideUp: function(moveBy) {
    Event.stopObserving(document, 'mouseup', AjaxCart.clickHandler);
    if (this.timeoutId) { window.clearTimeout(this.timeoutId); this.timeoutId = false; }
    new Effect.SlideUp('cart_slide_wrapper', {queue:'end', afterFinish:AjaxCart.cleanup});
  },
  slideUpDelay: function(moveBackBy) {
    if (this.timeoutId) { window.clearTimeout(this.timeoutId); this.timeoutId = false; }
    this.timeoutId = window.setTimeout('AjaxCart.slideUp()', 10000);
  },
  listenForClicks: function() {
    Event.observe(document, 'mouseup', AjaxCart.clickHandler);
  },
  clickHandler: function(e) {
    AjaxCart.pos = Position.cumulativeOffset($('cart_slide_wrapper'))
    AjaxCart.dims = $('cart_slide_wrapper').getDimensions();
    if ((Event.pointerX(e) >= AjaxCart.pos[0]) && (Event.pointerY(e) >= AjaxCart.pos[1]) && 
        (Event.pointerX(e) < AjaxCart.pos[0]+AjaxCart.dims.width) && (Event.pointerY(e) < AjaxCart.pos[1]+AjaxCart.dims.height)) {
      AjaxCart.slideUpDelay();
    } else {
//      AjaxCart.slideUp();
    }
  }
}