function switchToDetailedAscertainment() {	
	$('#anfangsbestand').height($('#anfangsbestand').height());
	$('#anfangsbestand').slideDown(600);
	
	//$('#zukaeufe').height($('#zukaeufe').height());
	$('#zukaeufe').slideDown(600);
	
	$('#endbestand').height($('#endbestand').height());
	$('#endbestand').slideDown(600);
	
	$('#verbrauchswert').slideUp(600);	
}


function switchToEstimatedAscertainment() {
	
	$('#anfangsbestand').slideUp(600);
	$('#zukaeufe').slideUp(600);
	$('#endbestand').slideUp(600);

	$('#verbrauchswert').height($('#verbrauchswert').height());		
	$('#verbrauchswert').slideDown(600);
}

function fetchMinimumHeatedLivingSpace() {
	
	var floorArea = $("input[name=user_iwosaveenergycheck_pi1[floorArea]]").val();
	var count = $("select[name=user_iwosaveenergycheck_pi1[heatedFloorCount]]").val();
	var topFloor = $("input[name=user_iwosaveenergycheck_pi1[heatedTopFloor]]:checked").val();
	
	if (!floorArea){
		return 0;
	}

	if (topFloor) {
		return (count - 1) * floorArea + (0.25 * floorArea);
	} else {
		return floorArea * count;
	}
}

jQuery(document).ready(function () {

	// event for the save button to save the whole form.
	$("#saveButton").click(function() {
		$("input[name=user_iwosaveenergycheck_pi1[cmd]]").val("save");
		$("form#energycheck_1").submit();
		return false;
	});
	
	if ($("input[name=user_iwosaveenergycheck_pi1[ascertainment]]:checked").val() == 'details') {
		switchToDetailedAscertainment();
	}
	
	// stuff for energy check forms..
	// roll all out we need for detail data entry
	$('input[name=user_iwosaveenergycheck_pi1[ascertainment]][value=details]').click(function() {
		switchToDetailedAscertainment();
	});
	
	// roll all in, leave the stuff for estimate data entry
	$('input[name=user_iwosaveenergycheck_pi1[ascertainment]][value=estimate]').click(function() {
		switchToEstimatedAscertainment();
	});
	

	function calculateFloors(event) {
	
		// only send a request if these values are given..
		if ( $("input[name=user_iwosaveenergycheck_pi1[floorArea]]").val() != '' ) {
			if (!checkFloors()) { return false; }
			
			/* Heated livingspace is not used anymore #13979
			var heatedFloorArea = fetchMinimumHeatedLivingSpace();
			
			$("input[name=user_iwosaveenergycheck_pi1[livingspace]]").val(
				heatedFloorArea
			);
			*/
		}
	}
	
	jQuery(document).bind("Loaded.HsEtuEvent", function(){
		// fire function one time ( if formular is prefilled and no value for floorarea is set )
		/* Heated livingspace is not used anymore #13979
		if( $("input[name=user_iwosaveenergycheck_pi1[livingspace]]").val() <= 0 || $("input[name=user_iwosaveenergycheck_pi1[livingspace]]").val() == '' ) {
			calculateFloors();
		}
		*/
		
		// request the heatedArea from the API if these settings are given
		$("input[name=user_iwosaveenergycheck_pi1[buildingtype]], select[name=user_iwosaveenergycheck_pi1[heatedFloorCount]], input[name=user_iwosaveenergycheck_pi1[floorArea]]").bind("change", '', calculateFloors);
		$("input[name=user_iwosaveenergycheck_pi1[heatedTopFloor]], input[name=user_iwosaveenergycheck_pi1[heatedCellar]]").bind("click", '', calculateFloors); 
		
		
		setWorking(false);
	});	
});


