/*************************
* CONFIGURATION
******************/
var ENERGYCHECK_CONFIG =  {
	//calculation-Values
	radix:        						10,
	heatedANCellarFactor: 				1.2,
	heatedANNormalFactor: 				1.35,
	oilBurningValue: 					10.08,

	// Default-Values
	// year of construction
	yearOfConstruction: 				1980,
	boilerType: 						"Standard",
	windowType: 						"DoubleGlazed",
	thermalPower:                       30,

	//animations	
	pointerAnimationMS: 				1500,
	pointerAnimationMS_Vertical: 		500,    //Do we need another animation time
	pointerMinOffset: 					10,		//Minimum offset of the pointers, set a horizontal displacement if below this offset
	pointerVerticalOffset: 				25,
	pointerWidth:                       48,
	barAnimationMS: 					1500,
	overviewBarLength: 					126,
	overviewBarScaleFactor: 			600,	//Hardcoded Scalefactor?
	tabAnimationMS: 					1000,
	tabBarScaleFactor: 					500,	//Hardcoded Scalefactor?
	minEnergyPositionValue: 			470		//What exactly is this?
}
var V_0					= 0;
var V_1					= 1;
var V_2					= 2;
var V_3					= 3;
var V_n					= 4;
var INF					= 999999999;

var buildingInfoExportStorage = [];

var getWallInsulationThickness = function( building, walltype, buildingindex, v0thickness ) {
	var storeyWalls;
	
	switch(walltype){
		case HsEtuStoreyWall.type.Floor:
			storeyWalls = building.lowestHeatedStorey().getHsEtuStoreyWall({ type: walltype });
		break;
		case HsEtuStoreyWall.type.Ceilling:
			storeyWalls = building.highestHeatedStorey().getHsEtuStoreyWall({ type: walltype });
		break;
		default:
			storeyWalls = building.getHsEtuStorey({ type: HsEtuStorey.type.EG })[0].getHsEtuStoreyWall({ type: walltype });
		
	}	

	for (var i=0; i < storeyWalls.length; i++)
	{
		
		if (storeyWalls[i].getHsEtuWall().getHsEtuInsulation().length > 0)
		{
			var res = storeyWalls[i].getHsEtuWall().getHsEtuInsulation()[0].getThickness() * 100;
			
			if(storeyWalls[i].getHsEtuWall().getHsEtuInsulation().length == 1 && buildingindex > V_0 )
				res = res - v0thickness;
			return res;
		}
	}
	
	
	return 0;
};

var getBoilerType = function( building ) {
	if( building.getHsEtuDevice({ type : HsEtuDevice.type.HeatingBoiler,	boilerType : HsEtuHeatingBoiler.boilerType.Condensing	}) != '' )
		return 'Brennwertkessel';
	if( building.getHsEtuDevice({ type : HsEtuDevice.type.HeatingBoiler,	boilerType : HsEtuHeatingBoiler.boilerType.LowTemperature	}) != '' )
		return 'Niedertemperaturkessel';
	
	return 	'Standardkessel';
}

var getWindowType = function( building ) {
	if( building.getHsEtuElement({ type : HsEtuElement.type.OutsideWindow, isolationType: HsEtuWindow.isolationType.HeatAbsorbingTrippleGlazed }) != '' )
		return '3-Scheiben-Wärmeschutzverglasung';
	if( building.getHsEtuElement({ type : HsEtuElement.type.OutsideWindow, isolationType: HsEtuWindow.isolationType.HeatAbsorbingDoubleGlazed }) != '' )
		return '2-Scheiben-Wärmeschutzverglasung';
	if( building.getHsEtuElement({ type : HsEtuElement.type.OutsideWindow, isolationType: HsEtuWindow.isolationType.DoubleGlazed }) != '' )
		return 'Doppelverglasung';
	
	return 	'Einfachverglasung';
}

/*************************
* INTERACTIVE ACTIONS
******************/
function getConsumptionText( energyValue, oilCosts ) {
	if (energyValue > 250) {
		html = "Der Energieverbrauchs-Kennwert Ihres Hauses liegt im " +
		"roten Bereich.<br />Das bedeutet, dass Ihr Energieverbrauch " +
		"überdurchschnittlich hoch ist. Höchstwahrscheinlich ist Ihr " +
		"Haus schlecht gedämmt und die Heizung veraltet.<br /><br />" +
		"Dadurch geben Sie jedes Jahr rund <strong>" + 
		oilCosts + 
		"</strong> Euro für Heizung und Warmwasser aus. Um die " +
		"Ausgaben deutlich zu senken, empfehlen wir Ihnen, Ihr Gebäude " +
		"energetisch zu sanieren. Finden Sie im zweiten Schritt " +
		"heraus, welche Maßnahmen infrage kommen, was sie bringen und " +
		"was sie kosten.";
	} else if (energyValue < 250 && energyValue > 100){
		html = "Der Energieverbrauchs-Kennwert Ihres Hauses liegt im " +
		"gelben Bereich.<br />Sie haben also einen durchschnittlich " +
		"hohen Energieverbrauch.<br /><br />Dadurch geben Sie jedes Jahr " +
		"rund <strong>" + 
		oilCosts + 
		"</strong> Euro für Heizung und Warmwasser aus. Hier gibt " +
		"es Einsparpotenzial. Finden Sie im nächsten Schritt heraus, " +
		"wo sich eine Modernisierung lohnt.";
	} else {
		html = "Herzlichen Glückwunsch! Der Energieverbrauchs-Kennwert " +
		"Ihres Hauses liegt im grünen Bereich. Das bedeutet, dass Sie " +
		"einen sehr niedrigen Energieverbrauch haben.<br />Vermutlich " +
		"haben Sie Ihr Haus bereits gut gedämmt und mit moderner " +
		"Heizungstechnik ausgestattet. Mehr Energie lässt sich durch " +
		"Sanierung kaum sparen.";
	}
	
	return html;
}


function ivActivateMenu (div, id, variation, areaType) {

	$('#configBuilding' + variation + ' div.configBuildingButton.active').removeClass('active');
	$('#configBuilding' + variation + ' div.configBuildingMenuOverlayForm').addClass('hidden');
	$('#' + id).removeClass('hidden');
	$("input[name=activeArea]").val(areaType);

	$(".configBuildingButton").removeClass('active');
	$(".configBuildingMenuOverlayForm").addClass('hidden');
	$(".area" + ucfirst(areaType)).addClass('active');
	$(".menu" + ucfirst(areaType)).removeClass('hidden');
}


function ivDeactivateMenu(object, areaType) {
	
	$(".area" + ucfirst(areaType)).removeClass('active');
	$(".menu" + ucfirst(areaType)).addClass('hidden');
	
	return false;
}


/**
 * shows the Vtab which was clicked and calls the setInvestmentBars function
 * 
 * @param {Object} element
 * @param {Object} variation
 * 
 * @see setInvestmentBars
 */
function showVtab (element, variation) {
	
	$("input[name=variationType]").val(variation);
	
	$('div.configBuildingWrapper').hide();

	$('#configBuilding' + variation).show();
	$('#small_tabs div.tab div').removeClass('act_tab');
	$('#small_tabs div.tab div').addClass('pas_tab');
	$(element).parent().removeClass('pas_tab');
	$(element).parent().addClass('act_tab');
	
	if (variation == V_0) {
		$("#descriptionBox").slideUp();
	} else {
		$(".description").hide();
		$("#descriptionBox").slideDown("slow", function() {
			$("#description" + variation).fadeIn("slow");
		});
	}
	
	if ($.browser.msie) {
		var tabs = $("#configBuilding" + variation + " .configBuildingMenuOverlayForm.hidden");
		// force redraw in IE
		tabs.removeClass("hidden");
		tabs.addClass("hidden");
	}
	setInvestmentBars(variation);
	return false;
}


/**
 * sets the clicked rooftype as active
 * 
 */
function chooseRoofType(element, value, variation){
	$('#roofType_v' + variation).val(value);
	$('a.chooseRoofType.active').removeClass('active');
	$(element).addClass('active');
	return false;
}


/*************************
* RENDERING
******************/

