function in_array(value, arr) {
	var key;
	for (key in arr) {
		if (arr[key] === value) {return true;}
	}
	return false; //false
}

function addToCart(itemId, howmuch, action){
	// possible actions with cart
	if(!in_array(action,new Array(
		'pluss'
	))) action='pluss';
	
	var obj = jQuery('#product-'+itemId);
	
	var cartItem = obj.clone();
	cartItem.css({
		opacity: '0.7',
		position: 'absolute',
		zIndex: '9999'
	}).attr({'id':''});
	
	obj.before(cartItem);
	var cartDiv = jQuery('.cart-btn');
	var left = cartDiv.offset().left - (cartItem.offset().left-cartItem.position().left) + cartDiv.width()/2;
	var top = cartDiv.offset().top - (cartItem.offset().top-cartItem.position().top);
	cartItem.animate({
		height: '20px',
		width: '20px',
		left: left + 'px',
		top: top + 'px'
	}, 1000, function() {
		cartItem.remove();
		
		cartDiv.animate({
			opacity: '0.1'
		}, 100, function() {
			cartAction( itemId, howmuch, action);
		});
	});	
}



function cartAction(itemId, howmuch, action){

	if(!in_array(action,new Array(
		'pluss', 'minuss', 'remove', 'equal'
	))) return;

	var cartDiv = jQuery('.cart-btn');
	
	jQuery.ajax({
		type: "POST",
		url: "/ll/controller/ajax.cart",
		data: "action=" + action + "&itemId=" + itemId + "&howMuch=" + howmuch,
		success: function( resp ){
			cartDiv.html(resp);
			jQuery(cartDiv).animate({
				opacity: '1'
			}, 500, function(){

			});
			
		}
	});
}

function changeCartValues(itemId, howmuch, action){
	var obj = $('#product_row_'+itemId);
	var inp = $('input',obj);
	var sum = $('.summ',obj);
	var total = $('#total');
	var tot=0;




	if(action=='pluss'){
		inp.val(parseInt(inp.val())+parseInt(howmuch));
		sum.html((parseInt(inp.val())*parseFloat($('.itemprice',obj).html())).toFixed(2));
	} else if(action=='minuss'){
		if(inp.val()>1){
			inp.val(parseInt(inp.val())-parseInt(howmuch));
			sum.html((parseInt(inp.val())*parseFloat($('.itemprice',obj).html())).toFixed(2));
		}
	} else if(action=='remove'){
		jQuery.ajax({
			type: "POST",
			url: "/ll/controller/ajax.cart",
			data: "action=" + action + "&itemId=" + itemId,
			success: function( resp ){
				window.location = window.location.href;
			}
		});
	}
	

	$('.summ').each(function(){
		tot += parseFloat($(this).html());
		total.html(tot.toFixed(2));
		
	})

	sum.html((parseInt(inp.val())*parseFloat($('.itemprice',obj).html())).toFixed(2));

	cartAction(itemId, howmuch, action);
}
