function recalc() {
	var mensualidad = $("#mensualidad").val().replace(/,/, ".");
	var interes = $("#interes").val().replace(/,/, ".");
	var annos = $("#annos").val().replace(/,/, ".");
	var pendiente = $("#deuda").val().replace(/,/, ".");
	var mensualidad_nueva = Math.round(pendiente*(interes/1200)/(1-Math.pow(1+interes/1200,-annos*12)));
	var var_mensual = Math.round(mensualidad_nueva - mensualidad);
//	var nueva_mensualidad = formatoNumero(mensualidad_nueva.toString());
	$("#nueva_mensualidad").html(mensualidad_nueva);
	$("#variacion_mensual").html(var_mensual);
	$("#variacion_anual").html(var_mensual*12);
	$("#variacion_porcentaje").html(Math.round(((mensualidad_nueva *100) / mensualidad)-100));

	formatoResultados();
}

function formatoResultados(){
	$(".resultados div").removeClass("valorNegativo");
	$("#nueva_mensualidad").html(formatoNumero($("#nueva_mensualidad").html()));
	$("#variacion_mensual").html(formatoNumero($("#variacion_mensual").html()));
	$("#variacion_anual").html(formatoNumero($("#variacion_anual").html()));
	$("#variacion_porcentaje").html(formatoNumero($("#variacion_porcentaje").html()));
	$(".resultados div:contains('-')").addClass("valorNegativo");
}

function valida() {
	var completo = 1;
/*
	if ($("#mensualidad").val() <= 0){
		$("#mensualidad").addClass("faltaDato");
		completo = 0;
	}else{
		$("#mensualidad").removeClass("faltaDato");
	}*/

	if ($("#interes").val().replace(/,/, ".") < 0){
		$("#interes").addClass("faltaDato");
		completo = 0;
	}else if($("#interes").val().replace(/,/, ".") == 0){
		$("#interes").val("0,001");
	}else{
		$("#interes").removeClass("faltaDato");
	}


	if ($("#annos").val().replace(/,/, ".") <= 0){
		$("#annos").addClass("faltaDato");
		completo = 0;
	}else{
		$("#annos").removeClass("faltaDato");
	}

	if ($("#deuda").val().replace(/,/, ".") <= 0){
		$("#deuda").addClass("faltaDato");
		completo = 0;
	}else{
		$("#deuda").removeClass("faltaDato");
	}
		return completo;
	}



$(document).ready(function()
{
  $(".vpos").focus(function() { $(this).parent().addClass("activo"); });
  $(".vpos").blur(function() { $(this).parent().removeClass("activo"); });

  $("form li").mouseover(function() { $(this).addClass("activo"); });
  $("form li").mouseout(function() { $(this).removeClass("activo"); });
  $("#interes").numeric(",");
  $("#deuda").numeric(",");
  $("#annos").numeric();
  $("#mensualidad").numeric(",");

  $("#calcular").click(function () {
  $("#error_msg").html("");
	if (valida()){
      //$("#calcular").removeAttr("disabled");
	  recalc();
	 }
	else{
	  $("#nueva_mensualidad").html("");
	  $("#variacion_mensual").html("");
	  $("#variacion_anual").html("");
	  $("#variacion_porcentaje").html("");
      	  $("#error_msg").html("falta algún dato por rellenar");
          formatoResultados();
    }
  });
});

function formatoNumero(numero){
  var formato = '0.0,00';
  var hasComma = numero.indexOf('.');
  var esNegativo = numero.indexOf('-');
  if (numero != "Infinity"){
	//alert (numero);
	if (esNegativo==0){
		numero = -numero;	
		//alert();
	}
	if (hasComma) {
		psplit = numero.toString().split('.');
		var cnum = psplit[0],
			parr = [],
			j = cnum.length,
			m = Math.floor(j / 3),
			n = cnum.length % 3 || 3; // n cannot be ZERO or causes infinite loop
		// break the number into chunks of 3 digits; first chunk may be less than 3
		for (var i = 0; i < j; i += n) {
			if (i != 0) {n = 3;}
			parr[parr.length] = cnum.substr(i, n);
			m -= 1;
		}
		// put chunks back together, separated by comma
		numero = parr.join('.');
		// add the precision back in
		if (psplit[1]) {numero += ',' + psplit[1];}
	}
	if (esNegativo==0){
		return "-" + formato.replace(/[\d,?\.?]+/, numero);
	}else{
		return formato.replace(/[\d,?\.?]+/, numero);
	}
  }else{
    return "Infinito";
  }
}

