

var CartClass = new Class({
	
	//implements
	Implements: Options,
	
	//options
	options:{
		ItemInCartMsg: '<span class="CartFeedback">You have %d in cart</span>'
	},
	
	cart: null,	// cart
	
	initialize: function(options) {
		this.setOptions(options);
		
		// attach action to all the add to cart buttons
		$$('input[name=addCartBtn]').addEvent('click', function(ev){
			this.addToCart(ev.target);	
			return false;
		}.bind(this));
		this.refresh();
		
		// attach a refresh when the page gets focus
		window.addEvent('focus',function(ev){
			this.refresh();
		}.bind(this));
		
	},
	
	addMore: function(els) {
		els.getElements('input[name=addCartBtn]').addEvent('click', function(ev){
			this.addToCart(ev.target);	
			return false;
		}.bind(this));
	},
		
	
	json: function(data) {
		var mySpinner = null;
		if (data.spinner) {
			var mySpinner = new Spinner();
			mySpinner.show();
		}
		//dbug.enable();
		var jsondata = $merge({sessionkey:this.options.sessionkey, cartid:this.options.cartid, time:new Date()},data);
		new Request.JSON({
			url: '/cart/json/json_cart.php',
			spinner: mySpinner,
			onComplete: function() {
				if (this.options.spinner) this.options.spinner.hide();
			},
			onSuccess: function(resp) {
				if (resp.rc==0) {
					// successfull
					//dbug.log(resp);
					// there are 4 parts
					// the current cart
					// 	 error message - display an alert
					//   form data - info for fields in the submitted form
					//   page data - info for fields on the document
					this.cart = resp.cart;
					if (resp.forminfo) this.updateFormInfo(resp.forminfo); // update the form info that was submitted
					this.updatePageInfo(resp);	// update the cart info on the the page
					//dbug.log(resp.errormsg);
					//dbug.log(typeof(resp.errormsg));
					if (typeof(resp.errormsg)=='string') {
						//dbug.log('call showerrormsg');
						this.showErrorMsg(resp.errormsg);
					}
				}
			}.bind(this)
		}).send($merge(this.options.jsonOptions, {method:'put', data:jsondata}));
	},
	
	getItemCount: function() {
		return this.cart.Items.length;
	},
	
	getCartTotal: function() {
		var total = 0;
		for (var i=0; i<this.cart.Items.length; i++) {
			var total = total + this.cart.Items[i].TotalPrice.toFloat();
		}
		return total;
	},
	
	formatAmt: function(amt) {
	 	var s = '$'+amt.toFloat().round(2).toFixed(2);
		return s;
	},
		
	
	addToCart: function(el) {
		// find the enclosing form
		var form = el.getParent('form');
		if (!form) {
			alert('Unable to find the enclosing form');
			return false;
		}
		
		// get the quantity
		var qty = form.getElements('.AddToCartQty')[0].get('value');
		if (qty == 0) {
			alert("Quantity needs to be entered");
			return false;
		}
		
		// get the prodid
		var prodid = form.getElements('.AddToCartProdId')[0].get('value');
		var prodname = form.getElements('.AddToCartProdName')[0].get('value');
		var rtn = form.getElements('.AddToCartRTN')[0].get('value');
		
		this.json({action:'add', prodid:prodid, prodname:prodname,qty:qty,spinner:1});
		return false;
	},
		
	refresh: function() {
		this.json({action: 'refresh'});
		return false;
	},
	
	showErrorMsg: function(msg) {
		if ($type(msg) == 'string') {
			var msgdiv = $('msgdiv');
			if (msgdiv) {
				msgdiv.set('html',msg);
			}
			if (msg != '') {
				var errmsg = msgdiv.getElements('.invalidMsg');
				//alert(msg)
				new MooDialog.Error(errmsg.get('html'));
			}
		}
	},
		
		
	updateFormInfo: function(forminfo) {
		// get the form id
		var prodid = forminfo.prodid;
		var el = $('id'+prodid);
		if (el) {
			qtyEl = el.getElements('.AddToCartQty')[0];	// get qty element
			if (qtyEl.get('type') != 'hidden')  {
				// if qty is hidden, dont change it
				//  otherwise change the quantity to zero or whatever the server returned
				if (forminfo.qty) {
					//dbug.log('set qty to forminfo data');
					el.getElements('.AddToCartQty').set('value',forminfo.qty);
				} else {
					//dbug.log('set qty to zero');
					el.getElements('.AddToCartQty').set('value',0);
				}
			}
		}
	},
			
	
	/*
	* update the information on the page about the cart
	*  the right hand menu needs the number of items in the cart and the value
	*  needs right hand menu needs the latest items added
	*  any items that are displayed on the page need to have the number of those items in the card displayed.
	*/
	updatePageInfo: function(resp) {
		//dbug.log('updatePageInfo');
		// update the number of items in the cart
		var cartStatusMsg = '';
		var tot = this.formatAmt(this.getCartTotal());
		
		if (this.getItemCount() == 0) {
			cartStatusMsg = 'Cart is empty';
		} else if (this.getItemCount() == 1) {
			cartStatusMsg = '1 item in cart<br>Total '+tot;
		} else {
			cartStatusMsg = this.getItemCount()+' items in cart<br>Total '+tot;
		}
		var cartItemCountElement = $('cartItemCount');
		if (cartItemCountElement) {
			cartItemCountElement.set('html',cartStatusMsg);
		}
		
		// display the message in any container with class="cartItemAddedAlert"
		$$('.cartItemAddedAlert').set('html',resp.statusmsg);
		
		// update any add to cart buttons with the number of items in the cart
		for (var i=0; i<this.cart.Items.length; i++) {
			var prodid = this.cart.Items[i].ID;
			var el = $('id'+prodid);
			if (el) {
				var msg = this.options.ItemInCartMsg;
				msg = msg.replace('%d',this.cart.Items[i].Quantity);
				el.getElements('.cartItemQty').set('html',msg);
			}
		}
	}
});



window.addEvent('domready', function(){
	new CartClass();	
});			
