$(document).ready(function(){
	$("#weigths_form").livequery("submit", check_weights);
	$("#weigths_form input").livequery("keydown", onlyNums);
	$("#packages_form input").keydown(onlyNums).keyup(disable_submit);
	
	$("#set_packages").click(set_weights);
});

function set_weights(){
	$.post(
	"core/modules/ajax.php",
	"a_action=set_weights&"+$("#packages_form").serialize(),
	function(response){
		$("#weights").html(response);
	}
	);
}

function disable_submit(){
	$("#set_weights").attr("disabled", "disabled");
}

function onlyNums(evt){
		
	evt = (evt) ? evt : event;
	var charCode = (evt.charCode) ? evt.charCode : ((evt.which) ? evt.which : evt.keyCode);
	
	if ((charCode > 47 && charCode < 58) || charCode == 8 || charCode == 9 || charCode == 37 || charCode == 39 || charCode == 46 || charCode == 13 || charCode == 190 ) {    //(charCode > 111 && charCode <124 )
		return true;
	} else {
		return false;
	} 		
}

function check_weights(){
	
	var weight_sum = $("#weight_sum").val();
	var error = 0;
	var weight = 0;
	var weight_s = 0;
	$(".weight").each(function(){
		weight = $(this).val();
		if(weight=='' || isNaN(weight)){
			error = 1;
		}
		else{
			weight = parseFloat(weight);
		}
		weight_s += weight;
	})
	
	if(error == 1){
		alert("Wszystkie podane wartości muszą być liczbami większymi od zera.");
	}else if(weight_sum != weight_s){
		alert("Suma wag nie odpowiada wadze sumarycznej");
	}else
		$("#weigths_form").submit();
	
	return false;
}

function roundNumber(num, dec) {
	var result = Math.round( Math.round( num * Math.pow( 10, dec + 1 ) ) / Math.pow( 10, 1 ) ) / Math.pow(10,dec);
	return result;
}
