$(function() {
		$(".draggable").draggable({
					cancel: 'a.ui-icon',// clicking an icon won't initiate dragging
					revert: 'invalid', // when not dropped, the item will revert back to its initial position
					cursor: 'move',
					helper: 'clone'
					});
		$("#drop").droppable({
			activeClass: 'ui-state-hover',
			hoverClass: 'ui-state-active',
			drop: function(event, ui) {
				//$(this).html(this.html()+'ui.draggable.find('#modelo_listado_producto').html()');
				if (!$(this).find('span').length>0){
					$(this).html('');
					$('#acciones_cesta').html('<span class="total_cesta_lateral">Total: <span id="total_cesta_lateral">0</span> &euro; + <span id="total_envio">0</span> &euro; envío</span><span class="detalle_cesta_lateral">	<a class="" href="/cesta/ver/">ver cesta</a></span><span class="tramitar_cesta_lateral">	<a href="/cesta/tramitarpedido/">tramitar pedido</a></span>');
				}
				referencia = leer_id(ui.draggable);
				marcaymodelo = leer_marcaymodelo(ui.draggable);
				precio = ui.draggable.parent().find('input[name="precio"]').val();
				if ($('#cesta_'+referencia).length>0){ //ya tenemos antes
					unidades_antes=$('#cesta_'+referencia).find('input[name=unidades]').val();
					$('#cesta_'+referencia).find('input[name=unidades]').val(parseInt(unidades_antes) + 1);
				}else{
					$(this).append('<span id="cesta_'+referencia+'" class="linea_pedido_lateral"><input class="unidades" type="text" name="unidades" value="1"/><input type="hidden" name="precio" value="'+precio+'"> / '+marcaymodelo+'</span>').hide().fadeIn();	
				}
				anadir_a_cesta(ui.draggable);
				totalizar();
				//Avisar a google de que lo hemos añadido:
				pageTracker._trackEvent('Cesta', 'Anadir', 'Articulo', marcaymodelo)
			}
		});

	});

function anadir_a_cesta($item){
	//Llamada a Ajax
	id_producto = leer_id($item);
	$.post("/cesta/anadir/", { seccion: "cesta", accion: "anadir", idproducto: id_producto, ajax: "1"},
		function(data){
			if (parseInt(data)){
				euro = parseInt(data)/100;
				$('#total_envio').html(euro+'.00');
			}else{
				$('#error').html(data);
				$("#error").dialog();
				$('#total_envio').hide();
			}
		});
	//$item.toggle('slow');
}
function leer_id($item){
	return $item.parent().find("input[name='idproducto']").val();
}
function leer_marcaymodelo($item){
	datos = $item.parent().find("input[name='marca']").val() +' - '+ $item.parent().find("input[name='modelo']").val() ;
	return datos;
}
function borrar_de_cesta($item){
	alert($item).width();
	$item.toggle('slow');
}
function totalizar(){
	total = 0;
	$('#drop span').each(function(){
		unidades = ($(this).find("input[name='unidades']").val());
		precio = ($(this).find("input[name='precio']").val());
		total = total + precio * unidades;
	});
	$('#total_cesta_lateral').html(Math.floor(total)/100);
}
