$(document).ready(function(){
	
	calculateEndPrice();
    
    // increase and decrease buttons
    $('a.plus').click( function() {
    	var currAmount = parseInt( $(this).parent().children('strong').html() ); 
    	currAmount += 1;
    	$(this).parent().children('strong').html( currAmount );
    	updateShoppingCart( $(this).siblings('.productId').val(), currAmount);
    	calculateEndPrice( $(this) );
    	return false;
    })
    
    // increase and decrease buttons
    $('a.minus').click( function() {
    	var currAmount = parseInt( $(this).parent().children('strong').html() );
    	if( 1 == currAmount ) {
    		currAmount = 0;
    		$(this).parent().parent().remove();
    	}
    	else {
	    	currAmount -= 1;
	    	$(this).parent().children('strong').html( currAmount );
    	}
    	updateShoppingCart( $(this).siblings('.productId').val(), currAmount);
    	calculateEndPrice( $(this) );
    	return false;
    })
    
    
});

function updateShoppingCart( productId, productAmount ) {
	// first update the price after the product
	if( $('#id' + productId ).length > 0) {
		$('#id' + productId ).parent().siblings('.price_down').find('.productPrice').html(
				parseFloat( productAmount * parseFloat( $('#singlePrice' + productId ).val().toString().replace(',','') ) )
		);
	}
	//then update the shopping cart
	var url = $('#baseUrl').val() + '/shopping-cart/update-shopping-cart';
	$.ajax({
	   type: "POST",
	   url: url,
	   data: 'productId=' + productId + '&productAmount=' + productAmount,
	   dataType: 'json',
	   success: function(msg){
			$('#productsAmount').html( parseInt( msg.productsAmount ) );
			$('#aggregatedPrice').html( parseFloat( msg.aggregatedPrice ).toFixed(2) );
	   }
	});
}



function calculateEndPrice() {
	var aggregatedShoopingCartPrice = 0;
	$('.singlePrice').each( function() {
    	aggregatedShoopingCartPrice = parseFloat( aggregatedShoopingCartPrice ) + 
    		parseFloat( $(this).val() * parseFloat( $(this).parent().children('strong').html().toString().replace(',','') ) );
    });
	$('#shoppingCartSumPrice').html( aggregatedShoopingCartPrice.toFixed(2) );
    if( aggregatedShoopingCartPrice == 0) {
    	$('#order').remove();
    }
    
}
