function Calculation() {
}
//Form labels
Calculation.prototype.getFieldLabel = function(name) {
	switch(name) {
	case	"amount"				: return "Beløb til udbetaling:"
	case "kommune" 					: return "Kommune";
	case "loan_type" 				: return "Låntype";
	case "loan_type_loan" 			: return "Låntype";
	case "loan_type_eq" 			: return "Låntype";
	case "period_all" 				: return "Lånets løbetid i år";
	case "paydown" 					: return "Afdragsfrihed";
	case "paydown_re" 				: return "Afdragsfrihed";
	case "obligations"				: return "Vælg obligationsrenteprocent";
	case "refinancing_frequency" 	: return "Vælg refinansieringsfrekvens";
	case "max_rate" 				: return "Vælg renteloftsprocent";
	case "period" 					: return "Vælg renteloftsperiode";
	case "obligations_rest"			: return "Obligationsrestgæld (kr.)";
	case "rest_lobetid"				: return "Restløbetid (år)";
	case "rest_lobetid_advanced"	: return "Restløbetid";
	case "ydelse_brutto"			: return "Nuværende månedlig ydelse (brutto kr.)";
	case "amount_rescheduling"		: return "Hvad tror du din ejedomsværdi er vurderet til?";
	case "loan_giver"				: return "Långiver";
	case "pantebrevsrestprocent"	: return "Pantebrevsrestprocent";
	case "pantebrevsrestgaeld"		: return "Pantebrevsrestgæld (kr.)";
	case "afdrag_termin"			: return "Afdrag i termin";
	case "rente_termin"				: return "Rente i termin";
	case "bidrag_termin"			: return "Bidrag i termin";
	case "antal_arlige"				: return "Antal årlige terminer";
	case "antal_kurs"				: return "Årligt kurstabsfradrag";
	case "eller_kurs"				: return "Eller kurstabssaldo";
	case "loan_giver_other"			: return "Långiver navn";
	//frivaerdi
	case "bolig_value"				: return "Vurderet salgspris";
	case "equity_amount"			: return "Hvor meget vil du belåne? (i kr.)";
	case "loan_name"				: return "Navngiv dit lån";
	case "loan_amount"				: return "Restgæld";
	case "fondskode"				: return "Fondskode";
	case "loan_obl"					: return "Obligationsrente";
	case "loan_duration"			: return "Restløbetid";		
	
	case "husstands_brutto_indtaegt": return "Månedlig bruttoløn  (kr.)";
	case "fradrag"					: return "Månedligt rentefradrag (kr.)";
	case "kontant_beholdning"		: return "Eventuel kontantbeholdning (kr.)";
	case "udgifter"					: return "Månedlige leveomkostninger (kr.)";
	case "oevrige_udgifter1"		: return "Månedlig udgift til opsparing (kr.)";
	case "oevrige_udgifter2"		: return "Årlig udgift til rejser, oplevelser m.m. (kr.)";
	case "forventet_ejendomsudgift"	: return "Månedlige forbrugsudgifter (kr.)";
	
	
	default							: return "";
	}
}
// loan display table columns
Calculation.prototype.columns = {
	'lantype':	{
			 'name'			: "lantype"
			,'width'		: "142px"		//column width
			,'align'		: "left"		//text align
			,'dictionary'	: "Låntype"		//dictionary key
			,'caption'		: "Låntype"		//header text - DOM allowed as Array
	}
	,'obligations' : {
		 	'name'			: "obligations"
			,'width'		: "120px"
			,'dictionary'	: "Obligationsrenteprocent"
			,'caption'		: "Obligations- renteprocent"
	}
	,'refinanceFrequency' : {
			 'name'			: "refinanceFrequency"
			,'width'		: "120px"
			,'dictionary'	: "Refinansierings- frekvens"
			,'caption'		: "Refinansie- ringsfrekvens"
	}
	,'cappedPercent' : {
			 'name'			: "cappedPercent"
			,'width'		: "60px"
			,'dictionary'	: "Rentelofts pct."
			,'caption'		: "Rente- loftspct."
	}
	,'cappedPeriod' : {
			 'name'			: "cappedPeriod"
			,'width'		: "60px"
			,'dictionary'	: "Renteloftets løbetid"
			,'caption'		: "Rentelofts løbetid"
	}
	
	,'paydown' : {
			 'name'			: "paydown"
			,'width'		: "87px"
			,'dictionary'	: "Indledende afdragsfrihed"
			,'caption'		: "Afdragsfrihed"
	}
	,'period' : {
			 'name'			: "period"
			,'width'		: "45px"
			,'dictionary'	: "Løbetid"
			,'caption'		: "Løbetid"
	}
	,'amountMonth' : {
			 'name'			: "amountMonth"
			,'width'		: "115px"
			,'align'		: "right"
			,'dictionary'	: "Ydelse pr. måned før og efter skat"
			,'caption'		: ["Ydelse pr. md. ", BR(), "før skat / efter"]
	}
	,'amountAll' : {
			 'name'			: "amountAll"
			,'width'		: "115px"
			,'dictionary'	: "Beløb til udbetaling"
			,'caption'		: "Beløb til udbetaling"
	}
}


Calculation.prototype.restoreSavedHash = function(hash) {
	json(
		 "user.calc"
		,{'hash': hash}
		,bind(this.restoreSavedCallback,this)
	);
}
Calculation.prototype.restoreSaved = function(calcId) {
	json(
		 "user.calc"
		,{'calc_id': calcId}
		,bind(this.restoreSavedCallback,this)
	);
}
Calculation.prototype.restoreSavedCallback = function(response) {
	var value = evalJSON(response.data);
	this.calculation = value;
	switch(value.type) {
	case 'ne_model' :
		ne_model.dom.restoreSavedCalc(value);
		break;
	case 'necalc' :
		necalc.restoreSavedCalc(value);
		break;
	case 'new':
		if (value.method == 'fast') {
			this.loanNew(bind(
				function(value) {
					this.loanNewSimple();
					$('amount').value = value.request.amount;
					var response = {};
					response['data'] = value.result;
					this.showResult(response);
				}
				,this,value
			)
		);
		} else {
			this.loanNew(
				bind(
					function(value) {
						this.loanNewAdvanced(
							null,
							bind(
								function(value) {
									$('amount').value = value.request.amount;
									this.selectValue("beloebstype",	value.request.beloebstype);
									this.selectValue("paydown",		value.request.paydown);
									this.selectValue("period_all",	value.request.period_all);
									this.selectValue("loan_type",	value.request.loan_type);
								}
								,this,value
							),
							bind(
								function(value) {
									this.selectValue("kommune",					value.request.kommune);
									this.selectValue("obligations",				value.request.obligations);
									this.selectValue("refinancing_frequency",	value.request.refinancing_frequency);
									this.selectValue("max_rate",				value.request.max_rate);
									this.selectValue("period",					value.request.period);
									this.selectValue("period_all",				value.request.period_all);
									this.selectValue("paydown",					value.request.paydown);
									
									var response = {};
									response['data'] = value.result;
									this.showResult(response);
								}
								,this,value
							)
						)
					}
					,this,value
				)
			);
		}
		break;
	case 'equity' :
		this.loanEquity(
			bind(
				function(value) {
					var next1 = function(value) {
						removeElementClass("h2_equity_form_loan","block_hidden");
						addElementClass("h2_equity_form_loan","block_visible");
						$("equity_form_loan").style.display = "";
						$("h2_equity_loans_table").style.display = "";
						$("equity_loans_table").style.display = "";
						$("h2_equity_form_bolig").style.display = "";
						$("equity_form_bolig").style.display = "";
						$("bolig_value").value = value.request.property_value;
						
						if ( value.request.property_type == 'summer_house') {
							$("bolig_summer").checked = true;
						}
						$("loan_name").value = value.request.loans[value.request.loans.length - 1].name;
						$("loan_amount").value = value.request.loans[value.request.loans.length - 1].value;
						for(var i = 0; i < value.request.loans.length; i++) {
							var loan = value.request.loans[i];
							this.addEquityLoansTableValue(loan.checked,loan.name,loan.value,loan.strloan);
						}
						$("equity_amount").value = value.request.equity_amount;	
						var response = {};
						response['data'] = value.result;
						this.showResult(response);
					}
					function next2(value) {
						this.selectValue("kommune",					value.request.kommune);
						this.selectValue("obligations",				value.request.obligations);
						this.selectValue("refinancing_frequency",	value.request.refinancing_frequency);
						this.selectValue("max_rate",				value.request.max_rate);
						this.selectValue("period",					value.request.period);
						this.selectValue("period_all",				value.request.period_all);
						this.selectValue("paydown",					value.request.paydown);
					}
					if (value.method == 'advanced') {
						this.loanEquityAdvanced(null,bind(next1,this,value),bind(next2,this,value));
					} else {
						this.loanEquitySimple(null, bind(next1, this, value));
					}
				}
				,this
				,value
			)
		);
		break;
	case 'expenses' :
		this.expenses();
		for (v in value.request) {
			$(v).value = value.request[v];
		}
		this.showExpensesResult({'data':value.result});
		break;
	case 'rescheduling':
		if (value.method == 'fast') {
			var next1 = function(value) { 
				this.loanReschedulingSimple();
				for (var i = 0; i < value.request.loan_type_H.length; i++) {
					for (v in value.request) {
						var realName = v.substring(0, v.length - 2);
						if (realName == "loan_type") {
							realName = "loan_type_loan";
						}
						if ($(realName)) {
							if ($(realName).nodeName == "SELECT") {
								this.selectValue(realName,value.request[v][i]);
							} else {
								$(realName).value = value.request[v][i]; 
							}
						}
					}
					this.addReschedulingLoan();
				}
				if (value.request.fordel == 2) {
					$("fordel_false").checked = true;
					$("kontant").readOnly = false; 
					$("kontant").style.backgroundColor = "";
					$("kontant").value = value.request.kontant;
				}
				this.showResult({'data':value.result});
			}
			this.loanRescheduling(bind(next1,this,value));
		} else {
			var next1 = function(value) { 
				this.loanReschedulingAdvanced();
				for (var i = 0; i < value.request.loan_type_H.length; i++) {
					for (v in value.request) {
						var realName = v.substring(0, v.length - 2);
						if (realName == "loan_type") {
							realName = "loan_type_loan";
						}
						if ($(realName)) {
							if ($(realName).nodeName == "SELECT") {
								this.selectValue(realName,value.request[v][i]);
							} else {
								$(realName).value = value.request[v][i]; 
							}
						}
					}
					this.addReschedulingLoanAdvanced();
				}
				if (value.request.fordel == 2) {
					$("fordel_false").checked = true;
					$("kontant").readOnly = false; 
					$("kontant").style.backgroundColor = "";
					$("kontant").value = value.request.kontant;
				}
				this.showResult({'data':value.result});
			}
			this.loanRescheduling(bind(next1,this,value));
		}
		break;
	}
	
}
Calculation.prototype.selectValue = function(field, value) {
	var select = $(field);
	if (select && value) {
		var notFound = false;
		for (var i = 0; i < select.options.length; i++) {
			if (select.options[i].value == value) {
				select.selectedIndex = i;
				notFound = true;
				break;
			}
		}
		if (notFound) {
			//TODO message - can not restore this value
		}
	}
}
Calculation.prototype.saveCalculationCallback = function() {
	var d = doXHR(
		 "page?action=user.save.calculation&method=json&name=" + urlEncode($('name').value)
		,{
			 'method'		: "POST"
			,'sendContent'	: serializeJSON(this.calculation)
		}
	);
	d.addCallback(bind(myplanner.refresh, myplanner));
	removeElement('calc_name');
	return false;
}
Calculation.prototype.saveCalculation = function(elem) {
	if (!this.calculation.result) {
		showError(elem, "error.loan.save");
	} else { 
		messageBox(elem,"Navngiv beregningen: ", bind(this.saveCalculationCallback,this));
	}
	return false;
}

