var SavingsCalc = function(container_id) {
	this.container = $(document.getElementById(container_id));
	this.container.addClass("enhanced");
	this.inputs = this.container.find("input[type=text][readonly!] , select");
	this.loadIcon = $("#calc-load");
	this.deposit = $("#deposit");
	this.noFix = $("#no-fix");
	
	this.form = this.container.find("form");

	// pretty select pre obdobie nefixacie
	new SavingsCalc.TermSelect(this);

	// validator vstupov
	this.validator = new SavingsCalc.Validator(this.inputs.not("select"));

	// napoveda
	new SavingsCalc.Tips({
		"deposit" : { x : 356 , y : 52 },
		"no-fix" : { x : 142 , y : 190 },
		"fix-6" : { x : 246 , y : 148 },
		"savings-label" : { x : 180 , y : 452 }
	});

	this.inputs.bind("change keyup", this.form, this.update());
	this.form.submit(function(){return false;});
};

SavingsCalc.prototype.update = function() {
	var $this = this;
	return function(e) {
		var iid = null;
		if ( e.keyCode && e.keyCode != 13 ) { // ENTER
			return true;
		}
		// copy value
		if ( this.id == "deposit" ) {
			var dep = parseInt($this.deposit.val());
			var amount = 0;
			$("#fixation input").not("#no-fix").each(function(){
				var val = parseInt(this.value);
				if (val>0) {
					amount += val;
				}
			});
			// prenasanie hodnoty z vkladu
			if (dep > 0) {
				$this.noFix.val(dep-amount);
			}
		} else if ( $(this).parent().attr("id") == "fixation" ) {
			if ( this.id != "no-fix" && this.tagName.toLowerCase() != "select" ) {
				var thisVal = parseInt($(this).val());
				var amount = 0;
				// spocitanie obdobi
				$("#fixation input").not("#no-fix").each(function(){
					var val = parseInt(this.value);
					if (val>0) {
						amount += val;
					}
				});
				var dep = parseInt($this.deposit.val());
                                if ( !$this.validator.validateFixation(thisVal, amount, dep) ) {
                                    return false;
                                }
				// odpocita a prenesie hodnoty
				if ( dep > 0 && amount > 0 ) {
					$this.noFix.val(dep - amount);
				}
			} else if  (this.id == "no-fix" ) {
				var amount = 0;
				var nofix = parseInt($this.noFix.val());
				$("#fixation input").not("#no-fix").each(function(){
					var val = parseInt(this.value);
					if (val>0) {
						amount += val;
					}
				});
				$("#deposit").val(amount+(nofix>0?nofix:0));
			}
		}
		e.stopPropagation();
		// ziska vysledky ajaxom
		$.get(asyncCalcUrl, e.data.serialize(), $this.reload);
		$this.loadIcon.show();
	};
};

SavingsCalc.prototype.reload = function(data) {
	$("#calc-load").hide();
	var focusedInput = document.activeElement.id;
	if ( focusedInput == "no-fix" || focusedInput == "deposit" ) focusedInput = "fix-6";
	$("#saving-calc-container").html(data);
	new SavingsCalc("savings-calc");
	try {
		document.getElementById(focusedInput).focus();
	} catch(e) {}
}

SavingsCalc.TermSelect = function(calc) {
	this.selectElement = $(calc.container.find("#no-fix-plan"));
	this.container = this.buildSelect();
	this.calc = calc;

	this.selectElement.find("option").each(this.buildOption());
	this.container.find("a:first").attr("id","first")
	this.selectElement.before(this.container);
	this.selectElement.attr("id","").hide();
};

SavingsCalc.TermSelect.prototype = {
	buildSelect : function() {
		var rootElement = $(document.createElement("div"));
		rootElement.attr("id",this.selectElement.attr("id"));
		rootElement.click(this.toggleMenu);
		return rootElement;
	},
	buildOption : function() {
		var $this = this;
		return function() {
			var option = $(this);
			var el = $(document.createElement("a"));
			el.text(option.text());
			if (option.attr("selected")) {
				el.addClass("active");
			}
			el.click($this.pickOption());
			$this.container.append(el);
		}
	},
	toggleMenu : function() {
		var el = $(this);
		el.toggleClass("active");
	},
	pickOption : function() {
		var $this = this;
		return function() {
			var el = $(this);
			if (el.parent().hasClass("active")) {
				$this.container.find("a.active").removeClass("active");
				el.addClass("active");
				var selIndex = el.parent().children().index(el);
				$this.selectElement.get(0).selectedIndex = selIndex;
				$this.selectElement.trigger("change");
				var nofix = $this.selectElement.get(0).options[selIndex].value;
				$("#nfp-label").text("za "+nofix+" měsíců"); // BAD ROBOT
				if (parseInt(nofix) < 12 ) {
					$("#savings-label").text("Za 6 měsíců naspoříte:")
				} else {
					$("#savings-label").text("Za 12 měsíců naspoříte:")
				}
			}
		}
	}
};

/* validates positive numbers in inputs */
SavingsCalc.Validator = function(inputs,messageHandler) {
	$(inputs).bind("change",messageHandler,this.validate).bind("keyup keydown",this.allowNumbers);
};

SavingsCalc.Validator.NUMBER_KEYS = "0123456789";

SavingsCalc.Validator.prototype.validate = function(e) {
	var val = parseInt( this.value );
	if ( typeof(val) != "number" || val < 1 ) {
		//e.data("Nesprávne vyplnené pole: "+$("label[for='"+this.id+"']").text()); // BAD ROBOT
	}
};

SavingsCalc.Validator.prototype.allowNumbers = function(e) {
	for (var i=0; i<this.value.length; i++) {
		if ( SavingsCalc.Validator.NUMBER_KEYS.indexOf(this.value.charAt(i)) < 0 ) {
			this.value = this.value.replace(this.value.charAt(i),'');
		}
	}
};

SavingsCalc.Validator.prototype.validateFixation = function(thisVal, amount, dep) {
	if ((dep - amount) < 0) {
		alert(window.dict["small_deposit"]);
		$(this).val("0");
		return false;
	}
	if (thisVal > 0 && thisVal < 30000) {
		alert(window.dict["small_fix"]);
		return false;
	}
	return true;
};

SavingsCalc.Tips = function(data) {
	this.calcEl =  document.getElementById("savings-calc");
	for ( var id in data ) {
		this.buildTip(id, data[id].x, data[id].y);
	}
	$(".calc-tip .tip-trigger").mouseenter(function(){ $(this).next().fadeIn("fast"); });
	$(".calc-tip").mouseleave(function(){ $(".tip-content",this).fadeOut("fast"); });
};

SavingsCalc.Tips.prototype.buildTip = function(id,x,y) {
	var srcEl =  document.getElementById(id);
	var tipText = srcEl.title;
	srcEl.title = "";
	var tipElement = document.createElement("div");
	tipElement.id = id+"-tip";
	tipElement.className = "calc-tip";
	tipElement.style.left = x+"px";
	tipElement.style.top = y+"px";

	var tipContentElement = document.createElement("div");
	tipContentElement.innerHTML = tipText;
	tipContentElement.className = "tip-content";
	var tipTrigger = document.createElement("div");
	tipTrigger.className = "tip-trigger";

	tipElement.appendChild(tipTrigger);
	tipElement.appendChild(tipContentElement);

	this.calcEl.appendChild(tipElement);
	$(tipContentElement).hide();
};

$(function(){
	new SavingsCalc("savings-calc");
});