function adjustPointers() {

	var i;
	var n;
	var positionValuesArray 	= [];
	var taintedPositionsArray 	= [];
	var pointersSet 			= false;
	var topValue 				= 0;
	var increaseFactor 			= ENERGYCHECK_CONFIG.pointerVerticalOffset;

	for (i = V_0; i < V_n; i++) {
		var position = $("#variante_" + i).css("left");
		positionValuesArray[i] = position.substr(0, (position.length - 2));
	}
	
	for (i = V_0; i < V_n; i++) {	
		for (n = V_0; n < V_n; n++) {
			if (i != n) {
				var result = (parseInt(positionValuesArray[i], ENERGYCHECK_CONFIG.radix) - parseInt(positionValuesArray[n], ENERGYCHECK_CONFIG.radix));

				if (result < ENERGYCHECK_CONFIG.pointerMinOffset) {
					array_push(taintedPositionsArray, i);
					break;
				}
			}
		}	
	}
	
	$("div.configBuilding").animate({
			paddingBottom: ((increaseFactor * taintedPositionsArray.length) - increaseFactor) + "px"
		}, 
		ENERGYCHECK_CONFIG.pointerAnimationMS_Vertical, 
		function() {
					
			for (var taintedCounter = V_0; taintedCounter < V_n; taintedCounter++) {
				if (taintedCounter > V_0) {
					topValue = topValue + increaseFactor; 
				}
	
				$('#variante_' + taintedPositionsArray[taintedCounter]).animate({
					top: topValue + "px"
				}, ENERGYCHECK_CONFIG.pointerAnimationMS_Vertical);
			}

		}
	);
		
	pointersSet	= true;
}


function setOverviewBars(variation) {
	
	if (variation == V_0){ return; }
	
	var total = $("input[name=totalInvestmentValue_v" + variation + "]").val();
	var single = $("#savings_v" + variation + "_number").val();
	var intervall = $("select[name=analysesIntervall_v" + variation + "]").val();
	
	var investment 	= ENERGYCHECK_CONFIG.overviewBarLength - Math.floor(Number(total) / ENERGYCHECK_CONFIG.overviewBarScaleFactor);
	var saving 		= ENERGYCHECK_CONFIG.overviewBarLength - Math.floor(Number(single * intervall) / ENERGYCHECK_CONFIG.overviewBarScaleFactor);

	// make sure value is between 0 and bar length
	investment = Math.max( 0, Math.min(investment, ENERGYCHECK_CONFIG.overviewBarLength) );
	saving = Math.max( 0, Math.min(saving, ENERGYCHECK_CONFIG.overviewBarLength) );

	$("#investmentCosts_v" + variation).animate({
		backgroundPosition: "-" + investment + "px"
	}, ENERGYCHECK_CONFIG.barAnimationMS );
	
	$("#savings_v" + variation).animate({
		backgroundPosition: "-" + saving + "px"
	}, ENERGYCHECK_CONFIG.barAnimationMS );
}


/**
 * caclulates the bars for the several sections in a tab
 * 
 * @param int index = number of the selected tab
 */
function setInvestmentBars(variation) {
	
	/**
	 * Assigns the value of a given field to the corresponding investment bar.
	 * @param {String} id The ID of the bar.
	 * @param {String} name The name of the field. 
	 */
	var _animate = function(id, name){
		var element = $("#" + id +"_v" + variation);
		var field = $("input[name=" + name + "_v" + variation + "]");
		var value = field.val();
		element.animate({width: calculateBars(value) + "px"}, ENERGYCHECK_CONFIG.tabAnimationMS);
	};
	
	// Hash with id:name values to animate.
	var parts = {
		heatingRed: 	"investmentcostsHeating",
		solarRed: 		"investmentcostsSolar",
		buildingRed: 	"investmentcostsBuilding",
		insulationRed: 	"investmentcostsInsulation",
		windowsRed: 	"investmentcostsWindow"
	};
	
	$.each(parts, _animate);
}


/*************************
* PRINT PDF
******************/
function generatePDF() {
	
}


/*************************
* CALCULATIONS
******************/


/**
 * helper function to caclulate the bars' length
 * 
 * @param {Object} value
 * @param {Object} savings
 */
function calculateBars(value) {
	return (value / ENERGYCHECK_CONFIG.tabBarScaleFactor) / 2;
}


/*************************
* API REQUESTS - this is where the music rocks and the lines are on fire..
******************/

/**
 * Returns the full API request URL. 
 * This mehtod cares about debug settings.
 * 
 * @param {String} method The API method to call.
 * @returns {String} The URL.
 * 
 * @example
 * 	var url = apiUrl("CalculateEnergyDemand");
 */
function apiUrl(method){
	var debug = $("input[name=debug]:checked").val();
	var stageHost   = "217.7.165.237/CalcServiceStage";
	var liveHost   = "217.7.165.237/CalcService";
	var host = debug ? "localhost:51377" : ((window.location.hostname == 'iwo.stage.kmf-port.de') ? stageHost : liveHost);
	var url = "http://" + host + "/HsEtuCalcService.svc/";
	return url + method;
}

function myConsoleLog( attr ) {
	//if (typeof console != "undefined" && window.location.hostname == 'iwo.stage.kmf-port.de') {
	if (typeof console != "undefined") {
		console.log( attr );
	}
}

/**
 * Sets the calculation base values in the investmentcosts-object
 *
 */
function setCalculationBaseOnBuilding(variation) {
	//Create investment-costs object
	var investmentCosts = new HsEtuInvestmentCosts();
	
	//Set Investment-costs from configuration-object
	investmentCosts.setWoodBurningStove( ENERGYCHECK_CONFIG.woodBurningStove );
	investmentCosts.setVentilationHeatRejectionSqm( ENERGYCHECK_CONFIG.ventilationHeatRejectionSqm );
	investmentCosts.setDrinkingWaterSolarSupport( ENERGYCHECK_CONFIG.solarSupportWarmWater );
	investmentCosts.setHeatingSolarSupport(	ENERGYCHECK_CONFIG.solarSupportHeating );
	investmentCosts.setHeatingCondensingBoilerDevice( ENERGYCHECK_CONFIG.heatCondensingBoiler );
	investmentCosts.setInsulationWindowHeatAbsorbingTrippleGlazedSqm( ENERGYCHECK_CONFIG.trippleGlazedHeatAbsorbingSqm );
	investmentCosts.setInsulationWindowHeatAbsorbingDoubleGlazedSqm( ENERGYCHECK_CONFIG.doubleGlazedHeatAbsorbingSqm );
	investmentCosts.setInsulationWindowDoubleGlazedSqm( ENERGYCHECK_CONFIG.doubleGlazedSqm );
	investmentCosts.setInsulationRoofSqm( ENERGYCHECK_CONFIG.roofInsulationSqm );
	investmentCosts.setInsulationOutsideWallSqm( ENERGYCHECK_CONFIG.wallInsulationSqm );
	investmentCosts.setInsulationBasementSqm( ENERGYCHECK_CONFIG.cellarCeilingSqm );
	investmentCosts.setInsulationCeillingSqm( ENERGYCHECK_CONFIG.topCeilingSqm );

	//Link investment-costs to the building
	hsEtuBuildings[variation].setHsEtuInvestmentCosts( investmentCosts );
}

function getOilStock() {

	var openingFillLevel = 0;


	if (ascertainment == 1) {
		openingFillLevel = mv_opening_stock + mv_oilpurchases;
	} else {
		openingFillLevel = mv_opening_stock;
	}
	
	var stock = new HsEtuStock();
	stock.setOpeningValue(openingFillLevel);
	stock.setOpeningDate(new Date(mv_opening_year, mv_opening_month - 1, mv_opening_day));
	stock.setClosingValue(mv_closing_stock);
	stock.setClosingDate(new Date(mv_closing_year, mv_closing_month - 1, mv_closing_day));
	
	return stock;
}


/**
 * Calculates the energy demand for a given variation.
 * This method will call the API and later update the interface.
 */