Calculation.prototype.run = function(type) {
	this.externalviewer=false;
	
	var extid = parseQueryString(document.location.search).extid;
	if (extid){
		this.externalviewer=true;
		//special stats for embedding
		if (this.externalvisitdone==false || !this.externalvisitdone) {
			if (type=="loan_new"){
				tstat("Beregning","Nyt boliglån","Velkommen,Beregning,Nyt boliglån",{'eVar12':extid,'prop24':extid});
			}
			this.externalvisitdone=true;
		}
	}	
	
	if ($("calculation")) {
		if (getNodeAttribute("calculation", "class") == 'print') {
			this.hideRules();
			return;
		}
	}
	this.calculation = {};
	
	switch(type) {
	case 'loan_new':
		//oldstat stat("Beregning :: Nyt boliglån");
		ADFtrack(7642,24696,['']);
		this.loanNew();
		break;
	case 'loan_rescheduling':
		this.loanRescheduling();
		break;
	case 'loan_equity':
		this.loanEquity();
		break;
	case 'my_expenses':
		//tstat("Beregning","Hvad har jeg råd til?","Velkommen,Beregning,Hvad har jeg råd til?");
		this.expenses();
		break;
	}
}
Calculation.prototype.expenses = function() {
	setNodeAttribute("mainpage","class", "");
	//var rules = A({'class':"a_link",'href':"#action=calc_rules"},"Se forbehold og vilkår for beregningerne her.");
	var rules = A({'href':"#action=calc_rules",'style':"margin-right: 16px;"},"Vilkår & forbehold for beregning");
	var link = A({'target':'_blank','href':"page?action=page&pageId=333"},"Information om lånetyper");
	var div_form1 = this.drawFormBox("expenses_form", "Indtægter", "expenses.form_box");
	var div_form2 = this.drawFormBox("expenses_form2", "Faste udgifter", "expenses.form_box2");
	var div_form3 = this.drawFormBox("expenses_form3", "Forventede udgifter til den nye bolig", "expenses.form_box3");
	var mainForm = FORM({'id':"calculation",'onsubmit':"return false;"}
			,DIV({'id':"intro_txt",'class':"p_paragraph"})
			//,DIV({'style':"margin: 12px 0pt 0pt 9px; width: 300px;",'class':"no_print"}
			//	,rules
			
			,BR()
			,div_form1
			,div_form2
			,div_form3
			//,BR()
		);
	connect(mainForm, "onsubmit", bind(this.loanExpensesRequest,this));
	replaceChildNodes("mainpage",
		H1({
				'id'	:"mainheader",
				'class'	:"fullheader"
			}
			,"Beregn, hvilken bolig du har råd til"
		),
		mainForm
		,H1({'class':"print"},"Betingelser og forbehold")
		,DIV({'id':"page", 'class':"print"})
		,footer(null,null,true,[rules])
	);
	toolbox(null,null,true);
	replaceChildNodes("expenses_form"
		,DIV({'style':"padding: 6px",'id':"amount_form"}
			,this.getValidationField({
				 'id'			: "husstands_brutto_indtaegt"
				,'valueType'	: "int"
				,'mandatory'	: true
				,'minValue'		: 0
			})
			,BR()
			,this.getValidationField({
				 'id'			: "fradrag"
				,'valueType'	: "int"
				,'minValue'		: 0
			})
			,BR()
			,this.getValidationField({
				 'id'			: "kontant_beholdning"
				,'valueType'	: "int"
				,'minValue'		: 0
			})
			,BR()
		)
	);
	replaceChildNodes("expenses_form2"
		,DIV({'style':"padding: 6px",'id':"amount_form"}
			,this.getValidationField({
				 'id'			: "udgifter"
				,'valueType'	: "int"
				,'mandatory'	: true
				,'minValue'		: 0
			})
			,BR()
			,this.getValidationField({
				 'id'			: "oevrige_udgifter1"
				,'valueType'	: "int"
				,'minValue'		: 0
			})
			,BR()
			,this.getValidationField({
				'id'			: "oevrige_udgifter2"
				,'valueType'	: "int"
			})
			,BR()
		)
	);
	var submit = INPUT({'type':"submit", 'class': "submit", 'value':"Beregn"});
	replaceChildNodes("expenses_form3"
		,DIV({'style':"padding: 6px",'id':"amount_form",'onsubmit':"return false;"}
			,this.getValidationField({
				 'id'			: "forventet_ejendomsudgift"
				,'valueType'	: "int"
				,'mandatory'	: true
				,'minValue'		: 0
			})
			,BR()
			,submit
			,BR()
		)
	);
	$("calculation").validator = new Validator(this.showErrorIcon, this.hideErrorIcon);
	json(
		"page",
		{'pageId':396}, 
		bind(this.printText, this)
	);
	jsonRequest(
	     {"key":"pagetxt.loan.expenses"}
		,function(result) {
			$("intro_txt").innerHTML = result.result;
		}
	    ,"help"
	);
	thepage.updateLocation("Beregn hvad du har råd til af boligkøb","my_expenses");
	this.calculation['type'] = "expenses";
}
Calculation.prototype.loanExpensesRequest = function() {
	var validator = $('calculation').validator;
	try {
		var args = validator.validateForm($('calculation'));
		var out = {};
		// other expenses is calculated as other_exp1*12 (input is monthly) plus other_exp2 (input is annual) - thus out is annual
		out["oevrige_udgifter"] = parseInt(args.oevrige_udgifter1,10) * 12 + parseInt(args.oevrige_udgifter2,10);
		// these 4 are all input monthly, convert to annual
		out["forventet_ejendomsudgift"] = parseInt(args["forventet_ejendomsudgift"],10) * 12;
		out["fradrag"] = parseInt(args["fradrag"],10) * 12;
		out["udgifter"] = parseInt(args["udgifter"],10) * 12;
		out["husstands_brutto_indtaegt"] = parseInt(args["husstands_brutto_indtaegt"],10) * 12;
		// this one is input as a fixed value, simply transfer value
		out["kontant_beholdning"] = parseInt(args["kontant_beholdning"],10);
		for (var i in out) {
			if (isNaN(out[i])) out[i] = 0;
		}
		// save request and send to service
		this.calculation['request'] = out;
		jsonRequest(out, bind(this.showExpensesResult, this), "my_expenses_calculation");
	} catch(e) {
		log(e);
	}

	return false;	
}
Calculation.prototype.showExpensesResult = function(result) {
	this.removeElement("h2_expenses_result");
	this.removeElement("expenses_result");
	var form = this.drawFormBox("expenses_result", "Resultat", "expenses.result_box");
	appendChildNodes("calculation", form);
	if (!result.experror){
		replaceChildNodes("expenses_result",
			DIV({'style':"padding: 6px"}
				,DIV({'style':"width: 300px; float: left;"},"Du kan købe en bolig for:")
				,DIV({'style':"font-weight: bold;"},dFormat(result.data.toFixed(0),"0,000")+ " kr.")
			)
		);
	}else{
		replaceChildNodes("expenses_result",
			DIV({'style':"padding: 6px"}
				,DIV({'style':"width: 480px;margin-bottom:10px float: left;"},""+result.experror)
			)
		);
	}	
	if (result.data) this.calculation['result'] = result.data;
}
Calculation.prototype.loanEquity = function(next) {
	jsonRequest(
	     {"key":"pagetxt.loan.equity"}
		,bind(this.drawSelectBox, this
			,this.loanEquitySimple
			,this.loanEquityAdvanced
			,"Beregn friværdien"
			,"loan_equity"
			,next
		)
	    ,"help"
	);
	this.calculation['type'] = "equity";
}
Calculation.prototype.loanRescheduling = function(next) {
	jsonRequest(
	     {"key":"pagetxt.loan.rescheduling"}
		,bind(this.drawSelectBox, this
			,this.loanReschedulingSimple
			,this.loanReschedulingAdvanced
			,"Låneomlægning"
			,"loan_rescheduling"
			,next
		)
	    ,"help"
	);
	this.calculation['type'] = "rescheduling";
}
/*
Calculation.prototype.loanNew = function(next) {
	var key = this.externalviewer ? "pagetxt.loan.new.external" : "pagetxt.loan.new";
	jsonRequest(
	     {"key":key}
		,bind(
			this.drawSelectBox
				,this
			    ,this.loanNewSimple
			    ,this.loanNewAdvanced
			    ,"Nyt boliglån"
			    ,"loan_new"
				,next
		)
	    ,"help"
	);	
	this.calculation['type'] = "new";
}
Calculation.prototype.drawSelectBox = function(simple, advanced, title, action, next, body) {
	setNodeAttribute("mainpage","class", "");
	var advButton = INPUT({'class':"submit", 'type':"submit", 'value':"Detaljeret", 'style':"margin: 9px 9px 0 0;background-color:orange;border: 1px solid black;"});
	var simpleButton = INPUT({'class':"submit", 'type':"submit", 'value':"Hurtig", 'style':"margin: 9px 9px 0 9px;background-color:orange;border: 1px solid black;"});
	connect(simpleButton, "onclick",bind(simple,this));
	connect(advButton, "onclick",bind(advanced,this));
	var rules = A({'href':"#action=calc_rules",'style':"margin-right: 16px;"},"Vilkår & forbehold for beregning");
	var link = A({'target':'_blank','href':"page?action=page&pageId=333"},"Information om lånetyper");
	//thepage.hookLink(link);
	connect(rules, "onclick", bind(this.showRules,this));
	var div_help = DIV({'class':"p_paragraph",'id':"intro_txt"});
	//if external link, dont show loan type info as it opens a separate page
	var footera;
	if (this.externalviewer==true) footera=footer(null,null,true,[rules]);
	else footera=footer(null,null,true,[rules,link]);
	
	div_help.innerHTML = body.result;
	
	replaceChildNodes("mainpage",
		H1({
				'id'	:"mainheader",
				'class'	:"fullheader"
			},
			title
		),
		DIV({'id':"calculation"}
			,div_help
			,advButton
			,simpleButton
			,BR()
			,BR()
			,BR()
		)
		,H1({'class':"print"},"Betingelser og forbehold")
		,DIV({'id':"page", 'class':"print"})
		,footera
	);

	toolbox(null,null,true);
	thepage.updateLocation(title, action);
	json(
		"page",
		{'pageId':396}, 
		bind(this.printText, this)
	);
	if (next) {
		next.apply();
	}
}
*/
 
Calculation.prototype.loanNew = function(next) {
	var key = this.externalviewer ? "pagetxt.loan.new.external" : "pagetxt.loan.new.ver2";
	jsonRequest(
	     {"key":key}
		,bind(
			this.drawSelectBox
				,this
			    ,this.loanNewSimple
			    ,this.loanNewAdvanced
			    ,"Nyt boliglån"
			    ,"loan_new"
				,next
		)
	    ,"help"
	);	
	this.calculation['type'] = "new";
}
Calculation.prototype.drawSelectBox = function(simple, advanced, title, action, next, body) {
	setNodeAttribute("mainpage","class", "");
	//var advButton = INPUT({'class':"submit", 'type':"submit", 'value':"Detaljeret", 'style':"margin: 9px 9px 0 0;background-color:orange;border: 1px solid black;"});
	//var simpleButton = INPUT({'class':"submit", 'type':"submit", 'value':"Hurtig", 'style':"margin: 9px 9px 0 9px;background-color:orange;border: 1px solid black;"});
	
	
	var rules = A({'href':"#action=calc_rules",'style':"margin-right: 16px;"},"Vilkår & forbehold for beregning");
	var link = A({'target':'_blank','href':"page?action=page&pageId=333"},"Information om lånetyper");
	connect(rules, "onclick", bind(this.showRules,this));
	var div_help = DIV({'class':"p_paragraph",'id':"intro_txt"});
	
	
	//if external link, dont show loan type info as it opens a separate page
	var footera;
	if (this.externalviewer==true) footera=footer(null,null,true,[rules]);
	else footera=footer(null,null,true,[rules,link]);
	
	div_help.innerHTML = body.result;
	
	replaceChildNodes("mainpage",
		H1({
				'id'	:"mainheader",
				'class'	:"fullheader"
			},
			title
		),
		DIV({'id':"calculation"}
			,div_help
			//,advButton
			//,simpleButton
			,BR()
			,BR()
			,BR()
		)
		,H1({'class':"print"},"Betingelser og forbehold")
		,DIV({'id':"page", 'class':"print"})
		,footera
	);
	
	if (this.externalviewer ){
		// "pagetxt.loan.new.external" <-- article containing this area
		var advButton = INPUT({'class':"submit", 'type':"submit", 'value':"Detaljeret", 'style':"margin: 9px 9px 0 0;"});
		var simpleButton = INPUT({'class':"submit", 'type':"submit", 'value':"Hurtig", 'style':"margin: 9px 9px 0 9px;"});
		connect(simpleButton, "onclick",bind(simple,this));
		connect(advButton, "onclick",bind(advanced,this));
		insertSiblingNodesAfter($('intro_txt'),simpleButton,advButton);
	}else{
		//connect buttons from helptext (they HAVE to be there).
		var simpleButton=$('newloanquick');
		var advButton=$('newloanadv');
		connect(simpleButton, "onclick",bind(simple,this));
		connect(advButton, "onclick",bind(advanced,this));
	}
	
	
	toolbox(null,null,true);
	thepage.updateLocation(title, action);
	json(
		"page",
		{'pageId':396}, 
		bind(this.printText, this)
	);
	if (next) {
		next.apply();
	}
}

Calculation.prototype.showRules = function() {
	$("mainheader").innerHTML = "Betingelser og forbehold";
	toolbox(null,null,true);
	addElementClass("calculation","print");
	removeElementClass("page","print");
	return false;
}
Calculation.prototype.hideRules = function() {
	$("mainheader").innerHTML = "Nyt boliglån";
	toolbox(null,null,true);
	addElementClass("page","print");
	removeElementClass("calculation","print");
	return false;
}
Calculation.prototype.printText = function(result) {
	var a = A({'href':"#", 'onclick':"return calc.hideRules();", 'class':"a_link"},"Tilbage");
	var back1 = INPUT({'type':"button", 'value':"Tilbage",'onclick':"return calc.hideRules();",'style':"float: right; margin-right:0; height: 17px;",'class':"submit"});
	var back2 = INPUT({'type':"button", 'value':"Tilbage",'onclick':"return calc.hideRules();",'style':"float: right; margin-right:0; height: 17px;",'class':"submit"});
	$("page").innerHTML = result.contents;
	appendChildNodes("page", back1, BR());
	insertSiblingNodesBefore($("page").firstChild, back2, BR());
	checkDefinitions();
}
Calculation.prototype.clearForm = function() {
	this.removeCompareTable();
	this.removeElement("h2_rescheduling_form");
	this.removeElement("rescheduling_form");
	this.removeElement("h2_new_loan_form");
	this.removeElement("h2_rescheduling_loans");
	this.removeElement("rescheduling_loans");
	this.removeElement("new_loan_form");
	this.removeElement("h2_equity_loans_table");
	this.removeElement("equity_loans_table");
	this.removeElement("h2_equity_form_bolig");
	this.removeElement("equity_form_bolig");
	this.removeElement("h2_equity_form_loan");
	this.removeElement("equity_form_loan");
	this.removeElement("h2_equity_form");
	this.removeElement("equity_form");
	this.removeElement("h2_rescheduling_loans_new_loan");
	this.removeElement("rescheduling_loans_new_loan");
	
	
	this.clearResult();
}
Calculation.prototype.loanNewSimple = function() {
	//stat("Beregning :: Nyt boliglån :: Hurtig");

	if (this.ev26sent){
		tstat("Beregning","Nyt boliglån - Hurtig","Velkommen,Beregning,Nyt boliglån,hurtig");
	}else{
		if(globaldolog) log("sending ev26");
		this.ev26sent=true;
		tstat("Beregning","Nyt boliglån - Hurtig","Velkommen,Beregning,Nyt boliglån,hurtig",{'events':"event26"});
	}
	this.calculation['method'] = "fast";
	this.clearForm();
	
	var div_form = this.drawFormBox("new_loan_form", "Forudsætninger", "loan_new.simple.form_box");
	var submit = INPUT({'type':"submit", 'class': "submit", 'value':"Beregn"});
	var form = FORM({'style':"padding: 6px",'onsubmit':"return false;",'id':"loan_simple_form"}
		,this.getValidationField({
			 'id'			: "amount"
			,'valueType'	: "int"
			,'mandatory'	: true
			,'minValue'		: 3000
			,'maxValue'		: 83000000
			,'mandatory'	: true
			,'no_help'		: true
		})
		,BR(),BR()
		,submit
		,IMG({'id':"loader_calc", 'style':"margin: 5px 8px 0 0; float: right; display: none;", 'src':"resources/images/loader.gif"})
		,BR()
		,BR()
	);
	connect(form, "onsubmit", bind(this.loanNewSimpleRequest, this));
	form.validator = new Validator(this.showErrorIcon, this.hideErrorIcon);
	
	appendChildNodes("calculation", div_form);
	appendChildNodes("new_loan_form", form);
}

