
var lastFocusedInput = null;

var minOwnPercent = 0.0;
var minDurationMonths = 3 * 12;
var maxDurationMonths = 45 * 12;

jQuery.fn.setValue = function(value) {
	this.val(numFormat(value));
}

jQuery.fn.formatNumber = function() {
	this.each(function() {
		$(this).val(numFormat($(this).val()));
	});
}

jQuery.fn.setContentProcessing = function(onType, onBlur) {
	this
		.each(function() {
			this.onTypeCallback = onType;
			this.onBlurCallback = onBlur;
		})
		.keyup(function(eventData, handler) {
			if (this.onTypeCallback)
				if (eventData.keyCode >= 0x20 || eventData.keyCode == 0x8)
					this.onTypeCallback();
		})
		.blur(function() {
			if (this.onBlurCallback)
				this.onBlurCallback();
		})
		.focus(function() {
			lastFocusedInput = this;
		})
}

$(document).ready( function() {
	
	$("input.number")
		.unbind()
		.focus(function() { this.select(); })
		.formatNumber()
	$("#value").setContentProcessing(valueOrOwnTyped, validateForm);
	$("#own").setContentProcessing(valueOrOwnTyped, validateForm);
	$("#own_percent").setContentProcessing(ownPercentTyped, validateForm);
	$("#mortgage").setContentProcessing(mortgageTyped, validateForm);
	$("#mortgage_percent").setContentProcessing(mortgagePercentTyped, validateForm);
	$("#duration_years").setContentProcessing(durationTyped, validateForm);
	$("#duration_months").setContentProcessing(durationTyped, validateForm);
	$("#interest_rate").setContentProcessing(interestRateTyped, validateForm);
	
	mortgageTyped();
	
	$("#sendEmailTrigger").fancybox({
		'titlePosition'		: 'inside',
		'transitionIn'		: 'true',
		'transitionOut'		: 'true',
		'onStart'			: function() {
			$("#sendEmailMessage").text("")
			$("#sendEmail .button")
				.removeAttr("disabled")
				.removeClass("disabled")
			$("#sendEmail .invalid").removeClass("invalid");
		}
	});
	
	$("input[type=submit]")
		.mouseover(function() { $(this).addClass("hover"); })
		.mouseout(function() { $(this).removeClass("hover"); })
});

function round(number, decimals) {
	var power = Math.pow(10.0, decimals);
	return Math.round(number * power) / power;
}

function numFormatRemove(str) {
	str = str.replace(/,/g, '.');
	str = str.replace(/[^0-9\.]+/g, '');
	return str == "" ? 0.0 : parseFloat(str);
}

function numFormat(number) {
	var str = number.toString().replace(/\.+/g, ',').replace(/[^0-9,]+/g, '');
	var floatRegexp = /^([0-9]*)(,[0-9]*)?.*$/;
	var integerPart = str.replace(floatRegexp, '$1');
	var decimalPart = str.replace(floatRegexp, '$2');
	var tripleRegexp = /^(\d+)(\d{3})/;
	while (tripleRegexp.test(integerPart))
		integerPart = integerPart.replace(tripleRegexp, '$1 $2');
	return integerPart + decimalPart;
}

function valueOrOwnTyped() {
	var value = numFormatRemove($("#value").val());
	var own = numFormatRemove($("#own").val());
	var mortgage = value > own ? value - own : 0.0;
	setValues(value, mortgage, own);
}

function mortgageTyped() {
	var value = numFormatRemove($("#value").val());
	var mortgage = numFormatRemove($("#mortgage").val());
	var own = value > mortgage ? value - mortgage : 0.0;
	setValues(value, mortgage, own);
}

function setValues(value, mortgage, own) {
	var mortgagePercent = value > 0.0 ? (mortgage / value) * 100.0 : 0.0;
	if (mortgagePercent > 100.0)
		mortgagePercent = 100.0;
	var ownPercent = 100.0 - mortgagePercent;
	$("#value").setValue(Math.round(value));
	$("#mortgage").setValue(Math.round(mortgage));
	$("#own").setValue(Math.round(own));
	$("#mortgage_percent").setValue(round(mortgagePercent, 1));
	$("#own_percent").setValue(round(ownPercent, 1));
}

function mortgagePercentTyped() {
	var value = numFormatRemove($("#value").val());
	var mortgagePercent = numFormatRemove($("#mortgage_percent").val());
	if (mortgagePercent > 100.0)
		mortgagePercent = 100.0;
	var mortgage = value * mortgagePercent / 100.0;
	var ownPercent = 100.0 - mortgagePercent;
	var own = value - mortgage;
	$("#mortgage").setValue(Math.round(mortgage));
	$("#own").setValue(Math.round(own));
	$("#own_percent").setValue(round(ownPercent, 1));
	$("#mortgage_percent").formatNumber();
}

function ownPercentTyped() {
	var value = numFormatRemove($("#value").val());
	var ownPercent = numFormatRemove($("#own_percent").val());
	if (ownPercent > 100.0)
		ownPercent = 100.0;
	var own = value * ownPercent / 100.0;
	var mortgagePercent =  100.0 - ownPercent;
	var mortgage = value - own;
	$("#mortgage").setValue(Math.round(mortgage));
	$("#own").setValue(Math.round(own));
	$("#mortgage_percent").setValue(round(mortgagePercent, 1));
	$("#own_percent").formatNumber();
}