function calculate_energy_demand(variation) {



	/**
	* Callback method that is invoked after the CalculateEnergyDemand-Api-Call
	*
	**/
	var callback = function(data){

		/**
		 * Sets the value of a given field.
		 * @param {String} name The base name of the field.
		 * @param {Number} value The value to assign.
		 * @example
		 * 	_setFieldValue("totalInvestmentValue", 10); 
		 */
		var _setFieldValue = function(name, value){
			var element = $("input[name=" + name + "_v" + variation + "]");
			element.val(Math.floor(value));
		};

		
		var energyPositionValue, energyValue, costs, investFields, totalInvestmentCosts;
	
		//Oilconsumption
		var oilConsumptionLitre			= hsEtuBuildings[variation].getHsEtuDevice({ type : HsEtuDevice.type.HeatingBoiler })[0].calcMeasuredConsumptionFromDemandPerYear( HsEtuEnergySource.type.Oil);
		var oilConsumptionDelta 		= ( hsEtuBuildings[0].getHsEtuDevice({ type : HsEtuDevice.type.HeatingBoiler })[0].calcMeasuredConsumptionFromDemandPerYear( HsEtuEnergySource.type.Oil) - oilConsumptionLitre);//We use the savings X0-X1
		var oilConsumptionCosts			= Math.round( oilConsumptionLitre *  ENERGYCHECK_CONFIG.oilLitrePrice );
		var oilConsumptionCostsDelta 	=  Math.round( oilConsumptionDelta *  ENERGYCHECK_CONFIG.oilLitrePrice );
		
		var v1consumption = hsEtuBuildings[V_0].getHsEtuConsumption({type: HsEtuConsumption.type.Current})[0];
		var V1consumptionVolume = v1consumption.getConsumptionAdditionalVol();

		// wood-consumption (http://redmine.kmf.de/issues/11657#note-17) difference if there is any wood-consumption in Step 1 or not
		if(V1consumptionVolume > 0)
			var additionalWoodConsumption = hsEtuBuildings[variation].getUltimateEnergyVolumeAdditionalHeatingByConsumption();
		else
			var additionalWoodConsumption = hsEtuBuildings[variation].getUltimateEnergyVolumeAdditionalHeatingByMainConsumption();
		
		
		var woodConsumptionDelta		 = (V1consumptionVolume - additionalWoodConsumption);//We use the savings X0-X1
		var additionWoodConsumptionCosts = Math.round( additionalWoodConsumption *  ENERGYCHECK_CONFIG.woodRMPrice );
		var woodConsumptionCostsDelta	 = Math.round( woodConsumptionDelta *  ENERGYCHECK_CONFIG.woodRMPrice );
		//

		var analysisInterval = 0;
		if (variation > V_0) {
			analysisInterval =  $("select[name=analysesIntervall_v" + variation + "]").val();
			$("#savings_v" + variation + "_number").val( oilConsumptionCostsDelta+woodConsumptionCostsDelta  );//Einsparung Öl PA
			$("#savings_v" + variation).html( formatNumber(   analysisInterval *  (oilConsumptionCostsDelta+woodConsumptionCostsDelta) ) );//Einsparung über Zeitraum
			//$("boilerNominalPower_v" + variation).val( hsEtuBuildings[variation].getHsEtuDevice()[0].getNominalPower() );
		}


		/*************
		 * investment costs and savings
		 ******/
		costs = data.HsEtuInvestmentCosts;
		
		// before we fill in the values check if investmentcosts are given 
		// because variant 3 is equal to variant 0 which means there is 
		// no investmentcost..
		if (costs) {
			totalInvestmentCosts = Math.floor(costs.TotalInvestmentCosts);
			
			// update 
			$("#investmentCosts_v" + variation).html(formatNumber(totalInvestmentCosts));

			myConsoleLog(costs);

			investFields = {
				totalInvestmentValue: 		costs.TotalInvestmentCosts,
				investmentcostsHeating: 	costs.VentilationHeatRejection + costs.HeatingCondensingBoiler + costs.WoodBurningStove,
				investmentcostsSolar: 		costs.HeatingSolarSupport + costs.DrinkingWaterSolarSupport,
				investmentcostsBuilding: 	0,
				investmentcostsInsulation: 	costs.InsulationOutsideWall + costs.InsulationBasement + costs.InsulationCeilling + costs.InsulationRoof,
				investmentcostsWindow: 		costs.InsulationWindowHeatAbsorbingTrippleGlazed || costs.InsulationWindowHeatAbsorbingDoubleGlazed || costs.InsulationWindowDoubleGlazed || 0
			};
			
		} else {
			$("#investmentCosts_v" + variation).html("-");
			
			totalInvestmentCosts = 0;
			
			investFields = {
				totalInvestmentValue: 		0,
				investmentcostsHeating: 	0,
				investmentcostsSolar: 		0,
				investmentcostsBuilding: 	0,
				investmentcostsInsulation: 	0,
				investmentcostsWindow: 		0
			};
		}
		
		// set value of each given field
		$.each(investFields, _setFieldValue);



		/*************
		 * setting pointers on scala
		 ******/
		// store the (adapted) consumption locally
		energyValue = Math.round( hsEtuBuildings[variation].getUltimateEnergyDemandByConsumption());

		if (variation == V_0) {
			//Write the consumption to text-field, if this is variant 0
			$("input[name=energyconsumptionparameter]").val( energyValue );
		}

		//Set the consumption information text in the print-layout
		$("#consumptionPrintInformation").html( getConsumptionText( energyValue,  Math.round( oilConsumptionLitre *  ENERGYCHECK_CONFIG.oilLitrePrice ) ) );
		//Set specific building information
		var boiler				= hsEtuBuildings[variation].getHsEtuDevice({ type : HsEtuDevice.type.HeatingBoiler })[0];
		var boilerYOC			= ( typeof boiler != 'undefined' ) ? boiler.getYearOfConstruction() : ENERGYCHECK_CONFIG.yearOfConstruction;
		var thermalPower		= ( typeof boiler != 'undefined' ) ? boiler.getFiringThermalPower() : ENERGYCHECK_CONFIG.thermalPower;
		var burner 				= ( typeof boiler != 'undefined' ) ? boiler.getHsEtuHeatingBurner()[0] : '';
		var burnerYOC			= ( typeof burner != 'undefined' && burner != '' ) ? burner.getYearOfConstruction() : boilerYOC;
		var heatrecovery	 	= hsEtuBuildings[variation].getHsEtuDevice({ type : HsEtuDevice.type.Ventilation, heatRecovery : true });
		var solardevice_ww 		= hsEtuBuildings[variation].getHsEtuDevice({ hsEtuEnergySource : { type: HsEtuEnergySource.type.Solar }, drinkingWaterType: HsEtuHeatingDevice.drinkingWaterType.StorageTank });
		var solardevice_h 		= ( solardevice_ww == '' ) ? hsEtuBuildings[variation].getHsEtuDevice({ hsEtuEnergySource : { type: HsEtuEnergySource.type.Solar } }) : '';

			
		var locationType		= "";
		switch( hsEtuBuildings[variation].getLocationType() ) {
			case HsEtuBuilding.locationType.Detached:
				locationType = 'freistehend';
				break;
			case HsEtuBuilding.locationType.Middle:
				locationType = 'Reihenmittelhaus';
				break;
			default:
				locationType = 'Doppelhaushälfte oder Reihenendhaus';
		}

		
		//Export Storage
		buildingInfoExportStorage[variation] = {
			zip							: zip, //global value energyFormStep_3.html
			objectlocation				: objectlocation, //global value energyFormStep_3.html
			address						: address, //global value energyFormStep_3.html
			objectname					: objectname, //global value energyFormStep_3.html
			additionalPurchaseDate1 	: additionalPurchaseDate1, //global value energyFormStep_3.html
			additionalPurchaseValue1 	: additionalPurchaseValue1, //global value energyFormStep_3.html
			additionalPurchaseDate2 	: additionalPurchaseDate2, //global value energyFormStep_3.html
			additionalPurchaseValue2 	: additionalPurchaseValue2, //global value energyFormStep_3.html
			additionalPurchaseDate3 	: additionalPurchaseDate3, //global value energyFormStep_3.html
			additionalPurchaseValue3 	: additionalPurchaseValue3, //global value energyFormStep_3.html
			additionalPurchaseDate4 	: additionalPurchaseDate4, //global value energyFormStep_3.html
			additionalPurchaseValue4 	: additionalPurchaseValue4, //global value energyFormStep_3.html
			additionalPurchaseDate5 	: additionalPurchaseDate5, //global value energyFormStep_3.html
			additionalPurchaseValue5 	: additionalPurchaseValue5,	//global value energyFormStep_3.html
			initialDate 				: ""+mv_opening_day+"."+mv_opening_month+"."+mv_opening_year+"", //global value energyFormStep_3.html
			initialFilllevel 			: mv_opening_stock, //global value energyFormStep_3.html
			closingDate 				: ""+mv_closing_day+"."+mv_closing_month+"."+mv_closing_year+"", //global value energyFormStep_3.html
			closingFilllevel 			: mv_closing_stock, //global value energyFormStep_3.html
			oilconsumption 				: mv_oilconsumption, //global value energyFormStep_3.html
			woodConsumptionStep1		: mv_woodconsumption,
			oilConsumptionLitrePA		: oilConsumptionLitre,
			woodConsumption 			: additionalWoodConsumption,
			yoc 						: hsEtuBuildings[variation].getYearOfConstruction(),
			locationType 				: locationType,
			flatType	 				: flatType,
			cellar						: (cellar == 1 		? 'Ja' : 'Nein'),
			heatedTopFloor 				: (heatedTopFloor == 1 		? 'Ja' : 'Nein'),
			heatedStoreys 				: heatedStoreys+1+(cellar == 1 ? 1 : 0)+(heatedTopFloor == 1 ? 1 : 0),
			basicFloorArea 				: basicFloorArea,
			/* heatedFloorArea is not used anymore #13979
			heatedFloorArea 			: heatedFloorArea,
			*/
			boilerYOC 					: boilerYOC,
			thermalPower 				: thermalPower,
			burnerRenewed 				: (burnerYOC > boilerYOC		? 'Ja' : 'Nein'),
			boilerType 					: getBoilerType(hsEtuBuildings[variation]),
			heatrecovery 				: (heatrecovery != "" 		? 'Ja' : 'Nein'),
			solardevice_ww 				: (solardevice_ww != "" 	? 'Ja' : 'Nein'),
			solardevice_h 				: (solardevice_h != "" 		? 'Ja' : 'Nein'),
			insulationWall				: getWallInsulationThickness( hsEtuBuildings[variation], HsEtuStoreyWall.type.Outside, 	variation , getWallInsulationThickness( hsEtuBuildings[V_0], HsEtuStoreyWall.type.Outside, V_0, 0) ),
			insulationRoof				: getWallInsulationThickness( hsEtuBuildings[variation], HsEtuStoreyWall.type.Ceilling,	variation , getWallInsulationThickness( hsEtuBuildings[V_0], HsEtuStoreyWall.type.Ceilling, V_0, 0) ),
			insulationCellar			: getWallInsulationThickness( hsEtuBuildings[variation], HsEtuStoreyWall.type.Floor, 	variation , getWallInsulationThickness( hsEtuBuildings[V_0], HsEtuStoreyWall.type.Floor, V_0, 0)),
			windowType					: getWindowType(hsEtuBuildings[variation]),
			energyValue					: energyValue,
			analysisInterval			: analysisInterval,
			totalInvestmentValue		: totalInvestmentCosts,

			oilConsumptionDeltaPA		: oilConsumptionDelta, 
			oilConsumptionCostsDelta  	: oilConsumptionCostsDelta*analysisInterval,
			oilConsumptionCostsPA  		: oilConsumptionCosts,

			woodConsumptionDeltaPA  	: woodConsumptionDelta,
			woodConsumptionCostsDelta  	: woodConsumptionCostsDelta*analysisInterval,
			woodConsumptionCostsPA		: additionWoodConsumptionCosts
		};

		

		/**
		* Variation 0 Output
		**/
		if (variation == V_0){
			$("#printESC3BuildingInformation_YOC").html(  							hsEtuBuildings[variation].getYearOfConstruction() );
			$("#printESC3BuildingInformation_flatType2").html(  				    locationType );
			$("#printESC3BuildingInformation_boilerYOC").html(  					boilerYOC );
			$("#printESC3BuildingInformation_boilerThermalPower").html(  			thermalPower );
			$("#printESC3BuildingInformation_burnerRenewed").html(  				(burnerYOC > boilerYOC 		? 'Ja' : 'Nein') );
			$("#printESC3BuildingInformation_boilerType").html(  					getBoilerType(hsEtuBuildings[variation]) );
			$("#printESC3BuildingInformation_heatRecovery").html( 					(heatrecovery != "" 		? 'Ja' : 'Nein')  );
			$("#printESC3BuildingInformation_solarSupportWarmwater").html( 			(solardevice_ww != "" 		? 'Ja' : 'Nein')  );
			$("#printESC3BuildingInformation_solarSupportWarmwaterHeating").html( 	(solardevice_h != "" 		? 'Ja' : 'Nein')  );
			$("#printESC3BuildingInformation_insulationWall").html( 				getWallInsulationThickness( hsEtuBuildings[variation], HsEtuStoreyWall.type.Outside, 	variation , getWallInsulationThickness( hsEtuBuildings[V_0], HsEtuStoreyWall.type.Outside, V_0, 0) )  );
			$("#printESC3BuildingInformation_insulationRoof").html( 				getWallInsulationThickness( hsEtuBuildings[variation], HsEtuStoreyWall.type.Outside, 	variation , getWallInsulationThickness( hsEtuBuildings[V_0], HsEtuStoreyWall.type.Ceilling, V_0, 0) )  );
			$("#printESC3BuildingInformation_insulationCellar").html( 				getWallInsulationThickness( hsEtuBuildings[variation], HsEtuStoreyWall.type.Outside, 	variation , getWallInsulationThickness( hsEtuBuildings[V_0], HsEtuStoreyWall.type.Floor, V_0, 0) )  );
			$("#printESC3BuildingInformation_windowType").html(  					getWindowType(hsEtuBuildings[variation]) );
		}


		/**
		* Erweiterte Berechnungsgrundlagen
		**/
	
		myConsoleLog( '---- Variation: ' + variation + '----' );
		/*
		myConsoleLog( 'Analysis-Interval: ' + analysisInterval );
		myConsoleLog( 'Investitionen: ' + totalInvestmentCosts );
		myConsoleLog( 'Grundfläche: ' + basicFloorArea );
		myConsoleLog( 'Nutzfläche AN (1): '+ hsEtuBuildings[0].getUseableFloorAreaConsumption() );
		if(typeof hsEtuBuildings[0].getUseableFloorArea != "undefined" ) myConsoleLog( 'Nutzfläche AN (2): '+ hsEtuBuildings[0].getUseableFloorArea() );
		myConsoleLog("Energy-Demand:" + energyValue );
		myConsoleLog( "--------------" );
		myConsoleLog( "Oil-Price / Litre :" + ENERGYCHECK_CONFIG.oilLitrePrice );
		myConsoleLog( 'Oil-Consumption p.a (Litre): ' + oilConsumptionLitre );
		myConsoleLog( 'Oil-Consumption Saving p.a (Litre): ' + oilConsumptionDelta );
		myConsoleLog( 'Oil-Consumption Costs Saving p.a (Euro): ' + oilConsumptionCostsDelta );
		myConsoleLog( "Oil-Costs p.a.:" + Math.round( oilConsumptionLitre *  ENERGYCHECK_CONFIG.oilLitrePrice ) );
		myConsoleLog( "--------------" );
		myConsoleLog( "Wood-Price / RM :" + ENERGYCHECK_CONFIG.woodRMPrice );
		myConsoleLog( 'Wood-Consumption p.a. (RM): ' + additionalWoodConsumption );
		myConsoleLog( 'Wood-Consumption Saving p.a. (RM): ' + woodConsumptionDelta );
		myConsoleLog( 'Wood-Consumption Costs Saving p.a. (Euro): ' + woodConsumptionCostsDelta );
		myConsoleLog( "Wood-Costs p.a:" + Math.round( additionalWoodConsumption *  ENERGYCHECK_CONFIG.woodRMPrice ) );
		myConsoleLog( "--------------" );
		if(typeof hsEtuBuildings[0].getExteriorWallArea != "undefined" ) myConsoleLog( "Größe der Außenwand in m²:" + hsEtuBuildings[0].getExteriorWallArea());
		if(typeof hsEtuBuildings[0].getRoofArea != "undefined" ) myConsoleLog( "Größe der Dachschrägen in m²:" + hsEtuBuildings[0].getRoofArea());
		if(typeof hsEtuBuildings[0].getTopFloorCeilingArea != "undefined" ) myConsoleLog( "Größe der obersten Geschossdecke in m²:" + hsEtuBuildings[0].getTopFloorCeilingArea());
		if(typeof hsEtuBuildings[0].getBottomFloorCeilingArea != "undefined" ) myConsoleLog( "Größe der Kellerdecke / Bodenplatte in m²:" + hsEtuBuildings[0].getBottomFloorCeilingArea());
		if(typeof hsEtuBuildings[0].getWindowArea != "undefined" ) myConsoleLog( "Größe der Fenster in m²:" + hsEtuBuildings[0].getWindowArea());
	
		myConsoleLog( "Solar H :" + solardevice_h );
		myConsoleLog( "Solar WW :" + solardevice_ww );
		myConsoleLog( buildingInfoExportStorage[variation] );		
		*/
		
		//adjust the pointers
		energyPositionValue = Math.min(Math.round(energyValue), ENERGYCHECK_CONFIG.minEnergyPositionValue);		
		$("#variante_" + variation).attr("title", energyValue);

		//set value for printing
		if(variation > V_0){
			$("#ovv"+variation+"_consumption_print").html(energyValue+" kWh/(m²a)");
		}
		

		if ($(".pointer #variante_" + variation + ":hidden").length > 0) {
			$(".pointer #variante_" + variation).css("left", energyPositionValue - (ENERGYCHECK_CONFIG.pointerWidth / 2) );
			$(".pointer #variante_" + variation).fadeIn();
			
		} else {
			$(".pointer #variante_" + variation).animate({ 
				left: ( energyPositionValue - (ENERGYCHECK_CONFIG.pointerWidth / 2) ) + "px"
			}, ENERGYCHECK_CONFIG.pointerAnimationMS );
		}


		/*************
		 * some actions
		 ******/
		window.setTimeout(function(){
			setInvestmentBars(variation);
			setOverviewBars(variation);
		}, 100);
		
		if (variation == V_3) {
			setWorking(false);
			window.setTimeout(function(){
				adjustPointers();
			}, 1000);
		}


		//Recursion
		if(variation < V_3) {
			
			calculate_energy_demand( variation + 1 );
		}

	};


	setCalculationBaseOnBuilding(variation);//Use the specified calculation base on the building-object

	/**
	*	Call the CalculateEnergyDemand-Function on passed building
	**/
	hsEtuBuildings[variation].calculate(apiUrl("CalculateEnergyDemand"), {
		draft: hsEtuBuildings[V_0],
		onLoad: callback
	});
}