Calculation.prototype.loanReschedulingAdvanced = function(ev,next1,next2) {
	tstat("Beregning","Låneomlægning - Detaljeret","Velkommen,Beregning,Låneomlægning,detaljeret");
	this.calculation['method'] = "advanced";
	this.clearForm();
	
	var div_form = this.drawFormBox("rescheduling_form", "Oplysninger om nuværende lån i boligen", "rescheduling.simple.form_box");
	
	var form = FORM({'style':"padding: 6px",'onsubmit':"return false;",'method':'get','action':"#"}
		,this.getSelect("loan_giver", true)
		,this.getField("loan_giver_other")
		,this.getSelect("loan_type_loan", true)
		,this.getFiledPostfix("paydown_re","år","margin: 0 5px 0 0; float: none; width: 78px;")
		,this.getFiledPostfix("pantebrevsrestprocent","%","margin: 0 5px 0 0; float: none; width: 78px;")
		,this.getField("pantebrevsrestgaeld")
		,this.getField("afdrag_termin")
		,this.getField("rente_termin")
		,this.getField("bidrag_termin")
		,this.getDropdown("antal_arlige", [OPTION({'value':2},2),OPTION({'value':4},4),OPTION({'value':12},12)], "width: 94px;")
		,this.getField("antal_kurs")
		,this.getField("eller_kurs")
		,this.getField("fondskode")
		,this.getDoubleFiledPostfix("rest_lobetid_advanced", "rest_lobetid_year", "år", "margin: 0 5px; float: none; width: 65px;", "rest_lobetid_month", "Mdr.", "margin: 0 5px 0 21px; float: none; width: 65px;")
		,BR()
		,DIV({}
			,INPUT({'type':"submit", 'class': "submit", 'value':"Tilføj lån"})
			,SPAN({'style':"margin: 6px 0pt 4px; float: left; width: 400px; display: block;"},"Husk, at du kan indtaste flere lån.")
		)
		,BR(),BR()
	);
	
	
	connect(form,"onsubmit",bind(this.addReschedulingLoanAdvanced, this));
	appendChildNodes("calculation", div_form);
	appendChildNodes("rescheduling_form", form);
	this.addReschedulingLoansTable();
	appendChildNodes("calculation", this.drawFormBox("rescheduling_loans_new_loan", "Forudsætninger for nyt lån", "rescheduling.simple.loans.new"));
	
	var radio1 = INPUT({'type':"radio",'name':"fordel",'checked':true,'style':"margin-right: 4px; width: 12px; vertical-align: bottom;",'value':false});
	connect(radio1, "onchange", bind(this.reschedulingLoanRadioChanged,this));
	var radio2 = INPUT({'type':"radio",'name':"fordel",'id':"fordel_false",'style':"margin-right: 4px; width: 12px; vertical-align: bottom;",'value':true});
	connect(radio2, "onchange", bind(this.reschedulingLoanRadioChanged,this));
	
	var error = IMG({'id':"kontant_error",'class':"error",'src':"resources/images/warning_icon.gif"}); 
	connect(error, "onmouseover", bind(showError, this, error, "error.loan.fill_kontant"));
	var newLoanForm = FORM({'style':"padding: 6px",'id':"amount_form",'onsubmit':"return false;"}
		,DIV({}
			,DIV({}
				,DIV({}
					,radio1
					,LABEL({'for':"fordel"},"Nyt lån så jeg får mindre månedlig ydelse")
				)
				,BR()
				,DIV({}
					,INPUT({'type':"text",'id':"kontant",'class':"text",'readonly':"readonly",'style':"background-color: #BDB6AA;"})
					,error
					,radio2
					,LABEL({'for':"fordel"},"Nyt lån der giver mig kontant overskud")
				)
				,BR()
			)
		)
		,BR()
		,BR()
		,INPUT({'type':"submit", 'class': "submit", 'value':"Beregn"})
		,BR(),BR()
	);
	$("loan_giver_other_div").style.display = "none";
	connect($("loan_giver"), "onchange", bind(this.loanReshedulingGiverChanged,this));
	
	var error = IMG({'id':"kontant_error",'class':"error",'src':"resources/images/warning_icon.gif"}); 
	connect(error, "onmouseover", bind(showError, this, error, "error.loan.fill_kontant"));
	var loanForm = FORM({'style':"padding: 6px",'id':"amount_form",'onsubmit':"return false;"}
		,DIV({'id':"radio_form"}
			,DIV({}
				,DIV({}
					,radio1
					,LABEL({'for':"fordel"},"Nyt lån så jeg får mindre månedlig ydelse")
				)
				,BR()
				,DIV({}
					,INPUT({'type':"text",'id':"kontant",'class':"text",'readonly':"readonly",'style':"background-color: #BDB6AA;"})
					,error
					,radio2
					,LABEL({'for':"fordel"},"Nyt lån der giver mig kontant overskud")
				)
				,BR()
			)
		)
		,this.getAdvancedForm(true)
		,INPUT({'type':"submit", 'class': "submit", 'value':"Beregn"})
		,BR(),BR()
	);
	connect(loanForm, "onsubmit", bind(this.loanReshedulingAdvancedRequest,this));
	appendChildNodes("rescheduling_loans_new_loan", loanForm);
	this.fillLoanGiver();
	this.fillLoanType('loan_type_loan',true);
	this.fillLoanType();
	$("h2_rescheduling_loans_new_loan").style.display = "none";
	$("rescheduling_loans_new_loan").style.display = "none";
	
	//add restrictions to input fields (numbers only)
	//this will make alphabetic letters disappear when entered
	/*
	connect($('paydown_re'),"onkeyup",bind(this.res, this,$('paydown_re'),numb));
	connect($('pantebrevsrestprocent'),"onkeyup",bind(this.res, this,$('pantebrevsrestprocent'),numb));
	connect($('pantebrevsrestgaeld'),"onkeyup",bind(this.res, this,$('pantebrevsrestgaeld'),numb));
	connect($('afdrag_termin'),"onkeyup",bind(this.res, this,$('afdrag_termin'),numb));
	connect($('rente_termin'),"onkeyup",bind(this.res, this,$('rente_termin'),numb));
	connect($('bidrag_termin'),"onkeyup",bind(this.res, this,$('bidrag_termin'),numb));
	connect($('antal_kurs'),"onkeyup",bind(this.res, this,$('antal_kurs'),numb));
	connect($('eller_kurs'),"onkeyup",bind(this.res, this,$('eller_kurs'),numb));
	connect($('rest_lobetid_year'),"onkeyup",bind(this.res, this,$('rest_lobetid_year'),numb));
	connect($('rest_lobetid_month'),"onkeyup",bind(this.res, this,$('rest_lobetid_month'),numb));
	*/
	
	 
	
	jsonRequest({}, bind(
			function(result) {
				this.dropdownResponse({}, result);
				if (next1) {
					next1.apply();
				}
				this.dropdownChange(null,next2);
			}
			, this), "municipality_list");
}
Calculation.prototype.loanEquityAdvanced = function(ev,next1,next2) {
	tstat("Beregning","Beregn friværdien - Detaljeret","Velkommen,Beregning,Beregn friværdien,Detaljeret");
	this.calculation['method'] = "advanced";
	this.loanEquityForm();
	var final_form = FORM({'style':"padding: 6px",'onsubmit':"return false;",'method':'get','action':"#",'id':"loan_equity_form"}
		,this.getField("equity_amount")
		,this.getAdvancedForm(true)
		,INPUT({'type':"submit", 'class': "submit", 'value':"Beregn"})
		,BR()
		,BR()
	);
	appendChildNodes("equity_form_bolig", final_form);
	$("h2_equity_form_bolig").style.display = "none";
	$("equity_form_bolig").style.display = "none";
	this.fillLoanType();
	jsonRequest({}, bind(
			function(result) {
				this.dropdownResponse({}, result);
				if (next1) {
					next1.apply();
				}
				this.dropdownChange(null,next2);
			}
			, this), "municipality_list");
	
	connect(final_form,"onsubmit", bind(this.loanEquityAdvancedRequest,this));
}
Calculation.prototype.loanEquitySimple = function(ev,next1,next2) {
	tstat("Beregning","Beregn friværdien - Hurtig","Velkommen,Beregning,Beregn friværdien,Hurtig");
	this.calculation['method'] = "fast";
	this.loanEquityForm();
		var final_form = FORM({'style':"padding: 6px",'onsubmit':"return false;",'method':'get','action':"#"}
			,this.getField("equity_amount")
			,BR()
			,INPUT({'type':"submit", 'class': "submit", 'value':"Beregn"})
			,BR()
			,BR()
	);
	connect(final_form,"onsubmit", bind(this.loanEquitySimpleRequest,this));
	appendChildNodes("equity_form_bolig", final_form);
	$("h2_equity_form_bolig").style.display = "none";
	$("equity_form_bolig").style.display = "none";
	if (next1) {
		next1.apply();
	}
}
Calculation.prototype.loanEquityForm = function(ev,next1,next2) {
	this.clearForm();
	var loangivers=[OPTION({'value':1},"Navn på pengeinstitut")];
	var loantypes=[OPTION({'value':1},"Låntype")];
	var loan_form = FORM({'style':"padding: 6px",'onsubmit':"return false;",'method':'get','action':"#"}
		,this.getField("loan_name")
		,this.getField("loan_amount")
		,P({'id':"txtloan_optional",'style':"padding:0;margin:10px 0 10px 0"},"Valgfrie oplysninger")
		,this.getDropdown("loan_type_eq"
			,loantypes
			, "width: 196px;")
		,this.getDropdown("loan_giver"
			,loangivers
			, "width: 196px;")
			
		,this.getField("fondskode")
		,this.getFiledPostfix("loan_obl","%","margin: 0 5px 0 0; float: none; width: 78px;")
		,this.getDoubleFiledPostfix("loan_duration", "loan_duration_year", "år", "margin: 0 5px; float: none; width: 65px;", "loan_duration_month", "Mdr.", "margin: 0 5px 0 21px; float: none; width: 65px;")
		,BR()
		,INPUT({'type':"submit",'id':'eqaddloan', 'class': "submit", 'value':"Tilføj lån"})
		,BR()
		,BR()
	);
	
	connect(loan_form,"onsubmit",bind(this.addEquityLoansTableValue,this));
	var radio1 = INPUT({'type':"radio",'name':"bolig_type",'style':"float: right;width: 12px;",'id':"bolig_full",'checked':true});
	connect(radio1, "onchange", bind(this.equityLoanUpdate, this));
	var radio2 = INPUT({'type':"radio",'name':"bolig_type",'style':"float: right; width: 12px;",'id':"bolig_summer"});
	connect(radio2, "onchange", bind(this.equityLoanUpdate, this));
	
	var form = FORM({'style':"padding: 6px",'onsubmit':"return false;",'method':'get','action':"#"}
		,DIV({'style':"clear:both;height:20px"}
			,DIV({'id':"bolig_type_print", 'class':"form_print"})
			,DIV({'style':"width: 100px; float: right;",'class':"no_print"}
				,radio1
				,LABEL({'style':"width: 80px;"},"Helårsbolig")
			)
			,DIV({'style':"width: 100px; float: right;",'class':"no_print"}
				,radio2
				,LABEL({'style':"width: 80px;"},"Fritidsbolig")
			)
			,INPUT({'type':"image",'style':"float:left", 'class':"field_help", 'src':"resources/images/white_help.gif", 'onclick':"return showHelp(this, 'help.loan.form.bolig_type');"})
			,P({'style':"padding:0;float:left;margin-left:3px"},"Ejendomskategori")
			
		)
		,BR({'style':"margin-top: 16px;",'class':"no_print"})
		,this.getField("bolig_value")
		,BR()
		,INPUT({'type':"submit", 'class': "submit", 'value':"OK"})
		,BR()
		,BR()
	);
	
	connect(form,"onsubmit",bind(this.addEquityPropertySelected,this));
	
	appendChildNodes("calculation", this.drawFormBox("equity_form", "Ejendomsoplysinger", "equity.simple.form_box"));
	appendChildNodes("equity_form", form);
	appendChildNodes("calculation", this.drawFormBox("equity_form_loan", "Oplysninger om nuværende lån i boligen", "equity.simple.form_box_loan"));
	appendChildNodes("equity_form_loan", loan_form);
	this.addEquityLoansTable();
	//fill dropdowns with predefined values
	this.fillLoanType("loan_type_eq",true);
	this.fillLoanGiver();
	
	appendChildNodes("calculation", this.drawFormBox("equity_form_bolig", "Forudsætninger for nyt lån", "equity.simple.form_box_bolig"));
	
	$("h2_equity_loans_table").style.display = "none";
	$("equity_loans_table").style.display = "none";
	removeElementClass("h2_equity_form_loan","block_visible");
	addElementClass("h2_equity_form_loan","block_hidden");
	addElementClass("h2_equity_form_loan","no_print");
	$("equity_form_loan").style.display = "none";
	
	//special cases
	//setNodeAttribute("fondskode","maxlength",9); //webservice expects 9 chars at max
}

