﻿/*
  File: cart-1.0.js

  Shopping Cart Class handling interaction at:
	- Homepage (Cart Icon);
	- Product Thumbs(Mini Cart);
	- Product Page (Product Cart);
	- Shop Cart Page (Page Cart), with sub totals and order link;

  Requires: MooTools Core 1.3

  Copyright: (C) 2011 by Bruno Torrinha <http://www.torrinha.com>
*/

var cart = new Class({

	Implements: [Options, Events, Chain],

	options: {
		minOrder: 10,				//	Min order value
		url: '/carro-compras/',
		roar: ''
	/*  Fired Events
		onChange:null,
		*/
	},

	/***************************************
	** Initialize Cart with Homepage Cart.
	****************************************/
	initialize: function(carticon, options){
		this.setOptions(options);
		this.cartLink = carticon.getElement('a');			// Where style events occurs (_update, _remove, empty)
		this.units = carticon.getElement('span.units');		// Total Items in cart
		this.cost = carticon.getElement('span.cost');		// Total Cost in cart
		this.cartText = carticon.getElement('span.text');	// Cart Text
		this.cartPage = false;								// If defined, will store Page Cart elements: SubTotal, Weight, VAT and Total Cost
	},

	_updateEl: function(el, elValue, lbl, color){
		var val = el.get('html').toFloat();
		if(val != elValue){
			el.set('html', elValue + lbl).highlight( color );
			return true;
		} else {
			return false;
		}
	},

	/*******************************
	** Update Cart Icon Board at HP
	********************************/
	_update: function(kind, units, cost){
		var uni = this.getTotals().units;
		if (uni === 0 && units > 0){			//----- Show
			this.cartText.slide('out');
			this.cartLink.addClass('full');
		} else if (uni > 0 && units <= 0){		//----- Hide
			this.cartText.show().slide('in');
			this.cartLink.removeClass('full');
		}
		this.setTotals(units, cost);
		this.cartLink.highlight('#fe0');
		this.fireEvent(kind, [cart]);
	},

	/*******************************
	** {private} Update Cart Values
	**
	**
	********************************/
	_updateCart: function(fireevent, id, cart, pvp, units, subTotal, totalUnits, totalCost){
		var c = this.getCost(cart);
		if (cart.cartClear){ cart.cartClear.fade((units > 0) ? 1 : 0); }
		this.setUnits(cart, units);
		this.setCost(cart, {costUnit: pvp, costTotal: subTotal});

		switch (cart.kind){
		case 'minicart': 
			break;
		case 'prdcart':
		case 'pgcart':
			if(c.costUnit != pvp){cart.cost.highlight('#fc3');}
			this._updateEl(cart.costTotal, subTotal, ' €', '#fc3');
			break;
		}

		if (id > 0){ cart.productID = id; }
		if (fireevent){ this._update('change', totalUnits, totalCost); }
	},

	/********************************************
	** Attach Cart 
	** Mini + Product + Page Cart.
	** 
	** Parameters:
	**  element - cart element
	**   object - params other, if defined will update each element:
	** 
	** 			element - costUnit (optional), Cost Unit element;
	** 			element - costTotal (optional), Cost Total element;
	** 			element - cartClear (optional), Link element for clear cart units;
	** 
	******************************************************************************************/
	attach: function(kind, cart, par){
		cart.kind = kind;
		switch (kind){
		case 'minicart':						//---------------------------------------------------- Attach Mini Cart used on Product Thumbs
			if (cart.hasClass('bulkorder')){
				cart.removeClass('bulkorder');		// Clean, do it prety
				cart.link = cart.getElement('a').addEvent('click', this.increment.bind(this));
				cart.units = this.getUnits(cart);
				cart.productID = cart.get('id').replace('rec-','');
				cart.cost = cart.getPrevious('span.cost');
			}
			break;

		case 'prdcart':							//---------------------------------------------------- Attach Product Cart;
			cart.cartClear = par.cartClear;
			cart.inp = cart.getElement('input');
			cart.productID = cart.inp.get('id').replace('rec-','');
			cart.parentID = cart.get('id').replace('pid-','');
			cart.units = this.getUnits(cart);
			cart.cost = par.costUnit;
			cart.costTotal = par.costTotal;

			cart.QTBox = new QTBox( cart.inp, {
				onChange: function(el){
					new Request.JSON({url: this.options.url + 'add',
						onSuccess: function(J){
							if(J.pvp > 0){
								this._updateCart(true, 0, cart, J.pvp, el.qtvalue, J.subtotal, J.cartTotalUnits, J.cartTotalCost);
							}
						}.bind(this)
					}).send('idProduct=' + cart.productID + '&units=' + el.qtvalue);
				}.bind(this)
			}, this);

			if (par.cartClear){
				var _this = this;
				cart.cartClear.addEvent('click', function(e){
					e.preventDefault();
					new Request.JSON({url: '/carro-compras/add',
						onSuccess: function(J){
							if(J.pvp > 0){
								_this._updateCart(true, 0, cart, J.pvp, 0, 0, J.cartTotalUnits, J.cartTotalCost);
							}
						}.bind(this)
					}, this).send('idProduct=' + cart.productID + '&units=' + 0);
				}, this).setStyle('display', 'block').fade((cart.units > 0) ? 1 : 0);
			}

			var c = this.getCost(cart);
			this._updateCart(false, 0, cart, c.costUnit, cart.units, (cart.units * c.costUnit).round(2), 0, 0);
			break;


		case 'pgcart':							//---------------------------------------------------- Attach Cart Page
			if(!this.cartPage){
				this.cartPage = true;
				this.subTotal = $('subtotal').getElement('td');
				this.weight = this.subTotal.getParent('tr').getNext('tr th small');
				this.shipping = this.weight.getParent('tr td');
				this.vat = this.shipping.getParent('tr').getNext('tr td');
				this.totalcost = this.vat.getParent('tr').getNext('tr td');
				this.minOrder = $('minOrder');
				this.minOrderRow = this.minOrder.getParent('tr');
				if(this.minOrder.get('html').toFloat() === 0){ this.minOrderRow.fade(); }
			}

			cart.cartClear = false;
			cart.inp = cart.getElement('input');
			cart.productID = cart.get('id').replace('rec-','');
			cart.units = this.getUnits(cart);
			cart.cost = par.costUnit;
			cart.costTotal = par.costTotal;

			cart.QTBox = new QTBox( cart.inp, {
				onChange: function(el){
					new Request.JSON({url: '/carro-compras/add',
						onSuccess: function(J){
							if(J.pvp > 0){
								this._updateEl( this.minOrder, J.cartMinOrder, ' €', '#fc3') ? this.minOrderRow.fade(1) : this.minOrderRow.fade(0);
								this._updateEl( this.minOrder, J.cartMinOrder, ' €', '#fc3');
								this._updateEl( this.subTotal, J.cartTotalCost, ' €', '#fff');
								this._updateEl( this.weight, J.weight, ' KG', '#fff');
								this._updateEl( this.shipping, J.shippingCost, ' €', '#fff');
								this._updateEl( this.vat, J.vat, ' €', '#fff');
								this._updateEl( this.totalcost, J.cartTotal, ' €', '#fc3');

								this._updateCart(true, 0, cart, J.pvp, el.qtvalue, J.subtotal, J.cartTotalUnits, J.cartTotalCost);
							}
						}.bind(this)
					}, this).send('idProduct=' + cart.productID + '&units=' + el.qtvalue);
				}.bind(this)
			}, this);
			break;
		}
		return cart;
	},

	/**********************************
	** Appends one unit to MINI CART.
	***********************************/
	increment: function(e){
		e.stop()
		var cart = e.target.getParent().addClass('full');
		var uni = this.getUnits(cart) + 1;
		new Request.JSON({url: this.options.url + 'add',
			onSuccess: function(J){
				if (J.sent){
					this._updateCart(true, 0, cart, J.pvp, uni, (J.pvp * uni).toFloat(), J.cartTotalUnits, J.cartTotalCost);
				}
			}.bind(this)
		}, this).send('idProduct=' + cart.productID + '&units=' + uni);
	},

	getTotals: function(){
		return { units: this.units.get('html').toInt(), cost: this.cost.get('html').toFloat() };
	},
	setTotals: function(units, cost){
		this.units.set('html', units);
		this.cost.set('html', cost);
	},

	getProductID: function(cart){	// Just affecten on Product Cart
		return (cart.parentID > 0) ? cart.parentID : cart.productID;
	},
	getUnits: function(cart){
		switch (cart.kind){
		case 'minicart': return cart.link.get('title').toInt(); break;
		case 'prdcart':
		case 'pgcart': return cart.inp.get('value').toInt(); break;
		}
	},
	setUnits: function(cart, units){
		switch (cart.kind){
		case 'minicart': cart.units = units; cart.link.set('title', units); break;
		case 'prdcart': 
		case 'pgcart': cart.units = units; cart.QTBox.setValue(units); break;
		}
	},
	getCost: function(cart){
		switch (cart.kind){
		case 'minicart': return cart.cost.get('html').replace(' €','').toFloat(); break;
		case 'prdcart': return {costUnit: (cart.cost.get('html').replace(' €','').toFloat()).round(2), costTotal: (cart.costTotal.get('html').toFloat()).round(2) }; break;
		case 'pgcart': return {costUnit: (cart.cost.get('html').replace(' €','').toFloat()).round(2), costTotal: (cart.costTotal.get('html').replace(' €','').toFloat()).round(2) }; break;
		}
	},
	setCost: function(cart, cost){
		switch (cart.kind){
		case 'minicart': cart.cost.set('html', cost.costUnit + ' €'); break;
		case 'prdcart': 
			cart.cost.set('html', cost.costUnit + ' €');
			cart.costTotal.set('html', cost.costTotal);
			break;
		case 'pgcart':
			cart.cost.set('html', cost.costUnit + ' €');
			cart.costTotal.set('html', cost.costTotal + ' €');
			break;
		}
	}
});