/**
 *  calculates the energy demand (native form - single call)
 *  @see calculate_energy_demand
 */
function calculate_energy_demand_native() {

	var callback = function(data){
		var energyValue, energyPositionValue, energyConsumptionLitre, oilCosts, html;

		//New method from Hottgenroth
		//var tmp_consumption = hsEtuBuilding.getHsEtuConsumption({type: HsEtuConsumption.type.Current})[0];
		//var tmp_consumptionLitre = tmp_consumption.getConsumptionPerSqm() * hsEtuBuilding.getUseableFloorAreaConsumption() / 10.08;

		energyValue         	= Math.round( hsEtuBuilding.getHsEtuConsumption()[0].getConsumptionPerSqm() );
		energyConsumptionLitre 	= hsEtuBuilding.getHsEtuConsumption()[0].getConsumptionLitre();
		
		//New Function from HS #11657 2010/08/09
		energyConsumptionAdditionalLitre = hsEtuBuilding.getHsEtuConsumption()[0].getConsumptionAdditionalVol();
				
		energyPositionValue 	= Math.min(energyValue, ENERGYCHECK_CONFIG.minEnergyPositionValue);
		
		//New method from Hottgenroth
		//oilCosts				= Math.round( tmp_consumptionLitre * ENERGYCHECK_CONFIG.oilLitrePrice);
		oilCosts				= Math.round( energyConsumptionLitre * ENERGYCHECK_CONFIG.oilLitrePrice);
		woodCosts				= Math.round( energyConsumptionAdditionalLitre * ENERGYCHECK_CONFIG.woodRMPrice);

		myConsoleLog("Energy-Consumption:" + energyValue );
		myConsoleLog("Oil-Consumption (Litre):" + energyConsumptionLitre );
		myConsoleLog("Wood-Consumption (RM):" + energyConsumptionAdditionalLitre );
		myConsoleLog("Oil-Price / Litre :" + ENERGYCHECK_CONFIG.oilLitrePrice );
		myConsoleLog("Wood-Price / RM :" + ENERGYCHECK_CONFIG.woodRMPrice );
		myConsoleLog("Oil-Costs :" + oilCosts );
		myConsoleLog("Wood-Costs :" + woodCosts );		
		myConsoleLog("Heating-Costs :" + (oilCosts+woodCosts) );		
		
		$("#energyResultMessage .resultText").html( getConsumptionText( energyValue, (oilCosts+woodCosts) ) );
		
		$("#energyResultMessage").slideDown();
		
		$("input[name='user_iwosaveenergycheck_pi1[energyconsumptionparameter]']").val(energyValue);
		
		$(".pointer img").css("left", energyPositionValue - (ENERGYCHECK_CONFIG.pointerWidth / 2));
		$(".pointer img").fadeIn();
		
		setWorking(false);
	};
	
	//Call the Calculate EnergyConsumption-Method
	hsEtuBuilding.calculate(apiUrl('CalculateEnergyConsumption'), { onLoad: callback } );
}