Calculation.prototype.addEquityPropertySelected = function() {
	var value = $("bolig_value").value;
	
	if ((value) && (parseInt(value)!="NaN")){
		value=parseInt(value);
		$("bolig_value").value=value;
	}
	var minmax_error = false;
	if (value == 0){
		minmax_error=true;
	}
	if (0 < value && value < 3000) {
		minmax_error = true;
		$("bolig_value").value = 3000;
	}
	if (value > 83000000) {
		minmax_error = true;
		$("bolig_value").value = 83000000;
	}
	if (minmax_error) {
		showError($("bolig_value_error"), "error.loan.fill_bolig_value");
		return false;
	}
	
	
	removeElementClass("h2_equity_form_loan","block_hidden");
	addElementClass("h2_equity_form_loan","block_visible");
	$("equity_form_loan").style.display = "block";
	this.equityLoanUpdate();
	return false;
}
Calculation.prototype.validateFieldData = function(field, min, max, mandatory, type, message, icon) {
	if (icon) {
		icon.style.visibility = 'hidden';
	} else {
		$(field.id + "_error").style.visibility = 'hidden';
	}
	if (!mandatory && field.value.length == 0) {
		return 1;
	}
	var value = field.value;
	var error = false;
	switch(type) {
	case 'int':
		value = parseInt(value,10);
		if (isNaN(value)) {
			error = true;
			field.value = '';
			break;
		}
		if (value < min) {
			error = true;
			field.value = min;
			break;
		}
		if (value > max) {
			error = true;
			field.value = max;
			break;
		}
		field.value = value;
		break;
	case 'float':
		value = parseFloat(value.replace(/[,]/,'.'));
		if (isNaN(value)) {
			error = true;
			field.value = '';
			break;
		}
		if (value < min) {
			error = true;
			field.value = min;
			break;
		}
		if (value > max) {
			error = true;
			field.value = max;
			break;
		}
		field.value = new String(value).replace(/[.]/,',');
		break;
	}
	if (error) {
		if (icon) {
			icon.style.visibility = 'visible';
			showError(icon, message);
		} else {
			$(field.id + "_error").style.visibility = 'visible';
			showError($(field.id + "_error"), message);
		}
		
		return 0;
	}
	return 1;
}
Calculation.prototype.addEquityLoansTableValue = function(checked,name,value,loanval) {
	//if this function gets parameters its restoring a saved calculation, 
	// if not, it takes values from the input fields
	if ($("eqerrortext")) removeElement($("eqerrortext"));
	
	var validation_error = false;
	$("loan_name_error").style.visibility = 'hidden';
	if ($("loan_name").value.length == 0) {
		$("loan_name_error").style.visibility = 'visible';
		showError($("loan_name_error"), 'error.loan.fill_loan_name');
		validation_error = true;
	}
	
	if ((0
		+ this.validateFieldData($("loan_obl"), 0, 1000, false, 'int', 'error.loan.fill_loan_obl')
		+ this.validateFieldData($("loan_amount"), 3000, 83000000, true, 'int', 'error.loan.fill_loan_amount')
		+ this.validateFieldData($("fondskode"), 0, 9999999, false, 'int', 'error.loan.fill_fondskode')
		+ this.validateFieldData($("loan_duration_year") , 0, 30, false, 'int', 'error.loan.fill_loan_duration', $('loan_duration_error'))
		+ this.validateFieldData($("loan_duration_month"), 0, 12, false, 'int', 'error.loan.fill_loan_duration', $('loan_duration_error'))
		
		) == 5 && !validation_error
	) {	
		var _checked = checked ? checked : true;
		var _name = name ? name : $("loan_name").value;
		var _value = value ? value : $("loan_amount").value;
		var strval;
	
		if (!loanval){
			
			var _loantype = $('loan_type_eq').options[$('loan_type_eq').selectedIndex].value;
			var _loangiver = $('loan_giver').options[$('loan_giver').selectedIndex].value;
			var _fondskode = $('fondskode').value;
			var _orente = $('loan_obl').value;
			var _dur = $('loan_duration_year').value*12 + $('loan_duration_month').value.parseInt();
			
			//Str representation of the loan
			strval=_name + "," 
				 + _value + "," 
				 +_loantype + "," 
				 + _loangiver + "," 
				 + (_fondskode ? _fondskode : "0") + "," 
				 + (_orente ? _orente : "0") + "," 
				 + (_dur ? _dur : "0");
			//for debug
			//log("LOANSTRING " +strval);	 
		} else {
			strval = loanval;
		}
		
		$("h2_equity_form_bolig").style.display = "";
		$("equity_form_bolig").style.display = "";
		$("h2_equity_loans_table").style.display = "";
		$("equity_loans_table").style.display = "";
		
		var a = A({'href':"#"},IMG({'src':"resources/images/panel_delete.gif",'style':"border: 0; margin-right: 2px;"}));
		connect(a, "onclick", bind(
			function(ev){
				removeElement(ev.src().parentNode.parentNode);
				if (!$("equityTable").tBodies[0].rows.length) {
					$("h2_equity_form_bolig").style.display = "none";
					$("equity_form_bolig").style.display = "none";
					$("h2_equity_loans_table").style.display = "none";
					$("equity_loans_table").style.display = "none";
				}
				this.equityLoanUpdate();
				return false;
			},this)
		);
		var check = INPUT({'type':'checkbox','name':"loanSelected",'checked':_checked,'value':strval});
		connect(check,"onchange", bind(this.equityLoanChanged,this));
			
		appendChildNodes("equityBody"
			,TR({}
				,TD({'style':"text-align: right; padding-right: 3px;"}
					,IMG({'src':"resources/images/flueben.gif",'style':"border: 0; margin: 0 2px 0 0; padding: 0;",'class':"print"})
					,check
				)
				,TD({'style':"text-align: left;"},_name)
				,TD({'name':"loan_sub_sum",'style':"text-align: right; padding-right: 3px;"},dFormat(_value,"0,000"))
				,TD({'class':"no_border"},a)
			)
		);
		this.equityLoanUpdate();
	}
	return false;
}
Calculation.prototype.equityLoanUpdate = function() {
	var loans=document.getElementsByName("loanSelected");
	
	var args=[];
	for (var i=0;i<loans.length;i++) {
		if (loans[i].checked) args.push(loans[i].value);
	}
	
	if (args.length==0){
		
		$("loan_sum").innerHTML = dFormat(0,"0,000");
		$("property").innerHTML = dFormat(0,"0,000");
		$("property_loan").innerHTML = dFormat(0,"0,000");
		$("loan_sum_H").value = (0);	
		return false; //if no loans selected or added, dont continue
	
	}	
	

 
	arg={'amount': parseInt($("bolig_value").value)
		,'type': $("bolig_full").checked ? 1 : 0
		,'userloans': args
		};
	
	jsonRequest(arg
		,bind(this.callbackEquity, this)
		,"loan_equity"
	);	
	
	return false;
}
Calculation.prototype.equityLoanChanged = function(ev) {
	if (ev.src().checked) {
		ev.src().previousSibling.style.display = "";
	} else {
		ev.src().previousSibling.style.display = "none";
	}
	if (filter(function(e){return e.checked;},document.getElementsByName("loanSelected")).length) {
		$("loan_sum_btn").disabled = false;
	} else {
		$("loan_sum_btn").disabled = true;
	}
	this.equityLoanUpdate();
}
Calculation.prototype.addEquityLoansTable = function() {
	var loans = this.drawFormBox("equity_loans_table", "Følgende lån indgår i beregningen", "equity.loans.table");
	appendChildNodes("calculation", loans);
	var form = FORM({'id':"loans",'onsubmit':"return false;",'action':"#",'method':"post"}
		,TABLE({'id':"equityTable"}
			,COLGROUP({}
				,COL({'style':"width: 22px;"})
				,COL({'style':"width: 248px;"})
				,COL({'style':"width: 214px;"})
				,COL({'style':"width: 26px; text-align: left;"})
			)
			,THEAD({}
				,TR({}
					,TD({'style':"width: 22px;",'class':"no_border"})
					,this.getHeaderCell('Lånets navn',"Lånets navn",'left','padding: 2px 1px;')
					,this.getHeaderCell('Restgæld','Restgæld','right')
					,TD({'style':"width: 16px;",'class':"no_border"})
				)
			)
			,TBODY({'id':"equityBody"})
		)
		,DIV({'style':"padding: 6px; margin-left: 18px;"}
			,INPUT({'type':"hidden",'id':"loan_sum_H",'value':0})
			,DIV({'style':"font-weight: bold; color: #878484; width: 300px;float: left;"},"Maksimal lånegrænse: ")
			,SPAN({'id':"property",'style':"font-weight: bold; color: #878484; float: right; margin-right: 24px;"})
			,BR()
			,DIV({'style':"font-weight: bold; color: #878484; width: 300px; float: left;"},"Værdi af nuværende lån ved indfrielse i dag: ")
			,SPAN({'id':"loan_sum",'style':"font-weight: bold; color: #878484; float: right; margin-right: 24px;"})
			,BR()
			,DIV({'style':"font-weight: bold; color: #878484; width: 300px; float: left;"},"Friværdi: ")
			,SPAN({'id':"property_loan",'style':"font-weight: bold; color: #878484; float: right; margin-right: 24px; border-top: 1px solid #878484"})
			,BR()
			,DIV({},
				INPUT({'type':"submit", 'class': "submit", 'value':"OK",'id':"loan_sum_btn"})
			)
			,BR()
			
		)
		,BR()
	);
	connect(form,"onsubmit",bind(this.loanEquitySumCalculate,this));
	appendChildNodes("equity_loans_table", form);
}

Calculation.prototype.loanEquitySumCalculate = function() {
	if (this.highlightFormErrors("bolig_value")) {
		$("equity_amount").value = parseInt($("loan_sum_H").value);  
	}
	
	return false;	
}
Calculation.prototype.loanReschedulingSimple = function(ev,next1,next2) {
	tstat("Beregning","Låneomlægning - Hurtig","Velkommen,Beregning,Låneomlægning,Hurtig");
	this.calculation['method'] = "fast";
	this.clearForm();
	
	var div_form = this.drawFormBox("rescheduling_form", "Oplysninger om nuværende lån i boligen", "rescheduling.simple.form_box");
	
	var form = FORM({'style':"padding: 6px",'onsubmit':"return false;",'method':'get','action':"#",'id':"resheduling_simple_form"}
		,this.getSelect("loan_giver", true)
		,this.getField("loan_giver_other")
		,this.getSelect("loan_type_loan", true)
		,this.getValidationField({
			 'id'			: "obligations_rest"
			,'valueType'	: "int"
			,'mandatory'	: true
			,'minValue'		: 3000
			,'maxValue'		: 83000000
		})
		,this.getValidationField({
			'id'			: "rest_lobetid"
			,'valueType'	: "int"
			,'mandatory'	: true
			,'minValue'		: 0
			,'maxValue'		: 30
		})
		,this.getValidationField({
			'id'			: "ydelse_brutto"
			,'valueType'	: "int"
			,'mandatory'	: true
			,'minValue'		: 0
		})
		,BR()
		,INPUT({'type':"submit", 'class': "submit", 'value':"Tilføj lån"})
		,BR(),BR()
	);
	form.validator = new Validator(this.showErrorIcon, this.hideErrorIcon);
	connect(form,"onsubmit",bind(this.addReschedulingLoan,this));
	appendChildNodes("calculation", div_form);
	appendChildNodes("rescheduling_form", form);
	this.addReschedulingLoansTable();
	appendChildNodes("calculation", this.drawFormBox("rescheduling_loans_new_loan", "Forudsætninger for nyt lån", "rescheduling.simple.loans.new"));
	
	var radio1 = INPUT({'type':"radio",'name':"fordel",'checked':true,'style':"margin-right: 4px; width: 12px; vertical-align: bottom;",'value':false});
	connect(radio1, "onclick", bind(this.reschedulingLoanRadioChanged,this));
	var radio2 = INPUT({'type':"radio",'name':"fordel",'id':"fordel_false",'style':"margin-right: 4px; width: 12px; vertical-align: bottom;",'value':true});
	connect(radio2, "onclick", bind(this.reschedulingLoanRadioChanged,this));
	
	var error = IMG({'id':"kontant_error",'class':"error",'src':"resources/images/warning_icon.gif"}); 
	connect(error, "onmouseover", bind(showError, this, error, "error.loan.fill_kontant"));
	var newLoanForm = FORM({'style':"padding: 6px",'id':"amount_form",'onsubmit':"return false;"}
		,DIV({'id':"radio_form"}
			,DIV({}
				,DIV({}
					,radio1
					,LABEL({'for':"fordel"},"Nyt lån så jeg får mindre månedlig ydelse")
				)
				,BR()
				,DIV({}
					,INPUT({'type':"text",'id':"kontant",'class':"text",'readonly':"readonly",'style':"background-color: #BDB6AA;"})
					,error
					,radio2
					,LABEL({'for':"fordel"},"Nyt lån der giver mig kontant overskud")
				)
				,BR()
			)
			,BR()
		)
		,INPUT({'type':"submit", 'class': "submit", 'value':"Beregn"})
		,BR(),BR()
	);
	connect(newLoanForm, "onsubmit", bind(this.loanReshedulingSimpleRequest,this));
	
	appendChildNodes("rescheduling_loans_new_loan", newLoanForm);
	$("loan_giver_other_div").style.display = "none";
	connect($("loan_giver"), "onchange", bind(this.loanReshedulingGiverChanged,this));
	this.fillLoanType('loan_type_loan',true);
	this.fillLoanGiver();
	$("h2_rescheduling_loans_new_loan").style.display = "none";
	$("rescheduling_loans_new_loan").style.display = "none";
	if (next1) {
		next1.apply();
	}
	//webservice won't allow more than 4 characters here
	setNodeAttribute("rest_lobetid","maxlength",4);
}
Calculation.prototype.loanReshedulingGiverChanged = function() {
	if ($("loan_giver").value == "REALKINS") {
		$("loan_giver_other_div").style.display = "block";
	} else {
		$("loan_giver_other_div").style.display = "none";
	}
}
Calculation.prototype.highlightFormErrors = function(name, empty) {
	$(name + "_error").style.visibility = "hidden";
	var error = false;
	if (empty) {
		if($(name).value.length == 0) {
			error = true;
		}
	} else if (this.validatePositiveNumber($(name).value)) {
			error = true;
	}
	if (error) {
		$(name + "_error").style.visibility = "visible";
		return 0;
	}
	return 1;
}

