SJCProducts = {
	
	_inCart: {},

	init: function()
	{	
		$( 'noJS' ).hide();
		
		Asset.css( '/Resources/SJCOBU/CSS/Print.css', { media: 'print' } );
	
		$$( ".product" ).each( function( $product ) {
			
			$log( $product );
			
			// Add event to quantity input		
			$product.getElement( '.quantityInput' ).addEvents({
				'keyup': (function() { SJCProducts.toggleInCart( $product ) } )
			});
			
			$product.getElement( '.quantityInput' ).fireEvent( 'keyup' );
			
			// Add event to size input		
			if ( $product.getElement( '.sizeInput' ) )
			{
				$product.getElement( '.sizeInput' ).addEvents({
					'keyup': (function() { SJCProducts.toggleInCart( $product ) } )
				});
				
				$product.getElement( '.sizeInput' ).fireEvent( 'keyup' );
			}
			
		});
			
		$( 'checkout_print' ).addEvent( 'click', function( e ) {
			
			e.stop();
			
			SJCProducts.makePurchase();
			
		});
		
	},

	toggleInCart: function( $product )
	{
		var itemId = $product.getProperty( 'id' );
		var name = $product.getElement( '.name' ).get( 'text' );
		var price = $product.getElement( '.itemPrice' ).get( 'text' );
	
		var qty = $product.getElement( '.quantityInput' );
		
		var size = '';
		
		if ( $product.getElement( '.sizeInput' ) )
			size = $product.getElement( '.sizeInput' );
			
		SJCProducts._inCart[ itemId ] = { id: itemId, name: name, price: price, $qty: qty, $size: size };
		
		SJCProducts.updateTotals();
		
	},
	
	updateTotals: function()
	{
		$( 'checkout_items_list' ).empty();
	
		var totalItems = 0;
		var totalPrice = 0;
		var totalPostage = 0;
		var totalCost = 0;
		
		for ( var i in SJCProducts._inCart )
		{
			var product = SJCProducts._inCart[ i ];
			
			if ( !product )
				continue;
			
			// Quantity
			var qty = parseInt( product.$qty.value ) || 0;
			
			if ( isNaN( qty ) )
				qty = 0;
			
			// Check if the quantity is now 0	
			if ( !qty || qty == 0 ) {
				$log( 'Quantity is 0' );
			
				SJCProducts._inCart[ product.id ] = null;
				SJCProducts.updateTotals();
				return;
			}
			
			totalItems += qty;
			
			var qtyPrice = qty * parseFloat( product.price );
			
			if ( !qtyPrice )
				qtyPrice = 0;
			
			totalPrice += qtyPrice;
			
			if ( !$chk( qtyPrice ) )
				return;
				
			// Size
			var size = '';
				
			if ( product.$size && product.$size.value )
				size = product.$size.value;
				
			// Create list item
			new Element( 'li', { html: qty + ' x ' + product.name + ( size ? ' (' + size + ')' : '' ) + ' - ' + '$' + qtyPrice + '.00' } ).inject( $( 'checkout_items_list' ) );
			
		}
		
		if ( !totalItems )
			new Element( 'li', { html: '(no items added)' } ).inject( $( 'checkout_items_list' ) );
		
		// Render total
		$( 'checkout_value_subtotal' ).set( 'html', ( totalItems ) ? '$' + totalPrice + '.00' : '0.00' );
		
		// Calculate postage and render
		totalPostage = ( totalPrice * 0.10 );
		$( 'checkout_value_postage' ).set( 'html', ( totalItems ) ? '$' + Number( totalPostage ).format(2) : '0.00' );
		
		// Calculate grand total and render
		totalCost = totalPrice + totalPostage;
		$( 'checkout_value_total' ).set( 'html', ( totalItems ) ? '$' + Number( totalCost ).format(2) : '0.00' );
		
		return {
			items: totalItems,
			price: totalCost
		};
		
	},
	
	makePurchase: function()
	{
		var data = {
			firstName: $( 'form_firstName' ).value,
			lastName: $( 'form_lastName' ).value,
			email: $( 'form_email' ).value,
			phone: $( 'form_phone' ).value,
			cardType: '',
			cardNumber: 'XXXX-XXXX-XXXX-XXXX',
			cardName: $( 'form_cardName' ).value,
			cardExpiryMonth: $( 'form_cardExpiryMonth' ).value,
			cardExpiryYear: $( 'form_cardExpiryYear' ).value
		};
		
		if ( $( 'form_mastercard' ).checked )
			data.cardType = 'MasterCard';
		
		if ( $( 'form_visa' ).checked )
			data.cardType = 'VISA';
		
		if ( $( 'form_amex' ).checked )
			data.cardType = 'Amex';
		
		data = SJCProducts.FormTools.removeDefaults( data, { firstName: 'first', lastName: 'last' } );
		
		var totals = SJCProducts.updateTotals();
		
		if ( !totals.price )
		{
			alert( "Please select something to purchase first." );
			return;
		}
		
		if ( !SJCProducts.FormTools.validateFields( data, {
				firstName: 'Please enter your first name.',
				lastName: 'Please enter your last name.',
				email: 'Please enter your email address.',
				phone: 'Please enter your phone number.',
				cardNumber: 'Please enter your card number.',
				cardName: 'Please enter your card name.',
				cardExpiryMonth: 'Please select your card expiry month number.',
				cardExpiryYear: 'Please select your card expiry year.'
			}) )
			return;
		
		data.name = data.firstName + ' ' + data.lastName + ' - Order for $' + totals.price + ' (' + totals.items + ' item' + ( ( totals.items > 1 ) ? 's' : '' ) + ')';
		data.amount = totals.price;
		data.purchase = 'Items Purchased:\n';
		
		for ( var i in SJCProducts._inCart )
		{
			var product = SJCProducts._inCart[ i ];
			
			if ( !product )
				continue;
			
			// Quantity
			var qty = parseInt( product.$qty.value ) || 0;
			
			if ( isNaN( qty ) || !qty )
				continue;
			
			// Size
			var size = '';
				
			if ( product.$size && product.$size.value )
				size = product.$size.value;
			
			data.purchase += '<ul><li>' + product.name + ( size ? ' Size: ' + size : '' ) + ' Cost: $' + product.price;
			
			if ( qty > 1 )
				data.purchase += ' (x ' + qty + ' - $' + ( product.price * qty ) + ')';
				
			data.purchase += '</li></ul>';
		}
		
		$( 'checkout_print' ).set( 'disabled', true );
		
		// log the order
		Aurora.callAPI({
		
			key: 'create order',
			
			data: data,
			
			onComplete: function( rtnData ) {
			
				window.print();
				
				SJCProducts.purchaseComplete();
				
				$( 'checkout_print' ).set( 'disabled', false );
			}
			
		});
		
	},
	
	purchaseComplete: function()
	{
		$log( 'Purchase is completed.' );
	}
	
}

