var x;
x=$(document);
x.ready(inicializarEventos);

function inicializarEventos(){
	// Capturem els clicks sobre eliminar llibre, afeg
  var x, y;

  for(var i=0; i<99; i++){
	x=$("#delete" + i);
	x.click(eliminaLlibre);
	
	y =$("#update" + i);
	y.click(actualitzaTotal);
  }
  
  x=$("#afegir");
  x.click(afegirLlibre);
}

function eliminaLlibre(){
	
	var x = $(this).attr('id');
	var y;
	

	if(x.length == 7){
		// y = x[x.length-1] ; -> NO VA EN INTERNET EXPLORER!!!!!!
		y = x.substring(6,7);
		//alert(y);
	}else{
		//alert(x.substring(6,7) );
		//alert(x.substring(7,8) );
		y = x.substring(6,7) + x.substring(7,8);
		//y = x[x.length-2] + x[x.length-1];
	}
		
		
		
	var isbn = $("#isbn" + y).attr('value');
	
	// Eliminem la cookie
	document.cookie= isbn+'=; expires=Thu, 01-Jan-70 00:00:01 GMT;';

	$("#tr" + y).remove();
	
	actualitzaTotal();
	
	// I restem un llibre en la cistella
	
	var num_llibres = $("#num_llibres").attr('value');
	
	num_llibres = parseInt(num_llibres) - 1;
	
	$("#num_llibres2").html(num_llibres);
	$("#num_llibres").attr('value',num_llibres);
	
	alert("Llibre eliminat.");
}

function actualitzaTotal(){
	var x,isbn,preu,unitats,total=0;

	for(var i=0; i<99; i++){

		isbn = $("#isbn" + i).attr('value');
	
		preu = $("#preu" + i).attr('value');
				
		unitats = $("#unitats" + i).attr('value');
		
		if(unitats == 0){
					
			// Eliminem la cookie
			document.cookie= isbn+'=; expires=Thu, 01-Jan-70 00:00:01 GMT;';

			$("#tr" + i).remove();
	
			actualitzaTotal();
	
			// I restem un llibre en la cistella
	
			var num_llibres = $("#num_llibres").attr('value');
				
			num_llibres = parseInt(num_llibres) - 1;
	
			$("#num_llibres2").html(num_llibres);
			$("#num_llibres").attr('value',num_llibres);
	
			alert("Llibre eliminat.");
		}else{
			total = total + (preu*unitats);
		
			document.cookie= isbn+" = "+unitats;
		}
	}
	
	x = $("#total_comanda");
	x.html("<p>Total comanda: <b>"+total+" €</b></p>");
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}


function afegirLlibre(){
	var isbn=$("#isbn").attr('value');
	
	if(readCookie(isbn) == null){ // El llibre no està en la cistella
		
		// Per tant, sumem un al número de llibres
		var num_llibres = $("#num_llibres").attr('value');
		
		if(parseInt(num_llibres) < 9){ // OK
			num_llibres = parseInt(num_llibres) + 1;
			$("#num_llibres2").html(num_llibres);
			
			document.cookie= isbn+" = 1";
			
			alert("S'ha afegit el llibre a la cistella.");
		}else{
			alert("La cistella està plena!");
		}
	}else{
		alert("El llibre ja està en la cistella.");
	}
}