Calculation.prototype.reschedulingLoanRadioChanged = function(ev) {
	if (filter(function(e){return e.checked;},document.getElementsByName("fordel"))[0].value == "true") {
		$("kontant").style.backgroundColor = "";
		$("kontant").readOnly = false; 
		$("kontant").focus();
	} else {
		$("kontant").style.backgroundColor = "#BDB6AA";
		$("kontant").readOnly = true; 
	}
	
	
}
Calculation.prototype.reschedulingLoanChanged = function(ev) {
	if (ev.src().checked) {
		ev.src().nextSibling.style.display = "";
	} else {
		ev.src().nextSibling.style.display = "none";
	}
	if (filter(function(e){return e.checked;},document.getElementsByName("loanSelected")).length) {
		$("h2_rescheduling_loans_new_loan").style.display = "";
		$("rescheduling_loans_new_loan").style.display = "";
	} else {
		$("h2_rescheduling_loans_new_loan").style.display = "none";
		$("rescheduling_loans_new_loan").style.display = "none";
	}
}
Calculation.prototype.validateReschedulingAdvanced = function(){
	//use these for "either antal kurs or eller kurs, but needs more logic
	//+((this.validateFieldData($("antal_kurs"), 				0, Number.MAX_VALUE, false, 'int', 'error.loan.fill_antal_kurs')
	//  +this.validateFieldData($("eller_kurs"), 				0, Number.MAX_VALUE, false, 'int', 'error.loan.fill_eller_kurs')
	//  )>=1 ? 1 : 0) 
	if (( 0
			+ this.validateFieldData($("paydown_re"), 				0, 30, true, 'int', 'error.loan.fill_paydown_re')
			+ this.validateFieldData($("pantebrevsrestgaeld"), 		0, Number.MAX_VALUE, true, 'int', 'error.loan.fill_pantebrevsrestgaeld')
			+ this.validateFieldData($("pantebrevsrestprocent"), 	0, Number.MAX_VALUE, true, 'float', 'error.loan.fill_pantebrevsrestprocent')
			+ this.validateFieldData($("afdrag_termin"), 			0, Number.MAX_VALUE, true, 'int', 'error.loan.fill_afdrag_termin')
			+ this.validateFieldData($("rente_termin"), 			0, Number.MAX_VALUE, true, 'int', 'error.loan.fill_rente_termin')
			+ this.validateFieldData($("bidrag_termin"), 			0, Number.MAX_VALUE, true, 'int', 'error.loan.fill_bidrag_termin')
			+ this.validateFieldData($("antal_kurs"), 				0, Number.MAX_VALUE, false, 'int', 'error.loan.fill_antal_kurs')
			+ this.validateFieldData($("eller_kurs"), 				0, Number.MAX_VALUE, false, 'int', 'error.loan.fill_eller_kurs')
			+ this.validateFieldData($("fondskode"), 		  	    0, 9999999, false, 'int', 'error.loan.fill_fondskode')
			+ this.validateFieldData($("rest_lobetid_year"), 		0, 30, true, 'int', 'error.loan.fill_rest_lobetid',$("rest_lobetid_advanced_error"))
			+ this.validateFieldData($("rest_lobetid_month"), 		0, 11, false, 'int', 'error.loan.fill_rest_lobetid',$("rest_lobetid_advanced_error"))
		) != 11
	) {
		return false;
	}
	return true;
}
Calculation.prototype.validateField = function(fieldname,validator){
	//not attached yet but will handle showing and hiding the error triangle
	//the validator argument is expected to be a function
	
	//hide incase its 2nd time the field is submitted
	$(fieldname + "_error").style.visibility = "hidden";
	var valid=validator($(fieldname));
	if (valid)	{
		return true;
	}else{
		$(fieldname + "_error").style.visibility = "visible";
		return false;
	}
}
Calculation.prototype.addReschedulingLoanAdvanced = function() {
	if (this.validateReschedulingAdvanced()){
		var loanGiver = null;
		var loanGiverValidation = 1;	
		if ($("loan_giver").value == "-1") {
			if ($("loan_giver_other").value) {
				$("loan_giver_other_error").style.visibility = "hidden";
				loanGiver = $("loan_giver_other").value;
			} else {
				$("loan_giver_other_error").style.visibility = "visible";
				loanGiverValidation = 0;
			}
		} else {
			loanGiver = $("loan_giver").options[$("loan_giver").selectedIndex].innerHTML;
		}
		$("h2_rescheduling_loans").style.display = "";
		$("rescheduling_loans").style.display = "";
		$("h2_rescheduling_loans_new_loan").style.display = "";
		$("rescheduling_loans_new_loan").style.display = "";
		var a = A({'href':"#"},IMG({'src':"resources/images/panel_delete.gif",'style':"border: 0;"}));
		connect(a,"onclick",bind(
			function(ev){
				removeElement(ev.src().parentNode.parentNode);
				if (!$("reschedulingTable").tBodies[0].rows.length) {
					$("h2_rescheduling_loans").style.display = "none";
					$("rescheduling_loans").style.display = "none";
					$("h2_rescheduling_loans_new_loan").style.display = "none";
					$("rescheduling_loans_new_loan").style.display = "none";
				}
				return false;
			},this)
		);
		var check = INPUT({'type':'checkbox','name':"loanSelected",'checked':true});
		connect(check,"onchange",bind(this.reschedulingLoanChanged,this));
		//for translating into months, if not number, set to 0
		//var restval=parseInt($("rest_lobetid_year").value)+parseInt($("rest_lobetid_month").value)/12;
		//if (!this.validatePositiveNumber(restval)) restval=0;
		var lyears=$("rest_lobetid_year").value;
		var lmonths=$("rest_lobetid_month").value;
		if (!lyears) lyears=0;
		if (!lmonths) lmonths=0;
		
		var restvalmonths=parseInt(lyears)*12+parseInt(lmonths);
			
		appendChildNodes("reschedulingBody",
			TR({}
				,TD({'class':"check"}
					,check
					,IMG({'src':"resources/images/flueben.gif",'style':"border: 0; margin: 0 2px 0 0; padding: 0;",'class':"print"})
				)
				,TD({'class':"obligation"},$("pantebrevsrestgaeld").value)
				,TD({'class':"loan_giver"},loanGiver)
				,TD({'class':"loan_type_loan",'style':"text-align:left;"},$("loan_type_loan").options[$("loan_type_loan").selectedIndex].innerHTML)
				,TD({'class':"rest",'style':"text-align:left;"},restvalmonths + " mdr."
					,INPUT({'type':"hidden", 'name':"loan_giver_H",'value':loanGiver})
					,INPUT({'type':"hidden", 'name':"loan_type_H",'value':$("loan_type_loan").value})
					,this.getHiddenNumFieldFor("pantebrevsrestgaeld")
					,this.getHiddenNumFieldFor("pantebrevsrestprocent")
					,this.getHiddenNumFieldFor("afdrag_termin")
					,this.getHiddenNumFieldFor("rente_termin")
					,this.getHiddenNumFieldFor("bidrag_termin")
					,this.getHiddenNumFieldFor("antal_kurs")
					,this.getHiddenNumFieldFor("eller_kurs")
					,this.getHiddenNumFieldFor("fondskode")
					,INPUT({'type':"hidden", 'name':"rest_lobetid_H"
						,'value':restvalmonths})
					,INPUT({'type':"hidden", 'name':"antal_arlige_H", 'value':$("antal_arlige").options[$("antal_arlige").selectedIndex].value})
				)
				,TD({'class':"trash no_border"},a)
			)
		);
		return false;
	}
	return false;
}
Calculation.prototype.getHiddenFieldFor = function(name) {
	return INPUT({'type':"hidden", 'name':name+"_H",'value':$(name).value});
}
Calculation.prototype.getHiddenNumFieldFor = function(name) {
	//same as above, but doesn't result in null/empty if there's no value
	var val = $(name).value;
	if (!val) val=0;
	return INPUT({'type':"hidden", 'name':name+"_H",'value':val});
}
Calculation.prototype.addReschedulingLoan = function() {
	var validator = $('resheduling_simple_form').validator;
	try {	
		validator.validateForm($('resheduling_simple_form'));
		var loanGiver = null;
		if ($("loan_giver").value == "REALKINS") {
			if ($("loan_giver_other").value) {
				$("loan_giver_other_error").style.visibility = "hidden";
				loanGiver = $("loan_giver_other").value;
			} else {
				$("loan_giver_other_error").style.visibility = "visible";
				return false;
			}
		} else {
			loanGiver = $("loan_giver").options[$("loan_giver").selectedIndex].innerHTML;
		} 
		
		
		$("h2_rescheduling_loans").style.display = "";
		$("rescheduling_loans").style.display = "";
		$("h2_rescheduling_loans_new_loan").style.display = "";
		$("rescheduling_loans_new_loan").style.display = "";
		var a = A({'href':"#"},IMG({'src':"resources/images/panel_delete.gif",'style':"border: 0;"}));
		connect(a,"onclick",bind(
			function(ev){
				removeElement(ev.src().parentNode.parentNode);
				if (!$("reschedulingTable").tBodies[0].rows.length) {
					$("h2_rescheduling_loans").style.display = "none";
					$("rescheduling_loans").style.display = "none";
					$("h2_rescheduling_loans_new_loan").style.display = "none";
					$("rescheduling_loans_new_loan").style.display = "none";
				}
				return false;
			},this)
		);
		var check = INPUT({'type':'checkbox','name':"loanSelected",'checked':true});
		connect(check,"onchange",bind(this.reschedulingLoanChanged,this));
		appendChildNodes("reschedulingBody",
			TR({}
				,TD({'class':"check",'style':"width: 22px;"}
					,check
					,IMG({'src':"resources/images/flueben.gif",'style':"border: 0; margin: 0 2px 0 0; padding: 0;",'class':"print"})
				)
				,TD({'class':"obligation"}
					,$("obligations_rest").value
					,INPUT({'type':"hidden", 'name':"obligations_rest_H",'value':$("obligations_rest").value})
				)
				,TD({'class':"loan_giver"}
					,loanGiver
					,INPUT({'type':"hidden", 'name':"loan_giver_H",'value':$("loan_giver").value})
				)
				,TD({'class':"loan_type",'style':"text-align:left"}
					,$("loan_type_loan").options[$("loan_type_loan").selectedIndex].innerHTML
					,INPUT({'type':"hidden", 'name':"loan_type_H",'value':$("loan_type_loan").value})
				)
				,TD({'class':"rest",'style':"text-align:left"},dFormat($("rest_lobetid").value,"0.00")
					,INPUT({'type':"hidden", 'name':"rest_lobetid_H",'value':$("rest_lobetid").value})
					,INPUT({'type':"hidden", 'name':"ydelse_brutto_H",'value':$("ydelse_brutto").value})
				)
				,TD({'class':"trash, no_border"},a)
			)
		);
	} catch(e) {
		log(e);
	}
	return false;
}
Calculation.prototype.addReschedulingLoansTable = function() {
	var loans = this.drawFormBox("rescheduling_loans", "Jeg vil omlægge følgende lån", "rescheduling.simple.loans");
	appendChildNodes("calculation", loans);
	appendChildNodes("rescheduling_loans", 	
		FORM({'id':"loans"}
			,TABLE({'id':"reschedulingTable"}
				,THEAD({}
					,TR({}
						,TD({'class':"check no_border",'style':"width: 22px;"})
						,this.getHeaderCellClass('Obligationsrestgæld',"Obligations- restgæld",'obligation')
						,this.getHeaderCellClass('Långiver',"Långiver",'loan_giver')
						,this.getHeaderCellClass('Låntype',"Låntype",'loan_type')
						,this.getHeaderCell('Restløbetid','Restløbetid','left','padding-left:0;width:70px')
						,TD({'class':"trash no_border"})
					)
				)
				,TBODY({'id':"reschedulingBody"})
			)
		)
	);
	$("h2_rescheduling_loans").style.display = "none";
	$("rescheduling_loans").style.display = "none";
}
Calculation.prototype.getAdvancedForm = function(simple) {
	var beloebstype = SELECT({'id':"beloebstype",'name':"beloebstype",'style':"float: none; margin: 2px 0 0 0;",'tabindex':3}
		,OPTION({'value':1}, "Beløb til udbetaling")
		,OPTION({'value':2}, "Hovedstol")
		,OPTION({'value':3}, "Ydelse pr. md. efter skat")
	);
	var submit = INPUT({'type':"submit", 'class': "submit", 'value':"Beregn",'tabindex':9});
	
//	var kommune = SELECT({'id':"kommune",'name':"kommune"});
	var error = IMG({'id':"amount_error",'class':"error",'src':"resources/images/warning_icon.gif"}); 
	connect(error, "onmouseover", bind(showError, this, error, "help.loan.form.amount"));
	
	if (!simple) {
		var amount_field = INPUT({'type':"text",'id':"amount",'name':"amount",'class':"text",'tabindex':4})
		connect(amount_field, "onkeypress", submitOnEnter);
	}
	var elements =[ 
		simple ? "" : 
		DIV({}
			,DIV({'id':"amount_print",'class':"form_print"})
			,LABEL({'id':"beloebstype_print",'class':"label_print"})
			,amount_field
			,error
			,IMG({ 'class':"field_help", 'style':"margin-top: 4px;",'src':"resources/images/white_help.gif", 'onclick':"return showHelp(this, 'help.loan.form.beloebstype');"})
			,beloebstype
			,BR()
			,BR()
		)
		,this.getSelect("kommune",false,5)
		,this.getSelect("loan_type",false,6)
		,this.getSelect("period_all",false,7)
		,this.getSelect("paydown",false,8)
		,DIV({'id':"advanced_subform"})
		,BR()
		,(simple ? "" : [
			submit
			,IMG({'id':"loader_calc", 'style':"margin: 5px 8px 0 0; float: right; display: none;", 'src':"resources/images/loader.gif"})
			,BR()
			,BR()
		])
	];
	if (simple) {
		return elements;
	} else {
		return FORM({'style':"padding: 6px;",'onsubmit':"return false;",'id':"loan_new_form"},elements);
	}
}
Calculation.prototype.loanNewAdvanced = function(ev,next1,next2) {
	//stat("Beregning :: Nyt boliglån :: Detaljeret");
	if (this.ev26sent){
		tstat("Beregning","Nyt boliglån - Detaljeret","Velkommen,Beregning,Nyt boliglån,Detaljeret");
	}else{
		if(globaldolog) log("sending ev26");
		this.ev26sent=true;
		tstat("Beregning","Nyt boliglån - Detaljeret","Velkommen,Beregning,Nyt boliglån,Detaljeret",{'events':"event26"});
	}
	
	this.calculation['method'] = "advanced";
	this.clearForm();
	
	var div_form = this.drawFormBox("new_loan_form", "Forudsætninger", "loan_new.advanced.form_box");
	
	appendChildNodes("calculation", div_form);
	var form =  this.getAdvancedForm();
	appendChildNodes("new_loan_form",form);
	
	this.fillLoanType();
	//Fill other...
	jsonRequest({}, bind(
			function(result) {
				this.dropdownResponse({}, result);
				if (next1) {
					next1.apply();
				}
				this.dropdownChange(ev,next2);
			}
			, this), "municipality_list");
	connect(form, "onsubmit", bind(this.loanNewAdvancedRequest, this));
}

