function NeModel() {
    this.ab_tester = 'B'; // Default to the old way
	this.state = new State(this);
	this.dom = new DOM(this);
	this.init = new Init(this)
	this.building = new Building(this);
	this.loan_calculation = new LoanCalculation(this);
	this.loan_calculation_result = new LoanCalculationResult(this);
	this.report = new Report(this);
	this.stepsDOM = [];
	this.stepFields = {};
	this.calculation = {};
	this.inflation = '3%';
	this.parent = this;
	this.current_state = 'base';
	
	this.changeBackground = true;
	
	this.elements = [];
	
	this.elements['report_generation'] = ['report-result-header', 'report-result'];
	this.elements['loan_calculation_result'] = this.elements['report_generation']; 
	this.elements['loan_calculation'] = concat(this.elements['report_generation'], ['ne-loan-calc-header', 'ne-loan-calc']);
	this.elements['simple_calculation'] = concat(this.elements['loan_calculation'], ['advanced-calculation-header', 'advanced-calculation']);
}
function DOM(parent) {this.parent = parent;};
function State(parent) {this.parent = parent;};
function Init(parent) {this.parent = parent;};
function Building(parent) {this.parent = parent;};
function LoanCalculation(parent) {this.parent = parent;};
function LoanCalculationResult(parent) {this.parent = parent;};
function Report(parent) {this.parent = parent;};
NeModel.prototype = {
	text	: {
		building : {
			 title : "Find din bolig"
			,intro_title: "Det eneste, vi skal bruge, er din adresse"
			,intro		: "Med Miljøberegneren kan du nemt, hurtig og enkelt se, hvor meget du potentielt kan spare på at miljøforbedre din bolig."
		}
		,building_result : {
			 firstchoice		: "-- Vælg en bolig --"
			,multiple_results	: "Vi har fundet flere bygninger på matriklen ud fra dine oplysninger. Vælg den bygning på listen du gerne vil beregne på."
			,no_result		: "Vi kan ikke hente oplysninger på den indtastede adresse. Har du indtastet korrekt adresse?"
			,appartment		: "Den indtastede adresse er et flerfamiliehus eller en bygning med lejligheder. Vær opmærksom på, at Miljøberegneren viser besparelsespotentiale for hele huset, og ikke den enkelte lejlighed." 
			,nothing_to_save_simple: "På baggrund af de oplysninger du har indtastet kan vi se, at du allerede har en god varmekilde i dit hus, og din bolig ser ud til at være rigtig godt isoleret."
		}
		,calculation_result	: {
			 switch_chart		:"Vis graf"
			,switch_map			:"Vis kort"	
		}
		,savingsbox : {
			 amount_title	: "Anslået økonomisk besparelse"
			,amount_unit	: " kr./år"
			,co2_title		: ["Anslået CO",SPAN({'class':"sub"},"2"),"-besparelse"]
			,co2_unit		: " ton/år"
			,invest_title	: "Estimeret investering"
			,invest_unit	: " kr."
		}
		,result : {
			 title			: "Resultat af miljøberegning"
			,sub_title		: "Er dine oplysninger korrekte?"
			,help_building	: "Byggeår og areal"
			,help_pri_src	: "Opvarmning"
			,help_sec_src	: ""
			,loan_leadin	: "Kan det betale sig at låne?"
			,help_insulation: "Isolering"
			,help_consumption: "Forbrug"
			,consumption_intro: "Miljøberegneren estimerer automatisk det årlige varmeforbrug. Hvis du kender dine omkostninger til det årlige varmeforbrug, kan du indtaste det for at få en mere præcis beregning."
		}
		,loancalc : {
			title		: "Låneberegning"
			,intro		: "Her er dit nye mulige lån"
			,intropara1 : "Du kan vælge mellem de forskellige låntyper ved at klikke på dem. Den månedlige fortjeneste vil så ændre sig i resultatfeltet. Du har også mulighed for at ændre det beløb, du ønsker at låne. Husk at trykke på 'Beregn igen', hvis du ændrer beløbet."
			,intropara2 : "Vær opmærksom på, at der kan være billigere alternativer end et Totalkredit-lån, hvis det drejer sig om et mindre beløb. Tal med din rådgiver i dit pengeinstitut."
			,intropara3 : "Nu, hvor du har tilpasset alle oplysningerne om din bolig og valgt den låntype, der passer dig, har du mulighed for at samle oplysningerne i en rapport, som du kan gemme, udskrive og sende til din rådgiver."
			,introstrong4: "Obs: "
                        ,intropara5 : "Det er i øjeblikket ikke muligt at beregne besparelsepotentialet på lån med variable renter"
			/*,intro2		: [ P({'class':"p_paragraph"},"Du kan vælge mellem de forskellige låntyper ved at klikke på dem. Den månedlige fortjeneste vil så ændre sig i resultatfeltet. Du har også mulighed for at ændre det beløb, du ønsker at låne. Husk at trykke på 'Beregn igen', hvis du ændrer beløbet.")
			         		   ,P({'class':"p_paragraph"},"Vær opmærksom på, at der kan være billigere alternativer end et Totalkredit-lån, hvis det drejer sig om et mindre beløb. Tal med din rådgiver i dit pengeinstitut.")
			         		   ,P({'class':"p_paragraph"},"Nu, hvor du har tilpasset alle oplysningerne om din bolig og valgt den låntype, der passer dig, har du mulighed for at samle oplysningerne i en rapport, som du kan gemme, udskrive og sende til din rådgiver.")
			         		  ]*/
		}
		,loanamountbox : {
			monthly		  : "Månedlig ydelse for lån (efter skat)"
			,monthlysavings : "Månedlig besparelse"
			,monthlyearnings: "Månedlig fortjeneste"
			,unit			  : " kr."
		}
		,loannotebox : {
			intro		  : "Følgende låntype er valgt til beregningerne: "
			,outtro 	  : "."
		}
		,resultbox : {
			simpletitle : "Resultat af simpel beregning"
			,simpletext : " "
			,advtitle	  : "Resultat af detaljeret beregning"
			,advtext	  : "Her kan du se den estimerede årlige besparelse - både økonomisk og i forhold til dit CO2-forbrug. For at opnå besparelsen kræver det, at du investerer i nedenstående miljøforbedringer af din bolig."
			,loantitle  : "Resultat af låneberegning"
			,loantext	  : " "
		}
		,report : {
			 intro	: "Sådan kommer du videre"
			,body 	:"Nu, hvor du har tilpasset alle oplysningerne om din bolig og valgt den låntype, der passer dig, har du mulighed for at samle oplysningerne i en rapport, som du kan gemme, udskrive og sende til din rådgiver."
		}
		,report_result : {
			 title			: "Rapport og kontakt"
			,headline		: "Vil du gøre din besparese til virkelighed?"
			,intro_overview : "Hvis du logger ind i 'Min boligmappe' til højre i skærmbilledet og gemmer rapporten, kan du sende den direkte til din rådgiver i pengeinstituttet og høre om dine muligheder under et uforpligtende møde."
			,intro		: [STRONG({'class':"ne-strong-title2"},"Vil du gøre din besparelse til virkelighed?")
							,BR()
							,BR()
							,P({'class':"p_paragraph"},"Her har du det fulde overblik over din mulige besparelse. Send rapporten direkte til din rådgiver, bestil et uforpligtende møde, og hør om dine muligheder. Husk, at du også kan gemme rapporten under 'Min Boligmappe'.")]
			,intro2		: [
								DIV({'style':"float:right;"},
										A({'href':"http://www.natur-energi.dk",'target':"_blank",'style':"text-decoration:underline",'class':"a_link"},
											IMG({'src':"/TKdk/resources/images/natur_logo.png",'width':"91",'height':"47",'alt':"Natur-Energi logo",'style':"border:0px"})
										)
								)
				         		,P({'class':"p_paragraph",'style':"display: block; width: 230px; padding-top: 9px;"}
									,"Besøg "
									,A( // privat/el-og-co2-beregner
										{'href':"http://www.natur-energi.dk",'target':"_blank",'style':"text-decoration:underline",'class':"a_link"},
										"natur-energi.dk"
									),", hvis du vil se, om du også kan spare på dit elforbrug."
										
								)
							]
			,reportbox_title: "Rapportens indhold"
		}
	}

	,label : {
		 street_name : "Vejnavn"
		,building_number : "Husnummer"
		,zip_code	: "Postnummer"
		,building_year	: "Byggeår"
		,total_area	: "Opvarmet areal"
		,built_up_area: "Grundareal"
		,primary_heat_source : "Primær varmekilde"
		,district_heat_provider	: "Varmeværk"
		,number_of_floors : "Antal plan"
		,heat_consumption: "Hvor meget bruger du årligt på varme (kr.)?"
		,heat_consumption_estimate: "Estimerede årlige varmeomkostninger (kr.)"
		,basement : "Krybekælder"
		,roof_type : "Tag"
		,primary_heat_source_installations_year : "Årgang"
		,primary_heat_source_energy_price : "Energipris"
		,secondary_heat_source : "Sekundær varmekilde"
		,number_of_persons : "Personer"
		,secondary_heat_source_installations_year : "Årgang"
		,secondary_heat_source_price : "Energipris"
		,secondary_heat_source_usage : "Brug af sekundær varmekilde"
		,roof_insulation : "Tag og lofter"
		,wall_insulation : "Ydermure"
		,windows : "Vinduer"
		,basement_insulation : "Krybekælder"
		,district:'Fjernvarme'
		,oil:'Oliefyr (eller anden flydende brændsel)'
		,natural_gas:'Naturgasfyr'
		,wood_pellets:'Træpillefyr'
		,woodburner:'Brændeovn'
		,heat_pump_air_water:'Varmepumpe (luft til vand)'
		,heat_pump_earth:'Varmepumpe (jordvarme)'
		,new_heat_source_none:'Ingen udskiftning'
		,electric_heating:'Elvarme'
		,gas_heaters:'Gasradiator'
		,loan_amount : "Lånebeløb"
		,insulation_table_warning : "De elementer, der er en økonomisk fordel i at udskifte, er markeret med flueben nedenfor."
		,insulation_table_empty : "Der er ikke muligt af efterisolere din bolig yderligere."
	}
};
State.prototype = {
	init : function() {
		this.parent.current_state = 'init';

		//facebook
		this.parent.facebookenabled=true; //flag for enabling facebook functionality
		this.hascalc=false;	
		this.fbconnected=false;
		
		//determine if calculator is being embedded
		this.parent.externalviewer=false;
		this.parent.extid = parseQueryString(document.location.search).extid;
		if (this.parent.extid){
			this.parent.externalviewer = true;
		}
		if (mbShowAlternate()){
        	//test if showing alternate version	
        	this.parent.ab_tester = 'B';	
        }    
        this.parent.init.clean();
		
		//page text for first step
		jsonRequest({"key":"pagetxt.necalc.intro"}, bind(
			function(request) {
				this.parent.init.build(request);
				this.parent.init.fill();
				var data = parseQueryString(document.location.search).data;
				var hasdata = false;
				if (data) {
					var splited_data = data.split(',');
					//check if string is urlencoded:
					var street_name = splited_data[0];
					if(street_name.indexOf("%")>-1){
						log("starting to unescape");
						street_name=unescape(street_name);
						log("unescaped: "+street_name);
					}		
					$("street_name").value = street_name;
					$("building_number").value = splited_data[1];
					$("zip_code").value = splited_data[2];
					this.parent.init.process();
					hasdata = true;
				}
				nestat(NESTAT_STEP_INIT, this.parent, {hasdata:hasdata});
				
			}
		,this),"help");
		
		json(
			"page",
			{'pageId':397}, 
			bind(
				function(result){
					var back1 = INPUT({'id':"backrules",'type':"button", 'value':"Tilbage",'onclick':"return ne_model.dom.hideRules();",'style':"float: right; margin-right:0; height: 17px;",'class':"submit"});
					$("page").innerHTML = result.contents;
					if (!$('backrules')) appendChildNodes("page", back1, BR());
				} 
				
			, this)
		);
		
	}
	,validation_step : function() {
		this.clear('validation_step');
		
		this.parent.validation_step.clean();
		this.parent.validation_step.build();
	}
	,simple_calculation : function() {
		this.clear('simple_calculation');
		
		this.parent.building.clean();
		
		if(this.parent.savedcalc){
			//do something smart here
			this.parent.building.build();
			this.parent.building.fill();
			this.parent.savedcalc==false;
		}else{	
			jsonRequest(
				{"building_id": this.parent.calculation.building.id, 'zip_code':this.parent.calculation.building.zipCode}
				,bind(
					function(result) {
						this.parent.calculation.result = result;
						this.parent.hascalc=true;
						this.build();
						this.fill(); 
						if (this.parent.ab_tester = 'A') nestat(NESTAT_STEP_CALC, this.parent, {result:result});
					}, this.parent.building
				)
				,"ne/simpleCalculation"
			);
		
		}
	}
	,simple_recalculation : function() {
		this.clear('loan_calculation');
	}
	,loan_calculation : function() {
		this.clear('loan_calculation');
	
		this.parent.loan_calculation.clean();
		this.parent.loan_calculation.build();
		this.parent.loan_calculation.fill();
		this.parent.loan_calculation.validate_result();
	}
	,loan_calculation_result : function() {
		this.clear('loan_calculation_result');
		this.parent.loan_calculation_result.build();
		jsonRequest(
			{'amount':parseInt($('loan_amount').value)}
			,bind(
				function(response) {
					this.parent.calculation.loan = response;
					this.fill();
				}
				,this.parent.loan_calculation_result
			)
			,"new_simple_calculation"
		);
	}
	,report_generation : function() {
		gstatNecalc(); //conversion track
		this.clear('report_generation');
		this.parent.report.build();
		
	}
	
	,clear : function(state) {
		this.parent.current_state = state;
		forEach(this.parent.elements[state], function(e){if ($(e)) removeElement(e);});
	}
};
DOM.prototype = {
	 icon_arrow_white_up : "resources/images/arrow_up_white_icon.gif"
	,icon_arrow_white_down : "resources/images/arrow_down_white_icon.gif"
	,class_block_hidden : "block-hidden"
	,class_block_visible : "block-visible"
	,class_table_visible : "table-visible"
	,class_tr_visible: "tr-visible"
	,class_closed : "closed"
	,block_notification_area : "notification-area"
	,header_id_link : function(id) { return id+"-link";}
	,header_id_img : function(id) { return id+"-img";}
	,header_id_h2 : function(id) { return id+"-header";}
	,form_id_error : function(id) { return id+"-error";}
	,form_id_help : function(id) { return id+"-help";}
	
	,header : function(title, childNode) {
		var span = SPAN();
		span.innerHTML = title;
		var id = childNode.id;

		var link = 
			A({'id': this.header_id_link(id), 'href': "#"}
				,IMG({'id': this.header_id_img(id), 'src': this.icon_arrow_white_up})
				,span
			);
		connect(link, "onclick", bind(this.collapseBox, this, id));
		
		return [
			 H2({'id':this.header_id_h2(id)}, link)
			,childNode
		];
	}
	,collapseBox : function(id) {
		this.switchBlockVisibility(id);
		addElementClass(this.header_id_h2(id), this.class_closed);
		
		$(this.header_id_img(id)).src = this.icon_arrow_white_down;
		
		var a = $(this.header_id_link(id));
		disconnectAll(a);
		connect(a, "onclick", bind(this.expandBox, this, id));
		return false;
	}
	,expandBox : function(id) {
		this.switchBlockVisibility(id);
		removeElementClass(this.header_id_h2(id), this.class_closed);
		
		$(this.header_id_img(id)).src = this.icon_arrow_white_up;
		var a = $(this.header_id_link(id));
		disconnectAll(a);
		connect(a, "onclick", bind(this.collapseBox, this, id));
		return false;
	}
	/*,NEMessageBox : function(elem, lblinput, message, callback,optsrc) {
		var form = FORM({},
			DIV(
				null,
				INPUT({
					'type'		:"text",
					'id'		:"name"
				}),
				LABEL(null,lblinput),
				BR()
			),
			DIV(null,
				INPUT({'type':"submit",'value':"Gem",'class':"submit"}),
				INPUT({'type':"button",'value':"Anullér",'class':"submit",'onclick': "removeElement('calc_name') ;return false;"}),
				SPAN({'class':"error",'id':"calc_name_error"})
			)
		);
		connect(form, 'onsubmit', callback);
		
		var div = DIV({'id':"calc_name",'style':'height:88px'},
			DIV({'class':"inside",'style':'height:86px'}
				,DIV({'style':'font-family:verdana;font-size:10;margin:2px'},message)
				,form
			),
			DIV(null,
				IMG({
						'style'	:"width: 305px; height: 3px;" ,
						'src'	:"/TKdk/resources/images/bottum_shadow.gif"
					}
				)
			)
		);
		var pos = findPos(elem);
		div.style.left = pos[0] + elem.offsetWidth - 312;
		div.style.top  = pos[1] + elem.offsetHeight - 50;
		if (optsrc){
			appendChildNodes(form,INPUT({'type':"hidden",'value':""+optsrc,'id':"optsrc"}));
		}
		
		appendChildNodes('main', div);
		return false;
	}
	*/	
	,appendChildNodes : function(node, tellafriend) {
		if (tellafriend) {
			this.tellafriend = tellafriend;
			appendChildNodes("necalculation", tellafriend);
		}
		if (this.tellafriend) {
			insertSiblingNodesBefore(this.tellafriend, node);
		} else {
			appendChildNodes("necalculation", node);
		}
	}
	,hideBlock : function(id) {
		removeElementClass(id, this.class_block_visible);
		removeElementClass(id, this.class_table_visible);
		removeElementClass(id, this.class_tr_visible);
		addElementClass(id, this.class_block_hidden);
	}
	,showBlock : function(id) {
		removeElementClass(id, this.class_block_hidden);
		if ($(id).nodeName == 'TBODY') {
			addElementClass(id, this.class_table_visible);
		}else if ($(id).nodeName == 'TR'){
			//log("TR found, id: "+id);
			addElementClass(id, this.class_tr_visible);
		}else {
			addElementClass(id, this.class_block_visible);
		}
	}
	,switchBlockVisibility : function(id, action) {
		if (hasElementClass(id, this.class_block_visible) || hasElementClass(id, this.class_table_visible) || (action && action == 'hide')) {
			this.hideBlock(id);
		} else {
			this.showBlock(id);
		}
	}
	/** 
	 * All labels are stored in object label [this.parent.label] with pattern:
	 * label.[CURRENT-STATE].[ID] e.g. label.building.zip 
	 */
	,label : function(id) {
		return LABEL({}, this.parent.label[id]);
	}
	,input_text : function(id, cssClass, value) {
		return [
			,this.label(id)
			,INPUT({
				 'type': "text"
				,'id': id
				,'name': id
				,'class': "nec-text " + cssClass
				,'value': (value) ? value : ''
			})
			,this.help_icon(id)
		];
	}
	,input_select : function(id, cssClass) {
		return [
	        ,this.label(id)
	        ,SELECT({
        		'id': id
        		,'name': id
	        })
	        ,this.help_icon(id)
        ];
	}
	,show_notification : function(id) {
		$(this.form_id_help(id)).style.visibility = 'visible';
	}
	,hide_notification : function(id) {
		try{
			$(this.form_id_help(id)).style.visibility = 'hidden';
		}catch(e){
			
		}
	}
	,getIconText : function(id,icon,text,onclick, style) {
		//exclamation,print,save,person,calc
		return DIV({'id':id,'class':"ne-iconelement",'style':style}
				,DIV({'class':"ne-icon ne-icon-"+icon})
				,DIV({'class':"ne-icontext"}
					,A({'href':"#",'onclick':onclick}, text)
				)
		);
	}
	,saveCalculation : function(elem) {
		if (myplanner.isLogged()){
			if (!this.parent.calculation) {
				showError(elem, "error.necalc.nocalc");
			} else {
				messageBox(elem,"Navngiv beregningen: ", bind(this.saveCalculationCallback,this));
			}
		}else{
			showError(elem, "error.necalc.notlogged");
		}	
		return false;
	}
	,saveCalculation : function(elem) {
		if (myplanner.isLogged()){
			if (!this.parent.calculation) {
				showError(elem, "error.necalc.nocalc");
			} else {
				messageBox(elem,"Navngiv beregningen: ", bind(this.saveCalculationCallback,this));
			}
		}else{
			showError(elem, "error.necalc.notlogged");
		}	
		return false;
	}
	,restoreSavedCalc : function(result){
		this.parent.calculation=result;
		this.parent.savedcalc=true;
		if (!$('necalculation')){
			/*ne_model.init.clean();
			ne_model.init.build(result);
			*/
			ne_model.state.init();
			this.parent.calculation=result;
			this.parent.savedcalc=true;
		}
		//determine where to go from here
		var gotostate=result.laststate;
		
		 necallback=function(gotostate){
			if (gotostate=="loan_calculation" && !ne_model.calculation.loan) gotostate="simple_calculation";
			if (gotostate=="report_generation"){
				 //gotostate="simple_calculation";
				ne_model.state["simple_calculation"]();
				ne_model.state["loan_calculation"]();
				//ne_model.state["report_generation"]();
			}else{	
				//log("going to: "+gotostate);
				ne_model.state[gotostate]();
			}
		};
		callLater(3,necallback,gotostate);
			
	}
	,saveCalculationCallback : function(e) {
		e.stop(); //stop propagation
		try {
			ADFtrack(7642,28993); //gem i boligmappe
		} catch (E) {}
		
		//need these to restore it again
		if (!this.parent.calculation.type)this.parent.calculation.type="ne_model";
		this.parent.calculation.laststate=this.parent.current_state;
		
		this.saved=true;
		
		//log($('name').value);
		var d = doXHR(
			 "page?action=user.save.calculation&method=json&name=" + urlEncode($('name').value)
			,{
				 'method'		: "POST"
				,'sendContent'	: serializeJSON(this.parent.calculation)
			}
		);
		d.addCallback(bind(myplanner.refresh, myplanner));
		//this.saved = true;
		
		removeElement('calc_name');
	
		return false;
	
	} 
	,envFooter : function(id,headline,calculation,extra_links) {
		if (this.parent.externalviewer){
			return DIV({'id':"nefooter"}
				,this.getIconText('ne_icon_top','calc','Til toppen','$("mainheader").scrollIntoView(true); return false;')
				//,this.getIconText('ne_icon_print','print','Udskriv','print(); return false')
				,DIV({'style':"margin-left:140px;"}
					,this.getIconText('ne_icon_rights','exclamation',"Vilkår & forbehold for beregning",'necalc.showRules()')
				)
			);
		}else{
			return DIV({'id':"nefooter"} 
				,DIV({'style':"width: 500px"}
					,this.getIconText('ne_icon_top','calc','Til toppen','$("mainheader").scrollIntoView(true); return false;')
					,this.getIconText('ne_icon_contact','person','Kontakt rådgiver','necalc.contactAdvisor(this);return false;')
					,this.getIconText('ne_icon_save','save','Gem i boligmappe','ne_model.report.saveCalculation(this);return false;')
				)
				,this.getIconText('ne_icon_print','print','Udskriv','tstatPrint();print();return false')
				,DIV({'style':"width: 500px"}
					,this.getIconText('ne_icon_rights','exclamation',"Vilkår & forbehold for beregning",'ne_model.dom.showRules()','width: 340px; float: right;')
				)
			);
		}
	}
	,showRules : function(){
		/*try {
		ADFtrack(7642,28994);
		} catch (E) {}
		*/
		setStyle("necalculation",{'display':'none'});
		setStyle("nefooter",{'display':'none'});
		setStyle("page",{'display':'block'});
		
		$("mainheader").innerHTML = "Betingelser og forbehold";
		//connect(elem,"onclick",bind(this.hideRules,this));
		return false;
	}
	,hideRules : function(){
		$("mainheader").innerHTML = "Miljøberegneren";
		setStyle("necalculation",{'display':'block'})
		setStyle("nefooter",{'display':'block'});
		setStyle("page",{'display':'none'})
		return false;
	}  
	,build_notification : function(id) {
		disconnectAll(id);
		disconnectAll(id+"-div");
		connect(id+"-div", 'onmouseenter', bind(this.show_notification, this, id));
		connect(id, 'onfocus', bind(this.show_notification, this, id));
		connect(id+"-div", 'onmouseleave', bind(this.hide_notification, this, id));
		connect(id, 'onblur', bind(this.hide_notification, this, id));
	}
	,img_src_help : function(id) {
		partial(this.img_src, "resources/images/white_help.gif")(id);
	}
	,img_src_error : function(id) {
		partial(this.img_src, "resources/images/warning_icon2.gif")(id);
	}
	,img_src_loader : function(id) {
		partial(this.img_src, "resources/images/loader.gif")(id);
	}
	,getVal : function(elem_id){
		//this method was made just for select but expand it if needed
		var elem=$(elem_id);
		
		if (elem){
			if (elem.type=="select-one") return elem.options[elem.selectedIndex].value;
		}else{
			return "";
		}
	}
	,img_src : function(path, id) {
		$(id).src = path;
	}
	/**
	 * help key pattern: necalc-[CURRENT-STATE]-[ID]-help
	 */
	,help_icon : function(id) {
		var img =  IMG({
			 'src': "resources/images/white_help.gif"
			,'class': 'no_print nec-help-icon'
			,'id': this.form_id_help(id)
		});
		connect(img, "onclick", bind(showHelp, this, img, "necalc-" + this.parent.current_state + "-" + this.form_id_help(id)));
		return img;
	}
	/**
	 * error key pattern: necalc-[CURRENT-STATE]-[ID]-error
	 */
	,error_icon : function(id) {
		var img = IMG({
			 'src': "resources/images/warning_icon2.gif"
			,'class': "hidden nec-error-icon no_print"
		});
		connect(img, "onclick", bind(showError, this, img, "necalc-" + this.parent.current_state + "-" + this.form_id_error(id)));
		
		return img;
	}
	,step_footer : function() {
		return DIV({'class':"ne-footer"});
	}
	,centeredSelectBox : function(id, clazz) {
		return DIV({'id': id+ '-div', 'class':clazz}
			,DIV({'class':"nec-centered-input"}
				,this.label(id)
				,this.help_icon(id)
			)
			,SELECT({'id':id,'name':id})
		);
	}
	,verticalSelectBox : function(id, clazz) {
		return DIV({'id': id+ '-div', 'class':clazz}
			,this.label(id)		
			,this.help_icon(id)
			,SELECT({'id':id,'name':id})
		);
	}
	,verticalInputBox : function(id, divClass, inputClass) {
		return DIV({'id': id+ '-div', 'class':divClass}
			,this.label(id)
			,this.help_icon(id)
			,INPUT({'name':id,'id':id,'type': "text", 'class': "nec-text " + (inputClass == undefined ? '' : inputClass)})
		);
	}
	,show_hide_on_value : function(field_id, when, to_hide, and) {
		connect(field_id, "onchange",
			bind(function(id, when) {
				if (($(field_id).value == when) == and) {
					this.showBlock(id);
				} else {
					this.hideBlock(id);
				}
			},
			this, to_hide, when
			)
		);
		signal(field_id, "onchange");
	}
	,hidden : function(name) {
		return INPUT({'type':"hidden",'id':name,'name':name,'value':''});
	}
	,clear : function() {
		return DIV({'class':"clear"});
	}
};
Init.prototype = {
	 clean : function() {
	 	// update topbanner
		thepage.changeBanner("resources/flash/test_nebanner.swf");
		
		replaceChildNodes("mainpage", 
			 H1({'id':"mainheader",'class'	:"nec-fullheader"}, "Miljøberegneren")
			,DIV({'id':"necalculation"})
			//,necalc.envFooter()
			,this.parent.dom.envFooter()
			,DIV({'id':"page",'style':'display:none;margin-top:0;padding-top:3px','class':"ne-page"})
		);
	}
	,build : function(body) {
		this.parent.dom.appendChildNodes(
			this.parent.dom.header(
				 this.parent.text.building.title
				,FORM({'id':"common-address",'class':"block-visible nec-main-background nec-main-border","onsubmit":"return false;"}
					//building icon
					,DIV({'class':"nec-content-image-building"})
					// intro text
					,DIV({'class':"nec-tb-margin12"}
						,STRONG({'class':"ne-strong-title nec-lr-margin9"}, this.parent.text.building.intro_title)
					)
					/*
					,IFRAME({
					'src'			: base_path+"flash/background_greenstarter.swf",
					'frameBorder'	: 0,
					'width'			: "1px",
					'height'		: "1px",
					'style'			: "z-index: -1;width:1px;height:1px"
					})*/
					,DIV({'class':"nec-lr-margin9"}
						,P({'class':"p_paragraph"}, this.parent.text.building.intro)
					)
					// form
					,DIV({'class':"nec-lr-margin9 nec-tb-margin9"}
						,DIV({'id':"street_name-div",'class':"float-box",'style':"width: 175px;"},this.parent.dom.input_text("street_name", "nec-triple-width"))
						,DIV({'id':"building_number-div",'style':"_width: 150px; width: 145px; margin-left: 10px; margin-right: 10px;",'class':"float-box"},this.parent.dom.input_text("building_number", "nec-single-width")) //horizontal glue
						,DIV({'id':"zip_code-div",'class':"float-box",'style':"width: 145px;"},this.parent.dom.input_text("zip_code", "nec-single-width"))
						,this.parent.dom.clear()
					)
					,DIV({'class':"nec-lr-center-tb-margin9 nec-double-height"}
						,INPUT({'type':"submit","class":"ne-button-address", 'value':"", 'style':"margin-right: 9px;"})
					)
					,DIV({'class':"nec-dot-line nec-tb-margin9 nec-lr-margin9"})
					// notification area
					,DIV({'id':this.parent.dom.block_notification_area, 'class': "nec-building-notification-area block-hidden"})
					// description
					,DIV({'class':"nec-lr-margin9"}
						,P({'class':"p_paragraph"}, this.buildBbDom(body))
					)
					,SPAN({'id':"greenstarter"})
					,this.parent.dom.step_footer()
				)
			),
			this.tellAFriendBanner()
			
		);
		
		//if tellafriendbanner adds any facebook elements
		try{
			FB.XFBML.Host.parseDomTree();
		}catch(E){} 	
		
		
		// update background
		if (this.parent.changeBackground) {
			try {
				// embed new flash that localconnects and runs green anim
				var so = new SWFObject(base_path+"flash/background_greenstarter.swf", "flash_green_starter", "1", "1", "0", "#FFFFFF");
				
				so.addParam("wmode", "transparent");
				so.write("greenstarter");
			} catch (e) {
				// ignore
		
			}
		}
		
		this.parent.dom.build_notification('street_name');
		this.parent.dom.build_notification('building_number');
		this.parent.dom.build_notification('zip_code');
		//thepage.updateLocation("Miljøberegner", "ne.calculation");
		connect($("common-address"), "onsubmit", bind(this.process, this));
	}
	,fill : function() {
	}
	,process : function() {
		var args = {};
		var form_data = formContents('common-address');
		for (var i = 0; i< form_data[0].length; i++) {
			args[form_data[0][i]] = form_data[1][i];
		}
		jsonRequest(
			args
			,bind(this.validate_result, this)
			,"ne/requestBuildings"
		);
		return false;
	}
	,validate_result : function(result) {
		var buildings = result.buildings2;
		this.parent.loltest=buildings;
		
		jsonRequest({}, function(e){}, "simple_hit");
		
		if (result.count == 0 || buildings == undefined) {
			//no result
			this.showBuildingNotification(this.parent.text.building_result.no_result);
		}else if(result.count ==1 && buildings[0].numHousingUnits>1){ 
			//appartment or similar
			this.showBuildingNotification(this.parent.text.building_result.appartment);
			this.parent.calculation.building = buildings[0];
			this.parent.appartment=true;
            this.parent.state.simple_calculation();
		}else if (result.count==1) {
			//one result, continue
			this.parent.calculation.building = buildings[0];
            this.parent.state.simple_calculation();
		} else {
			//multiple, allow user to pick
			var select = SELECT({'style': "width: 464px;"} //XXX css class
					,OPTION({'value':"INGEN"}, "-- Vælg venligst --")
					,map(function(b) {
						return OPTION({'value':serializeJSON(b),'data':b.id}, b.street+" "+b.number+", "+b.inhabitedArea+"m²");
					}
						,buildings
					)
			);
			connect(select, "onchange", bind(
				function(ev) {
					var tempoption=ev.src().options[ev.src().selectedIndex];
					var data=tempoption.value;
					log("data: "+data);
					this.parent.calculation.building = evalJSON(data); 
					this.parent.state.simple_calculation(); 
				}, this.parent));
			this.showBuildingNotification([this.parent.text.building_result.multiple_results, select]);
		}
	}
	,buildBbDom : function(body) {
		var text = body.result.replace(/[\r\n]/, "");
		var texts = [];
		var nelogo = 
			DIV(
				{'style':"float:right;"},
				A({'href':"http://www.natur-energi.dk",'target':"_blank",'style':{'text-decoration':"underline",'class':"a_link"}},
					IMG({'src':"/TKdk/resources/images/natur_logo.png",'width':"91",'height':"47",'alt':"Natur-Energi logo",'style':{'border':"0px"}})
				)
			);
		var flow = DIV({'class':"nec-lr-center-tb-margin9"}, IMG({'src':"/TKdk/resources/images/ne-icon.png",'alt':"Miljøberegner flow"}));
		var nelink = [" ", A({'href':"http://www.natur-energi.dk",'target':"_blank",'style':{'text-decoration':"underline"},'class':"a_link"},"Natur-Energi")];
		var m;
		while(m = text.match(/\[(br|nelogo|flow|nelink|h2)\]/i)) {
			var end = m.index+m[0].length;
			texts.push(text.substring(0,m.index).trim());
			switch (m[1].toLowerCase()) {
			case "br":		texts.push(BR());	break;
			case "nelogo":	texts.push(nelogo);	break;
			case "nelink":	texts.push(nelink);	break;
			case "flow":	texts.push(flow);	break;
			case "h2":
				// special case, find [/h2] and handle what's in-between
				var h2end = text.toLowerCase().indexOf("[/h2]",end);
				if (h2end != -1) {
					texts.push(STRONG({},text.substring(end, h2end)));
					texts.push(BR());
					end = h2end + "[/h2]".length;
				}
				break;
			}
			text = text.substring(end);
		}
		texts.push(text);
	
		return texts;
	}
	
	,showBuildingNotification : function(body) {
		replaceChildNodes(this.parent.dom.block_notification_area
			,DIV({'class': "nec-building-notification-message"}
				,IMG({'src': "resources/images/warning_icon2.gif"})
				,body
			)
		);
		this.parent.dom.switchBlockVisibility(this.parent.dom.block_notification_area);
	}
	,showBuildingNotification2 : function(body) {
		
	}
	,tellAFriendBanner : function() {
		//banner in bottom of each page
		if (this.parent.externalviewer)	return;
		
		//Image and tell a friend link
		var tellAFriend = IMG({'src':"/TKdk/resources/images/ne-tell-friend2.gif",'style':"border: 0 none; width: 307px;height:59px"});//old width 503px
		
		if (this.parent.facebookenabled){
			doFbInit();
			//make a container for tell a friend and fb connect link
			var fbconlink=A({'id':"fbconnlink",'href':"#",'onclick':"doFbAction();",'class':"fb_connect_link"},"Vis på Facebook");	
			var friendlink=A({'href':"#",'style':"border: 0 none;margin-top:12px",'class':"mb_tipfriend_link",'id':"ne-tell-a-friend"},"Tip en ven");
			connect(friendlink, "onclick", bind(this.neshowTellAFriend, this, tellAFriend, 'ne.calculation', 'Miljøberegner', false));
			var linkdiv = DIV({'id':"fblinkdiv",'style':"float:right;width:180px;"},friendlink,fbconlink);
			return DIV({'class':"green-border",'id':"facebookcontainer",'style':"border-top: 0px; border-bottom: 4px solid #A4BF7A;"},linkdiv,tellAFriend);
		}else{
			//make a container with only tell a friend
			var friendlink=A({'href':"#",'style':"border: 0 none;margin-top:0",'class':"mb_tipfriend_link",'id':"ne-tell-a-friend"},"Tip en ven");
			connect(friendlink, "onclick", bind(this.neshowTellAFriend, this, tellAFriend, 'ne.calculation', 'Miljøberegner', false));
			var linkdiv = DIV({'style':"float:right;width:180px;margin-top:22px"},friendlink);
			return DIV({'class':"green-border",'id':"facebookcontainer",'style':"border-top: 0px; border-bottom: 4px solid #A4BF7A;"},linkdiv,tellAFriend);
		}	

		
	}
	,neshowTellAFriend : function(elem,id,headline,top,event) {
		//messagebox for tell a friend
		showTellAFriend(elem,id,headline,top, true);
		$('tcontent').value = 'Jeg har lige været forbi Totalkredits hjemmeside og prøvet Miljøberegneren - et redskab, som på få minutter viser, om det kan betale sig at miljøforbedre sit hus. Og ofte er der penge at spare.\nMåske er Miljøberegneren også interessant for dig at prøve? Klik her: \nhttp://' + (document.location.host + document.location.pathname + document.location.hash.replace(/#/,'?'));
		event.stop(); 
	}
};

Building.prototype = {
	 clean : function() {
		this.parent.dom.switchBlockVisibility(this.parent.dom.block_notification_area, 'hide');
	}
    // Fake validation submit for A/B tester
    ,validate_info_submit : function() {
        // Unhide step 2
        removeElementClass($("adv-calc-step2"), "display-hidden");
        removeElementClass($("adv-calc-step2-header"), "display-hidden");

        // Collapse step1 (step 2 is expanded per default)
        this.parent.dom.collapseBox("adv-calc-step1");
      	
        if (this.parent.ab_tester = 'B' || !this.parent.ab_tester) nestat(NESTAT_STEP_CALC, this.parent, {result:ne_model.calculation.result});
		ne_model.building.generateMap($('google-map'),ne_model.calculation.building.latitude,ne_model.calculation.building.longitude);
		
        return false;
    }
	,build : function(result) {
        // Lookup A/B mode in querystring
        var querystring = parseQueryString(window.location.search.substring(1));
        if ( querystring['mode'] ) {
            this.parent.ab_tester = 'B';
        }else{
            	
        }

		this.parent.dom.collapseBox("common-address");
		var switch_link = A({'id':"switch_link",'href':"#",'class':"a_link"},this.parent.text.calculation_result.switch_chart);
		connect(switch_link, "onclick", bind(this.switchMapChart, this));
		var amount_title = SPAN();

        var savings_overview = DIV({'id':"savings-overview"}
		 	//chart
	 		,this.generateChart(
 				 "google-chart"
		 		,this.parent.calculation.result.response.savings_out
 				,this.parent.calculation.result.response.co2_reduction_out
 				,parseInt(this.parent.inflation)
	 		)
	 		//google map
		 	,DIV({'id':"google-map",'class':"nec-small-box nec-float-left nec-margin-small-left block-visible"})
	 		//switch google map / chart
		 	,DIV({'class':"ne-show-chart"}, switch_link)
		 	// saving box
		 	,DIV({'class':"nec-obg-stripes-background nec-result-box nec-float-left nec-margin-small-right", "style":"margin-top: 5px;"}
	 			,DIV({'class':"nec-stripes-small"}
	 				,DIV({'class':"ne-help-icon-orange",'onclick':"return showHelp(this, 'help.encalc.savingsbox.saving');"})
	 				,this.parent.text.savingsbox.amount_title
	 			)
	 			,DIV({'class':"nec-stripes-large"}
	 				,SPAN({'id':"savingsbox-amount"})
	 				,SPAN({}, this.parent.text.savingsbox.amount_unit)
	 			)
	 			,DIV({'class':"nec-stripes-small"}
	 				,DIV({'class':"ne-help-icon-blue",'onclick':"return showHelp(this, 'help.encalc.savingsbox.co2');"})
	 				,this.parent.text.savingsbox.co2_title
	 			)
	 			,DIV({'class':"nec-stripes-large"}
	 			,SPAN({'id':"savingsbox-co2"})
 				,SPAN({}, this.parent.text.savingsbox.co2_unit)
	 			)
	 			,DIV({'class':"nec-stripes-small"}
	 				,DIV({'class':"ne-help-icon-gray",'onclick':"return showHelp(this, 'help.encalc.savingsbox.investments');"})
	 				,this.parent.text.savingsbox.invest_title
	 				)
	 			,DIV({'class':"nec-stripes-large"}
		 			,SPAN({'id':"savingsbox-invest"})
	 				,SPAN({}, this.parent.text.savingsbox.invest_unit)
	 			)
	 		)
            ,HR({'class':"ne-separation-line",'style':"float:left;"})
		);

        var savings_options = DIV({'class':"nec-lr-margin9"},
            this.insulationTable(),
            this.heatSourceTable(),
            TABLE({'class':"insulation_table", 'cellpadding':"0", 'cellspacing':"0",'style':"width:478px"},THEAD({}), TBODY({},
                TR({'class':"gray"}, TD({'class':"table_heats_name"}, "Estimeret investering i alt"), TD({'class':"table_heats_icon"}), TD({'class':"table_heats_value"}, SPAN({'id':"tablesavings-invest"})," kr.")),
                TR({'class':"orange"}, TD({'class':"table_heats_name"}, "Besparelse"), TD({'class':"table_heats_icon"}), TD({'class':"table_heats_value"}, SPAN({'id':"tablesavings-amount"}), " kr.")),
                TR({'class':"blue"}, TD({'class':"table_heats_name"}, "CO",SPAN({'class':"sub"},"2"), "-besparelse"), TD({'class':"table_heats_icon"}), TD({'class':"table_heats_value"}, SPAN({'id':"tablesavings-co2"}), " ton/år"))
            )),
            this.parent.dom.clear()
        );

        // Button that calls the fake validation step
        var validation_button = ( this.parent.ab_tester == 'A' ) ? []
            : [
                
                DIV({'class':"ne-validate-info-arrow-box"},
                   DIV({'class':'ne-validate-info-arrow-box-inner'},"Miljøberegneren er ved at foretage beregningen. Beregningen er baseret på den information om boligen, der er tilgængelig i Bygnings- og Boligregistret (BBR). Denne information kan være forældet,  hvis der er foretaget ændringer af boligen. Derfor får du den mest korrekte beregning ved at tilrette ovenstående oplysninger om boligen.")
                ),
                INPUT({
                    'id':"validate-info",
                    'class':"ne-button-validate-info",'style':"margin-bottom:5px; float: right;",
                    'type':"submit",
                    'onclick':'ne_model.building.validate_info_submit();return false;',
                    'value':""
                })
            ];

        // The bottom of the "Building" step
        var building_footer = ( this.parent.ab_tester == 'A' )
            ? [
                savings_options,
                INPUT({'name':"zip_code", 'id':"hidden_zip_code", 'type':"hidden"}),
                DIV({'style':"float: left;margin: 16px 16px 0 30px;"}, STRONG({'class':"ne-strong-title",'style':"width: 240px; height: 25px;margin:0"},this.parent.text.result.loan_leadin)),
                INPUT({'type':"submit",'id':"addr_sub",'class':"ne-button-advanced-calc",'style':"margin-bottom:5px", 'value':""}),
            ]
            : [
            ];

        var step1 = DIV({id:"advanced-calculation-step1"}
    		 	,H2({'class':"result",'id':"calculation-result-title"})
    		 	,DIV({'id':"ne-calc-message",'style':"float:none;margin-left:60px"})
                ,( this.parent.ab_tester == 'A' ) ? savings_overview : []
    			,DIV({'class':"nec-content-image-calc"})
    			,DIV({'id':"calculation-advanced-form"}
    				,DIV({'class':"margin-lrtb-wide",'style':"margin-right:40px"}
					
    					,DIV({'class':"nec-lr-tb-margin9 nec-triple-height"}
    						,STRONG({'class':"ne-strong-title"}, this.parent.text.result.sub_title)
						
    					)
				
    					,DIV({'class':"highlight"}, this.parent.text.result.help_building)
    					,DIV({}
    						,DIV({'class':"float-box-half", 'style':"width:146px;margin-right:12px"}
    							,DIV({'id':"building_year-div",'class':"float-box",'style':"_margin-top: 6px;"}, this.parent.dom.input_text("building_year", "nec-single-width"))
    							,DIV({'id':"total_area-div",'class':"float-box",'style':"_margin-top: 6px;"}, this.parent.dom.input_text("total_area", "nec-single-width"))
    							//,DIV({'id':"built_up_area-div",'class':"float-box",'style':"_margin-top: 6px;"}, this.parent.dom.input_text("built_up_area", "nec-single-width"))
    							,this.parent.dom.hidden("built_up_area")
    							,this.parent.dom.clear()
    						)
    						,DIV({'class':"float-box-half", 'style':"width:240px;"}
    							,DIV({'id':"roof_type-div",'class':"float-box"}, this.parent.dom.input_select('roof_type', 'ne-vertical-box roof-fix-width'))
    							,DIV({'id':"number_of_floors-div",'class':"float-box"}, this.parent.dom.input_select('number_of_floors', 'ne-vertical-box'))
    							,DIV({'id':"basement-div",'class':"float-box"}, this.parent.dom.input_select('basement', 'ne-vertical-box nec-lr-margin9'))
    							,this.parent.dom.clear()
    						)
    						,this.parent.dom.clear()
    					)
    					,DIV({'class':"nec-dot-line nec-tb-margin9"})
    					,DIV({'class':"highlight"}, this.parent.text.result.help_pri_src)
    					,DIV({'class':"nec-lr-center-tb-margin9 nec-triple-height"}
    						,this.parent.dom.verticalSelectBox('primary_heat_source', 'ne-vertical-box')
    						,this.parent.dom.verticalInputBox('primary_heat_source_installations_year', 'ne-small-vertical-box nec-lr-margin2','nec-double-width')
    						,DIV({'id': "primary_heat_source_energy_price-div", 'class': "ne-small-vertical-box", 'style':"width: 125px;"}
    							,this.parent.dom.label("primary_heat_source_energy_price")
    							,this.parent.dom.help_icon("primary_heat_source_energy_price")
    							,DIV({'style':"float: left;"}//margin-top: 3px;
    								,INPUT({'id':"primary_heat_source_energy_price",'name':"primary_heat_source_energy_price",'type': "text", 'class': "nec-text nec-double-width"})
    								,SPAN({'id':"primary_heat_source_energy_unit", 'class':"nec-input-block"}, "")
    							)
    						)
    						,this.parent.dom.clear()
    					)
    					,this.parent.dom.verticalSelectBox('district_heat_provider', 'ne-vertical-box nec-triple-height no-float')
    					,DIV({'class':"highlight"}, this.parent.text.result.help_sec_src)
    					,DIV({'class':"nec-lr-center-tb-margin9  nec-triple-height"}
    						,this.parent.dom.verticalSelectBox('secondary_heat_source', 'ne-vertical-box')
    						//,this.parent.dom.verticalInputBox('secondary_heat_source_installations_year', 'ne-small-vertical-box nec-lr-margin9','nec-double-width')
    						,this.parent.dom.verticalInputBox('number_of_persons', 'ne-small-vertical-box nec-lr-margin2 ne-small-wider','nec-double-width nec-t-margin5')
    						,DIV({'id': "secondary_heat_source_price-div", 'class': "ne-small-vertical-box nec-lr-margin2", 'style':"width: 125px;margin-left:4px;"}
    							,this.parent.dom.label("secondary_heat_source_price")
    							,this.parent.dom.help_icon("secondary_heat_source_price")
    							,DIV({'style':"float: left;"} //margin-top: 4px;
    								,INPUT({'id':"secondary_heat_source_price",'name':"secondary_heat_source_price",'type': "text", 'class': "nec-text nec-double-width"})
    								,SPAN({'id':"secondary_heat_source_energy_unit",'name':"secondary_heat_source_energy_unit", 'class':"nec-input-block"}, "")
    							)
    						)
    						,this.parent.dom.clear()
    					)
    					,DIV({'id':"secondary_heat_source_usage-div-frame",'class':"nec-lr-center-tb-margin9  nec-triple-height"}
    						,this.parent.dom.verticalSelectBox('secondary_heat_source_usage', 'ne-vertical-box')
    					)	
    					/*,DIV({}
    						,DIV({'style':"width:108px;"}
    								,DIV({'id':"number_of_persons-div",'class':"float-box",'style':"_margin-top: 6px;"},this.parent.dom.input_text('number_of_persons','nec-single-width'))
    								,this.parent.dom.clear()
    						)
    					)
    					*/
					 	
    					/*,DIV({'class':"nec-lr-center-tb-margin9  nec-triple-height"}
    						,DIV({'id':"number_of_persons-div",'class':"nec-single-height"}, this.parent.dom.input_text('number_of_persons','nec-single-width'))
    					)*/
    					,DIV({'class':"nec-dot-line nec-tb-margin9"})
    					,DIV({'class':"highlight"}, this.parent.text.result.help_insulation)
    					,DIV({}
    						,this.parent.dom.centeredSelectBox('roof_insulation', 'nec-centered')
    						,this.parent.dom.centeredSelectBox('wall_insulation', 'nec-centered')
    						,this.parent.dom.centeredSelectBox('windows', 'nec-centered')
    						,this.parent.dom.centeredSelectBox('basement_insulation', 'nec-centered')
    					)
    					,DIV({'class':"nec-dot-line nec-tb-margin9"})
    					,DIV({'class':"highlight"}, this.parent.text.result.help_consumption)
    					,DIV({'style':"float:left;width:370px;height:50px;"}
    						,P({'class':"p_paragraph",'style':"margin-top:5px;"},this.parent.text.result.consumption_intro)
    					)
    					,DIV({'class':"frame-heatconsumption"}
    						,DIV({'id':"heat_consumption_estimate-div",'class':"float-box",'style':"_margin-top: 6px;"}
    							,this.parent.dom.input_text("heat_consumption_estimate", "nec-triple-width")
    						)
    						,DIV({'id':"heat_consumption-div",'class':"float-box",'style':"_margin-top: 6px;"}
    							,this.parent.dom.input_text("heat_consumption", "nec-triple-width")
    						)
    						,this.parent.dom.clear()
    					)
    				),
    				validation_button,
    				building_footer
                )
            );

        var step2 = ( this.parent.ab_tester == 'B' ) ? DIV({id:'advanced-calculation-step2'},
            DIV({id:"calculation-result-part2"},
                H2({'class':"result",'id':"calculation-result-title-2"}),
			    DIV({'id':"ne-calc-message-2",'style':"float:none;margin-left:60px"}),
		        savings_overview,
                savings_options
		    ),
			INPUT({'name':"zip_code", 'id':"hidden_zip_code", 'type':"hidden"}),
			DIV({'style':"float: left;margin: 16px 16px 0 30px;"}, STRONG({'class':"ne-strong-title",'style':"width: 240px; height: 25px;;margin:0"},this.parent.text.result.loan_leadin)),
            INPUT({'type':"submit",'id':"addr_sub",'class':"ne-button-advanced-calc",'style':"margin-bottom:5px", 'value':""})
		) : '';

        var form = FORM({'id':"advanced-calculation", "onsubmit":"return false;"},
		    this.parent.dom.header(
			    ( this.parent.ab_tester == 'B' ) ? this.parent.text.result.sub_title : this.parent.text.result.title,
			    DIV({id:"adv-calc-step1", 'class':"block-visible nec-main-background nec-main-border"},
			        step1,
			        this.parent.dom.step_footer()
			    )
		    ),
            ( this.parent.ab_tester == 'B' )
                ? this.parent.dom.header(
			        this.parent.text.result.title,
			        DIV({id:"adv-calc-step2", 'class':"block-visible nec-main-background nec-main-border closed display-hidden"},
			            step2,
			            this.parent.dom.step_footer()
			        )
	            )
	            : []
        );
		this.parent.dom.appendChildNodes(form);

        // Hide step 2 until the user clicks "info is ok"
        if ( this.parent.ab_tester == 'B' ) {
            addElementClass('adv-calc-step2-header','display-hidden');
        }

		//put fixes here
		$('primary_heat_source-div').style.cssText="_width:192px";
		$('primary_heat_source').style.cssText="_width:192px";
		addElementClass("primary_heat_source_energy_price-help", "leftelement");
		addElementClass("secondary_heat_source_price-help", "leftelement");
		
		//help icon margins
		$('roof_type').style.cssText="margin-left:2px;width:150px";
		$('number_of_floors').style.cssText="margin-left:2px;width:150px"
		$('basement').style.cssText="margin-left:2px;width:150px"
		
		//setStyle($('roof_type'),"width:150px"); //roof_type has some long options so will be needed

		connect(form, "onsubmit", bind(this.validate_result, this));
        this.generateMap(
            $("google-map"),
            this.parent.calculation.building.latitude,
            this.parent.calculation.building.longitude
        );
		// set target=_blank for all links in google map
		map(rpartial(setNodeAttribute, "target", "_blank"), $$("#google-map a"));
		this.checkForNote(this.parent.calculation.result.response.savings_out);
		
		// make sure to reset these dropdowns initially to the returned defaults
		this.reset_minimum = ['roof_insulation', 'wall_insulation', 'windows', 'basement_insulation'];
		this.minimums = {};
		
		// renaming parameters before send
		this.renaming = {'primary_heat_source_installations_year': 'primary_heat_source_installations_year_user'}
	
	}
	,checkForNote : function(amount){
            var node_names = new Array()
            node_names.push('ne-calc-message');
            if ( this.parent.ab_tester == 'B' ) {
                node_names.push('ne-calc-message-2');
            }

            for ( var i = 0 ; i < node_names.length ; i++ ) {
    			if (amount<=1000){
    				//house is already good
    				replaceChildNodes(node_names[i],
    						DIV({'class':"ne-form",'style':"color:#878484;margin-top: 5px;margin-bottom: 10px;border: 1px solid #718E44;width:345px;padding-left:34px; padding-right: 8px;background:url(resources/images/ne_godthus.gif) no-repeat;background-color: #FFFFFF !important"},
    								"På baggrund af de indtastede oplysninger kan vi se, at du har gode brugsvaner eller en god varmekilde i dit hus, og din bolig ser ud til at være rigtig godt isoleret. "
    						)
    				);
    			}
    			if (this.parent.appartment==true){
    				//make sure user knows its an appartment
    				replaceChildNodes(node_names[i],
    						DIV({'class':"ne-form",'style':"color:#878484;margin-top: 5px;margin-bottom: 10px;border: 1px solid #718E44;width:345px;padding-left:34px; padding-right: 8px;background:url(resources/images/ne_godthus.gif) no-repeat;background-color: #FFFFFF !important"},
    							this.parent.text.building_result.appartment
    						)
    				);
    				this.parent.appartment=null;
    			}
			}
	}
	,fill : function() {
		var form = $('advanced-calculation');
		for (var i=0; i < form.elements.length; i++) {
		   disconnectAll(form.elements[i]);
		}
		
		var options = this.parent.calculation.result.options;
		var response = this.parent.calculation.result.response;
		
		var amount = dFormat(parseInt(response.savings_out), "0,000");
		$("savingsbox-amount").innerHTML = amount;
		$("tablesavings-amount").innerHTML = amount;
		var co2 = dFormat(parseInt(response.co2_reduction_out) / 1000);
		$("savingsbox-co2").innerHTML = co2;
		$("tablesavings-co2").innerHTML = co2;
		var invest = dFormat(parseInt(response.combined_investments_out), "0,000");
		$("savingsbox-invest").innerHTML = invest;
		$("tablesavings-invest").innerHTML = invest;
		var building = this.parent.calculation.building;
		$("calculation-result-title").innerHTML = building.street + " " + building.number + ", " + building.zipCode;
        if ( this.parent.ab_tester == 'B' ) {
		    $("calculation-result-title-2").innerHTML = building.street + " " + building.number + ", " + building.zipCode;
	    }
		$("total_area").value = response.total_area;
		$("building_year").value = response.building_year;
		$("built_up_area").value = response.built_up_area;
		$('primary_heat_source_energy_price').value = dFormat(response.primary_heat_source_energy_price);
		
		// heat year is either user input or model output - and should be converted to number
		var heat_year = response.primary_heat_source_installations_year_user || response.primary_heat_source_installations_year;
		if (typeof heat_year != "number") {
			heat_year = heat_year.replace(/[^\d]/g, '');
		}
		$('primary_heat_source_installations_year').value = heat_year;
		$('primary_heat_source_energy_unit').innerHTML = response.primary_heat_source_energy_unit.replace(/\s/g,'');
		$('secondary_heat_source_energy_unit').innerHTML = response.secondary_heat_source_unit.replace(/\s/g,'');
		$('secondary_heat_source_price').value = dFormat(response.secondary_heat_source_price);
		
		$('new_heat_source_price').innerHTML = dFormat(response.new_heat_source_price, "0,000");
		$('heat_consumption_estimate').value = dFormat(response.heat_consumption_estimate, "0,000");//estimated by system
		$('heat_consumption').value = dFormat((response.heat_consumption > 0 ? response.heat_consumption : response.heat_consumption_estimate), "0,000");//user input but with estimate if not filled
		
		// hide relevant rows about insulation and fix cycling
		var any_investment_possible = false;
		var cycler = cycle(['first','second']);
		if (response.roof_insulation_invest_out == 0) {
			// hide roof insul row
			$("row_roof_insulation_invest_out").style.display = 'none';
		} else {
			any_investment_possible = true;
			$("row_roof_insulation_invest_out").style.display = '';
			setNodeAttribute("row_roof_insulation_invest_out","class",cycler.next());
		}
		if (response.wall_insulation_invest_out == 0) {
			// hide wall insul row
			$("row_wall_insulation_invest_out").style.display = 'none';
		} else {
			any_investment_possible = true;
			$("row_wall_insulation_invest_out").style.display = '';
			setNodeAttribute("row_wall_insulation_invest_out", "class", cycler.next());
		}
		if (response.new_windows_invest_out == 0) {
			// hide new windows row
			$("row_new_windows_invest_out").style.display = 'none';
		} else {
			any_investment_possible = true;
			$("row_new_windows_invest_out").style.display = '';
			setNodeAttribute("row_new_windows_invest_out","class",cycler.next());
		}
		if (options.basement.selected == 'Ja') {
			if (response.basement_insulation_invest_out == 0) {
				// hide base insul row
				$("row_basement_insulation_invest_out").style.display = 'none';
			} else {
				any_investment_possible = true;
				$("row_basement_insulation_invest_out").style.display = '';
				setNodeAttribute("row_basement_insulation_invest_out","class",cycler.next());
			}
		}
		// if no investments shown, replace warning text with an explaining text
		if (!any_investment_possible) {
			replaceChildNodes("insulation_table_warning", this.parent.label.insulation_table_empty);
		} else {
			replaceChildNodes("insulation_table_warning", this.parent.label.insulation_table_warning);
		}
		
		$('roof_insulation_invest_out').innerHTML = dFormat(response.roof_insulation_invest_out, "0,000");
		$('new_windows_invest_out').innerHTML = dFormat(response.new_windows_invest_out, "0,000");
		$('wall_insulation_invest_out').innerHTML = dFormat(response.wall_insulation_invest_out, "0,000");
		$('basement_insulation_invest_out').innerHTML = dFormat(response.basement_insulation_invest_out, "0,000");
		$('table_insulation_sum').innerHTML = dFormat(response.insulation_investments_out, "0,000");
		$('roof_insulation_out_check').checked = response.roof_insulation_out == "Ja" ? true : false;
		$('new_windows_out_check').checked = response.new_windows_out == "Ja" ? true : false;
		$('wall_insulation_out_check').checked = response.wall_insulation_out == "Ja" ? true : false;
		$('basement_insulation_out_check').checked = response.basement_insulation_out == "Ja" ? true : false;
		$('roof_insulation_out').value = response.roof_insulation_out;
		$('new_windows_out').value = response.new_windows_out;
		$('wall_insulation_out').value = response.wall_insulation_out;
		$('basement_insulation_out').value = response.basement_insulation_out;
		$('hidden_zip_code').value = response.zip_code;
		
		//disable estimated consumption cost for user input
		setNodeAttribute('heat_consumption_estimate',"disabled","true");
		
		// any options need to be reset?
		if (this.reset_minimum && this.reset_minimum.length) {
			if (!this.minimums) {
				this.minimums = {};
			}
			for (var i = 0; i < this.reset_minimum.length; i++) {
				if (!options[this.reset_minimum[i]]) continue;
				this.minimums[this.reset_minimum[i]] = options[this.reset_minimum[i]].selected;
			}
		}
		this.fillSelect('primary_heat_source', options.primary_heat_source);
		this.fillSelect('number_of_floors', options.number_of_floors);
		this.fillSelect('basement', options.basement);
		this.fillSelect('roof_type', options.roof_type);
		this.fillSelect('secondary_heat_source', options.secondary_heat_source);
		this.fillSelect('roof_insulation', options.roof_insulation, this.minimums.roof_insulation || '');
		this.fillSelect('wall_insulation', options.wall_insulation, this.minimums.wall_insulation || '');
		this.fillSelect('windows', options.windows, this.minimums.windows || '');
		this.fillSelect('basement_insulation', options.basement_insulation, this.minimums.basement_insulation || '');
		this.fillSelect('district_heat_provider', options.distric_providers);
		this.fillSelect('secondary_heat_source_usage', options.secondary_heat_source_usage);
		
		this.parent.dom.show_hide_on_value('primary_heat_source', 'Fjernvarme', 'district_heat_provider-div', true);
		this.parent.dom.show_hide_on_value('secondary_heat_source', 'Solvarme til brugsvand', 'number_of_persons-div', true);
		//this.parent.dom.show_hide_on_value('secondary_heat_source', 'Solvarme til brugsvand', 'secondary_heat_source_usage-div-frame', false);
		//this.parent.dom.show_hide_on_value('secondary_heat_source', 'Ingen', 'secondary_heat_source_installations_year-div', false);
		this.parent.dom.show_hide_on_value('secondary_heat_source', 'Ingen', 'secondary_heat_source_price-div', false);
		this.parent.dom.show_hide_on_value('secondary_heat_source', 'Ingen', 'secondary_heat_source_usage-div-frame', false);
		this.parent.dom.show_hide_on_value('basement', 'Nej', 'basement_insulation-div', false);
		this.parent.dom.show_hide_on_value('basement', 'Nej', 'row_basement_insulation_invest_out', false);
		
		//this.parent.dom.show_hide_on_value('number_of_floors','1 plan og kælder','basement-div',false);
		//this.parent.dom.show_hide_on_value('number_of_floors','3 plan og kælder','basement-div',false);
		//this.parent.dom.show_hide_on_value('number_of_floors','2 plan og kælder','basement-div',false);
		
		//special case for basement cause the above doesnt work
		if($("number_of_floors").options[$("number_of_floors").selectedIndex].value.indexOf("og kælder")>-1){
			//hide basement until next recalculation			
			this.parent.dom.hideBlock('basement-div');
		}else{
			this.parent.dom.showBlock('basement-div');
		}
		
		if($('secondary_heat_source').value == "Solvarme til brugsvand")this.parent.dom.hideBlock('secondary_heat_source_usage-div-frame');
	
		
		//this.parent.dom.show_hide_on_value('basement', 'Ja', 'row_basement_insulation_invest_out', true);
		
		// add "new_heat_source_none" to heat options
		// and set value of this investment to 0
		response.new_heat_source_none = 0;
		var heat_options = ["new_heat_source_none"].concat(options.heat_options);
		replaceChildNodes(
			"heat_source_table_body",
			TR(
				{'class':"first",'id':"heat_source_table_warning",'style':'display:none'},
				TD(
					{'colspan':"3",'style':"margin:0px;padding:1px"},
					DIV(
						{'class':"ne-form",'style':"color:#878484;border: 1px solid #718E44;width:434px;_width:478px;padding-left:34px; padding-right: 8px;background:url(resources/images/ne_godthus.gif) no-repeat;background-color: #FFFFFF !important"},
						"Vores beregninger viser, at du ikke opnår nogen økonomisk fordel ved at udskifte din primære varmekilde. Der kan dog være mulighed for en CO",SUB("2"),"-besparelse."
					)
				)
			),
			map(
				bind(this.heatSourceRow, this),
				cycle(['first','second']), 
				heat_options
			)
		);
		// set value of new heat source - if new_heat_source_switch = Nej, then "none", else new_heat_source:
		var new_heat_source = response.new_heat_source;
		if (response.new_heat_source_switch == "Nej") {
			new_heat_source = this.parent.label.new_heat_source_none;
			$("heat_source_table_warning").style.display = '';
		} else {
			$("heat_source_table_warning").style.display = 'none';
		}
		forEach(
			$$("[name=new_heat_source]"),
			bind(
				function(s, v){
					if(v.value == s){v.checked = true;}
				}, 
				this,
				new_heat_source
			)
		);

		
		this.parent.dom.build_notification('building_year');
		this.parent.dom.build_notification('total_area');
		//this.parent.dom.build_notification('built_up_area');
		this.parent.dom.build_notification('number_of_floors');
		this.parent.dom.build_notification('basement');
		this.parent.dom.build_notification('roof_type');

		this.parent.dom.build_notification('primary_heat_source');
		this.parent.dom.build_notification('primary_heat_source_installations_year');
		this.parent.dom.build_notification('primary_heat_source_energy_price');
		this.parent.dom.build_notification('district_heat_provider');
		
		this.parent.dom.build_notification('secondary_heat_source');
		this.parent.dom.build_notification('secondary_heat_source_price');
		this.parent.dom.build_notification('number_of_persons');
		
		/*this.parent.dom.build_notification('roof_insulation');
		this.parent.dom.build_notification('wall_insulation');
		this.parent.dom.build_notification('windows');
		this.parent.dom.build_notification('basement_insulation');
		
		this.parent.dom.build_notification('district');
		this.parent.dom.build_notification('oil');
		this.parent.dom.build_notification('natural_gas');
		this.parent.dom.build_notification('wood_pellets');
		//this.parent.dom.build_notification('woodburner');
		this.parent.dom.build_notification('heat_pump_air_water');
		this.parent.dom.build_notification('heat_pump_earth');
		//this.parent.dom.build_notification('electric_heating');
		//this.parent.dom.build_notification('gas_heaters');
		*/
		
		this.parent.dom.build_notification('heat_consumption_estimate');
		this.parent.dom.build_notification('heat_consumption');
		
		this.smudgeData('building_year', ['roof_insulation', 'wall_insulation', 'windows', 'basement_insulation','primary_heat_source_energy_price','wall_insulation_out','new_windows_out','roof_insulation_out','basement_insulation_out'], true);
		this.smudgeData('primary_heat_source', ['primary_heat_source_energy_price', 'primary_heat_source_installations_year','district_heat_provider']);
		this.smudgeData('district_heat_provider', ['primary_heat_source_energy_price']);
		this.smudgeData('secondary_heat_source', ['secondary_heat_source_price', 'number_of_persons','secondary_heat_source_usage']);
		this.smudgeData('wall_insulation', ['primary_heat_source_energy_price','wall_insulation_out']);
		this.smudgeData('windows', ['primary_heat_source_energy_price','new_windows_out']);
		this.smudgeData('roof_insulation', ['primary_heat_source_energy_price','roof_insulation_out']);
		this.smudgeData('basement_insulation', ['primary_heat_source_energy_price','basement_insulation_out']);
		
		for (var j=0; j < form.elements.length; j++) {
			//if(!form.elements[j].type == "checkbox" || !form.elements[j].type == "radio"){
				if (form.elements[j].type!="hidden"){
					//if (form.elements[j].type!="checkbox" && form.elements[j].type!="radio"){
					 	connect(form.elements[j], "onchange", bind(this.requestRecalculation, this));
					//}
				}
				if (form.elements[j].type=="radio"){
					//log("connecting: "+form.elements[j].type + " i: "+form.elements[j].id + " n: "+form.elements[j].name);
					//connect(form.elements[j], "onfocus", bind(this.fireBlur, this));
					//connect(form.elements[j], "onclick", bind(this.requestRecalculation, this));
					connect(form.elements[j], "onclick", bind(this.fireBlur, this));
				}
				if (form.elements[j].type=="checkbox"){
					
					connect(form.elements[j], "onclick", bind(this.updateAndRequest, this));
					
				}	 
				
			//}
			
			//connect(form.elements[j], "onchange", bind(this.requestRecalculation, this));
			//roof_insulation_out_check wall_insulation_out_check new_windows_out_check
			
			//log("form.element.type: "+form.elements[j].type);
			
		   //connect(form.elements[j], "onblur", bind(this.requestRecalculation, this));
		}
		/*
		var desiredevent="onclick";
		
		connect('roof_insulation_out_check', desiredevent, bind(this.requestRecalculation, this));
		connect('wall_insulation_out_check', desiredevent, bind(this.requestRecalculation, this));
		connect('new_windows_out_check', desiredevent, bind(this.requestRecalculation, this));
		
		connect('district', desiredevent, bind(this.requestRecalculation, this));
		connect('oil', desiredevent, bind(this.requestRecalculation, this));
		connect('natural_gas', desiredevent, bind(this.requestRecalculation, this));
		connect('wood_pellets', desiredevent, bind(this.requestRecalculation, this));
		connect('heat_pump_air_water',desiredevent, bind(this.requestRecalculation, this));
		connect('heat_pump_earth', desiredevent, bind(this.requestRecalculation, this));
		*/
		
	}
	,fireBlur : function (ev){
		//log("blurring: "+ev.src().id);
		ev.src().blur();
		return false;
	}
	,fillSelect : function(id, data, minimum) {
		replaceChildNodes(id,
				map(bind(
						function(s,o) {
							var option = OPTION({'value':o},o);
							if (o.trim() == s) {
								option['selected'] = "selected";
							}
							return option;
						}
						, this, data.selected.trim()
					)
					, (findValue(data.values,minimum||'') != -1 ? data.values.slice(findValue(data.values,minimum)) : data.values)
				)
		);
	}
	,fillSelectEncoded : function(id, data, minimum) {
		//tries to convert utf8 to readable characters (for special danish letters)
		var enc_sel = data.selected.trim();
		/*try{
			enc_sel=decodeURIComponent(escape(data.selected.trim()));
			log("Encoded version is: "+enc_sel);
		}catch(E){
			log("Error: "+E);
			log("Unencoded version: "+data.selected);			
		}*/
		
		replaceChildNodes(id,
				map(bind(
						function(s,o) {
							var option = OPTION({'value':o},o);
							//log("Comparing: o: "+o+" with s: "+data.selected);
							if (o == s) {
								option['selected'] = "selected";
							}
							/*else{
								try{
									var encoded_s=decodeURIComponent(escape(data.selected.trim()));
									var encoded_o=decodeURIComponent(escape(o.trim()));
									if (encoded_s == encoded_o) option['selected'] = "selected";									
								}catch(E){}
							}*/
							return option;
						}
						, this, enc_sel
					)
					, (findValue(data.values,minimum||'') != -1 ? data.values.slice(findValue(data.values,minimum)) : data.values)
				)
		);
	}
	,validate_result : function() {
		this.parent.state.loan_calculation();
	}
	,insulationTable : function() {
		var a = A( {'id':this.parent.dom.header_id_link("insulation_table_body"),'href' : "#",'style':"color: white"} 
			,IMG({'src':"resources/images/arrow_up_white_icon.gif",'id':this.parent.dom.header_id_img("insulation_table_body")})
			,SPAN({},"Investering i efterisolering")
		);
		connect(a, "onclick", bind(this.parent.dom.collapseBox, this.parent.dom, "insulation_table_body"));
		
		var table = TABLE({'class':"insulation_table",'cellpadding':"0", 'cellspacing':"0"}
			,THEAD({'id':this.parent.dom.header_id_h2("insulation_table_body")}
				,TR({}
					,TD({'class':"table_insulation_name"},a)
					,TD({'class':"table_heats_icon"})
					,TD({'class':"table_heats_value"},SPAN({'id':"table_insulation_sum"})," kr.")
				)
			)
			,TBODY({'id':"insulation_table_body",'class':"table-visible"}
				,TR(
					{'class':"first"},
					TD(
						{'colspan':"3",'style':"margin:0px;padding:1px"},
						DIV(
							{'id':"insulation_table_warning",'class':"ne-form",'style':"color:#878484;border: 1px solid #718E44;width:462px;_width:478px;padding-left:8px; padding-right: 8px;background-color: #FFFFFF !important"},
							this.parent.label.insulation_table_warning
						)
					)
				)
				,this.insulationRow("second","Tag"		, "Tag", "roof_insulation_invest_out")
				,this.insulationRow("first", "Ydermure", "Ydermurer", "wall_insulation_invest_out")
				,this.insulationRow("second","Vinduer"	, "Vinduer", "new_windows_invest_out")
				,this.insulationRow("first", "Krybekælder", "Fundament", "basement_insulation_invest_out")
			)
		);
		return table;
	}


	,insulationRow : function(clazz, caption, type, id) {
		return TR({'class':clazz,'id':"row_"+id},
				TD({'class':"table_insulation_name"} 
					,INPUT({
						'type':"checkbox"
						,'id': id.replace(/_invest/,'')+"_check"
						,'style': "vertical-align:middle;"
						//,"onchange" :"$("+id.replace(/_invest/,'')+").value = (this.checked ? 'Ja' : 'Nej');log('done with value: '+$("+id.replace(/_invest/,'')+").value);" 
					})
					,INPUT({
						'type':"hidden"
							,'name':id.replace(/_invest/,'')
							,'id': id.replace(/_invest/,'')
					})
					,LABEL({'class':"vertical-align-color"}, caption)
					
				)
				,TD({'class':"table_heats_icon"})
				,TD({'class':"table_heats_value"}, SPAN({'class':"vertical-align-color",'id':id}), " kr.")
		);
	}
	,heatSourceRow : function(cssClass, id) {
		return TR({'class':cssClass,'id':id+"-div"},
				TD({'class':"table_heats_name"} 
					,INPUT({
						 'type':"radio"
						,'name':"new_heat_source"
						,'style':"vertical-align:middle"
						,'value':  this.parent.label[id]
						,'id':id
					})
					//,LABEL({}, this.parent.label[id])
					,this.parent.label[id]
				)
				,TD({'class':"table_heats_icon"})
				/*	,this.parent.dom.help_icon(id)
					//,IMG({'src':"resources/images/white_help.gif", 'class':'no_print', 'onclick':"return showHelp(this, 'help.necalc.heat_source." + id + "');"})
				)*/
				,TD({'class':"table_heats_value"}, dFormat(this.parent.calculation.result.response[id],"0,000"), " kr.")
			);
	}
	,heatSourceTable : function() {
		var a = A( {'id':this.parent.dom.header_id_link("heat_source_table_body"),'href' : "#", 'style':"color: white;"} 
			,IMG({'src':"resources/images/arrow_up_white_icon.gif",'id':this.parent.dom.header_id_img("heat_source_table_body")})
			,SPAN({},"Investering i udskiftning af primær varmekilde")
		);
		connect(a, "onclick", bind(this.parent.dom.collapseBox, this.parent.dom, "heat_source_table_body"));

		var table = TABLE({'class':"heat_source_table", 'cellpadding':"0", 'cellspacing':"0"}
			,THEAD({'id':this.parent.dom.header_id_h2("heat_source_table_body")}
				,TR({'id':this.parent.dom.header_id_h2("heat_source_table_body")}
					,TD({'class':"table_heats_name"},a)
					,TD({'class':"table_heats_icon"})
					,TD({'class':"table_heats_value"},SPAN({'id':"new_heat_source_price"})," kr.")
				)
			)
			,TBODY({'id':"heat_source_table_body",'class':"table-visible"}
		));
		return table;
	}
	
	,switchMapChart : function () {
		this.parent.dom.switchBlockVisibility("google-map");
		this.parent.dom.switchBlockVisibility("google-chart");
		//hasElementClass(id, this.class_block_visible
		
		if($('switch_link').innerHTML==this.parent.text.calculation_result.switch_map) $('switch_link').innerHTML=this.parent.text.calculation_result.switch_chart;
		else $('switch_link').innerHTML=this.parent.text.calculation_result.switch_map;
	}
	,generateChart : function(id, current, future, inflation){
		var chart = "http://chart.apis.google.com/chart?chs=210x160&cht=lc&chd=t:[S1]|[S2]&chds=0,[MAX]&chl=0|5|10|15|20&chco=A4BF7A,FE9A16&chdl=Uden+forbedring|Med+forbedring&chdlp=b&chxt=x,y&chxr=0,0,25|1,0,[MAX]&chtt=%C3%85rlig+varmeudgift";
		var s1 = [parseInt(current)];
		var s2 = [parseInt(future)];
		for (var i = 1; i < 20; i++) {
			s1[i] = Math.round(s1[i-1]*(1+inflation/100));
			s2[i] = Math.round(s2[i-1]*(1+inflation/100));
		}
		var max = Math.max(listMax(s1),listMax(s2));
		var url = chart
					.replace("[S1]", s1.join(","))
					.replace("[S2]", s2.join(","))
					.replace("[MAX]", max)
					.replace("[MAX]", max);
		return DIV({'id':id, 'class' : "nec-small-box nec-float-left nec-margin-small-left block-hidden"}
				,IMG({'src' : url})
			);
	}
	,generateMap : function(map_div, latitude, longitude) {
		var gmap = new GMap2(map_div);
		var point = new GLatLng(latitude, longitude);
		//log("Setting map on div: "+map_div.id+" with coords (lat/lng): "+latitude + ", "+longitude);
		gmap.setCenter(point, 18, G_SATELLITE_MAP);
		var mgr = new GMarkerManager(gmap);
		var marker = new GMarker(point);
		mgr.addMarker(marker, 2);
		mgr.refresh();
		gmap.checkResize();
		gmap.panTo(point);
	}
	,smudgeData : function(option, dirty, onlymore) {
		$(option).smudge = dirty;
		$(option).onlymore = onlymore;
	}
	,requestRecalculation: function(ev) {
		ev.stop(); //stop propagation
		this.parent.state.simple_recalculation();

		var id = ev.src().id;
		
		if ($(this.parent.dom.form_id_help(id))) {
			disconnectAll(id);
			disconnectAll(id+"-div");
			this.parent.dom.img_src_loader(this.parent.dom.form_id_help(id));
			this.parent.dom.show_notification(id);
		}else{
			disconnectAll(id);
			disconnectAll(id+"-div");
			//this.parent.dom.img_src_loader(this.parent.dom.form_id_help(id));
			//this.parent.dom.show_notification(id);
		}
		
		//check if number of persons are below minimum allowed
		if (this.parent.dom.getVal("secondary_heat_source")=="Solvarme til brugsvand"){
			//validate persons vs area in building
			//total_area number_of_persons
			try{
				var personsSqm = 10;//persons per sqm
				var maxpers=($('total_area').value/personsSqm);
				var numpersons=$('number_of_persons').value
				if (numpersons>maxpers){
					//set to maximum allowed
					$('number_of_persons').value=parseInt(maxpers);
				}
			}catch(e){}
		}
		
		var form = formContents('advanced-calculation');
		var values = {};
		for (var i = 0; i < form[0].length; i++) {
			values[form[0][i]] = form[1][i];
		}
		
		//if heat_consumption is still equal to heat_consumption_estimate remove both from submit
		if($('heat_consumption').value == $('heat_consumption_estimate').value || $('heat_consumption').value == ""){
			delete values.heat_consumption;
			delete values.heat_consumption_estimate;
		}else{
			// user put his own value
			// remove the estimate so it doesnt interfere and convert consumption to something excel understands
			// and limit uservalue within 80% of estimate
			var estimate = parseInt(values.heat_consumption_estimate.replace(".",""));
			var uservalue = parseInt(values.heat_consumption);
			values.heat_consumption = Math.max(uservalue, parseInt(estimate*0.8));
			delete values.heat_consumption_estimate;
			//notify user if the value he/she entered was below 80% of the estimate
			//this is a limit set due to how the model works (80% of estimate is minimum allowed consumption).
			if (uservalue < parseInt(estimate*0.8)){
				showError($('heat_consumption'),"error.necalc.heat_consumption");
			}
			//show this to user with: showError($('heat_consumption'),"error.loan.fill_amount");
		}	
		
		// replace numbers in the form "#.###,#" with "####.#" to allow for parsing in java
		// and thus correct number insertion in model (in stead of string insertion)
		for (var parm in values) {
			if (/^[\d.,]+[.,][\d.,]+$/.test(values[parm])) 
				values[parm] = values[parm].replace(".","").replace(",","."); 
		}
		
		var smudge = ev.src().smudge;
		if (!isArrayLike(smudge)) {smudge=[];}
		
		// should any dropdowns be reset after callback to only show options greater than what was returned?
		if (smudge.length && ev.src().onlymore) {
			this.reset_minimum = smudge;
		} else {
			this.reset_minimum = [];
		}

		// manual fix for new_heat_source and new_heat_source_switch
		if (ev.src().id == "primary_heat_source" || ev.src().id == "primary_heat_source_installations_year") {
			// remove currently selected new heatsource
			delete values.new_heat_source;
			// switch does not exist in values, no need to set it
		} else if (values.new_heat_source === this.parent.label.new_heat_source_none) {
			// set new_heat_source_switch = "Nej";
			values.new_heat_source_switch = "Nej";
			// set new_heat_source to current_heat_source
			values.new_heat_source = values.primary_heat_source;
		} else {
			// set switch to "Ja"
			values.new_heat_source_switch = "Ja";
		}
		
		// rename and join fields into single parameter;
		var renamer = this.renaming;
		var joiner = function(field) {
			if (findValue(smudge, field[0]) != -1) {
				return '';
			}
			if (renamer[field[0]]) {
				field[0] = renamer[field[0]];
			}
			return field.join(':');
		}
		var parameters = map(joiner, items(values));
		var parameter = parameters.join(';');
		
		jsonRequest(
				{"parameters": parameter}
				,bind(
					function(id, result) {
						this.callbackRecalculation(result);
						if ($(id) && $(id).type!= "radio" && $(id).type!="checkbox") {
							//log("inside wrong if with type:"+ev.src().type);
							this.parent.dom.hide_notification(id);
							if ($(this.parent.dom.form_id_help(id))) this.parent.dom.img_src_help(this.parent.dom.form_id_help(id));
							this.parent.dom.build_notification(id);
							connect(id, "onchange", bind(this.requestRecalculation, this));
						}else{
							if ($(id).type=="checkbox") connect(id, "onclick", bind(this.updateAndRequest, this));
							if ($(id).type=="radio") connect(id, "onclick", bind(this.requestRecalculation, this));
						}
						
					}
					, this ,ev.src().id
				)
				,"ne/reCalculation"
			);
			return false;
		
	}
	,updateAndRequest : function(ev){
		var cid=ev.src().id;
		var hid=ev.src().id;
		$(hid.replace(/_check/,'')).value = ($(cid).checked ? 'Ja' : 'Nej');
		//log($(cid).checked);
		ev.src().blur();
		//this.requestRecalculation(ev);	
	}
	,callbackRecalculation: function(result) {
		this.parent.calculation.result = result;
		this.fill();
	}
};
LoanCalculation.prototype = {
	clean : function() {
        if ( this.parent.ab_tester == 'A' ) {
		    this.parent.dom.collapseBox("adv-calc-step1");
	    }
	    else {
	        this.parent.dom.collapseBox("adv-calc-step2");
	    }
	}
	,build : function() {
		var form = FORM({'id':"ne-loan-calc",'class':"block-visible nec-main-background nec-main-border",'onsubmit':"return false;"}
			,DIV({'class':"nec-content-image-cross"})
			,DIV({'class':"margin-lrtb-wide"}
				,STRONG({'class':"ne-strong-title"}, this.parent.text.loancalc.intro)
				,DIV({'style':"margin-top:12px;"}
					,P({'class':"p_paragraph"}, this.parent.text.loancalc.intropara1)
					,P({'class':"p_paragraph"}, this.parent.text.loancalc.intropara2)
					,P({'class':"p_paragraph"}, this.parent.text.loancalc.intropara3)
					,P({'class':"p_paragraph"}, STRONG({},this.parent.text.loancalc.introstrong4),this.parent.text.loancalc.intropara5)
				)	
				,DIV({'style': "width: 400px; float: right;"},DIV({'id':"loan_amount-div",'class':"float-box",'style':"width: 180px; float: right;"},this.parent.dom.input_text("loan_amount", "nec-triple-width")))
				,INPUT({'type':"submit",'id':"addr_sub",'class':"ne-button-calc", 'value':"", 'style':"float: right;"})
				,this.parent.dom.clear()
			)
			,this.parent.dom.step_footer()
		);
		this.parent.dom.appendChildNodes(this.parent.dom.header(this.parent.text.loancalc.title, form));
		connect(form, 'onsubmit', bind(this.validate_result, this));
	}
	,fill : function() {
		this.parent.dom.build_notification('loan_amount');
		$('loan_amount').value = parseInt(this.parent.calculation.result.response.combined_investments_out);
	}
	,validate_result : function() {
		this.parent.state.loan_calculation_result();
	}
};
LoanCalculationResult.prototype = {
	build : function() {
		var button_new = INPUT({'type':"button",'value':"",'class':"ne-button-new-calc"});
		connect(button_new, 'onclick', bind(this.parent.state.init, this.parent.state));
		
		var button_report = INPUT({'type':"button",'value':"",'class':"ne-button-report"});
		connect(button_report, 'onclick', bind(this.parent.state.report_generation, this.parent.state));
		
		if (!$("calculation")) {
			// only create and append all this if not already added
			appendChildNodes('ne-loan-calc',[
			   DIV({'id':'calculation'})
		      ,H2({'class':"result",'id':"h2_ne-calculation"}, this.parent.text.resultbox.loantitle)
		      ,DIV({'id':"ne-calculation"}
			      ,DIV({'class':"ne-loan-result"}
				      ,DIV({'class':"ne-loan-result-box-title"},this.parent.text.loannotebox.intro)
				      ,DIV({'class':"ne-loan-result-box-value",'id':"loan-result-box-value"})
			      )
			      ,DIV({'id':"savings_box"}
			      	,DIV({'class':"ne-loan-box-middle"}
						,DIV({'class':"ne-help-icon-first ne-help-icon-gray",'onclick':"return showHelp(this, 'help.encalc.savingsbox.saving');"})
						,DIV({'class':"ne-savings-box-amount-title"},this.parent.text.loanamountbox.monthlysavings)
						,DIV({'class':"ne-savings-box-amount-value",'id':"ne-monthlysavings"})
						,DIV({'class':"ne-help-icon-second ne-help-icon-gray",'onclick':"return showHelp(this, 'necalc-loan_calculation-loan_payment_help');"})
						,DIV({'class':"ne-co2-box-amount-title"},this.parent.text.loanamountbox.monthly)
						,DIV({'class':"ne-co2-box-amount-value",'id':"ne-monthly"})
						,DIV({'class':"ne-help-icon-third ne-help-icon-orange",'onclick':"return showHelp(this, 'necalc-loan_calculation-loan_profit_help');"})
						,DIV({'class':"ne-inv-box-amount-title"}, this.parent.text.loanamountbox.monthlyearnings)
						,DIV({'class':"ne-inv-box-amount-value",'id':"ne-monthlyearnings"})
			      	)
			      )
		      )
		      ,HR({'class':"ne-separation-line"})
		      ,DIV({'class':"margin-lrtb-wide"}
			      ,STRONG({'class':"ne-strong-title"}, this.parent.text.report.intro)
			      ,P({'class':"p_paragraph",'style':"margin-top:12px;"}, this.parent.text.report.body)		
			      ,button_report
			      ,button_new
			      ,this.parent.dom.clear()
		      )
		      ,this.parent.dom.clear()
		      ,this.parent.dom.step_footer()
		 	]);
		}
	}
	,fill : function() {
		var result = this.parent.calculation.loan;
		// changed "appendChildNodes" to "replaceChildNodes" to clear old tables
		replaceChildNodes("calculation",
			calc.resultTable(
				 "fixed"
				,"Lån med fast rente"
				,[
					 this.columns.lantype
					,this.columns.obligations
					,this.columns.paydown
					,this.columns.period
					,this.columns.amountMonth
				]
				,result.data.fixed
			),
			/*calc.resultTable(
				 "variable"
				,"Lån med variabel rente"
				,[
					 this.columns.lantype
					,this.columns.refinanceFrequency
					,this.columns.paydown
					,this.columns.period
					,this.columns.amountMonth
				]
				,result.data.variable
			),*/
			calc.resultTable(
				 "capped"
				,"Lån med renteloft"
				,[
					 this.columns.lantype
					,this.columns.cappedPercent
					,this.columns.cappedPeriod
					,this.columns.paydown
					,this.columns.period
					,this.columns.amountMonth
				]
				,result.data.capped
			)
		);
		var selectLoan = bind(this.selectLoan, this);
		var selectRow  = bind(this.selectRow , this);
		map(
			bind(
				function(e) {
					var value = evalJSON(e.getAttribute('value'));
					// manual match on "30-års 5%-obligationslån uden afdragsfrihed"
					var manual_match = value.afdragsfrihed == false && value.laantype == 1 && value.loebetid == 360 && value.obligationsRente == 4;
					if (value.primary || manual_match) {
						// if primary, select and highlight
						addElementClass(e,"row_highlight");
						selectLoan(e);
					} else {
						// not primary, hook select-function
						connect(e, "onclick", selectRow);
					}
				}
				,this
			)
			,concat($("cappedBody") ? $("cappedBody").rows : [], $("variableBody") ? $("variableBody").rows : [], $("fixedBody") ? $("fixedBody").rows : [])
		);
	}
	,getLoanAmountText : function(loan_info) {
		var loan_desc = loan_info.laanebetegnelse;
		var formatter = numberFormatter("#.00","",MochiKit.Format.LOCALE.de_DE);
		switch (loan_info.laantype) {
		case "1":
		case "2":
			loan_desc += " " +
					"på "+formatter(parseFloat(loan_info.obligationsRente))+"% " +
					""+(loan_info.afdragsfrihed ? "med" : "uden")+" afdragsfrihed " +
					"og en løbetid på "+(loan_info.loebetid/12)+" år";
			break;
		case "5":
			loan_desc += " " +
					"og en refinansieringsfrekvens på "+loan_info.refFrekvens+" år " +
					""+(loan_info.afdragsfrihed ? "med" : "uden")+" afdragsfrihed";
			break;
		case "3":
			loan_desc += " " +
					"på "+formatter(parseFloat(loan_info.renteLoft))+"% " +
					"i "+loan_info.udloebsAar+" år " +
					""+(loan_info.afdragsfrihed ? "med" : "uden")+" afdragsfrihed " +
					"og en løbetid på "+(loan_info.loebetid/12)+" år";
			break;
		}
		return [loan_desc,this.parent.text.loannotebox.outtro];
	}
	,updateLoanAmountBox : function(loan_info) {
		var savings = this.parent.calculation.result.response.savings_out / 12;
		var earnings = savings - loan_info.ydelsePrMndEfterSkat;
		this.parent.selectedloan=loan_info.laantype+ ","+loan_info.fondskode+","+loan_info.afdragsfrihed+","+loan_info.refFrekvens;
		this.loanstat = loan_info;
		var formatter = numberFormatter("#,###","",MochiKit.Format.LOCALE.de_DE);
		$('ne-monthlyearnings').innerHTML = "" + formatter(earnings) + this.parent.text.loanamountbox.unit;
		$('ne-monthlysavings').innerHTML = "" + formatter(savings) + this.parent.text.loanamountbox.unit;
		$('ne-monthly').innerHTML = "" + formatter(loan_info.ydelsePrMndEfterSkat) + this.parent.text.loanamountbox.unit;
		
		replaceChildNodes('loan-result-box-value',this.getLoanAmountText(loan_info));
		nestat(NESTAT_STEP_LOAN, this.parent, {result: this.parent.calculation.result, loaninfo:loan_info});
	}
	,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'		: "114px"
				,'dictionary'	: "Obligationsrenteprocent"
				,'caption'		: "Obligations- renteprocent"
		}
		,refinanceFrequency : {
				 'name'			: "refinanceFrequency"
				,'width'		: "114px"
				,'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'		: "44px"
				,'dictionary'	: "Løbetid"
				,'caption'		: "Løbetid"
		}
		,amountMonth : {
				 'name'			: "amountMonth"
				,'width'		: "110px"
				,'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"
		}
	}
	,deselectRow : function(ev) {
		removeElementClass(ev.src(),"row_highlight");
		disconnectAll(ev.src());
		connect(ev.src(),"onclick",bind(this.selectRow,this));
	}

	,selectRow : function(ev) {
			//Needs to be done in a smarter fashion maybe
	 		map(
				bind(
					function(e) {
						if (hasElementClass(e, "row_highlight")) {
							removeElementClass(e,"row_highlight");
							connect(e,"onclick",bind(this.selectRow,this));
						}
					}
					,this
				)
				,concat($("cappedBody") ? $("cappedBody").rows : [], $("variableBody") ? $("variableBody").rows : [], $("fixedBody") ? $("fixedBody").rows : [])
			);
			
			addElementClass(ev.src(),"row_highlight");
			this.selectLoan(ev.src());
			disconnectAll(ev.src());
	}
	,selectLoan : function(row) {
		this.updateLoanAmountBox(evalJSON(row.getAttribute('value')));
	}
};
Report.prototype = {
	build : function() {
		if ($('ne-loan-calc')) this.parent.dom.collapseBox("ne-loan-calc");
		
		if (!this.parent.externalviewer) {
			var contactBtn = INPUT({'type':"submit",'value':"",'class':"ne-button-contact"});
			connect(contactBtn,"onclick",bind(this.contactAdvisor,this));
		} else {
			var contactBtn = "";
		}
		
		var reportSendBtn = INPUT({'type':"submit",'id':"report_send",'value':"",'class':"ne-button-report-send"});
		reportSendBtn.style.display = "none";
		
		var reportSaveBtn = INPUT({'type':"submit",'id':"report_save",'value':"",'class':"ne-button-report-save"});
		reportSendBtn.style.display = "none";
		
		var reportPrintBtn = INPUT({'type':"submit",'id':"report_print",'value':"",'class':"ne-button-report-print"});
		reportSendBtn.style.display = "none";
		
		var generating = SPAN({'id':"report_generating"},"Genererer...");
		generating.style.display = "inline";
		
		this.parent.dom.appendChildNodes(
			this.parent.dom.header(
				this.parent.text.report_result.title
		   		,DIV({'id':"report-result",'class':"block-visible nec-main-background nec-main-border"}
		   			,DIV({'class':"nec-content-image-report"})
			   		,DIV({'class':"margin-lrtb-wide"}
			   			//,this.parent.text.report_result.intro
						,DIV({'style': "width: 400px;float:right"}			   			
				   			,STRONG({'class':"ne-strong-title2",'style':"margin-top:12px;margin-bottom:12px"},"Vil du gøre din besparelse til virkelighed?")
							,P({'class':"p_paragraph",'style':"margin-top:5px;"},this.parent.text.report_result.intro_overview)	
			   			)
			   			,contactBtn
			   			//,DIV({'style': "width: 400px;float:right;height:40px"},contactBtn)
			   			,DIV({'style': "width: 400px;float:right;margin-top:5px"}	
			   				,this.parent.text.report_result.intro2)
			   				
			   			//,this.parent.dom.clear()
			   		)
			   		,this.parent.dom.step_footer()
			   		,H2({'class':"result"}, this.parent.text.report_result.reportbox_title)
			   		,DIV({'style':"background-color: white;"}
				   		,DIV({'class':"nec-reportbox"}
							,UL({'id':"ne-report-content"}
								,LI({},"Estimeret investering")
								,LI({},"Økonomisk besparelse")
								,LI({},"Samlet økonomisk besparelse for alle gennemførte beregninger i Miljøberegneren")
								,LI({},"CO",SPAN({'class':"sub"},"2"),"-besparelse")
								,LI({},"Samlet CO",SPAN({'class':"sub"},"2"),"-besparelse for alle gennemførte beregninger i Miljøberegneren")
								,LI({},"Månedlig ydelse efter skat")
								,LI({},"Månedlig besparelse")
								,LI({},"Månedlig fortjeneste")
								,LI({},"Samlet besparelse på 30 år")
							)
				   		)
				   		,DIV({'class':"report-image"}
							,reportSaveBtn
							,reportSendBtn
							,reportPrintBtn
							,generating
				   		)
			   		)
			   		,this.parent.dom.clear()
		   		)
			)
		);
		
		this.requestReport();
		nestat(NESTAT_STEP_REPORT, this.parent);
		
	}
	,requestReport : function() {
		
		try {
		ADFtrack(7642,29002);
		} catch (E) {}
		
		var parms = {};
		parms.buildingId = this.parent.calculation.building.id;
		parms.constructionYear = this.parent.calculation.result.response.building_year;
		parms.numberOfFloors = this.parent.calculation.result.options.number_of_floors.selected;
		parms.heatedArea = this.parent.calculation.result.response.total_area;
		parms.basement = this.parent.calculation.result.options.basement.selected;
		parms.inhabitedArea = this.parent.calculation.result.response.built_up_area;
		parms.roof = this.parent.calculation.result.options.roof_type.selected;
		parms.primaryHeatInstallationType = this.parent.calculation.result.options.primary_heat_source.selected;
		parms.primaryHeatInstallationYear = this.parent.calculation.result.response.primary_heat_source_installations_year;
		parms.primaryHeatPrice = this.parent.calculation.result.response.primary_heat_source_energy_price;
		parms.primaryUnit = this.parent.calculation.result.response.primary_heat_source_energy_unit;
		parms.heatingPlant = this.parent.calculation.result.options.distric_providers.selected;
		parms.secondaryHeatInstallationType = this.parent.calculation.result.options.secondary_heat_source.selected;
		parms.secondaryHeatInstallationYear = 0;
		parms.secondaryHeatPrice = this.parent.calculation.result.response.secondary_heat_source_price;
		parms.secondaryUnit = this.parent.calculation.result.response.secondary_heat_source_unit;
		parms.secondaryPeople = $("number_of_persons").value ? parseInt($("number_of_persons").value) : 0;
		parms.supplementalContribution = $("secondary_heat_source_usage") ? $("secondary_heat_source_usage").options[$("secondary_heat_source_usage").selectedIndex].value : 0;
		parms.afterIsolationLevelRoof = this.parent.calculation.result.options.roof_insulation.selected;
		if (this.parent.calculation.result.response.roof_insulation_out == "Ja") {
			parms.afterIsolationInvestmentRoof = this.parent.calculation.result.response.roof_insulation_invest_out;
		} else {
			parms.afterIsolationInvestmentRoof = 0;
		}
		parms.afterIsolationLevelWalls = this.parent.calculation.result.options.wall_insulation.selected;
		if (this.parent.calculation.result.response.wall_insulation_out == "Ja") {
			parms.afterIsolationInvestmentWalls = this.parent.calculation.result.response.wall_insulation_invest_out;
		} else {
			parms.afterIsolationInvestmentWalls = 0;
		}
		parms.afterIsolationLevelWindows = this.parent.calculation.result.options.windows.selected;
		if (this.parent.calculation.result.response.new_windows_out == "Ja") {
			parms.afterIsolationInvestmentWindows = this.parent.calculation.result.response.new_windows_invest_out;
		} else {
			parms.afterIsolationInvestmentWindows = 0;
		}
		parms.afterIsolationLevelBasement = this.parent.calculation.result.options.basement_insulation.selected;
		if (this.parent.calculation.result.response.basement_insulation_out == "Ja") {
			parms.afterIsolationInvestmentBasement = this.parent.calculation.result.response.basement_insulation_invest_out;
		} else {
			parms.afterIsolationInvestmentBasement = 0;
		}
		parms.heatSourceReplacement = this.parent.calculation.result.response.new_heat_source;
		parms.heatSourceReplacementInvestment = this.parent.calculation.result.response.new_heat_source_price;
		parms.totalInvestment = this.parent.calculation.result.response.combined_investments_out;
		parms.savings = this.parent.calculation.result.response.savings_out;
		parms.co2Savings = this.parent.calculation.result.response.co2_reduction_out;
		parms.inflation = 0;
		parms.heatingCost = this.parent.calculation.result.response.heat_consumption_estimate;
		
		parms.selectedLoan =this.parent.selectedloan;
		
		// GO!
		jsonRequest(parms, bind(this.reportGenerated, this), "ne/report");
	}
	,reportGenerated : function(result){
		$('report_generating').style.display = 'none';
		if (!this.parent.externalviewer) $('report_send').style.display = 'inline';
		$('report_save').style.display = 'inline';
		$('report_print').style.display = 'inline';
		connect('report_send','onclick',bind(this.contactAdvisor, this,$('report_send')));
		connect('report_save','onclick',bind(this.openReport, this, result.report, true));
		connect('report_print','onclick',bind(this.openReport, this, result.report, false));
	}
	,openReport : function(link, save){
		// whether mode=save is specified from service or not,
		// both links must work
		if (save) {
			//save report
			link = link+"&mode=save";
			tlsavepdf($('report_save'));
			gstatMbSaveReport();
			try{
				ADFtrack(7642,29004);//save report
			} catch (E) {}
		} else {
			//print report
			tlprintpdf($('report_print'));
			link = link.replace("mode=save", "mode=open");
			gstatMbPrint();
			try{
				ADFtrack(7642,29005);//print(open)
			} catch (E) {}	
		}
		if (this.parent.selectedloan) link = link + "&selectedloan="+this.parent.selectedloan;
		window.open(link, "_blank");
	}
	,contactAdvisor : function (elem){
		try {
			if (!myplanner.isLogged()){
				if (elem.src()) showError(elem.src(), "error.necalc.notloggedbook");
				else showError(elem, "error.necalc.notloggedbook");
			} else if (!this.parent.calculation) {
				if (elem.src()) showError(elem.src(), "error.necalc.notloggedbook");
				else showError(elem, "error.necalc.notloggedbook");
			} else if (!this.saved) {
				var introtext = ["For at du kan sende til din rådgiver, skal du først gemme beregningen i din boligmappe."];
				//change the report_send id to a special callback to allow stats for succesful clicks on send
				if (elem.src().id=='report_send') NEMessageBox(elem,"Navngiv beregning",introtext,bind(this.saveCalculationForAdvisorCallback,this),"report");
				else NEMessageBox(elem.src(),"Navngiv beregning",introtext,bind(this.saveCalculationForAdvisorCallback,this));
			} else if (!myplanner.getBranchId()) {
				lookup = new Lookup('lookup_map');
				lookup.bookMode = true;
				if (elem.src().id=='report_send') tlsendpdf($('report_send'));
				lookup.showSearchByList();
				lookup.origination = "nemodel";
			} else {
				if (elem.src().id=='report_send') tlsendpdf($('report_send'));
				bank_book.show(myplanner.getBranchId());
			}
			return false;
		} catch (e) {
		}
	}
	,saveCalculationForAdvisorCallback : function(e) {
		this.saveCalculationCallback(e);
		this.contactAdvisor();
	}
	,saveCalculation : function(elem) {
		if (myplanner.isLogged()){
			if (!this.parent.calculation) {
				showError(elem, "error.necalc.nocalc");
			} else {
				messageBox(elem,"Navngiv beregningen: ", bind(this.saveCalculationCallback,this));
			}
		}else{
			showError(elem, "error.necalc.notlogged");
		}	
		return false;
	}
	,saveCalculationCallback : function(e) {
		e.stop(); //stop propagation
		
		if (!this.parent.calculation.type)this.parent.calculation.type="ne_model";
		this.parent.calculation.laststate=this.parent.current_state;
		
		
		var d = doXHR(
			 "page?action=user.save.calculation&method=json&name=" + urlEncode($('name').value)
			,{
				 'method'		: "POST"
				,'sendContent'	: serializeJSON(this.parent.calculation)
			}
			);
		d.addCallback(bind(myplanner.refresh, myplanner));
		this.saved = true;
		removeElement('calc_name');
		return false;
	
	}
	,requestLinks : function() {
	}
	,calbackLinks : function(result) {
	}
};
var NESTAT_STEP_INIT = "init";
var NESTAT_STEP_CALC = "calc";
var NESTAT_STEP_LOAN = "loan";
var NESTAT_STEP_REPORT = "report";
var NESTAT_EVENT21 = false;
var NESTAT_EVENT22 = false;
var NESTAT_EVENT23 = false;
var NESTAT_EVENT24 = false;
function nestat(step, model, extra) {
	result=ne_model.calculation.result;
	
	switch (step) {
	case NESTAT_STEP_INIT:
	
		// adftrack
		try { ADFtrack(7642,28991); } catch (E) {}
		
		// simple hit track
		jsonRequest({}, function(e){}, "simple_hit");
		
		// tstat track
		if (extra.hasdata) {
			// set event21 as used and abort completely
			NESTAT_EVENT21 = true;
			break;
		}
		var parms = {};
		
		/*
		parms.eVar11 = "totalkredit.dk";
		if (!NESTAT_EVENT21) {
			NESTAT_EVENT21 = true;
			parms.events = "event21";
		}
		if (model.externalviewer){
			parms.eVar10 = parms.prop23 = model.extid;
		}
		*/
		
		if (!NESTAT_EVENT21) {
			NESTAT_EVENT21 = true;
			parms.events = "event21";
		}
		if (ne_model.externalviewer){
			parms.eVar10 = parms.prop23 = ne_model.extid;
		} else {
			parms.eVar11 = "totalkredit.dk";
		}
		
		//Append multivariate testing parms (see stats.js for details)
		parms=setCalcVariant(parms);
		
		tstat("Miljø", "Miljøberegner - Introduktion", "Velkommen,Miljø,Miljøberegner,Introduktion", parms);	
	
		break;
		
		
		
	case NESTAT_STEP_CALC:
	
		// adftrack
		try { ADFtrack(7642,28996); } catch (E) {}
		
		// tstat track
		var insulation_investment =
			(
			 extra.result.response.wall_insulation_invest_out +
			 extra.result.response.roof_insulation_invest_out +
			 extra.result.response.new_windows_invest_out +
			 extra.result.response.basement_insulation_invest_out
			) || 0;
		var installation_investment = extra.result.response.new_heat_source_price || 0;
		var parms = {
			'prop5':"Efterisolering - Udskiftning af primær varmekilde",
			'prop6':insulation_investment+" - "+installation_investment
		};
		if (!NESTAT_EVENT22) {
			NESTAT_EVENT22 = true;
			parms.events = "event22";
		}
		
		//Append multivariate testing parms (see stats.js for details)
		parms=setCalcVariant(parms);
		
		tstat("Miljø","Miljøberegner - Beregning","Velkommen,Miljø,Miljøberegner,Beregning",parms);

		break;
		
		
		
	case NESTAT_STEP_LOAN:
	
		// adftrack
		try { ADFtrack(7642,28998); } catch (E) {}
		
		// internal track result
		var val = extra.result.response.savings_out;
		var co2 = extra.result.response.co2_reduction_out;
		jsonRequest({'co2':Math.round(co2),'val':Math.round(val)}, function(e) {}, "update_total");
		
		
		// tstat track 	
 		var stats = extra.loaninfo;
 		var parms;
 		
 		if (stats.laantype==1||stats.laantype==2){
 			//fast rente
 			var desc=stats.laanebetegnelse;
 			var orente=stats.obligationsRente;
 			var afdrag=""+(stats.afdragsfrihed ? "10 år" : "Nej");
 			var loebetid=stats.loebetid;
 			var ydelse=stats.ydelsePrMndFoerSkat + "/"+stats.ydelsePrMndEfterSkat;
 			var amount=stats.beloebTilUdbetaling;
 			
 			var loanstring=desc
 						+", "+orente
 						+", "+afdrag
 						+", "+loebetid
 						+" mdr, " + ydelse; 	
 			parms={'prop10':loanstring
 				 ,'prop11': desc
 				 ,'prop16': orente
 				 ,'prop13': afdrag
 				 ,'prop14': loebetid
 				 ,'prop15': ydelse
 				 ,'eVar5' : loanstring
 				 ,'prop21': amount
 			}	
 		}
 		if (stats.laantype==5){
 			//variabel rente
 			var desc=stats.laanebetegnelse;
 			var reff=stats.refFrekvens;
 			var afdrag=""+(stats.afdragsfrihed ? "10 år" : "Nej");
 			var loebetid=stats.loebetid;
 			var ydelse=stats.ydelsePrMndFoerSkat + "/"+stats.ydelsePrMndEfterSkat;
 			var amount=stats.beloebTilUdbetaling;
 			
 			var loanstring=desc
 						+", "+reff
 						+", "+afdrag
 						+", "+loebetid
 						+" mdr, " + ydelse; 	
 			parms={'prop10':loanstring
 				 ,'prop11': desc
 				 ,'prop12': reff
 				 ,'prop13': afdrag
 				 ,'prop14': loebetid
 				 ,'prop15': ydelse
 				 ,'eVar6' : loanstring
 				 ,'prop21': amount
 			}	
 			
 		}
 		if (stats.laantype==3){
 			//renteloft
 			var desc=stats.laanebetegnelse;
 			var renteloft=stats.renteLoft;
 			var udrente=stats.udloebsAar;
 			var afdrag=""+(stats.afdragsfrihed ? "10 år" : "Nej");
 			var loebetid=stats.loebetid;
 			var ydelse=stats.ydelsePrMndFoerSkat + "/"+stats.ydelsePrMndEfterSkat;
 			var amount=stats.beloebTilUdbetaling;
 			
 			var loanstring=desc
 						+", "+renteloft
 						+", "+udrente
 						+", "+afdrag
 						+", "+loebetid
 						+" mdr, " + ydelse; 	
 			parms={'prop10':loanstring
 				 ,'prop11': desc
 				 ,'prop17': renteloft
 				 ,'prop18': udrente
 				 ,'prop13': afdrag
 				 ,'prop14': loebetid
 				 ,'prop15': ydelse
 				 ,'eVar7' : loanstring
 				 ,'prop21': amount
 			}	
 		}
		if (!NESTAT_EVENT23) {
			NESTAT_EVENT23 = true;
			parms.events = "event23";
		}
		
		//Append multivariate testing parms (see stats.js for details)
		parms=setCalcVariant(parms);
		
		tstat("Miljø","Miljøberegner - Låneberegning","Velkommen,Miljø,Miljøberegner,Låneberegning",parms);
		break;
		
		
		
	case NESTAT_STEP_REPORT:
		
		// adftrack
		try { ADFtrack(7642,28999); } catch (E) {}
		
		// tstat track 	
		var parms = {};
		if (!NESTAT_EVENT24) {
			NESTAT_EVENT24 = true;
			parms.events = "event24";
		}
		
		//Append multivariate testing parms (see stats.js for details)
		parms=setCalcVariant(parms);
		
		tstat("Miljø","Miljøberegner - Rapport","Velkommen,Miljø,Miljøberegner,Rapport", parms);
		
		//fb conversion tracking from banners	
		try{
				var visitor=parseQueryString(document.location.search).visitor;
				if (visitor && visitor == 'fbannonce')fb_convert_report();
		}catch(e){}
		
		
		break;
	}
}
addLoadEvent(function () {
	ne_model = new NeModel();
});