function check() {
	
	/**
	 * Returns the field of a given name. Optionally you can add a pseudo
	 * eg "checked" to select a special state.
	 * 
	 * @param {String} name The name of the field. 
	 * @param {Strin} [pseudo] Optional pseudo selector.
	 * @returns The matched elements.
	 */
	var _field = function(name, pseudo){
		var selector = ":input[name=user_iwosaveenergycheck_pi1[" + name + "]]";
		if (pseudo){
			selector += ":" + pseudo;
		}
		return $(selector);
	};

	/**
	 * Returns the value of a field. Optionally you can add a pseudo
	 * eg "checked" to select a special state.
	 * 
	 * @param {String} name The name of the field. 
	 * @param {Strin} [pseudo] Optional pseudo selector.
	 * @returns The value of the field.
	 */	
	var _val = function(name, pseudo){
		return _field(name, pseudo).val();
	};
	
	/**
	 * Returns true if a field is empty.
	 * @param {String} name The name of the field. 
	 * @param {Strin} [pseudo] Optional pseudo selector.
	 * @returns True if value is blank.
	 */ 
	var _blank = function(name, pseudo){
		return /^\s*$/.test(_val(name, pseudo));
	};

	/**
	 * Focusses the field. Optionally you can add a pseudo eg "checked" to 
	 * select a special state.
	 * 
	 * @param {String} name The name of the field. 
	 * @param {Strin} [pseudo] Optional pseudo selector.
	 * @returns The matched elements.
	 */	
	var _focus = function(name){
		return _field(name).focus();
	};
	
	// Make sure building type is selected.
	if (!_field("buildingtype", "checked").val()) {
		alert("Bitte wählen Sie einen Gebäudetyp!");
		_field("buildingtype");
		return false;
	}
	
	// Validate floors.
	if (!checkFloors()) { return false; }
	
	// Make sure floor area is between 20 and 1000.
	if (_val("floorArea") < 20 || _val("floorArea") > 1000) {
		alert("Die Grundfläche muss zwischen 20m² und 1000m² liegen!");
		_focus("floorArea");
		return false;
	}
	
	/* Heated livingspace is not used anymore #13979
	// beheizte wohnflaeche
	if (_val("livingspace") < 80 || _val("livingspace") > 1000) {
		alert("Die beheizte Wohnfläche muss zwischen 80m² und 1000m² liegen!");
		_focus("livingspace");
		return false;
	}

	// minimale beheizte Wohnflaeche		
	var referenceLivingSpace = fetchMinimumHeatedLivingSpace();
	// beheiztes Dachgeschoss
	var topFloor = $("input[name=user_iwosaveenergycheck_pi1[heatedTopFloor]]:checked").val();

	//Mit beheiztem DG
	if ( topFloor && ( _val("livingspace") < referenceLivingSpace ) ) {
		alert("Die beheizte Wohnfläche darf nicht kleiner als " + referenceLivingSpace + " m² sein. ");
		_focus("livingspace");
		return false;
	} 

	//Änderung OHNE beh. DG Änderung IWO #11100
	if ( !topFloor && ( _val("livingspace") > referenceLivingSpace ) ) {
		alert("Die beheizte Wohnfläche darf nicht größer als " + referenceLivingSpace + " m² sein. ");
		_focus("livingspace");
		return false;
	} 
	*/
	
	// postleitzahl
	if (_val("zip").length < 5 && _val("zip") < 1000) {
		 alert("Bitte geben Sie eine gültige Postleitzahl ein!");
		 _focus("zip");
		 return false;
	}

	var startDate, startTimeS, endDate, endTimeS, ascertainment;
	
	ascertainment = _val("ascertainment", "checked");

	if (ascertainment == 'estimate') {
		
		startDate = new Date(
			_val("timeframestartyear"),
			_val("timeframestartmonth"),
			_val("timeframestartday")
		);
		
		startTimeS = startDate.getTime() / 1000;
		
		endDate = new Date(
			_val("timeframeendyear"),
			_val("timeframeendmonth"),
			_val("timeframeendday")
		);
		endTimeS = endDate.getTime() / 1000;
		
	} else {
		startDate = new Date(
			_val("initialinventoryyear"),
			_val("initialinventorymonth"),
			_val("initialinventoryday")
		);
		 
		startTimeS = startDate.getTime() / 1000;
		
		endDate = new Date(
			_val("closinginventoryyear"),
			_val("closinginventorymonth"),
			_val("closinginventoryday")
		);
		
		endTimeS = endDate.getTime() / 1000;	
	}
	
	// Make sure start date is before end date
	if (startDate > endDate) {
		alert("Das Endbestandsdatum liegt vor der letzten Betankung!");
		return false;
	}

	// Check for min. 10 months (1000ms * 60s * 60m * 24h * (356d/12m)).
	if ((endTimeS - startTimeS) < 25920000) { 
		alert("Der Verbrauchszeitraum muss mindestens 10 Monate betragen!");
		return false;
	}
	
	// Validate presence of oil consumption.
	if (ascertainment == "estimate") {
		if (_blank("oilconsumption")) {
			alert("Bitte geben Sie einen Verbrauch an!");
			_focus("oilconsumption");
			return false;
		}
	}
	
	if (ascertainment == 'details') {
		
		if (_blank("closinginventoryfilllevel") && _blank("initialinventoryfilllevel")) {
			alert("Bitte geben Sie einen Anfangs- und Endverbrauch an!");
			_focus("initialinventoryfilllevel");
			return false;
		}
		
		if (_blank("initialinventoryfilllevel")) {
			alert("Bitte geben Sie einen Verbrauch an");
			_focus("initialinventoryfilllevel");
			return false;
		}

		if (_blank("closinginventoryfilllevel")) {
			alert("Bitte geben Sie einen Verbrauch an");
			_focus("closinginventoryfilllevel");
			return false;			
		}
		
		for (var n = 1; n <= 5; n++) {
			var amount = _val("refueled" + n + "amount"); 
			if (amount && amount > 0 ) {
				tmpPurchaseDate  = new Date(
					_val("refueled" + n + "year"),
					_val("refueled" + n + "month"),
					_val("refueled" + n + "day") 
				);
				
			 	tmpPurchaseDateS = tmpPurchaseDate.getTime() / 1000;
				
				if (tmpPurchaseDateS < startTimeS || tmpPurchaseDateS > endTimeS) {
					alert('Die Datumsangaben zu den zusätzlichen Zukäufen sind nicht gültig!');
					_focus("refueled" + n + "year");
					return false;
				}
			 }
		}
	}
	
	// Check rm on month-basis
	var datediff  = new Date( endDate - startDate );
	// This does not work (Because of februaries 29 days ) var monthdiff = ( ( datediff.getFullYear() - 1970 ) * 12 )  + datediff.getMonth();
	var monthdiff = Math.round( datediff / 1000 / 60 / 60 / 24 / (365/12) );
	var maxrm     = Math.round( 10.0 / 12.0 *  monthdiff );
	
	if (str_replace(',', '.', _val("woodconsumption")) > maxrm ) {
		alert("Der Wert für die Verbrauchsmenge von Holz darf 10rm/Jahr nicht überschreiten!");
		return false;
	}
	
	return true;
}