/**
 * Updates all preview images based on the current form state. 
 */
function updatePreviewImage(){
	var variation;
	
	// b1 : haus_basis_xx            
	// b2 : fenster_neu_02           			mainlyWindowType
	// b3 : daemmung_fassade         			insulationWall
	// b4 : daemmung_dach            			insulationRoof
	
	// b5 	: oel_brennwertgeraet      			boilerType = 3
	// b5n 	: oel_brennwertgeraet_neutral      	boilerType = 3						always in "IST-Zustand" and shown in variants if there is no improvement
	
	// b6 	: speicher_200_neu         			boilerType = 3
	// b6n 	: speicher_200_neu_neutral			boilerType = 3						always in "IST-Zustand" and shown in variants if there is no improvement
	
	// b7 	: speicher_300_neu         			solarSupportWarmWater
	// b7n 	: speicher_300_neu_neutral			solarSupportWarmWater				always in "IST-Zustand" and shown in variants if there is no improvement
	
	// b8 	: speicher_1000_neu        			woodOven, solarSupportHeating
	// b8n 	: speicher_1000_neu_neutral			woodOven, solarSupportHeating		always in "IST-Zustand" and shown in variants if there is no improvement
	
	// b9 	: abluft_system            			ventilationHeatRecovery
	// b9n 	: abluft_system_neutral				ventilationHeatRecovery				always in "IST-Zustand" and shown in variants if there is no improvement
	
	// b10	: kamin                    			woodOven
	// b10n	: kamin_neutral           			woodOven							always in "IST-Zustand" and shown in variants if there is no improvement
	
	// b11	: solar_klein              			solarSupportWarmWater
	// b11n	: solar_klein              			solarSupportWarmWater				always in "IST-Zustand" and shown in variants if there is no improvement
	
	// b12	: solar_gross              			solarSupportHeating
	// b12n	: solar_gross_neutral				solarSupportHeating					always in "IST-Zustand" and shown in variants if there is no improvement
	
	/**
	 * Returns the value of a given field.
	 * @param {String} name The base name of the field.
	 * @param {Str} [pseudo] A pseudo selector (optional)
	 * @returns {String} The value of the field.
	 * @example
	 * 	_value("insulationRoof"); 
	 */
	var _value = function(name, pseudo){
		var selector = ":input[name=" + name + "_v" + variation + "]";
		if (pseudo){ selector += ":" + pseudo; }
		return $(selector).val();
	};
	
	
	/**
	 * Returns the value of a given field in variant 0 ("IST-Zustand").
	 * @param {String} name The base name of the field.
	 * @param {Str} [pseudo] A pseudo selector (optional)
	 * @returns {String} The value of the field.
	 * @example
	 * 	_value("insulationRoof"); 
	 */
	var _valueV0 = function(name, pseudo){
		var selector = ":input[name=" + name + "_v0]";
		if (pseudo){ selector += ":" + pseudo; }
		return $(selector).val();
	};
	
	/**
	 * Returns the value of a given field if checked.
	 * @param {String} name The base name of the field.
	 * @returns {String} The value of the field.
	 * @example
	 * 	_value("boilerType"); 
	 */
	var _checked = function(name){
		return _value(name, "checked");
	};
	
	/**
	 * Returns true or false. "True" if improved in comparison to variant 0 otherwise false.
	 * @param {String} name The base name of the field.
	 * @returns {String} The value of the field.
	 * @example
	 * 	_value("boilerType"); 
	 */
	var _checkImprovement = function(name){
		
		valueV0 = _valueV0(name, "checked");
		if(typeof(valueV0) == "undefined"){
			valueV0 = 0;
		}
		
		if(valueV0 < _checked(name)){
			return true;
		}else{
			return false;
		}
	};
	
	// Hash with id: condition statements.
	var states = {
		b2: function(){
			// if double or tripple window type selected
			var value = _value("mainlyWindowType", "checked");
			return value == "thermalInsulationTripple" || value == "thermalInsulationDouble";
		},
		
		b3: function(){
			// if default or additional wall insulation is given
			if (Number($(":input[name=insulationWall_v0]").val())){ 
				return true; 
			}
			return !!Number(_value("insulationWall"));
		},
		
		b4: function(){
			// if default or additional roof insulation is given
			if (Number($(":input[name=insulationRoof_v0]").val())){ 
				return true; 
			}
			return !!Number(_value("insulationRoof"));
		},
		
		b5: function(){
			// if boiler type is "Brennwertkessel" and there is an improvement
			if(_checked("boilerType") == 3 && _checkImprovement("boilerType")){
				return true;
			}else{
				return false;
			}
			
		},
		
		b5n: function(){
			// if boiler type is "Brennwertkessel" and there is NO improvement
			if(_checked("boilerType") == 3 && !_checkImprovement("boilerType")){
				return true;
			}else{
				return false;
			}
		},
		
		b6: function(){
			// if boiler type is "Brennwertkessel" and there is an improvement
			if(_checked("boilerType") == 3 && _checkImprovement("boilerType")){
				return true;
			}else{
				return false;
			}
		},
		
		b6n: function(){
			// if boiler type is "Brennwertkessel" and there is NO improvement
			if(_checked("boilerType") == 3 && !_checkImprovement("boilerType")){
				return true;
			}else{
				return false;
			}
		},
		
		b7: function(){
			// if solar warm water is selected and there is an improvement
			if(_checked("solarSupportWarmWater") && _checkImprovement("solarSupportWarmWater")){
				return true;
			}else{
				return false;
			}
		},
		
		b7n: function(){
			// if solar warm water is selected and there is NO improvement
			if(_checked("solarSupportWarmWater") && !_checkImprovement("solarSupportWarmWater")){
				return true;
			}else{
				return false;
			}
		},
		
		b8: function(){
			// if wood oven and solar heating are selected and there is an improvement
			if( (_checked("woodOven") && _checkImprovement("woodOven") && !_checked("solarSupportHeating") && !_checkImprovement("solarSupportHeating")) ||
				(_checked("solarSupportHeating") && _checkImprovement("solarSupportHeating") && !_checked("woodOven") && !_checkImprovement("woodOven") ) ||
				(_checked("solarSupportHeating") && _checkImprovement("solarSupportHeating") && _checked("woodOven") && _checkImprovement("woodOven") )
			){
				//Improvement for woodOven doesn't need to get checked because it can't be different to variant 0 ("Ist-Zustand")
				return true;
			}else{
				return false;
			}
		},
		
		b8n: function(){
			if( 
				( _checked("solarSupportHeating") && !_checkImprovement("solarSupportHeating")) || 
			    ( _checked("woodOven") && !_checkImprovement("woodOven")) 
			){
				//Improvement for woodOven doesn't need to get checked because it can't be different to variant 0 ("Ist-Zustand")
				return true;
			}else{
				return false;
			}
		},
		
		b9: function(){
			// if ventilation heat recovery is selected and there is an improvement
			if(_checked("ventilationHeatRecovery") && _checkImprovement("ventilationHeatRecovery")){
				return true;
			}else{
				return false;
			}
		},
		
		b9n: function(){
			// if ventilation heat recovery is selected and there is NO improvement
			if(_checked("ventilationHeatRecovery") && !_checkImprovement("ventilationHeatRecovery")){
				return true;
			}else{
				return false;
			}
		},
		
		b10: function(){
			// if wood oven and no solar heating is selected and there is an improvement
			if((_checked("woodOven") && !_checked("solarSupportHeating")) && _checkImprovement("woodOven")){
			//An improvement for the wood oven can't actually happen because you can't change it in the variations
				return true;
			}else{
				return false;
			}
		},
		
		b10n: function(){
			// if wood oven and no solar heating is selected and there is NO improvement
			if((_checked("woodOven") && !_checked("solarSupportHeating")) && !_checkImprovement("woodOven")){
			//An improvement for the wood oven can't actually happen because you can't change it in the variations
				return true;
			}else{
				return false;
			}
		},
		
		b11: function(){
			// if solar warm water is selected and there is an improvement
			if(_checked("solarSupportWarmWater") && _checkImprovement("solarSupportWarmWater")){
				return true;
			}else{
				return false;
			}
		},
		
		b11n: function(){
			// if solar warm water is selected and there is NO improvement
			if(_checked("solarSupportWarmWater") && !_checkImprovement("solarSupportWarmWater")){
				return true;
			}else{
				return false;
			}
		},
		
		b12: function(){
			// if solar heating is selected and there is an improvement
			if(_checked("solarSupportHeating") && _checkImprovement("solarSupportHeating")){
				return true;
			}else{
				return false;
			}
		},
		
		b12n: function(){
			// if solar heating is selected and there is NO improvement
			if(_checked("solarSupportHeating") && !_checkImprovement("solarSupportHeating")){
				return true;
			}else{
				return false;
			}
		}
	};
	
	// cycle through all variations and images
	var updateStates = function(){
		for (variation = 0; variation < 4; variation ++){
			$.each(states, function(id, check){
				// display image if condition is met
				var image = "#configBuilding"+variation+" #v" + variation + id;

				if (check()){
						$(image).show();
						if($.browser.msie){
							$(image).css('z-index', '50');
						}
				} else {

						$(image).hide();
						if($.browser.msie){//IE doesn't hide the elements without set the z-index to -1 
							$(image).css('z-index', '-1');
						} 
				}
			});
		}
	};
	
	var overlay = $(".configBuildingWrapper:visible div.configBuildingMenuOverlayForm:visible");
	
	// fade overlay is currently visible
	if (overlay[0]){
		overlay.fadeTo(300, 0.2, function(){
			updateStates();
			overlay.fadeTo(300, 1);
		});
	} else {
		updateStates();
	}
}