jQuery.fn.numeric = function(decimal, callback)
{
	decimal = ",";
	var otroDecimal=".";
	callback = typeof callback == "function" ? callback : function(){};
	this.keypress(
		function(e)
		{
			var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
			// allow enter/return key (only when in an input box)
			if(key == 13 && this.nodeName.toLowerCase() == "input")
			{
				return true;
			}
			else if(key == 13)
			{
				return false;
			}
			var allow = false;
			// allow Ctrl+A
			if((e.ctrlKey && key == 97 /* firefox */) || (e.ctrlKey && key == 65) /* opera */) return true;
			// allow Ctrl+X (cut)
			if((e.ctrlKey && key == 120 /* firefox */) || (e.ctrlKey && key == 88) /* opera */) return true;
			// allow Ctrl+C (copy)
			if((e.ctrlKey && key == 99 /* firefox */) || (e.ctrlKey && key == 67) /* opera */) return true;
			// allow Ctrl+Z (undo)
			if((e.ctrlKey && key == 122 /* firefox */) || (e.ctrlKey && key == 90) /* opera */) return true;
			// allow or deny Ctrl+V (paste), Shift+Ins
			if((e.ctrlKey && key == 118 /* firefox */) || (e.ctrlKey && key == 86) /* opera */
			|| (e.shiftKey && key == 45)) return true;
			// if a number was not pressed
			if(key < 48 || key > 57)
			{
				/* '-' only allowed at start */
				if(key == 45 && this.value.length == 0) return true;
				/* only one decimal separator allowed */
				if((key == decimal.charCodeAt(0) || key == otroDecimal.charCodeAt(0) ) && (this.value.indexOf(decimal) != -1 || this.value.indexOf(otroDecimal) != -1 ))
				{
					allow = false;
				}

				// check for other keys that have special purposes
				if(
					key != 8 /* backspace */ &&
					key != 9 /* tab */ &&
					key != 13 /* enter */ &&
					key != 35 /* end */ &&
					key != 36 /* home */ &&
					key != 37 /* left */ &&
					key != 39 /* right */ &&
					key != 46 /* del */
				)
				{
					allow = false;
				}
				else
				{
					// for detecting special keys (listed above)
					// IE does not support 'charCode' and ignores them in keypress anyway
					if(typeof e.charCode != "undefined")
					{
						// special keys have 'keyCode' and 'which' the same (e.g. backspace)
						if(e.keyCode == e.which && e.which != 0)
						{
							allow = true;
						}
						// or keyCode != 0 and 'charCode'/'which' = 0
						else if(e.keyCode != 0 && e.charCode == 0 && e.which == 0)
						{
							allow = true;
						}
					}
				}
				// if key pressed is the decimal and it is not already in the field
				if((key == otroDecimal.charCodeAt(0) || key == decimal.charCodeAt(0)) && (this.value.indexOf(otroDecimal) == -1 && this.value.indexOf(decimal) == -1))
				{
					allow = true;
					//alert ("siii");
				}


			}
			else
			{
				allow = true;
			}
			return allow;
		}
	)
	.blur(
		function()
		{
			var val = jQuery(this).val();
			if(val != "")
			{
				var re = new RegExp("^\\d+$|\\d*" + decimal + "\\d+");
				if(!re.exec(val))
				{
					callback.apply(this);
				}
			}
		}
	);
	return this;
}
