$(function(){

	$('.productform_buy').click(function(e){

		return true; // submit form
	});

	$('.productform_add_to_cart').click(function(e){

		var target     = e.target;
		var form       = target.form;
		var formValues = OxGetFormValues( form );

		formValues[ target.name ] = target.value;
		//console.log( formValues );

		AddToCartForm( formValues );

		return false;
	});

	$('.productform_add_to_cart_a').click(function(e){

		$.get( e.target.href, function(data)
		{
			$("#site_cart").html(data);
		});

		return false;
	});
});

function OxGetFormValues( form )
{
	var values = {};

	$.each($(form).serializeArray(), function(i, field) {
		values[field.name] = field.value;
	});

	return values;
}

function BuyProduct(form)
{
	return true;
}

function AddToCartForm( form )
{
	$.get(current_uripr + "/cart/ajaxAdd/" + form.product_id + "?cart_block=" + form.cart_block + "&from=" + form.from + '&action=add_to_cart', function(data)
	{
		$("#" + form.cart_block ).html(data);
	});
}

function AddToCart(products_id, cart_block, from)
{
	$.get(current_uripr + "/cart/ajaxAdd/" + products_id + "?cart_block=" + cart_block + "&from=" + from, function(data)
	{
		$("#" + cart_block ).html(data);
	});

	return false;
}

function RemoveFromCart(products_id, cart_block)
{
	$.get(current_uripr + "/cart/ajaxChange/" + products_id + "?delete=1&cart_block=" + cart_block, function(data)
	{
		$("#" + cart_block ).html(data);
	});

	return false;
}

function ChangeCartItemsQuantity(products_id, quantity, cart_block)
{
	$.get(current_uripr + "/cart/ajaxChange/" + products_id + "?quantity=" + quantity + "&cart_block=" + cart_block, function(data)
	{
		$("#" + cart_block ).html(data);
	});

	return false;
}

function UpdateShoppingCart( data )
{
	if ( data && 'cart' == cart_module )
	{
		$("#shoppingCart").html(data);
	}
	else
	{
		$.post(current_uripr + "/" + cart_module + "/ajax", function(data){
			$("#shoppingCart").html(data);
		});
	}
}

function ChangeShippingType( shipping_type )
{
	$.post(current_uripr + "/checkout/ajax?shippingType=" + shipping_type, function(data){
		if (data)
		{
			$("#shoppingCart").html(data);
		}
	});
}

function UseBonus(bonus_value)
{
	$.post(current_uripr + "/" + cart_module + "/ajax?useBonus=" + bonus_value, function(data){
		if (data)
		{
			$("#shoppingCart").html(data);
		}
	});
}

function fmtMoney( n, c, d, t )
{
	n = n || 0; // if n is Nan
	n = Math.round( n * 10000 ) / 10000; // rounding x.yyyy

	var m = ( c = Math.abs(c) + 1 ? c : 2, d = d || ",", t = t || ".", /(\d+)(?:(\.\d+)|)/.exec(n + "") );
	var x = m[1].length > 3 ? m[1].length % 3 : 0;
	return ( n < 0 ? '-' : '' ) + (x ? m[1].substr(0, x) + t : "") + m[1].substr(x).replace(/(\d{3})(?=\d)/g,  "$1" + t) + (c ? d + (+m[2] || 0).toFixed(c).substr(2) : "");
}

