/*

	@Class: CartInterface
	
	@Brief: 
			
	@Notes: This class requires MooTools!
	
*/

var CartInterface = new Class({
	options: {
		CartFormID:		Class.empty,	// Cart Form ID
		UpdateCartID:		Class.empty, 	// Update Cart Button ID
		ApplyCodeID:		Class.empty,	// ID of the Apply Promo Code Button
		WebRoot:			Class.empty	// The web root for this site
	}, 
	
	initialize: function(options) {
		// Start-Up Code	
		this.setOptions(options);
				
		// Find Instances
		this.CartForm			= $( this.options.CartFormID );
		this.UpdateCartBtn 		= $( this.options.UpdateCartID );
		this.ApplyCodeButton	=  $( this.options.ApplyCodeID );
		this.WebRoot			=    this.options.WebRoot;
		
		if( this.CartForm && this.UpdateCartBtn )
			this.UpdateCartBtn.addEvent( 'click', this.UpdateCart.bindWithEvent( this ) );
			
		if( this.ApplyCodeButton )
			this.ApplyCodeButton.addEvent( 'click', this.ApplyCode.bindWithEvent( this ) );
				
	},
	
	UpdateCart: function( event ) {
		// loop through all quantity fields and clear any non-numeric values
		for ( var i=1; i<=$('items').value; i++ ) {
			if( ( isNaN( $('Quantity_' + i).value ) ) || ( $('Quantity_' + i).value < 0 ) ) {
				$('Quantity_' + i).value = 0;
			}
		}
		
		this.CartForm.action = this.WebRoot + "cart.cfm";
		this.CartForm.submit();
		
		event.stop();
				
	},
	
	ApplyCode: function( event ) {
		if($('promo_code_value_init').value == "") {
			
			alert('Please enter a valid promo code.');
			
		} else {
			
			$('promo_code_value').value = $('promo_code_value_init').value;
			var newURL = this.WebRoot + 'Cart.cfm?AJAXRequest=true&ApplyCode=true&PromoCode=' + $('promo_code_value').value + '&total=' + $('subT').value;
			var myCart = new Request.HTML( {url: newURL, onComplete: this.CompleteApplyCode.bind( this ) } ).send();

		}
		
	},
	
	CompleteApplyCode: function( ) {
		
		location.href = this.WebRoot + 'Cart.cfm';
		
	},

	StripSlash: function( sMessage ) {
		return sMessage.replace( /\//g, "slash_" );	
	},
	
	Echo: function( sMessage ) {
		alert( sMessage ); 
	}

});


//	//////////////////////////////////////////////////////////////////////////////////////////////// //
//	//////////////////////////////////////////////////////////////////////////////////////////////// //


CartInterface.implement(new Options);

window.addEvent('load', function() {
	var MyCart = new CartInterface({
		CartFormID:	'theCart',
		UpdateCartID:	'UpdateCartBtn',
		ApplyCodeID:	'ApplyCode',
		WebRoot:		'/'
	});
});