Calculation.prototype.fillLoanType = function(loanType,eq) {
	//Fill loan types 
	var response = {};
	if (!eq){
	response[loanType == null ? 'loan_type' : loanType] = [
			{'value':-1,'text':"Beregn alle"}
			,{'value':12,'text':"Lån med fast rente"}
			//,{'value':3 ,'text':"Lån med renteloft"}
			,{'value':5 ,'text':"Lån med variabel rente"}
		];  
	}else{
		response[loanType == null ? 'loan_type' : loanType] = [
			 {'value':1,'text':"Lån med fast rente"}
			//,{'value':3 ,'text':"Lån med renteloft"}
			,{'value':5 ,'text':"Lån med variabel rente"}
		];		
		
	}
		
	this.dropdownResponse({}, response);
}
Calculation.prototype.fillLoanGiver = function() {
	//Fill loan types 
	jsonRequest({}, bind(this.dropdownResponse,this,{}), "rescheduling_loan_giver_list");
//	this.dropdownResponse({}, {'loan_giver':[
//			 {'value':1 ,'text':"TotalKredit"}
//			,{'value':2 ,'text':"Nykredit"}
//			,{'value':3 ,'text':"RealKredit Danmark"}
//			,{'value':4 ,'text':"BRF Kredit"}
//			,{'value':-1,'text':"Andet"}
//		]
//	});
}
/* @private Add field (dropdown, input) value to argument list. Skip -1 = not selected value. */
Calculation.prototype.addFieldValue = function(field, args) {
	var f = $(field);
	if (f && f.value != -1 && f.value != "-1") {
		args[field] = f.value;
	}
	
}
/* @private Listener method fired if dropdown value changed. Request new fields values from servlet. */
Calculation.prototype.dropdownChange = function(ev,next) {
	var args = {};
	this.addFieldValue("paydown", args);
	this.addFieldValue("period_all", args)
	this.addFieldValue("loan_type", args);
	
	if (args.loan_type) {
		switch(args.loan_type) {
		case "12":
			this.addFieldValue("obligations", args);
			break;
		case "5":
			this.addFieldValue("refinancing_frequency", args);
			break;
		case "3":
			if (ev.src().id == "max_rate") {
				this.addFieldValue("max_rate", args);
			} else if (ev.src().id == "period") {
				this.addFieldValue("period", args);
			} else {
				this.addFieldValue("max_rate", args);
				this.addFieldValue("period", args);
			}
			break;
		}
	}
	if (next) {
		jsonRequest(args, bind(
				function(args,next,response) {
					this.dropdownResponse(args,response);
					next.apply();
				}
		, this, args, next), "advanced_loan_field");
		
	} else {
		var resultArgs = args;
//		if (ev) {
//			resultArgs[ev.src().id] = undefined;
//		}
		jsonRequest(args, bind(this.dropdownResponse, this, resultArgs), "advanced_loan_field");
	}
}
/* @private Call fillField method for every list from response object. Method binded with servlet request. @see(Calculation#dropdownChange) */
Calculation.prototype.dropdownResponse = function(args, result) {
	if ($("advanced_subform")) {
		replaceChildNodes("advanced_subform", "");
	}
	for (f in result) {
		this.fillField(f, result[f],args[f]);
	}
}
Calculation.prototype.getDoubleFiledPostfix = function(field, field1, postfix1, style1, field2, postfix2, style2) {
	var error = IMG({'id':field + "_error",'class':"error",'src':"resources/images/warning_icon.gif",'style':"3px 0;"}); 
	connect(error, "onmouseover", bind(showError, this, error, "error.loan.fill_" + field));
	return DIV({'id':field + "_div"}
		,DIV({'id':field + "_print", 'class':"form_print"})
		,DIV({'style':"float: right; margin-top: 2px; height: 20px;"}
			,INPUT({'id':field1,'name':field1,'type':"text", 'class':"text", 'style':style1}),postfix1
			,INPUT({'id':field2,'name':field2,'type':"text", 'class':"text", 'style':style2}),postfix2
		)
		,error
		,IMG({'class':"field_help", 'src':"resources/images/white_help.gif", 'onclick':"return showHelp(this, 'help.loan.form." + field + "');"})
		,LABEL({'for':field}, this.getFieldLabel(field))
	);
}
Calculation.prototype.getFiledPostfix = function(field,postfix,style) {
	var error = IMG({'id':field + "_error",'class':"error",'src':"resources/images/warning_icon.gif"}); 
	connect(error, "onmouseover", bind(showError, this, error, "error.loan.fill_" + field));
	return DIV({'id':field + "_div"}
		,DIV({'id':field + "_print", 'class':"form_print"})
		,DIV({'style':"float: right; margin-top: 2px; height: 20px;"}
			,INPUT({'id':field,'name':field,'type':"text", 'class':"text", 'style':style}),postfix
		)
		,error
		,IMG({'class':"field_help", 'src':"resources/images/white_help.gif", 'onclick':"return showHelp(this, 'help.loan.form." + field + "');"})
		,LABEL({'for':field}, this.getFieldLabel(field))
	);
}
Calculation.prototype.getRadio = function(field,value1,value2,id1,id2) {
	return DIV({'id':field + "_div"}
		,DIV({'id':field + "_print", 'class':"form_print"})
		,DIV({'style':"float: right; margin-top: 2px; height: 20px;"}
			,SPAN({}
				,INPUT({'type':"radio",'name':field,'style':"margin-right: 4px; width: 12px; vertical-align: bottom;",'value':value1,'id':id1})
				,LABEL({'for':field,'style':"width: 20px;"}, value1)
			)
			,SPAN({}
				,INPUT({'type':"radio",'name':field,'style':"margin-right: 4px; width: 12px; vertical-align: bottom;",'value':value2,'id':id2,'checked':true})
				,LABEL({'for':field,'style':"width: 20px;"}, value2)
			)
			,BR()
		)
		,INPUT({'type':"image", 'class':"field_help", 'src':"resources/images/white_help.gif", 'onclick':"return showHelp(this, 'help.loan.form." + field + "');"})
		,LABEL({'for':field}, this.getFieldLabel(field))
	);
}
Calculation.prototype.getValidationField = function(properties) {
	var error = IMG({'id':properties.id + "_error",'class':"error",'src':"resources/images/warning_icon.gif"});
	error.error = true;
	connect(error, "onmouseover", bind(showError, this, error, "error.loan.fill_" + properties.id));
	var input = INPUT({'type':"text",'id':properties.id,'class':"text",'value' : properties.value ? properties.value : ""});
	
	input.valueType		= properties.valueType 	== undefined	? 'string'			:properties.valueType
	input.maxValue		= properties.maxValue 	== undefined	? Number.MAX_VALUE	:properties.maxValue; 
	input.minValue 		= properties.minValue 	== undefined	? Number.MIN_VALUE	:properties.minValue;
	input.defaultValue	= properties.defaultValue == undefined	? ''				:properties.defaultValue;
	input.mandatory		= properties.mandatory 	== undefined	? false				:properties.mandatory; 
	input.message 		= "help.loan.form." + properties.id;
	
	return DIV({'id':properties.id + "_div"}
		,DIV({'id':properties.id + "_print", 'class':"form_print"})
		,input
		,error
		,(properties.no_help ? '' : IMG({'class':"field_help", 'src':"resources/images/white_help.gif", 'onclick':"return showHelp(this, 'help.loan.form." + properties.id + "');"}))
		,LABEL({'for':properties.id}, this.getFieldLabel(properties.id))
	);
}
Calculation.prototype.getField = function(field,value,type) {
	var error = IMG({'id':field + "_error",'class':"error",'src':"resources/images/warning_icon.gif"}); 
	connect(error, "onmouseover", bind(showError, this, error, "error.loan.fill_" + field));
	var input = INPUT({'type':"text",'id':field,'class':"text",'value' : value ? value : ""});
	if (type) {
		connect(input, "onfocus", bind(this.clearMask, this, value, type));
		connect(input, "onblur", bind(this.addMask, this, value, type));
	}
	return DIV({'id':field + "_div"}
		,DIV({'id':field + "_print", 'class':"form_print"})
		,input
		,error
		,IMG({'class':"field_help", 'src':"resources/images/white_help.gif", 'onclick':"return showHelp(this, 'help.loan.form." + field + "');"})
		,LABEL({'for':field}, this.getFieldLabel(field))
	);
}
Calculation.prototype.clearMask = function(value, type, ev) {
	switch(type) {
	case 'double':
		var v = parseFloat(ev.src().value.replace(',','.'));
		if (isNaN(v)) {
			ev.src().value = "";
		} else {
			ev.src().value = ("" + v).replace('.',',');
		}
		break;
	case 'int':
	case 'uint':
		var v = parseInt(ev.src().value);
		if (isNaN(v)) {
			ev.src().value = "";
		} else {
			if (type == 'uint') {
				v = Math.abs(v);
			}
			ev.src().value = v;
		}
		break;
	default:
		ev.src().value = ev.src().value.substring(0, ev.src().value.length - value.length);
	}
}
Calculation.prototype.addMask = function(value, type, ev) {
	switch(type) {
	case 'double':
		var v = parseFloat(ev.src().value.replace(',','.'));
		if (isNaN(v)) {
			ev.src().value = value;
		} else {
			ev.src().value = ("" + v).replace('.',',') + value;
		}
		break;
	case 'int':
	case 'uint':
		var v = parseInt(ev.src().value);
		if (isNaN(v)) {
			ev.src().value = "";
		} else {
			if (type == 'uint') {
				v = Math.abs(v);
			}
			ev.src().value = v;
		}
		break;
	default:
		ev.src().value = ev.src().value + value;
	}
}
Calculation.prototype.getDropdown = function(field,options,style) {
	var error = IMG({'id':field + "_error",'class':"error",'src':"resources/images/warning_icon.gif"}); 
	connect(error, "onmouseover", bind(showError, this, error, "error.loan.fill_" + field));
	return DIV({'id':field + "_div"}
		,DIV({'id':field + "_print", 'class':"form_print"})
		,SELECT({'id':field,'name':field,'style':style ? style : ""}, options)
		,error
		,IMG({'class':"field_help", 'src':"resources/images/white_help.gif", 'onclick':"return showHelp(this, 'help.loan.form." + field + "');"})
		,LABEL({'for':field}, this.getFieldLabel(field))
	);
}
/* @private Build div conteiner with field elements. */
Calculation.prototype.getSelect = function(field,skipOnchange,tabindex) {
	var new_select = SELECT({'id':field,'name':field,'tabindex':tabindex});
	if (!skipOnchange) {
		connect(new_select, "onchange", bind(this.dropdownChange, this));
	}
	return DIV({'id':field + "_div"}							//Field continer - $field_div
			,DIV({'id':field + "_print", 'class':"form_print"})	//Printed verion value - $field_print
			,new_select
			,IMG({'class':"field_help", 'src':"resources/images/white_help.gif", 'onclick':"return showHelp(this, 'help.loan.form." + field + "');"})
			,LABEL({'for':field}, this.getFieldLabel(field))
			,BR()
		);
}
/* @private Fill dropdown list (field) with (result) data, select last selection if occure (arg). */
Calculation.prototype.fillField = function(field,result,arg) {
	var div = $(field + "_div");

	if (div) { 	//clear drop down options if field exist
		replaceChildNodes(field, "");
	} else {	//build field if doesn't exist
		appendChildNodes("advanced_subform", this.getSelect(field));
	}
	map(function(e){
		appendChildNodes(field
			,OPTION({'value':e.value}, e.text)
		);
	}, result);
	
	//$(field).disabled = false;
	$(field).parentNode.style.display = "block";	
	if (result.length < 3 ) {
		$(field).selectedIndex = result.length - 1;
		//$(field).disabled = true;
		$(field).parentNode.style.display = "none";
	} else if (arg) {
		for (var i = 0; i < result.length; i++) {
			if (result[i].value == arg) {
				$(field).selectedIndex = i;
				break;		
			}
		}
	}
}
/* @private Build custom box with title, help button and collapsing/expanding capatibility */
Calculation.prototype.drawFormBox = function(id, title, help_key,extra_header) {
	var a = A({'href' : "#"}, IMG({'src':"resources/images/arrow_up_white_icon.gif",'id':"img_"+id}));
	connect(a, "onclick", bind(this.collapse, this, a, id));
	var span = SPAN();
	span.innerHTML = title;
	return [
		H2({'id':"h2_"+id},
			IMG({
				 'class'	:"help"
				,'src'		:"resources/images/calc_help.gif"
				,'onclick'	:"return showHelp(this, '" + help_key + "');"
			}),
			a,
			span
		)
		,extra_header ? extra_header : ""
		,DIV({'id':id,'class':"block_visible"})
	];
}
/* @private Collapse div box */
Calculation.prototype.collapse = function(elem, id) {
	removeElementClass(id, "block_visible");
	addElementClass(id, "block_hidden");
	$(id).style.display = 'none';
	$("img_"+id).src = "resources/images/arrow_down_white_icon.gif";
	$("h2_"+id).style.borderBottom = "1px solid white";
	disconnectAll(elem);
	connect(elem, "onclick", bind(this.expand, this, elem, id));
	
	return false;
}
/* @private Expand collapsed div box */
Calculation.prototype.expand = function(elem, id) {
	removeElementClass(id,"block_hidden");
	addElementClass(id,"block_visible");
	$(id).style.display = 'block';
	$("img_"+id).src = "resources/images/arrow_up_white_icon.gif";
	$("h2_"+id).style.borderBottom = "0";
	disconnectAll(elem);
	connect(elem, "onclick", bind(this.collapse, this, elem, id));
	
	return false;
}
Calculation.prototype.resultRowValue = function(column,data) {
	switch(column.name) {
	case 'lantype':
		return data.laanebetegnelse;
	case 'obligations':
		return dFormat(data.obligationsRente, "0.00");
	case 'refinanceFrequency':
		return data.refFrekvens;
	case 'cappedPercent':
		return dFormat(data.renteLoft,"0.00");
	case 'cappedPeriod':
		return data.udloebsAar;
	case 'paydown':
		return data.afdragsfrihed ? "10 år" :"Nej";
	case 'period':
		var mth = (data.loebetid / 12);
		return mth.toFixed(0) + " år";
	case 'amountMonth':
		return dFormat(data.ydelsePrMndFoerSkat,"0,000") + " / " + dFormat(data.ydelsePrMndEfterSkat,"0,000");
	case 'amountAll':
		return dFormat(data.beloebTilUdbetaling,"0,000");
	}
}
Calculation.prototype.resultRow = function(columns, data) {
	return TR({'style' : data.row > 3 ? "display: none;" : '', 'value' : serializeJSON(data)},
		map(
			bind(
				 function(data,column) {
				 	var properties = {};
				 	if (column.align && column.align == 'left') {
				 		properties['class'] = "calc_left"; 	
				 	}
				 	return TD(properties, this.resultRowValue(column,data));
				 }
				,this
				,data
			)
			,columns
		)
	);
}
/*
Calculation.prototype.hideResult=function(id){
	
}

Calculation.prototype.isolateResult = function(type){
	if (type==12){
		//isolate "lån med fast rente
	}else if (type==3){
		//isolate Lån med renteloft
	}else if (type==5){
		//isolate
	} 
	
}
*/