// checks if the amount of floors is working with the heatedTopFloor and Cellar settings.
// this function is being used in the check function of the form in step 1_1 and in the calculation of the heatedFloorArea
function checkFloors() {
	if (($("input[name=user_iwosaveenergycheck_pi1[heatedTopFloor]]:checked").val() && $("input[name=user_iwosaveenergycheck_pi1[heatedCellar]]:checked").val()) && $("select[name=user_iwosaveenergycheck_pi1[heatedFloorCount]]").val() < 3) {
		alert("Da Sie sowohl ein beheiztes Dachgeschoss als auch einen beheizten Keller angewählt haben muss die Anzahl der Geschosse mindestens 3 betragen!");
		$("input[name=user_iwosaveenergycheck_pi1[heatedTopFloor]]").focus();
		return false;
	} else if (($("input[name=user_iwosaveenergycheck_pi1[heatedTopFloor]]:checked").val() || $("input[name=user_iwosaveenergycheck_pi1[heatedCellar]]:checked").val()) && $("select[name=user_iwosaveenergycheck_pi1[heatedFloorCount]]").val() < 2) {
		alert("Da Sie ein beheiztes Dachgeschoss / einen beheizten Keller angewählt haben muss die Anzahl der Geschosse mindestens 2 betragen!");
		$("input[name=user_iwosaveenergycheck_pi1[heatedTopFloor]]").focus();
		return false;
	}
	return true;
}