SJCProducts.FormTools = {
	
	removeDefaults: function( data, fields )
	{
		for ( var i in fields )
		{
			if ( data[ i ] == fields[ i ] )
				data[ i ] = '';
		}
		
		return data;
	},
	
	validateFields: function( data, fields )
	{
		var rtn = true;
		
		for ( var i in fields )
		{
			if ( !$chk( data[ i ] ) )
			{
				alert( fields[ i ] );
				rtn = false;
				break;
			}
		}
		
		return rtn;
			
	},
	
	initDefaultValueAsHint: function( field, defaultValue, passwordField )
	{
		var $field = $( field );
		
		if ( !$field )
			return;
		
		if ( !$chk( field.value ) )
			$field.value = defaultValue;
			
		// make sure the default colour is still set
		$field.setStyle( 'color', '#92BDCE' );
		
		$field.addEvent( 'focus', function() {
				
				if ( this.value != defaultValue )
					return;
				
				if ( passwordField )
					this.setProperty( 'type', 'password' );
				
				this.value = '';
								
				this.setStyle( 'color', '#262626' );
			
			})
			.addEvent( 'blur', function() {
				
				if ( !this.value.length )
				{
					if ( passwordField )
						this.setProperty( 'type', 'text' );
					
					this.value = defaultValue;
					
					this.setStyle( 'color', '#92BDCE' );
				}
			
			});
		
		return $field;
	}
	
}

Number.implement({
	format: function( decimals ) {
		
		decimals = $pick( decimals, 2 );
		
		var floatsep = '.'
		var kSep = '';
		
		var parts = this.round(decimals).toString().split('.');
		var integer = parts[0];
		while (integer != (integer = integer.replace(/([0-9])(...($|[^0-9]))/, '$1' + kSep + '$2')));
		if (decimals == 0) return integer;
		return integer + floatsep + ((parts[1] || '') + '0000000000').substr(0, decimals);
	
	}
});

window.addEvent( 'domready', SJCProducts.init );