function durationTyped() {
	$("#duration_years").formatNumber();
	$("#duration_months").formatNumber();
}

function interestRateTyped() {
	$("#interest_rate").formatNumber();
}

function validateForm() {
	
	var durationYears = numFormatRemove($("#duration_years").val());
	var durationMonths = numFormatRemove($("#duration_months").val());
	var durationDecimal = durationYears - Math.floor(durationYears);
	
	if (durationDecimal > 0.0)
		durationMonths = durationDecimal * 12.0;
	if (durationMonths > 11.0)
		durationMonths = 11.0;

	durationYears -= durationDecimal;
	durationMonths = Math.round(durationMonths);
	$("#duration_years").setValue(durationYears);
	$("#duration_months").setValue(durationMonths);
	
	var value = numFormatRemove($("#value").val());
	var mortgagePercent = numFormatRemove($("#mortgage_percent").val());
	var mortgage = numFormatRemove($("#mortgage").val());
	var ownPercent = numFormatRemove($("#own_percent").val());
	var own = numFormatRemove($("#own").val());
	var duration = getDuration();
	
	if (own > value) {
		$("#own").setValue(Math.round(value));
		valueOrOwnTyped();
		validateForm();
		return;
	}
	
	if (mortgage > value) {
		$("#mortgage").setValue(Math.round(value));
		mortgageTyped();
		validateForm();
		return;
	}
	
	if (mortgagePercent > (100.0 - minOwnPercent)) {
		$("#mortgage_percent").setValue(100.0 - minOwnPercent);
		mortgagePercentTyped();
		validateForm();
		return;
	}
	
	if (ownPercent > 100.0) {
		$("#own_percent").setValue(100.0);
		ownPercentTyped();
		validateForm();
		return;
	}
	
	if (ownPercent < minOwnPercent) {
		$("#own_percent").setValue(minOwnPercent);
		ownPercentTyped();
		validateForm();
		return;
	}
	
	if (duration < minDurationMonths) {
		$("#duration_years").setValue(minDurationMonths / 12.0);
		$("#duration_months").setValue(0);
		validateForm();
		return;
	}
	
	if (duration > maxDurationMonths) {
		$("#duration_years").setValue(maxDurationMonths / 12.0);
		$("#duration_months").setValue(0);
		validateForm();
		return;
	}
	
}

function recalculate() {
	if (lastFocusedInput) {
		lastFocusedInput.onTypeCallback();
		lastFocusedInput.onBlurCallback();
	}
	document.location = "?" + getMortgageParameters();
	return false;
}

function getMortgageParameters() {
	var value = numFormatRemove($("#value").val());
	var mortgage = numFormatRemove($("#mortgage").val());
	var duration = getDuration();
	var interestRate = numFormatRemove($("#interest_rate").val());
	var bonus = $("#state_bonus:checked").length > 0 ? 1 : 0;
	return "hodnota_nehnutelnosti=" + value.toString()
		+ "&hypoteka=" + mortgage.toString()
		+ "&splatnost=" + duration.toString()
		+ "&urokova_sadzba=" + interestRate.toString()
		+ "&statny_prispevok_pre_mladych=" + bonus.toString();
}

function getDuration() {
	return Math.round(numFormatRemove($("#duration_years").val()) * 12 + numFormatRemove($("#duration_months").val()));
}

function sendEmail(frm) {
	
	if ($(frm).find(".button").hasClass("disabled"))
		return false;
	
	var ok = true;
	$("#sendEmail .invalid").removeClass("invalid");
	
	var emailRegexp = /^[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*@([a-z0-9]([a-z0-9-]*[a-z0-9])?\.)+[a-z0-9]([a-z0-9-]*[a-z0-9])?$/i;
	if (!emailRegexp.test(frm.sendto.value)) {
		ok = false;
		$(frm.sendto).addClass("invalid");
	}
	
	var nameRegexp = /[a-z]{3}/;
	if (!nameRegexp.test(frm.sendfrom.value)) {
		ok = false;
		$(frm.sendfrom).addClass("invalid");
	}
	
	if (!ok) {
		$("#sendEmailMessage")
			.removeClass("success")
			.addClass("error")
			.text("Nesprávne vyplnený formulár.")
		return false;
	}
	
	$.ajax({
		
		type: "POST",
		url: "sendmail.php",
		data: $(frm).serialize() + "&" + getMortgageParameters(),
		dataType: "html",
		
		beforeSend: function() {
			$(frm).find(".button")
				.attr("disabled", "disabled")
				.addClass("disabled")
		},
		
		error: setEmailError,
		
		success: function(result){
			if (result == "1") {
				setEmailSuccess();
				setTimeout('$.fancybox.close();', 3000);
			}
			else
				setEmailError();
		}
		
	});
	
	return false;
}

function setEmailError() {
	$("#sendEmailMessage")
		.removeClass("success")
		.addClass("error")
		.text("Pri odosielaní nastala chyba.")
	$("#sendEmail .button")
		.removeAttr("disabled")
		.removeClass("disabled")
}

function setEmailSuccess() {
	$("#sendEmailMessage")
		.removeClass("error")
		.addClass("success")
		.text("Správa odoslaná.")
	$("#sendEmail .button").not("[type=submit]")
		.removeAttr("disabled")
		.removeClass("disabled")
}

