/*--------------------------------------------------------------------------
 *  The Bad Back Shop Website Dynamic Cart JavaScript, version 1.6.0.3
 *  (c) 2009-2010 Mark Haussmann, etraction
 *
 *  Allows users to seemlessly interact with the shopping cart to view
 *  edit and delete items.
 *
 *--------------------------------------------------------------------------*/

var AjaxCart = Class.create();
AjaxCart.prototype = {
    initialize: function(varienForm){
        this.varienForm = varienForm;
        this.validator = varienForm.validator;
        this.form = varienForm.form;
        if ($(this.form)) {
          varienForm.submit = this.save.bind(this);
        }
        this.saveUrl = this.form.action;
        this.deleteUrl = '/checkout/cart/delete/id/{id}/'
        this.onSave = this.updateAjaxCart.bindAsEventListener(this);
        this.onComplete = this.resetLoadWaiting.bindAsEventListener(this);
        this.failureUrl = window.location.href;
        
        $$('.cart-item').each(function (item) {
          this._truncateProductName(item);
          this._addEvents(item);
        }.bind(this));
    },

    save: function(button, url){
        if (this.validator.validate()) {
          var form = this.form,
              oldUrl = form.action,
              e = null;

          if (url) {
             form.action = url;
          }
          
          try {
              if (this.loadWaiting!=false) return;
              this.setLoadWaiting(true);
              
              var params = Form.serialize(this.form);
              params.save = true;
              var request = new Ajax.Request(
                  this.saveUrl,
                  {
                      method:'post',
                      parameters:params,
                      onComplete: this.onComplete,
                      onSuccess: this.onSave,
                      onFailure: this.ajaxFailure.bind(this)
                  }
              );
          } catch (e) {}
          
          this.form.action = oldUrl;
          if (e) {
              throw e;
          }

          if (button && button != 'undefined') {
              button.disabled = true;
              $(button).addClassName('loading');
          }
        }
    },
    
    delete: function(id) {
      var request = new Ajax.Request(
          this.deleteUrl.replace('{id}', id),
          {
              method:'get',
              onComplete: this.onComplete,
              onSuccess: this.onSave,
              onFailure: this.ajaxFailure.bind(this)
          }
      );
    },
    
    ajaxFailure: function(){
        location.href = this.failureUrl;
    },

    resetLoadWaiting: function(transport){
        this.setLoadWaiting(false, this.isSuccess);
    },
    
    setLoadWaiting: function(step, keepDisabled) {
        if (step) {
            if (this.loadWaiting) {
                this.setLoadWaiting(false);
            }
            $$('.loading').each(function (button) {
              button.removeClassName('loading');
              if (button.disabled) {
                button.disabled = false;
              }
            });
        } else {
            if (this.loadWaiting) {
              $$('.loading').each(function (button) {
                button.removeClassName('loading');
                if (button.disabled) {
                  button.disabled = false;
                }
              });
            }
        }
        this.loadWaiting = step;
    },

    updateAjaxCart: function(transport){
        if (transport && transport.responseText) {
            try{
                response = eval('(' + transport.responseText + ')');
            }
            catch (e) {
                response = {};
            }
            if (response.redirect) {
                this.isSuccess = true;
                location.href = response.redirect;
                return;
            }
            if (response.success) {
                this.isSuccess = true;
                window.location=this.successUrl;
            }
            else{
                var msg = response.error_messages;
                if (typeof(msg)=='object') {
                    msg = msg.join("\n");
                }
                if (msg) {
                    alert(msg);
                }
            }

            if (response.replace_section) {
              $(response.replace_section.name).replace(response.replace_section.html);
            }

            if (response.update_section) {
              $(response.update_section.name).update(response.update_section.html);
            }

            if (response.goto_section) {
                checkout.gotoSection(response.goto_section);
                checkout.reloadProgressBlock();
            }
            
            $$('.cart-item').each(function (item) {
          		this._truncateProductName(item);
          		this._addEvents(item);

          		if (response.product &&  response.product == item.down('#cartProductId').value) {
                // animate dropping into cart
                this._animateAddProduct(item);
          		  //this._highlightProduct(item);
          		}
          	}.bind(this));
        }
    },
    
    _truncateProductName: function (item) {
      // check if name is > 25px, if so remove offending line and add '...'
  		if (item.down('.details .name').getHeight() > 116) {
  			var itemNameBox = item.down('.details .name');
  			var fullName = itemNameBox.innerHTML;
  			var clipName = fullName.substring(0, fullName.length - 2) + '...';

  			for (var i = 2; i < fullName.length; i++) {
  				itemNameBox.innerHTML = clipName;

  				clipName = fullName.substring(0,  fullName.length - i ) + '...';
  				if (itemNameBox.getHeight() <= 116) {
  					break;
  				}
  			}
  		}
    },
    
    _highlightProduct: function (item) {
      // show items that have just been added
  		item.down('.details').addClassName('details-hover');
			item.down('.form').setStyle({visibility: 'visible'});
			//new Effect.Highlight(item.down('.popup-content'), {startcolor: '#ff9900'});

			if (!Prototype.Browser.IE) {
			  new Effect.Move(item.down('.form'), { y: 5, mode: 'relative', duration: 0.5 });
			}

			setTimeout( function () {
				item.down('.form').setStyle({visibility: 'hidden'});
				item.down('.details').removeClassName('details-hover');
			}, 3000 );
    },
    
    _animateAddProduct: function (item) {
      // create animate object.
      Element.insert(document.body, "<div id='dropProduct' style='opacity:0'>" + $("qty").value + "</div>");
      var drop = $('dropProduct');
      Element.clonePosition(drop, $("qty"), {setWidth: false, setHeight: false});
      
      var target = item.cumulativeOffset();
      
      element = drop;
      options = {};
      
      var oldStyle = {
        top: drop.getStyle('top'),
        left: drop.getStyle('left'),
        opacity: drop.getInlineOpacity() 
      };
      
      new Effect.Parallel(
        [ new Effect.Move(element, {x: element.style.left, y: target.top + 150, mode: 'absolute', transition: function (pos) {
            var s = 1.70158; 
            return pos*pos*((s+1)*pos - s);
          } }),
          new Effect.Morph(element, {style: 'margin-left: '+(target.left - parseInt(element.style.left))+'px;', transition: Effect.Transitions.sinoidal })
        ],
        Object.extend({ 
          duration: 0.5,
          beforeSetup: function(effect) {
            effect.effects[0].element.setOpacity(1); 
          },
          afterFinishInternal: function(effect) {
            effect.effects[0].element.remove();
            this._highlightProduct(item);
          }.bind(this)
        }, options)
      );
      
    },
    
    _addEvents: function (item) {
      // attach the display function to each cart item
    	item.observe('mouseenter', function (ev) {
  			item.down('.details').addClassName('details-hover');
  			// get the form div
  			var formdiv = this.down('.form');

  			if (formdiv.getStyle('visibility') == 'hidden') {
  				if (Prototype.Browser.IE) {
  					formdiv.setStyle({opacity: '0', visibility: 'visible' });
  				} else {
  					formdiv.setStyle({opacity: '0', visibility: 'visible', top: '' });
  					new Effect.Move(formdiv, { y: 5, mode: 'relative', duration: 0.5 });
  				}
  				this.fadein = formdiv.appear({ duration: 0.7, afterFinish: function() {formdiv.setStyle({backgroundColor:''})} } );
  			}
  		});

  		item.observe('mouseleave', function () {
  			//this.fadein.stop();
  			item.down('.details').removeClassName('details-hover');
  			// hide div
  			this.down('.form').setStyle({visibility: 'hidden'});
  		});
    },

    isSuccess: false,
    loadWaiting: false
}

Event.observe(window, 'load', function(){
  if (typeof productAddToCartForm != "undefined") {
    window.ajaxCart = new AjaxCart(productAddToCartForm);
  }
});