/*************************
* COLLECTING VALUES
******************/

function collectValues() {


	// create building
	hsEtuBuilding = new HsEtuBuilding();
	hsEtuBuilding.setCalculateInvestmentCosts(false);
	
	// set the buildingtype
	// possible values for our forms: OneFamily, Multiple
	if (typeof flatTypeValue == "undefined") {
		window.flatTypeValue = 'OneFamily';
	}
	
	hsEtuBuilding.setType(HsEtuBuilding.type[flatTypeValue]);
	hsEtuBuilding.setYearOfConstruction(ENERGYCHECK_CONFIG.yearOfConstruction);

	// generate one floor
	var eg = new HsEtuStorey(); // Erdgeschoss
	eg.setType(HsEtuStorey.type.EG);
	eg.setIsHeated(true);

	hsEtuBuilding.addHsEtuStorey(eg);
	
	var ug = new HsEtuStorey(); // Erdgeschoss
	ug.setType(HsEtuStorey.type.UG);
	ug.setIsHeated(!!cellar);

	hsEtuBuilding.addHsEtuStorey(ug);
	
	// adding storeys
	for (var counter = 0; counter < heatedStoreys; counter++) {
		var og = new HsEtuStorey();
		og.setType(HsEtuStorey.type.OG);
		og.setIsHeated(true);
		hsEtuBuilding.addHsEtuStorey(og);
	}
	
	var dg = new HsEtuStorey(); // Dachgeschoss
	dg.setType(HsEtuStorey.type.DG);
	dg.setIsHeated(!!heatedTopFloor);

	hsEtuBuilding.addHsEtuStorey(dg);
	hsEtuBuilding.initStoreys();

	// create address
	var address = new HsEtuAddress();
	address.setPostCode(zip);
	
	hsEtuBuilding.setHsEtuAddress(address);
	hsEtuBuilding.setBasicFloorArea(basicFloorArea);
	/* Heated livingspace is not used anymore #13979
	hsEtuBuilding.setHeatedFloorArea(heatedFloorArea);
	*/

	var boiler, fuel, heater, source, hsEtuWindow, stock;

	// set default boiler
	boiler = new HsEtuHeatingBoiler(); 
	boiler.setBoilerType(HsEtuHeatingBoiler.boilerType[ENERGYCHECK_CONFIG.boilerType]);
	boiler.setYearOfConstruction(ENERGYCHECK_CONFIG.yearOfConstruction);

	fuel = new HsEtuFuel(); 
	fuel.setType(HsEtuEnergySource.type.Oil);
	
	stock = getOilStock();
	fuel.addHsEtuStock( stock );

	boiler.addHsEtuEnergySource(fuel);
	hsEtuBuilding.addHsEtuDevice(boiler);



	if (mv_woodconsumption > 0) {
		//additional heating of type wood
		heater = new HsEtuHeatingDevice();
		heater.setIsAdditional(true);
		source = new HsEtuFireWood();
		heater.addHsEtuEnergySource(source);
		hsEtuBuilding.addHsEtuDevice(heater);

		woodstock = stock.clone();
		woodstock.setOpeningValue(mv_woodconsumption);
		woodstock.setClosingValue(0);		
		source.addHsEtuStock(woodstock);
	}

	hsEtuWindow = new HsEtuWindow();
	hsEtuWindow.setIsolationType(HsEtuWindow.isolationType[ENERGYCHECK_CONFIG.windowType]);
	hsEtuBuilding.addHsEtuElement(hsEtuWindow);

	calculate_energy_demand_native();//Call the passed callback-method
}