function doFbInit(){
		//Initialize FB app code
		
		//Keys to idenfify the app
		//8dbec3ec6ce3fb2887fc8c5667a69249 <-- dev
		//53936fad67d530a83f449544c1b04010 <-- live
		//var api_key = "8dbec3ec6ce3fb2887fc8c5667a69249";
		var api_key = "53936fad67d530a83f449544c1b04010";				
		
		//url for fb stuff: /TKdk/resources/fb/xd_receiver.html used for receiving callbacks
		var channel_path = "/TKdk/resources/fb/xd_receiver.html";
		try{
			FB.init(api_key, channel_path, {"ifUserConnected": fbMbConnected});
		}catch(E){}
}
function doFbAction(){
	//action for fb link
	
	//Stats for facebook share
	if ($('fbconnlink')) tlfacebookshare($('fbconnlink'));
	
	//check if already connected/logged in facebook
	if (ne_model.fbconnected){
		//connected, determine if link or story
		if (ne_model.current_state != "init") doFbFeed();
		else doFbShare();
	}else{
		//login before checking what to do
		doFbConnect();
	}
}
function doFbConnect (){
		//call fb.connect, maybe init first
		FB.Connect.requireSession(onfbconnect);
		return false;
}

function fbMbConnected(val_uid){
		//callback if user is already logged in when visiting page
		ne_model.fbconnected=true;
}
function onfbconnect(){
		//callback on user login
		//straight to feed dialog after succesful login
		ne_model.fbconnected=true;
		doFbAction();
}
function doFbShare(){
			//share link, javascript version
			var mbdeeplink="http://www.totalkredit.dk/TKdk/page?action=ne.calculation&js=f";
			//if ((window.location+"").indexOf("calc.tkdk")>-1) mbdeeplink="http://calc.tkdk.internal.shockwaved.com/TKdk/?action=ne.calculation&js=f";
			FB.Connect.showShareDialog(mbdeeplink);
			return false;			
}
function doFbFeed(){
		//collect args (in json object)dFormat(parseInt(response.savings_out), "0,000");
		//new template id for dev: 103929133948, live: 125049735984
		var tdata={"savings":dFormat(parseInt(ne_model.calculation.result.response.savings_out), "0,000")
					,"comment-title":"har sparet penge med Miljøberegneren"
					,"calc-title":"Totalkredits miljøberegner"
					,"calc-link-name":"Prøv Miljøberegneren"
					,"calc-link-url":"http://www.totalkredit.dk/TKdk/page?action=ne.calculation"
					,"images":[{"src":"http://calc.tkdk.internal.shockwaved.com/TKdk/resources/fb/mblogo.jpg"
								,"href":"http://www.totalkredit.dk/TKdk/page?action=ne.calculation"}]};
		//activate feed where first param is template id and tdata is the json object
		FB.Connect.showFeedDialog(125049735984,tdata); 
}

function doFbLogout(){
		//Log out Facebook and change state
		ne_model.fbconnected=false;
		FB.Connect.logout();
}

function fb_convert_report(){
	//fb conversion tracking from banners
	try {
		//specific for tkdk facebook banner campaign
		var params={'id' : 6002455847699,'h' : 'dcf45132b6','value' : 12};
	
 	  var g = 'f' + (Math.random() * (1<<30)).toString(16).replace('.', '');
	  var u = "//ah8.facebook.com/impression.php/" + g + "/";
	  var i = new Image(1, 1);
	  var s = [];
	
	  for (var k in params) {
	    s.push(encodeURIComponent(k) + '=' + encodeURIComponent(params[k]));
	  }
	
	  u += '?' + s.join('&');
	  i.src = u;
  } catch (e) {}
}