$(document).ready(function(){
    $(".hoverable").mouseover(imgHover);
    $(".hoverable").mouseout(imgHover);
		$("#slider1").slider({
			slide:function(ev,ui)  {
				sliderHandler(ui.value,"amount");
			}
		});

		$("#slider2").slider({
			slide:function(ev,ui)  {
				sliderHandler(ui.value,"years");
			}
		});
		
		$("#slider3").slider({
			step:50,
			slide:function(ev,ui)  {
				sliderHandler(ui.value,"rente");
			}
		});
		ss(); 
    $("#ringmeg").submit(function() {
    	var ring_mob = $('#ring_mob').val();
    	if (ring_mob.match(/[0-9 ]{8,}/)===null) {
    		$('#ring_mob_err').show();
    		return false;
    	}
    	return true;
    });
});

var Calc, amount, years, interest;

Calc = (function() {
  function Calc(element_id, lower_val, upper_val) {
    this.element_id = element_id;
    this.lower_val = lower_val;
    this.upper_val = upper_val;
    this.float_precision = false;
    this.calc(0);
  }
  Calc.prototype.calc = function(val) {
    val = (val / 100) * (this.upper_val - this.lower_val);
    if(!this.float_precision) val = Math.ceil(val);
    this.current_val = val + this.lower_val;
    return this.current_val;
  };
  Calc.prototype.html = function(content) {
    return $(this.element_id).html(content);
  };
  return Calc;
})();

amount = new Calc("#slider1-val", 50000, 350000);
amount.calc = function(val) {
  val = (val / 100) * (this.upper_val - this.lower_val);
  if(!this.float_precision) val = Math.ceil(val);
  this.current_val = val + this.lower_val;
  this.current_val = this.current_val - (this.current_val%5000);
  return this.current_val;
};
years = new Calc("#slider2-val", 1, 12);
interest = new Calc("#slider3-val", 8.9, 21.6);
interest.calc = function(val) {
  if(val/3 < 10) { val=8.9; }
  else if(val/3 < 20) { val=15.5; }
  else {val=21.6;}
  this.current_val = val;
  return val;
};
interest.float_precision = true;

function sliderHandler(value,type) {
	switch(type) {
	  case "amount": amount.html(amount.calc(value) ); ss();break;
	  case "years": years.html( years.calc( value ) ); ss();break;
	  case "rente": interest.html( interest.calc( value ).toFixed(1) );ss();break;
	  default: break;
	}
}

function ss() {
  $("#calc-result").html( calculateLoanAmount() );
}

function calculateLoanAmount() {
  
  var balance, rate, term, payment;
  
  balance     = amount.current_val;
  rate        = interest.current_val / 1200;
  term        = years.current_val*12;

  payment = Math.round(balance * rate / (1 - (Math.pow(1/(1 + rate), term))));
	
	return payment;
}

function imgHover() {
  var s,ext;
  if(this.src.match(/-hover/)) {
    s = this.src.split(/-hover/).join("");
    this.src = s;
  } else {
    s = this.src.split(".");
    ext = s.pop();
    s[s.length-1] += "-hover";
    s.push(ext);
    this.src = s.join(".");
  }
}