Calculation.prototype.resultTable = function(id, title, columns, data) {
	if (!data.length) { return ''; }
	// see all button
	var all = A({'href':"#",'class':"a_link"}, "Vis flere");
	connect(all, "onclick", bind(this.removeFooter, this, all, id + "Table"));
	
	// hide table button
	var hide = A({'href':"#"},IMG({'src':"resources/images/arrow_up_icon.gif"}));
	connect(hide, "onclick", bind(this.hideBody, this, hide, id + "Table"));
	
	// table help button
	var help = INPUT({'type':"image", 'src':"resources/images/help_icon.gif"});
	connect(help, "onclick", bind(showHelp, this, help, 'help.loan.new.loanlist.' + id + "Table"));
	for (var i = 0; i < data.length; i++) { data[i]['row'] = i; }
	return [
		 DIV({'id':id+'_tablecaption','class':"caption"}
			,help
			,hide
			,title
		)
		,TABLE({'id':id + "Table"}
			,COLGROUP({},
				map(
					function(e) {
						return COL({'style': "width: " + e.width + (e.align ? "; text-align: " + e.align : '') })
					}
					,columns
				)
			)
			,THEAD({},TR({},
				map(
					bind(
						function(e) {
							return this.getHeaderCell(e.dictionary, e.caption, e.align);
						}
						,this
					)
					,columns
				)
			))
			,TBODY({'id':id + "Body"},
				map(
					bind(
						 this.resultRow
						,this
						,columns
					)
					,data
				)
			)
			,(data.length > 4) ? TFOOT({}, TR({}, TD({'colspan':columns.length,'style':"text-align: right;"},all))) : ''
		)
	];
}
Calculation.prototype.getHeaderCellClass = function(key,name,clazz) {
	var a = A({'href':"#", 'class':"dictionary_word",'onmouseover':"return showDefinition(this,'" + key + "');"});
	appendChildNodes(a,name);
	var th = TH({},a);
	setNodeAttribute(th,"class",clazz);
	return th;
}
Calculation.prototype.getHeaderCell = function(key,name,align,style) {
	var a = A({'href':"#", 'class':"dictionary_word",'onmouseover':"return showDefinition(this,'" + key + "');"});
	appendChildNodes(a,name);
	var th = TH({},a);
	var _style = '';
	if (align) {
		_style += "text-align: " + align;
	}
	if (style) {
		_style += ";" + style;
	}
	setNodeAttribute(th,"style",_style);
	return th;
}
Calculation.prototype.showBody = function(e,id) {
	$(id).style.display = "";
	
	e.parentNode.style.borderBottom = "";
	e.firstChild.src = "resources/images/arrow_up_icon.gif";	disconnectAll(e);
	disconnectAll(e);
	connect(e, "onclick", bind(this.hideBody, this, e, id));
	return false;
}
Calculation.prototype.hideBody = function(e,id) {
	$(id).style.display = "none";

	e.parentNode.style.borderBottom = "1px solid white";
	e.firstChild.src = "resources/images/arrow_down_icon.gif";
	disconnectAll(e);
	connect(e, "onclick", bind(this.showBody, this, e, id));
	return false;
}
Calculation.prototype.removeCompareTable = function() {
	this.removeElement("h2_new_loan_compare");
	this.removeElement("new_loan_compare");
}
Calculation.prototype.getCompareRow = function(title,show) {
	return show 
		? TR({},
			TD({'class':"compare_left"},
				A({'href':"#", 'class':"dictionary_word",'onmouseover':"return showDefinition(this,'" + title + "');"},title)
			),TD(),TD(),TD()
		) 
		: '';
}
Calculation.prototype.drawCompareTable = function() {
	this.removeCompareTable();
	var box = this.drawFormBox("new_loan_compare", "Resultat af sammenligning", "loan_new.simple.compare_box");
	appendChildNodes("calculation", box);
	appendChildNodes("new_loan_compare"
		,TABLE({'id':"compareTable"}
		,TBODY({}
			,TR({'id':"compare_header"}
				,TD({'style':"height: 32px;"})
				,TD({'style':"font-weight: bold;"},SPAN({'style':"color: #FE9A16;"},"Vælg lån 1",BR(),"ovenfor"))
				,TD({'style':"font-weight: bold;"},SPAN({'style':"color: #FE9A16;"},"Vælg lån 2",BR(),"ovenfor"))
				,TD({'style':"font-weight: bold;"},SPAN({'style':"color: #FE9A16;"},"Vælg lån 3",BR(),"ovenfor"))
			)
			,this.getCompareRow("1. års  ydelse før skat", true)
			,this.getCompareRow("- heraf afdrag", true)
			,this.getCompareRow("1. års  ydelse efter skat", true)
			,this.getCompareRow("Obligationshovedstol", true)
			,this.getCompareRow("Tilbudskurs", true)
			,this.getCompareRow("Kursværdi (hovedstol x tilbudskursen)", true)
			,this.getCompareRow("Samlede omkostninger", true)
			,this.getCompareRow("Beløb til udbetaling", (!this.calculation.request.beloebstype || this.calculation.request.beloebstype != 3) )
			,this.getCompareRow("Ydelse pr. måned før skat", (this.calculation.request.beloebstype && this.calculation.request.beloebstype == 3))
			,this.getCompareRow("Ydelse pr. måned efter skat", (this.calculation.request.beloebstype && this.calculation.request.beloebstype == 3))
		))
	);
	var i = 0;
	map(bind(function(e) {
			if (e.id != "compare_header") {
				connect(e,"onmouseover",bind(this.highlightRow,this));
				connect(e,"onmouseout",bind(this.removeHighlightRow,this));
			}
		},this),$("compareTable").rows);
}
Calculation.prototype.highlightRow = function(ev) {
	ev.src().style.backgroundColor = "#BDB6AA";
	ev.src().style.color = "#061746";
}
Calculation.prototype.removeHighlightRow = function(ev) {
	ev.src().style.backgroundColor = "";
	ev.src().style.color = "";
}
Calculation.prototype.removeFooter = function(elem, id) {
	map(function(e){e.style.display = '';}, $(id).rows);
	removeElement(elem.parentNode.parentNode.parentNode);
	return false;
}
Calculation.prototype.loanEquityAdvancedRequest = function() {
	$("equity_amount_error").style.visibility = "hidden";
	
	var noerror = true;
	var value = parseInt($("equity_amount").value);
	if (isNaN(value)) {
		noerror = false
		$("equity_amount").value = '';
	}
	if (value < 3000) {
		noerror = false;
		$("equity_amount").value = 3000;
	}
	if (value > 83000000) {
		noerror = false;
		$("equity_amount").value = 83000000;
	}
	
	
	if (noerror) {
		var form = $("loan_equity_form");
		var params = {'amount':value,'beloebstype':1};
		this.addFieldValue("kommune", params);
		this.addFieldValue("paydown", params);
		this.addFieldValue("period_all", params);
		
		if (form.loan_type && form.loan_type.value != -1) {
			params["loan_type"] = form.loan_type.value;
			switch (form.loan_type.value) {
			case "12":
				this.addFieldValue("obligations",params);
				break;
			case "5":
				this.addFieldValue("refinancing_frequency",params);
				break;
			}
		}
		this.calculation['request'] = params;
		this.calculation.request['equity_amount'] = parseInt(value);
		this.calculation.request['property_type'] = $("bolig_full").checked ? 'full_year' : 'summer_house';
		this.calculation.request['property_value'] = $("bolig_value").value;
		
		$("equity_amount_print").innerHTML = $("equity_amount").value;
		$("bolig_type_print").innerHTML = $("bolig_full").checked ? "Helårsbolig" : "Fritidsbolig";
		$("bolig_value_print").innerHTML = parseInt($("bolig_value").value); 
		
		this.updateEquityLoans();
		jsonRequest(params,bind(this.showResult, this), "new_advanced_calculation");
		
		//TODO clean up - universal
		$("equity_amount").value = parseInt(value);
		$("loan_type_print").innerHTML = $("loan_type").options[$("loan_type").selectedIndex].text;
		$("kommune_print").innerHTML = $("kommune").options[$("kommune").selectedIndex].text;
		$("period_all_print").innerHTML = $("period_all").options[$("period_all").selectedIndex].text;
		$("paydown_print").innerHTML = $("paydown").options[$("paydown").selectedIndex].text;
		$("equity_amount_print").innerHTML = $("equity_amount").value;
		if ($("obligations")) {
			$("obligations_print").innerHTML = $("obligations").options[$("obligations").selectedIndex].text;
		}
		$("paydown_print").innerHTML = $("paydown").options[$("paydown").selectedIndex].text;
		
		//calulation tracking
		var statargs={'prop4':"Beregn friværdi - Detaljeret",'eVar4':"Beregn friværdi - Detaljeret",'events':"event5"};
		tstat("Beregning","Beregn friværdien - Detaljeret - Resultat","Velkommen,Beregning,Beregn friværdien,Detaljeret - Resultat",statargs);
	} else {
		$("equity_amount_error").style.visibility = "visible";
		showError($("equity_amount_error"), 'error.loan.fill_equity_amount');
	}
	return false;
}
Calculation.prototype.loanNewAdvancedRequest = function() {
	$("amount_error").style.visibility = "hidden";
	
	var value = $("amount").value;
	var form = $("loan_new_form");
	var params = {'amount':parseInt(value)};
	this.addFieldValue("beloebstype", params);
	var minmax_error = false;
	if (isNaN(params.amount)) {
		minmax_error = true;
	} else {
		switch(params.beloebstype){
		case "1":
			if(params.amount < 3000) {
				minmax_error = true;
				$("amount").value = 3000;
			}
			if(params.amount > 83000000) {
				minmax_error = true;
				$("amount").value = 83000000;
			}
		case "2":
			if(params.amount < 3000) {
				minmax_error = true;
				$("amount").value = 3000;
			}
			if(params.amount > 83000000) {
				minmax_error = true;
				$("amount").value = 83000000;
			}
		case "3":
			if(params.amount < 3000) {
				minmax_error = true;
				$("amount").value = 3000;
			}
			if(params.amount > 83000000) {
				minmax_error = true;
				$("amount").value = 83000000;
			}
	}
	}
	if(minmax_error) {
		$("amount_error").style.visibility = "visible";
		showError($("amount_error"),"help.loan.form.amount");
		return false;
	}
	
	this.addFieldValue("kommune", params);
	this.addFieldValue("paydown", params);
	this.addFieldValue("period_all", params);
	
	var stat_type = "Alle";
	if (form.loan_type && form.loan_type.value != -1) {
		params["loan_type"] = form.loan_type.value;
		switch (form.loan_type.value) {
		case "12":
			this.addFieldValue("obligations",params);
			stat_type = "Lån med fast rente";
			break;
		case "5":
			this.addFieldValue("refinancing_frequency",params);
			stat_type = "Lån med variabel rente";
			break;
		case "3":
			this.addFieldValue("period", params);
			this.addFieldValue("max_rate", params);
			stat_type = "Lån med renteloft";
			break;
		}
	}
	this.calculation['request'] = params;
	//stat("Beregning :: Nyt boliglån :: Detaljeret :: " + stat_type + " :: Resultat");
	gstatCalc("a");
	var statargs={'prop4':"Nyt boliglån - Detaljeret",'eVar4':"Nyt boliglån - Detaljeret",'events':"event5"};
	
	if (this.ev5sent){
		 delete statargs.events;
	}else{
		this.ev5sent=true;
	}
	tstat("Beregning","Nyt boliglån - Detaljeret - Resultat","Velkommen,Beregning,Nyt boliglån,Detaljeret - Resultat",statargs);
	
	if ($("error_box")) {
		$("error_box").style.display = "none";
	}
	ADFtrack(7642,24697,['']);
	jsonRequest(params,bind(this.showResult, this), "new_advanced_calculation");
	
	//TODO clean up - universal
	$("amount").value = parseInt(value);
	$("loan_type_print").innerHTML = $("loan_type").options[$("loan_type").selectedIndex].text;
	$("beloebstype_print").innerHTML = $("beloebstype").options[$("beloebstype").selectedIndex].text;
	$("kommune_print").innerHTML = $("kommune").options[$("kommune").selectedIndex].text;
	$("period_all_print").innerHTML = $("period_all").options[$("period_all").selectedIndex].text;
	$("paydown_print").innerHTML = $("paydown").options[$("paydown").selectedIndex].text;
	$("amount_print").innerHTML = $("amount").value;
	if ($("obligations")) {
		$("obligations_print").innerHTML = $("obligations").options[$("obligations").selectedIndex].text;
	}
	$("paydown_print").innerHTML = $("paydown").options[$("paydown").selectedIndex].text;

	return false;
}
Calculation.prototype.getLoanValues = function(args,name) {
	args[name] = [];
	if (!$("loans").loanSelected.length) {
		args[name][0] = $("loans")[name].value;
	} else {
		var active = map(function(e){return e.checked;},$("loans").loanSelected);
		for (var i = 0; i < active.length; i++) {
			if (active[i]) {
				args[name][args[name].length] = $("loans")[name][i].value;	
			}
		}
	}
}
Calculation.prototype.loanReshedulingAdvancedRequest = function() {
	var args = {};
	this.getLoanValues(args, "loan_type_H");
	this.getLoanValues(args, "loan_giver_H");
	this.getLoanValues(args, "pantebrevsrestgaeld_H");
	this.getLoanValues(args, "pantebrevsrestprocent_H");
	
	this.getLoanValues(args, "afdrag_termin_H");
	this.getLoanValues(args, "rente_termin_H");
	this.getLoanValues(args, "bidrag_termin_H");
	this.getLoanValues(args, "antal_arlige_H");
	this.getLoanValues(args, "antal_kurs_H");
	this.getLoanValues(args, "eller_kurs_H");
	this.getLoanValues(args, "rest_lobetid_H");
	this.getLoanValues(args, "fondskode_H");
	
	$("kontant_error").style.visibility = "hidden";
	var error = false;	
	if (filter(function(e){return e.checked;}, document.getElementsByName("fordel"))[0].value == "true") {
		args['fordel'] = 2;
		var value = parseInt($("kontant").value);
		var minmax_error = false;
		$("kontant_error").style.visibility = "hidden";
		if (isNaN(value)) {
			$("kontant").value = '';
			minmax_error = true;
		}
		if (value < 3000) {
			$("kontant").value = 3000;
			minmax_error = true;
		}
		if (value > 83000000) {
			$("kontant").value = 83000000;
			minmax_error = true;
		}
		if (minmax_error) {
			$("kontant_error").style.visibility = "visible";
			showError($('kontant_error'), 'error.loan.fill_kontant');
			return false;
		}
		args['kontant']	= value;
	} else {
		args['fordel'] = 1;
	}
	this.calculation['request'] = args;
	//calulation tracking
	var statargs={'prop4':"Låneomlægning - Detaljeret",'eVar4':"Låneomlægning - Detaljeret",'events':"event5"};
	tstat("Beregning","Låneomlægning - Detaljeret - Resultat","Velkommen,Beregning,Låneomlægning,Detaljeret - Resultat",statargs);
	
	jsonRequest(args, bind(this.showResult, this), "rescheduling_advanced_calculation");
	return false;
}
Calculation.prototype.loanReshedulingSimpleRequest = function() {
	var args = {};
	this.getLoanValues(args,"loan_type_H");
	this.getLoanValues(args,"obligations_rest_H");
	this.getLoanValues(args,"rest_lobetid_H");
	this.getLoanValues(args,"ydelse_brutto_H");
	this.getLoanValues(args,"loan_giver_H");
	$("kontant_error").style.visibility = "hidden";
	var error = false;	
	if (filter(function(e){return e.checked;}, document.getElementsByName("fordel"))[0].value == "true") {
		args['fordel'] = 2;
		var value = parseInt($("kontant").value);
		var minmax_error = false;
		$("kontant_error").style.visibility = "hidden";
		if (isNaN(value)) {
			$("kontant").value = '';
			minmax_error = true;
		}
		if (value < 3000) {
			$("kontant").value = 3000;
			minmax_error = true;
		}
		if (value > 83000000) {
			$("kontant").value = 83000000;
			minmax_error = true;
		}
		if (minmax_error) {
			$("kontant_error").style.visibility = "visible";
			showError($('kontant_error'), 'error.loan.fill_kontant');
			return false;
		}
		args['kontant']	= value;
	} else {
		args['fordel'] = 1;
	}
	this.calculation['request'] = args;
	//calulation tracking
	tstat("Beregning","Låneomlægning - Hurtig - Resultat","Velkommen,Beregning,Låneomlægning,Hurtig - Resultat",{'prop4':"Låneomlægning - Hurtig",'eVar4':"Låneomlægning - Hurtig",'events':"event5"});
	
	jsonRequest(args, bind(this.showResult, this), "rescheduling_simple_calculation");
	return false;
}
Calculation.prototype.updateEquityLoans= function(){
	
	this.calculation.request['loans'] = 
			map(
				function(e){
	        		return {
	            		'checked' : e.childNodes[0].firstChild.checked,
	            		'strloan' : e.childNodes[0].firstChild.value,
	            		'name' : e.childNodes[1].innerHTML,
	            		'value' : e.childNodes[2].innerHTML
	        		};
	    		}
	    		,$('equityBody').rows
	);	
}
Calculation.prototype.loanEquitySimpleRequest = function() {
	$("equity_amount_error").style.visibility = "hidden";
	
	var noerror = true;
	var value = parseInt($("equity_amount").value);
	if (isNaN(value)) {
		noerror = false
		$("equity_amount").value = '';
	}
	if (value < 3000) {
		noerror = false;
		$("equity_amount").value = 3000;
	}
	if (value > 83000000) {
		noerror = false;
		$("equity_amount").value = 83000000;
	}
	if (noerror) {
		jsonRequest({'amount':parseInt(value)}, bind(this.showResult, this), "new_simple_calculation");
		$("equity_amount").value = parseInt(value);//remaining equity from calc
		
		this.calculation['request'] = {};
		this.calculation.request['equity_amount'] = parseInt(value);
		this.calculation.request['property_type'] = $("bolig_full").checked ? 'full_year' : 'summer_house';
		this.calculation.request['property_value'] = $("bolig_value").value;

		$("equity_amount_print").innerHTML = $("equity_amount").value;
		$("bolig_type_print").innerHTML = $("bolig_full").checked ? "Helårsbolig" : "Fritidsbolig";
		$("bolig_value_print").innerHTML = parseInt($("bolig_value").value); 
		
		this.updateEquityLoans();
	//calculation tracking
	var statargs={'prop4':"Beregn friværdi - Hurtig",'eVar4':"Beregn friværdi - Hurtig",'events':"event5"};
	tstat("Beregning","Beregn friværdien - Hurtig - Resultat","Velkommen,Beregning,Beregn friværdien,Hurtig - Resultat",statargs);	
	} else {
		$("equity_amount_error").style.visibility = "visible";
		showError($("equity_amount_error"), 'error.loan.fill_equity_amount');
	}
	return false;
}
Calculation.prototype.loanNewSimpleRequest = function() {
	var validator = $('loan_simple_form').validator;
	try {
		var args = validator.validateForm($('loan_simple_form'));
		this.calculation.request = args;
		
		if (this.ev5sent){
			tstat("Beregning", "Nyt boliglån - Hurtig - Resultat","Velkommen,Beregning,Nyt boliglån,Hurtig - Resultat", {'prop4':"Nyt boliglån - Hurtig",'eVar4':"Nyt boliglån - Hurtig"});
		}else{
			tstat("Beregning", "Nyt boliglån - Hurtig - Resultat","Velkommen,Beregning,Nyt boliglån,Hurtig - Resultat", {'prop4':"Nyt boliglån - Hurtig",'eVar4':"Nyt boliglån - Hurtig",'events':"event5"});
			this.ev5sent=true;
		}
		gstatCalc("q")
		jsonRequest(args, bind(this.showResult, this), "new_simple_calculation");
	} catch(e) {
		log(e);
	}

	return false;
}