/**
*
*
*/
function setVariationValues( div ) {
	var buildingIndex, counter;
	var v0WallInsulation = 0;
	var v0RoofInsulation = 0;
	var v0CellarInsulation = 0; //Default V0 Values Hotfix
	
	updatePreviewImage();
	
	setWorking(true);
	
	// clear the object
	hsEtuBuildings = [];
	
	$("input[name=caclulationValues]").val("");
	
	/**
	 * Returns an jQuery object using the following selector:
	 * "#configBuildingINDEX :input[name=NAME_vINDEX]"
	 * 
	 * @param {String} name The field base name. Use ":" to pass pseudos.
	 * @param {Number} [index] Building index. Uses current if not present.
	 * 
	 * @example
	 * 	_getElement("boilerNominalPower");		// current field
	 * 	_getElement("boilerNominalPower", 1);	// field for building 1
	 * 	_getElement("buildingType:checked");	// field only if checked
	 */
	var _getElement = function(name, index){
		var parts, pseudo, selector, fieldName;
		
		// use current index if not passed as argument
		index = (typeof index == "undefined") ? buildingIndex : index;
		
		// add index and check if pseudo selector is given
		parts = name.split(":");
		name = parts[0] + "_v" + index;
		pseudo = parts[1];
		
		// create selector
		selector = "#configBuilding" + index;		// #configBuilding0
		selector += " :input[name=" + name + "]";	// :input [name=xyz_1]
		selector += pseudo ? ":" + pseudo : "";		// :checked
		
		return $(selector);
	};
	
	/**
	 * Returns the value of a given field.
	 * @param {String} name The field base name. Use ":" to pass attribue.
	 * @param {Number} [index] Building index. Uses current if not present.
	 * 
	 * @example
	 * 	_get("boilerNominalPower");		// current field value
	 * 	_get("boilerNominalPower", 1);	// value for building 1
	 * 	_get("buildingType:checked");	// value only if checked
	 */
	var _get = function(name, index){
		return _getElement(name, index).val();
	};

	/**
	 * Sets the value of a given field.
	 * @param {String} name The field base name. Use ":" to pass attribue.
	 * @param {Number} [index] Building index. Uses current if not present.
	 * 
	 * @example
	 * 	_set("boilerNominalPower", 100);
	 */	
	var _set = function(name, value, index){
		return _getElement(name, index).val(value);
	};

	/**
	 * Returns the default value (bulding 0) of a given field.
	 * @param {String} name The field base name. Use ":" to pass attribue.
	 * 
	 * @example
	 * 	_default("boilerNominalPower");
	 */	
	var _default = function(name){
		return _get(name, 0);
	};



	for (buildingIndex = V_0; buildingIndex < V_n; buildingIndex++) {

		/*********************
		 * BUILDING
		 *******************/
		// create a new object of the building
		var building = new HsEtuBuilding();
		hsEtuBuildings[buildingIndex] = building;
		
	
		var isCurrentState = (buildingIndex == V_0);
		/* <!MV!> Hotfix
		building.setCalculateInvestmentCosts(isCurrentState);
		*/
		
		//setting the year of construction for building..
		if (isCurrentState) {
			_set("buildingDate", _default("buildingDate"));
		}

		var year = Number(_default("buildingDate")) || ENERGYCHECK_CONFIG.yearOfConstruction;
		building.setYearOfConstruction(year);
		
		// create address
		var address = new HsEtuAddress();
		address.setPostCode(zip);
		building.setHsEtuAddress(address);
		
		// if new value is given in the form.. use it
		
		if (_default("floorArea") != '') {
		
			if (!isCurrentState) {
				_set("floorArea", _default("floorArea"));
			}

			building.setBasicFloorArea(parseInt(_default("floorArea"), ENERGYCHECK_CONFIG.radix));
			
		} else {
			_set("floorArea", basicFloorArea);
			building.setBasicFloorArea(basicFloorArea);
		}
		
		/* Heated livingspace is not used anymore #13979
		building.setHeatedFloorArea(heatedFloorArea);
		*/
		
		// setting flatType
		building.setType(HsEtuBuilding.type[flatTypeValue]);
		
		// set locationType
		var locationType = HsEtuBuilding.locationType.Detached;
		switch (_default("buildingType:checked")) {
			case 'detached':
				locationType = HsEtuBuilding.locationType.Detached;
			break;
			case 'middle':
				locationType = HsEtuBuilding.locationType.Middle;
			break;
			case 'other':
				locationType = HsEtuBuilding.locationType.Corner;
			break;
		}
		
		if (!isCurrentState) {
			var buildingName = _default("buildingType:checked");
			var selector = "#configBuilding" + buildingIndex;
			selector += " input[value=" + buildingName + "]";
			$(selector).attr("checked", "checked");
		}
		building.setLocationType(locationType);
		


		/*********************
		 * storeys begin
		 *******************/
		
		//generate cellar
		var ug = new HsEtuStorey();
		ug.setType(HsEtuStorey.type.UG);
		ug.setIsHeated(!!cellar);

		building.addHsEtuStorey(ug);
		
		//generate first floor
		var eg = new HsEtuStorey(); // Erdgeschoss
		eg.setType(HsEtuStorey.type.EG);
		eg.setIsHeated(true);

		building.addHsEtuStorey(eg);

		//adding floors of the type OG
		for (counter = 0; counter < heatedStoreys; counter++) {
			var og = new HsEtuStorey();
			og.setType(HsEtuStorey.type.OG);
			og.setIsHeated(true);
			building.addHsEtuStorey(og);
		}
		
		//adding a top floor
		var dg = new HsEtuStorey(); // Dachgeschoss
		dg.setType(HsEtuStorey.type.DG);
		dg.setIsHeated(!!heatedTopFloor);
		
		building.addHsEtuStorey(dg);
		building.initStoreys();
		
		/*********************
		 * storeys end
		 *******************/

		/*********************
		 * heating
		 *******************/
		
		var boiler = new HsEtuHeatingBoiler(); 
		
		var boilerType = HsEtuHeatingBoiler.boilerType[ENERGYCHECK_CONFIG.boilerType];
		
		// set boilerType
		switch(_get("boilerType:checked") || _default("boilerType:checked")) {
			case '1':
				boilerType = HsEtuHeatingBoiler.boilerType.Standard;
				break;
			case '2':
				boilerType = HsEtuHeatingBoiler.boilerType.LowTemperature;
				break;
			case '3':
				boilerType = HsEtuHeatingBoiler.boilerType.Condensing;
				break;
		}
		
		boiler.setBoilerType(boilerType);

		var fuel, flowHeater, source, heater, heating, 
			thermalPower, solarHeater, burner, stock;
		
		fuel = new HsEtuFuel();
		fuel.setType(HsEtuEnergySource.type.Oil);
		
		stock = getOilStock();
		fuel.addHsEtuStock( stock );	
		
		boiler.addHsEtuEnergySource(fuel);
		boiler.setYearOfConstruction(Number(_default("boilerDate")));

		//if there is any consumption of wood..
		if (mv_woodconsumption > 0 || (buildingIndex > V_0 && _get('woodOven:checked',buildingIndex) == 1) ) {
			// additional heating of type wood
			heater = new HsEtuHeatingDevice();
			heater.setIsAdditional(true);
			source = new HsEtuFireWood();
			heater.addHsEtuEnergySource(source);
			building.addHsEtuDevice(heater);
			
			// consumption
			if(mv_woodconsumption > 0) {
				woodstock = stock.clone();
				woodstock.setOpeningValue(mv_woodconsumption);
				woodstock.setClosingValue(0);
				source.addHsEtuStock(woodstock);
			}
		}
				
		thermalPower = _get("boilerNominalPower");
		
		
		boiler.setFiringThermalPower(parseInt(thermalPower, ENERGYCHECK_CONFIG.radix) || 0);
		boiler.setNominalPower(parseInt(thermalPower, ENERGYCHECK_CONFIG.radix) || 0);

		// if burner was modernized
		
		if (_default("burnerUpgraded:checked")) {
			var burners = boiler.getHsEtuHeatingBurner();
			burner = burners[0] || new HsEtuHeatingBurner();
			burner.setYearOfConstruction(boiler.getYearOfConstruction() + 1);
			boiler.setHsEtuHeatingBurner([burner]);
		}
		
		building.addHsEtuDevice(boiler);//DeviceIndex 0 ??

		//set ventilation
		if (_get("ventilationHeatRecovery:checked")) {
			var ventilation = new HsEtuVentilation();
			ventilation.setHeatRecovery(true);
			building.addHsEtuDevice(ventilation);
		}	
		
		/*********************
		 * solar
		 *******************/
		
		//solar heating support
		if (_get("solarSupportHeating:checked")) {
			heater = new HsEtuHeatingDevice();
			heater.setIsAdditional(true);
			source = new HsEtuEnergySource();
			source.setType(HsEtuEnergySource.type.Solar);
			heater.addHsEtuEnergySource(source);
			building.addHsEtuDevice(heater);
		}
		
		//solar warm water
		if (_get("solarSupportWarmWater:checked")) {
			solarHeater = new HsEtuHeatingDevice({
				drinkingWaterType: HsEtuHeatingDevice.drinkingWaterType.StorageTank //If drinkingWaterType is set, its just a warmwater-support device
			});
			solarHeater.setIsAdditional(true);
			source = new HsEtuEnergySource();
			source.setType(HsEtuEnergySource.type.Solar);
			solarHeater.addHsEtuEnergySource(source);
			building.addHsEtuDevice(solarHeater);
		}
		
		/*********************
		 * insulation
		 *******************/
		
		var walls, storey;
				
		var _insulation = function(name){
			var value = Number(_get(name)) || 0;
			return value / 100;
		};

		/**
		* insulation wall <!MV!>
		**/
		storey = building.getHsEtuStorey({ type: HsEtuStorey.type.EG })[0];
		walls  = storey.getHsEtuStoreyWall({ type: HsEtuStoreyWall.type.Outside });
			
		$.each(walls, function(){
			var wall = this.getHsEtuWall();
				
			//Compare v0 Insulation and store the thickiest insulation <!MV!>
			if( buildingIndex == V_0 && _insulation("insulationWall") > v0WallInsulation ) {
				v0WallInsulation = _insulation("insulationWall");
			}

			//Append an insulation for the wall, if an insulation is set <!MV!>
			if( _insulation("insulationWall") > 0 ) {	
				wall.addHsEtuInsulation(new HsEtuInsulation({
					type: HsEtuInsulation.type.From1995, 
					thickness: _insulation("insulationWall")
				}));
			}
			
			//If the current building is not the V0 variation, then append the insulation from v0 <!MV!>
			if( buildingIndex > V_0 && v0WallInsulation > 0 ) {
				wall.addHsEtuInsulation(new HsEtuInsulation({
					type: HsEtuInsulation.type.From1995, 
					thickness:v0WallInsulation
				}));
			}

			wall.setConstructionType(HsEtuWall.constructionType.Massive);
		});
		/**
		* EOF insulation wall <!MV!>
		**/

		/**
		* insulation roof <!MV!>
		**/
		storey = building.highestHeatedStorey();
		walls = storey.getHsEtuStoreyWall({ type: HsEtuStoreyWall.type.Ceilling	});
	
		$.each(walls, function(){
			var wall = this.getHsEtuWall();
			//Compare v0 Insulation and store the thickiest insulation <!MV!>
			if( buildingIndex == V_0 && _insulation("insulationRoof") > v0RoofInsulation ) {
				v0RoofInsulation = _insulation("insulationRoof");
			}

			//Append an insulation for the roof, if an insulation is set <!MV!>
			if( _insulation("insulationRoof")  > 0 ) {	
				wall.addHsEtuInsulation(new HsEtuInsulation({
					type: HsEtuInsulation.type.From1995, 
					thickness: _insulation("insulationRoof")
				}));
			}
			
			//If the current building is not the V0 variation, then append the insulation from v0 <!MV!>
			if( buildingIndex > V_0 && v0RoofInsulation > 0 ) {
				wall.addHsEtuInsulation(new HsEtuInsulation({
					type: HsEtuInsulation.type.From1995, 
					thickness:v0RoofInsulation
				}));
			}

			wall.setConstructionType(HsEtuWall.constructionType.Wooden);
		});
		/**
		* EOF insulation roof <!MV!>
		**/


		/**
		* insulation cellar <!MV!>
		**/
	   storey = building.lowestHeatedStorey();
	   walls = storey.getHsEtuStoreyWall({	type: HsEtuStoreyWall.type.Floor });
		$.each(walls, function(){
			var wall = this.getHsEtuWall();

			//Compare v0 Insulation and store the thickiest insulation <!MV!>
			if( buildingIndex == V_0 && _insulation("insulationCellar") > v0CellarInsulation ) {
				v0CellarInsulation = _insulation("insulationCellar");
			}

			//Append an insulation for the cellar, if an insulation is set <!MV!>
			if( _insulation("insulationCellar") > 0  ) {	
				wall.addHsEtuInsulation(new HsEtuInsulation({
					type: HsEtuInsulation.type.From1995, 
					thickness: _insulation("insulationCellar")
				}));
			}

			//If the current building is not the V0 variation, then append the insulation from v0 <!MV!>
			if( buildingIndex > V_0 && v0CellarInsulation > 0 ) {
				wall.addHsEtuInsulation(new HsEtuInsulation({
					type: HsEtuInsulation.type.From1995, 
					thickness:v0CellarInsulation
				}));
			}

			wall.setConstructionType(HsEtuWall.constructionType.Massive);
		});
		/**
		* EOF insulation cellar <!MV!>
		**/

		
		/*********************
		 * windows
		 *******************/
		
		// Hash with value: type relation
		var pairs = {
			simpleSingle: "SingleGlazed",
			simpleDouble: "DoubleGlazed",
			thermalInsulationDouble: "HeatAbsorbingDoubleGlazed",
			thermalInsulationTripple: "HeatAbsorbingTrippleGlazed"
		};
		
		var value = _get("mainlyWindowType:checked");
		var windowType = pairs[value] || ENERGYCHECK_CONFIG.windowType;

		hsEtuWindow = new HsEtuWindow();
		hsEtuWindow.setIsolationType(HsEtuWindow.isolationType[windowType]);
		building.addHsEtuElement(hsEtuWindow);
	}


	var v0DemandCompleted = function( data ) {
		calculate_energy_demand( V_0 );
	};	
	
	var v0ConsumptionCompleted = function( data ) {
		hsEtuBuildings[V_0].calculate(apiUrl('CalculateEnergyDemand'), { onLoad: v0DemandCompleted } );
	};
	

	
	//Call the Calculate EnergyConsumption-Method
	hsEtuBuildings[V_0].calculate(apiUrl('CalculateEnergyConsumption'), { onLoad: v0ConsumptionCompleted } );
	
}
