/*************************************************************
 ** Simple Ecommerce
 ************************************************************/
(function ($) { // protect the namespace

$.widget( "ui.simpleECommerce", {

    /* _init - Constructor
     */
    _init: function () {
	var self = this;
	
	// Find quantity inputs & fees
	self.qtys = $( '.rtg-quantity input', self.element );
	self.fees = $( '.rtg-fee', self.element );
	
	// Create handler function
	var update = function () { self._updateOrderTotal.call( self ) }
	
	// Attach to quantity and price inputs
	self.qtys.bind( 'change.simpleECommerce', update );
	$( 'input.rtg-price', self.element ).bind( 'change.simpleECommerce', update );

	// Attach to fee inputs
	$( 'input', self.fees ).bind( 'change.simpleECommerce', update );

	self._updateOrderTotal();

	return;
    }, // _init

    destroy: function () {
	var self = this;

	self.qtys.unbind( '.simpleECommerce' );
	self.fees.unbind( '.simpleECommerce' );
	$( 'input.rtg-price', self.element ).unbind( '.simpleECommerce' );

	self.qtys = null;
	self.fees = null;

	$.widget.prototype.destroy.apply( self, arguments );
    }, // destroy

    _updateOrderTotal: function () {
	var self = this;

	// Calculate subtotal
	var subtotal = 0;
	self.qtys.each( function () { // loop through qty inputs
	    var qtyEl = this;
	    
	    // Find price
	    var parent = $( qtyEl ).parents( '.rtg-widget' );
	    var priceEl = $( '.rtg-price', parent );
	    var price
		= priceEl[0].tagName.toUpperCase() == 'INPUT' ? priceEl.val()
	        :                                               priceEl.html()
	        ;
	    
	    price  = $.parse_money( price ) || 0;
	    price *= 100;

	    // Add line item to subtotal
	    var qty = $.parse_number( $( qtyEl ).val() );
	    
	    if( qty == null )
		qty = 0;

	    $( '.rtg-linetotal', parent ).html( qty > 0 ? $.format_money( (qty * price)/100 ) : '' );

	    subtotal += qty * price;
	} ); // qtys.each

	// Show subtotal
	$( '.rtg-subtotal', self.element ).html( $.format_money( subtotal/100 ) );

	// Calculate order total
	var total = subtotal;

	// Find additional "fees"
	self.fees.each( function () { // loop through fees
	    var feeEl    = this;
	    var feeInput = $( 'input', feeEl );

	    // Figure out amount of fee
	    var fee = feeInput.length > 0 ? feeInput.val()
	            :                       feeEl.innerHTML
	            ;
	    
	    fee = $.parse_money( fee );

	    if( fee == null )
		fee = 0;

	    fee *= 100;

	    // Add fee to total
	    total += fee;
	} ); // fees.each

	// Show total
	$( '.rtg-grandtotal', self.element ).html( $.format_money( total/100 ) );

	// TODO: Trigger a "total changed" event if total has changed
	if( self.options.onTotalChange ) {
	    self.options.onTotalChange( total );
	}

	return;
    } // _updateOrderTotal

}); // $.widget

$.extend( $.ui.simpleECommerce, { 
    version: "1.0",
    defaults: { }
});

})(jQuery); // function ($)
