jsImport ("com.applynx.mvc.view.ViewCartView");
jsImport ("com.applynx.xmlHttp.XmlHttpUtils");
jsImport ("com.applynx.mvc.controller.UpdateCartController");

function ViewCartController(anchorId) {

  /* remove the href and add the javascript behavior */
  this.anchor = document.getElementById(anchorId);
  this.anchor.controller = this;
  this.anchor.removeAttribute("href");
  this.anchor.onclick = function() {this.controller.showCart()};

	this.showCart = function(evt) {
	  if (this.view == null)
		  XmlHttpUtils.sendAndWait(this, "/view-cart.ajax");
	}
	
	this.handleSuccess = function(response) {
	
	  var model = new Object();
	  model.order = eval('(' + response.order + ')');
	  model.lineItems = eval('(' + response.lineItems + ')');
	  
	  if (model.lineItems.length > 0) {
			this.view = new ViewCartView(model);
			NodeUtils.addSibling(this.anchor, this.view);

			NodeUtils.addClass(document.getElementsByTagName("body")[0], "layered");
			NodeUtils.addClass(this.view, "layer");
		
			for (var i=0; i<this.view.quantities.length; i++) {
				this.view.quantities[i].controller = this;
				this.view.quantities[i].onfocus = function() {this.select()};
				this.view.quantities[i].onchange = function() {this.controller.updateQuantity(this)};
			}
		
			this.view.closeAnchor.controller = this;
			this.view.closeAnchor.onclick = function() {this.controller.closeCart() };
		} else {
			this.anchor.title = "There are no items in your cart";
			NodeUtils.replaceClass(this.anchor, "view-cart-full", "view-cart-empty");
		}

	}
	
	this.handleFailure = function(response) {
	  alert(response);
	}
	
	/**
	 * remove the view and change the layer names
	 */
	this.closeCart = function() {
	  NodeUtils.removeElement(this.view);
	  this.view = null;
		NodeUtils.removeClass(document.getElementsByTagName("body")[0], "layered");
	}
	
	this.updateQuantity = function(qty) {
	  var updateCartController = new UpdateCartController(this);
	  var url = "/update-cart.ajax?json=true&id=" + qty.itemId + "&quantity-" + qty.itemId + "=" + qty.value;
		XmlHttpUtils.sendAndWait(updateCartController , url);
	}
	
	/** removes the cart and adds a new one -- called when the cart has been updated **/
	this.refresh = function() {
		this.closeCart();
		this.showCart();
	}
  
}