Calculation.prototype.validatePositiveNumber = function(value) {
	if(value && !isNaN(value) && parseInt(value) > 0 && parseInt(value) <= 850000000 /* max value */)	{
		return false;
	}
	return true;
}

Calculation.prototype.clearResult = function() {
	this.removeElement("fixedTable");
	this.removeElement("orange_result_header");
	this.removeElement("variableTable");
	this.removeElement("cappedTable");
	this.removeElement("h2_new_loan_result");
	this.removeElement("new_loan_result");
}
Calculation.prototype.showResult = function(result) {
	
	this.clearResult();
	this.removeCompareTable();
	
	if (result.data) {
		this.calculation.result = result.data;
	
		appendChildNodes(
			"calculation"
			,this.drawFormBox(
				 "new_loan_result"
				,"Resultat af beregningen"
				,"loan_new.simple.result_box"
				//,DIV({'class':"caption_orange",'id':"orange_result_header"},"Klik på tre lån for at sammenligne dem - se resultatet nederst")
			)
		);
		appendChildNodes("new_loan_result"
			,DIV({'class':"caption_orange",'id':"orange_result_header"},"Klik på tre lån for at sammenligne dem - se resultatet nederst"))
		appendChildNodes("new_loan_result",
			this.resultTable(
				 "fixed"
				,"Lån med fast rente"
				,[
					 this.columns.lantype
					,this.columns.obligations
					,this.columns.paydown
					,this.columns.period
					,this.getLastColumn()
				]
				,result.data.fixed
			)
		);
		appendChildNodes("new_loan_result",
			this.resultTable(
				 "variable"
				,"Lån med variabel rente"
				,[
					 this.columns.lantype
					,this.columns.refinanceFrequency
					,this.columns.paydown
					,this.columns.period
					,this.getLastColumn()
				]
				,result.data.variable
			)
		);
		appendChildNodes("new_loan_result",
			this.resultTable(
				 "capped"
				,"Lån med renteloft"
				,[
					 this.columns.lantype
					,this.columns.cappedPercent
					,this.columns.cappedPeriod
					,this.columns.paydown
					,this.columns.period
					,this.getLastColumn()
				]
				,result.data.capped
			)
		);
		map(
			bind(
				function(e) {
					connect(e, "onclick", bind(this.selectRow, this));
				}
				,this
			)
			,concat($("cappedBody") ? $("cappedBody").rows : [], $("variableBody") ? $("variableBody").rows : [], $("fixedBody") ? $("fixedBody").rows : [])
		);
		$("h2_new_loan_result").scrollIntoView(true);
	} else if (result.error) {
		appendChildNodes("calculation",this.drawFormBox("new_loan_result", "Der er sket en fejl", "loan_new.simple.result_box_error"));
		
		appendChildNodes("new_loan_result",
			DIV({'class':"result_error"}, IMG({'src':"resources/images/warning_icon.gif"}) , result.error)
		);
	}
	return false;	
}
Calculation.prototype.getLastColumn = function() {
	if (this.calculation.request.beloebstype && this.calculation.request.beloebstype == 3) {
		return this.columns.amountAll;
	} else {
		return this.columns.amountMonth;
	}
}
Calculation.prototype.deselectRow = function(ev) {
	setNodeAttribute(ev.src(),"class","");
	disconnectAll(ev.src());
	removeElement(ev.src().nextSibling);
	connect(ev.src(),"onclick",bind(this.selectRow,this));
	map(
		bind(
			function(col,row) {
				if (row.cells[col].childNodes.length == 1) {
					row.cells[col].innerHTML = "";
				}
			}
			,this
			,ev.src().col_no
		)
		,$("compareTable").rows
	);
	var chlidNodes = $("compareTable").rows[0].cells[ev.src().col_no].childNodes;
	chlidNodes[0].style.display = "";
	removeElement(chlidNodes[1]);
	this.removeHighlightCol(ev.src().col_no);
	if (this.allEmptyCol()) {
		this.removeCompareTable();
	}
}
Calculation.prototype.selectRow = function(ev) {
	if (!$("h2_new_loan_compare")) {
		this.drawCompareTable();		
	}
	var empty = this.getEmptyCol();
	if (empty) {
		setNodeAttribute(ev.src(),"class","row_highlight");
		disconnectAll(ev.src());
		connect(ev.src(),"onclick",bind(this.deselectRow,this));
		connect(ev.src(),"onmouseover",bind(this.highlightCol,this,empty));
		connect(ev.src(),"onmouseout",bind(this.removeHighlightCol,this,empty));
		ev.src().col_no = empty;
		this.addLoanToCompare(ev.src(),empty);
	} else {
		showError(ev.src(), "error.loan.compare_max");
	}
}
Calculation.prototype.removeHighlightCol = function(col) {
	map(bind(function(col,row){removeElementClass(row.cells[col],"row_highlight");},this,col),$("compareTable").rows);
}
Calculation.prototype.highlightCol = function(col) {
	map(bind(function(col,row){addElementClass(row.cells[col],"row_highlight");},this,col),$("compareTable").rows);
}
Calculation.prototype.getEmptyCol = function() {
	if (this.isColumnEmpty(1)) { return 1; }
	if (this.isColumnEmpty(2)) { return 2; }
	if (this.isColumnEmpty(3)) { return 3; }
	return null;
}
Calculation.prototype.allEmptyCol = function() {
	if (!this.isColumnEmpty(1)) {return false; }
	if (!this.isColumnEmpty(2)) { return false;  }
	if (!this.isColumnEmpty(3)) { return false;  }
	return true;
}
Calculation.prototype.isColumnEmpty = function(no) {
	var table = $("compareTable");
	if(table && table.rows[1].cells[no].innerHTML) {
		return false;
	}
	return true;
}
Calculation.prototype.addLoanToCompare = function(row, empty) {
	var value = evalJSON(row.getAttribute('value'));
	insertSiblingNodesAfter(row, 
		TR({'class':"row_highlight"}
			,TD({'colspan':row.childNodes.length, 'class':"highlighted_info"}
				,A ({'href':"#compare_header",'class':"a_link", 'onclick':"$('h2_new_loan_compare').scrollIntoView(true); return false;"}, "Klik her for at se sammenligning")
			)
		)
	);
	var cols = map(bind(function(col,r){return r.cells[col];},this,empty),$("compareTable").rows)
	
	appendChildNodes(cols[0], value.laanebetegnelse);
	cols[0].firstChild.style.display = "none";
	appendChildNodes(cols[1], dFormat(value.ydelseFoersteAarFoerSkat,"0,000"));	
	appendChildNodes(cols[2], dFormat(value.ydelseFoersteAarAfdrag,"0,000"));	
	appendChildNodes(cols[3], dFormat(value.ydelseFoersteAarEfterSkat,"0,000"));	
	appendChildNodes(cols[4], dFormat(value.obligationHovedstol,"0,000"));	
	appendChildNodes(cols[5], dFormat(value.tilbudskurs,"0,000.000"));	
	appendChildNodes(cols[6], dFormat(value.kursVaerdi,"0,000"));	
	appendChildNodes(cols[7], dFormat(value.omkostningerSamlet,"0,000"));	
	if (this.calculation.request.beloebstype && this.calculation.request.beloebstype == 3) {
		appendChildNodes(cols[8], dFormat(value.ydelsePrMndFoerSkat,"0,000"));
		appendChildNodes(cols[9], dFormat(value.ydelsePrMndEfterSkat,"0,000"));
	} else {
		appendChildNodes(cols[8], dFormat(value.beloebTilUdbetaling,"0,000"));
	}
};
function submitOnEnter(ev) {
	if (ev.event().keyCode == 13) {
		signal(ev.src().form, "onsubmit");
   		return false;
   	}
   	return true;
}
function dFormat(num, format) {
	return new Number(num).format(format ? format : "0,000.00");
}
Calculation.prototype.removeElement = function(name) {
	if ($(name)) {
		removeElement(name);
	}
}

Calculation.prototype.requestEquity=function(){
	//document.getElementsByName("loanSelected")[0].value
	//map(function(e){return e.checked;},$("loans").loanSelected);

	//send checked loans
/*	loans=document.getElementsByName("loanSelected");
	
	
	var args=[];
	for (var i=0;i<loans.length;i++) if (loans[i].checked) args.push(loans[i].value);
	
	if (args.length==0){
		
		$("loan_sum").innerHTML = dFormat(0);
		$("property").innerHTML = dFormat(0);
		$("property_loan").innerHTML = dFormat(0);
		$("loan_sum_H").value = (0);	
		return false; //if no loans selected or added, dont continue
	
	}	

 
	arg={'amount': parseInt($("bolig_value").value)
		,'type': $("bolig_full").checked ? 1 : 0
		,'userloans': args
		};
	
	jsonRequest(arg
				,bind(this.callbackEquity, this)
				,"loan_equity");	*/
	
}
Calculation.prototype.callbackEquity = function(result){
	if (!result.eqerror){
		// first field is 60% or 80% of property value
		var property_value = ($("bolig_full").checked ? 0.80 : 0.60) * parseInt($("bolig_value").value, 10);
		$("property").innerHTML = dFormat(property_value, "0,000");
		// last value is returned from webservice
		$("property_loan").innerHTML = dFormat(result.eqvalue, "0,000");
		// middle value is difference between these 
		$("loan_sum").innerHTML = dFormat(property_value - result.eqvalue, "0,000");
		
		// this value is used for loan calculation in second step
		$("loan_sum_H").value = result.eqvalue;
	}else{
		//remove last table row that was put in
		removeElement($('equityBody').rows[$('equityBody').rows.length-1])
		//add the eqerror message to the error div
		insertSiblingNodesBefore($("eqaddloan"), DIV({'id':'eqerrortext','style':"color:red;margin-bottom:10px"},""+result.eqerror));
	}
}
/**
 * Formats the number according to the 'format' string; adherses to the american number standard where a comma is inserted after every 3 digits.
 *  note: there should be only 1 contiguous number in the format, where a number consists of digits, period, and commas
 *        any other characters can be wrapped around this number, including '$', '%', or text
 *        examples (123456.789):
 *          '0' - (123456) show only digits, no precision
 *          '0.00' - (123456.78) show only digits, 2 precision
 *          '0.0000' - (123456.7890) show only digits, 4 precision
 *          '0,000' - (123,456) show comma and digits, no precision
 *          '0,000.00' - (123,456.78) show comma and digits, 2 precision
 *          '0,0.00' - (123,456.78) shortcut method, show comma and digits, 2 precision
 *
 * @method format
 * @param format {string} the way you would like to format this text
 * @return {string} the formatted number
 * @public
 */
Number.prototype.format = function(format) {
	var hasComma = -1 < format.indexOf(','),
		psplit = filter(function(a){return a.match(/[0-9\.]/);}, format.split('')).join('').split('.'),
		that = this;

	// compute precision
	if (1 < psplit.length) {
		// fix number precision
		that = that.toFixed(psplit[1].length);
	}
	// error: too many periods
	else if (2 < psplit.length) {
		throw('NumberFormatException: invalid format, formats should have no more than 1 period: ' + format);
	}
	// remove precision
	else {
		that = that.toFixed(0);
	}

	// get the string now that precision is correct
	var fnum = that.toString();

	// format has comma, then compute commas
	if (hasComma) {
		// remove precision for computation
		psplit = fnum.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
		fnum = parr.join('.');

		// add the precision back in
		if (psplit[1]) {fnum += ',' + psplit[1];}
	} else {
		fnum = fnum.replace(/\./,',');
	}

	// replace the number portion of the format with fnum
	return fnum;
};
//predefined restrictions
var numb = "0123456789";
var numb2 = "0123456789,.";

Calculation.prototype.res = function (t,v){
	//restrict t(element) to the characters in v(string)
	var w = "";
	for (i=0; i < t.value.length; i++) {
		x = t.value.charAt(i);
		
		if (v.indexOf(x,0) != -1) w += x;
	}
	
	t.value = w;
}
Calculation.prototype.showErrorIcon = function(field, message) {
	if (!$(field.id+"_error")) {
		return;
	}
	$(field.id+"_error").style.visibility = "visible";
	showError($(field.id+"_error"), message);
}
Calculation.prototype.hideErrorIcon = function(field, message) {
	if (!$(field.id+"_error")) {
		return;
	}
	$(field.id+"_error").style.visibility = "hidden";
}
function Validator(showError, hideError) {
	this.validator(showError, hideError);
};
Validator.prototype = {
	validator :function(showError, hideError) {
		this.showError = showError;
		this.hideError = hideError;
	}
	,validateForm :function(form) {
		var values = {};
		var exceptions = [];
		for (var i = 0; i < form.elements.length; i++) {
			var field = form.elements[i];
			if (field.type == 'text') {
				try {
					values[field.id] = this.validate({'src':function(){return field;}})
					$(field.id + "_print").innerHTML = values[field.id];
				} catch(e) {
					exceptions.push(e);
				}
			}
		}
		if(exceptions.length > 0) {
			throw(exceptions);
		}
		return values;
	}
	,get :function(field) {
		switch(field.valueType) {
		case 'float':
			if (!field.mandatory && field.value.length == 0) {
				return '';
			}
			return
				new String(
					this.range(
						 field.value
							.replace(/[,]/,'.')
							.parseFloat()
						,field.minValue
						,field.maxValue
					)
				).replace(/[.]/,',');
		case 'int':
			if (!field.mandatory && field.value.length == 0) {
				return '';
			}
			return this.range(
					 field.value.parseInt(10)
					,field.minValue
					,field.maxValue
				);
		case 'string':
		default:
			if (!field.mandatory && field.value.length == 0) {
				return '';
			}
			if (field.value.length < (field.minValue < 0 ? 0 : field.minValue)) {
				throw('STRING_MIN_LENGTH');
			}
			if (field.value.length > field.maxValue) {
				throw('STRING_MAX_LENGTH');
			}
			return field.value;
		}
	}
	,validate :function(ev) {
		try {
			this.hideError(ev.src());
			ev.src().value = this.get(ev.src(), ev.src().message)
			return ev.src().value;
		} catch(ex) {
			var value;
			switch(ex) {
			case 'MIN':
				value = ev.src().minValue;
				break;
			case 'MAX':
				value = ev.src().maxValue;
				break;
			case 'STRING_MAX_LENGTH':
				value = ev.src().value.substring(0, ev.src().maxValue);
			case 'STRING_MIN_LENGTH':
				value = ev.src().value;
			case 'NaN':
			default:
				value = ev.src().defaultValue;
				break;
			}
			ev.src().value = value;
			this.showError(ev.src(), "error.loan.fill_"+ev.src().id);
			throw(ex);
		}
	}
	,range :function(value,min,max) {
		if (value < min) {
			throw("MIN");
		}
		if (value > max) {
			throw('MAX');
		}
		return value;
	}
}
	
addLoadEvent(function () {
	calc = new Calculation();
});
