function isNumber(n) { return !isNaN(parseFloat(n)) && isFinite(n); }

function addItem2Cart(ref) {
   $("#cartmodule_body").html("<center><table id='cart_full'><tr><td><img src='images/mini_loading.gif'/></td></tr></table>");
   
   $.ajax({    
      type: "POST",   
	  url: "./lib/ajax_cart.php", 
	  data: "action=ADD_ITEM&ref="+ref,
	  success: function(data) { updateCartModule();	},
	  error: function(xhr, status, error) { alert('Error...'); } 
   });   

}
	
function updateCartModule() {
   $.post('./lib/ajax_cart.php', { action: "UPDATE_CART_MODULE" }, function(data) {
      $("#cartmodule_body").html(data);
   });	
}

function updateQuantity(domElem) {
   var elem = domElem.parent().parent();
   var ref = domElem.attr("id");
   var qty_element = $(".update_input input", elem);
   var qty = $(".update_input input", elem).val();

   if (!isNumber(qty)) {
      $.post("./lib/ajax_cart.php", { action: "GET_ITEM_QTY", ref: ref }, function (data) {
         qty_element.val(data) 
	  });
   } else {
	   $("#cartmodule_body").html("<center><table id='cart_full'><tr><td><img src='images/mini_loading.gif'/></td></tr></table>");
 	   $(".sub_total", elem).html("<img src='images/mini_loading.gif'/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");  	
	   $("#table_cart tr .total_price").html("<img src='images/mini_loading.gif'/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
       
	   $.ajax({    
	    type: "POST",   
		url: "./lib/ajax_cart.php", 
		data: "action=UPDATE_ITEM_QTY&ref="+ref+"&qty="+qty,
		dataType: 'json',
		success: function(data) {
		   if (qty > 0) {
 		      $(".sub_total", elem).html(data[0] + "&nbsp;&nbsp;");  	
		      $("#table_cart tr .total_price").html(data[2] + "&nbsp;&nbsp;");
	       } else { //SE O ARTIGO FICAR VAZIO ELIMINA.				
	          if (data[1] > 0) { //SE AINDA HOUVER ARTIGOS NO CARRINHO
   		         $(elem).slideUp();
			     $("#table_cart tr .total_price").html(data[2] + "&nbsp;&nbsp;");
	          } else {
				  $("#checkout_content").load("./lib/cart_empty.php");
				  $("#container_validate_cart").slideUp();
			      //$("#to_print").slideUp();
			  }    
	       }  
		   updateCartModule();  },
	    error: function(xhr, status, error) { alert('Error...'); } }); 
	}
}

$(document).ready( function() {
/*
   $.ajaxSetup({
        cache: false,
		error:function(x,e){
			if(x.status==0){
			alert('You are offline!!\n Please Check Your Network.');
			}else if(x.status==404){
			alert('Requested URL not found.');
			}else if(x.status==500){
			alert('Internel Server Error.');
			}else if(e=='parsererror'){
			alert('Error.\nParsing JSON Request failed.');
			}else if(e=='timeout'){
			alert('Request Time out.');
			}else {
			alert('Erro Desconhecido.\n'+x.responseText);
			}
		}
	});
*/

	//Remover Carrinho
	$("#table_cart tr .remove input").click(function() {	
	    var elem = $(this);
		var ref = $(this).attr("id");
        $("#cartmodule_body").html("<center><table id='cart_full'><tr><td><img src='images/mini_loading.gif'/></td></tr></table>");

    
	$.ajax({    
	    type: "POST",   
		url: "./lib/ajax_cart.php", 
		data: "action=REMOVE_ITEM&ref="+ref,
		dataType: 'json',
		success: function(data) {
          //data[0] = num items
		  //data[1] = preco cart
		  if (data[0] > 0) {
			$(elem).parent().parent().slideUp();
			$("#table_cart tr .total_price").html(data[1] + "&nbsp;&nbsp;");
		  } else {
		     $("#checkout_content").load("./lib/cart_empty.php");          
			 $("#container_validate_cart").slideUp();     
			 $("#to_print").slideUp(); 
		  }
		  updateCartModule();  },
	    error: function(xhr, status, error) { alert('Error...'); } }); 


    $.post("./lib/ajax_cart.php", { action: "REMOVE_ITEM", ref: ref }, function (data) {
          //data[0] = num items
		  //data[1] = preco cart
		  if (data[0] > 0) {
			$(elem).parent().parent().slideUp();
			$("#table_cart tr .total_price").html(data[1] + "&nbsp;&nbsp;");
		  } else {
		     $("#checkout_content").load("./lib/cart_empty.php");          
			  $("#container_validate_cart").slideUp(); 
		  }
		  updateCartModule();
	   }, "json");
	
	});



	//Actualiza qtd
	$("#table_cart tr .updateqty input").click(function() {
		updateQuantity($(this));
	});
	
	$("#table_cart tr .update_input input").change(function() {
		updateQuantity($(this));
	});

});
