document.observe('dom:loaded', function()
{
	var preparedModal = false;
	
	var body = $j('body');
	var jWindow = $j(window);
	
	var modalContainer	= body.find('.cart-modal');
	var modalOverlay	= modalContainer.find('.overlay');
	var modal			= modalContainer.find('.modal');
	
	var modalContentCache = [];
	
	body.append(modalContainer);
	
	modalOverlay.css({
		height: body.height() - modal.height()
	});
	
	var webshopOverviewElementId;
	
	modalContainer.css({display: 'none'});
	
	/**
	 * Set up functions for the modal window.
	 */
	function modal_open()
	{
		var self	= $j(this);
		var input	= self.find('input[type=hidden]');
		
		if( !webshopOverviewElementId )
		{
			webshopOverviewElementId = self.closest('.module').attr("id").split('-')[1];
		}
		
		self.click( function()
		{
			if( modalContentCache[ input.val() ] )
			{
				modal.html( modalContentCache[ input.val() ] );
				
				// Bind close event on the Continue shopping button.
				modal.find('#continue-shopping').click( modal_hide );
				modal.find('#add-to-cart').click( function(){ modal_submit(); return false; } );
				modal.find('#order-now').click( modal_submitOrderNow);
			}
			else
			{
				modal.html('');
				modal.addClass('loading');
				
				$j.get(	
					'/boeken?element:' + webshopOverviewElementId +  '/ajax/mode:getProductInformation/productId:' + input.val(), null,
					function( data, textStatus )
					{
						modal.removeClass('loading');
						modal.append( data );
						
						modalContentCache[ input.val() ] = data;
						
						// Bind close event on the Continue shopping button.
						modal.find('#continue-shopping').click( modal_hide );
						modal.find('#add-to-cart').click( function(){ modal_submit(); return false; } );
						modal.find('#order-now').click( modal_submitOrderNow);
					}
				);
			}
			
			modalContainer.show();
			modal_repositionWindow();
			return false;
		} );
	}
	
	function modal_submitOrderNow()
	{
		var func = function( data )
		{
			window.location.href = $j( $j('#total_price').closest('.module').find('a')[0] ).attr('href') || $j( $j('#products_count').closest('.module').find('a')[0] ).attr('href');
		};
		
		modal_submit( func );
		
		return false;
	}
	
	function modal_submit( onSuccess )
	{
		var foundAmount = false;
		
		modal.find('.amount input').each( function( i, e )
		{
			foundAmount = foundAmount || $j(e).val() > 0;
		});
		
		if( !foundAmount )
		{
			$j('#invalid_product_amount').show();
			return false;
		}

		$j('#invalid_product_amount').hide();
		
		var successFunc = null;
		
		if( onSuccess )
		{
			successFunc = onSuccess;
		}
		else
		{
			successFunc = function(data)
			{
				modal_hide();
				$j('#total_price').html('&euro; '+$j.getHeaderJson().total_price_formatted);
				$j('#products_count').html($j.getHeaderJson().total_products);
			}
		}
		
		$j.ajax(
			{
				type: 'POST',
				url: '/boeken?element:' + webshopOverviewElementId + '/ajax/mode:addToCart',
				data: modal.find('form').serialize(),
				success: successFunc,
				error: function()
				{
					alert('Er is iets misgegaan tijdens het toevoegen aan het winkelmandje, probeer het nogmaals.')
				}
			}
		);

		return false;
	}
	
	function modal_repositionWindow()
	{
		if( modalContainer.css('display') == 'block' )
		{
			modal.css({
				'position' : 'absolute',
				'top' : ( ( jWindow.height() / 2 ) - ( modal.height() / 2 ) ) + jWindow.scrollTop(),
				'left' : ( jWindow.width() / 2 ) - ( modal.width() / 2 )
			});
		}
	}
	
	function modal_hide()
	{
		modalContainer.hide();
		return false;
	}
		
	// Bind the window resize and scroll function.
	jWindow.bind( 'resize', modal_repositionWindow );
	jWindow.bind( 'scroll', modal_repositionWindow );
	
	/**
	 * Bind the onclick event on the modal window overlay so it will close when clicked.
	 */
	modalOverlay.click( modal_hide );
	
	/**
	 * Prepare the modal window for the product overview.
	 */
	$j('.mod_webshopcartv2_default.mod_webshopoverview .product .order').each( modal_open );
	$j('a.add-to-cart').each( modal_open );
});
