/**
 * @author buenger
 */

var firstRun = true;
var pageFirstRun = true;
var leasingOptions = {
	
	//Input
	customerTypeId: 'kundenart',
	carKindId: 'fahrzeugart',
	carTypeId: 'fahrzeugtyp',
	makeId: 'marke',
	priceId: 'barkaufpreis',
	runtimeId: 'laufzeit_monate',
	kmId: 'km_pro_jahr',
	depositId: '1_leasingrate',
	decliningBalanceKindId: 'restwert',
	decliningBalanceId: 'restwert_1',
	PPIDeathId: 'versicherung_todesfall',
	PPIUnemploymentId: 'versicherung_erwerbslosigkeit',	
	
	//Results
	nomInterestId: 'jahreszinsen_nominal',
	effInterestId: 'jahreszinsen_effektiv',
	rateId: 'leasingrate_ohne_absicherung',
	rateInclPPIId: 'leasingrate_inkl_absicherung',
	securityId: 'kaution',
	resultBox1Id: 'box_leasing_resultat_1',
	resultBox2Id: 'box_leasing_resultat_2'
}


var leasingRequest = new LeasingService ('BanknowOverviewCalcLeaseRequest');
var leasingCalculator = new Leasing ();

function addLeasingEvents () {
	$E(leasingOptions.kmId).addEvent("propChange", handleKm);
	$E(leasingOptions.customerTypeId).addEvent("propChange", handleCustomerType);
	$E(leasingOptions.carTypeId).addEvent("propChange", handleCarType);
	$E(leasingOptions.makeId).addEvent("propChange", handleMake);
	$E(leasingOptions.runtimeId).addEvent("propChange", handleRuntime);
	$E(leasingOptions.priceId).addEvent("propChange", handlePrice);
	$E(leasingOptions.depositId).addEvent("propChange", handleDeposit);
	$E(leasingOptions.decliningBalanceKindId).addEvent("propChange", handleDecliningBalanceKind);
	$E(leasingOptions.PPIDeathId).addEvent("propChange", handlePPIDeath);
	$E(leasingOptions.PPIUnemploymentId).addEvent("propChange", handlePPIUnemployment);	
}



function handleCustomerType () {	
	if ($E(leasingOptions.customerTypeId).value () == 2) {
		$('box_ratenabsicherung').setStyle('display', 'none');
		$('leasingrate_inkl_absicherung').setStyle('display', 'none');
	} else {
		$('box_ratenabsicherung').setStyle('display', 'block');
		$('leasingrate_inkl_absicherung').setStyle('display', 'block');
	}
	$('continueButton').style.display = "none";
}
function handleCarType () {
	
	Settings.setLeasingMinPrice($E(leasingOptions.carTypeId).formValue());
	Settings.setLeasingMaxPrice();
	
	leasingRequest.setCarType($E(leasingOptions.carTypeId).formValue());
	leasingRequest.addEvent("success", handleMakeResponse);
	leasingRequest.getMake();
	$('continueButton').style.display = "none";
}

function handleMake () {
	
	if (POST['amount'] != 0) {
		$E(leasingOptions.priceId).setNumValue(Number(POST['amount']));
		leasingRequest.setPrice($E(leasingOptions.priceId).numValue);
		leasingCalculator.setPrice($E(leasingOptions.priceId).numValue);
		delete POST['amount'];
	}
	
	leasingRequest.setMake($E(leasingOptions.makeId).formValue());
	leasingRequest.addEvent("success", handleCarDataResponse);
	leasingRequest.getCarData();
	$('continueButton').style.display = "none";
}

function handlePrice () {
		
	leasingRequest.setPrice($E(leasingOptions.priceId).numValue);
	leasingCalculator.setPrice($E(leasingOptions.priceId).numValue);
	if ($E(leasingOptions.runtimeId).value() != 0) {
		if (firstRun == true) {
			//$E(leasingOptions.kmId).addEvent("propChange", getDecliningBalance);
			firstRun = false;
		} else getDecliningBalance();
	}
	$('continueButton').style.display = "none";
}

function handleDeposit () {
	leasingRequest.setDepositExclVAT(Utilities.exclVAT($E(leasingOptions.depositId).numValue));
	leasingCalculator.setDeposit($E(leasingOptions.depositId).numValue);
	$('continueButton').style.display = "none";
}

function handleKm () {
	leasingRequest.setKm($E(leasingOptions.kmId).formValue());
	getDecliningBalance("handleCarDataResponse");
	$('continueButton').style.display = "none";
}

function handleDecliningBalanceKind () {
	
	if ($E(leasingOptions.decliningBalanceKindId).value() == 1) {
		$E(leasingOptions.decliningBalanceId).addEvent("propChange", handleDecliningBalance);
		$E(leasingOptions.decliningBalanceId).setReadOnly(false);
	} else {
		$E(leasingOptions.decliningBalanceId).removeEvent("propChange", handleDecliningBalance);
		$E(leasingOptions.decliningBalanceId).setNumValue(leasingCalculator.getStandardDecliningBalance());
		leasingCalculator.setDecliningBalance(leasingCalculator.getStandardDecliningBalance());
		$E(leasingOptions.decliningBalanceId).setReadOnly(true);
		
	}
	$('continueButton').style.display = "none";
}

function handleDecliningBalance () {
	leasingRequest.setDecliningBalance(Utilities.exclVAT($E(leasingOptions.decliningBalanceId).numValue));
	leasingCalculator.setDecliningBalance($E(leasingOptions.decliningBalanceId).numValue);
	$('continueButton').style.display = "none";
}

function handleRuntime () {
	leasingCalculator.setRuntime($E(leasingOptions.runtimeId).formValue());
	leasingRequest.setRuntime($E(leasingOptions.runtimeId).formValue());
			
	if ($E(leasingOptions.priceId).numValue != undefined && $E(leasingOptions.priceId).numValue != 0) {
		if (firstRun == true) {
			//$E(leasingOptions.kmId).addEvent("propChange", getDecliningBalance);
			firstRun = false;
		}
		getDecliningBalance("handleRuntime");
	}
	$('continueButton').style.display = "none";
}

function handlePPIDeath () {
	leasingCalculator.setPPIDeath($E(leasingOptions.PPIDeathId).value());
	$('continueButton').style.display = "none";
}

function handlePPIUnemployment () {
	leasingCalculator.setPPIUnemployment($E(leasingOptions.PPIUnemploymentId).value());
	$('continueButton').style.display = "none";
}

function handleCarTypeResponse  () {
	leasingRequest.removeEvent("success", handleCarTypeResponse);
	var options = [];
	$A(arguments).each(function (a_item, a_index ){
		var option = new Element ("option");
		option.innerHTML = a_item.value;
		option.value = a_item.id;
		options.push(option);
	})
	$E(leasingOptions.carTypeId).replaceOptions(options);
	initReadOnlys();	
	
	if (POST['customerType'] != 0) {
		$E(leasingOptions.customerTypeId).setValue(Number(POST['customerType']));
		$E(leasingOptions.customerTypeId).fireEvent("propChange");
		delete POST['customerType'];
	}
	
	if (POST['type'] != 0) {
		$E(leasingOptions.carKindId).setValue(Number(POST['type']));
		$E(leasingOptions.carKindId).fireEvent("propChange");
		delete POST['type'];
	}
	
	if (POST['product'] != 0) {
		$E(leasingOptions.carTypeId).setFormValue(Number(POST['product']));
		$E(leasingOptions.carTypeId).fireEvent("propChange");
		delete POST['product'];
	}
}

function handleMakeResponse  () {
	
	
	leasingRequest.removeEvent("success", handleMakeResponse);
	var options = [];
	$A(arguments).each(function (a_item, a_index ){
		var option = new Element ("option");
		option.innerHTML = a_item.value;
		option.value = a_item.id;
		options.push(option);
	})
	$E(leasingOptions.makeId).replaceOptions(options);	
	
	setTimeout( function(){
		if (POST['model'] != 0) {
			$E(leasingOptions.makeId).setFormValue(Number(POST['model']));
			$E(leasingOptions.makeId).fireEvent("propChange");
			delete POST['model'];
		}
	}, 1);
}

function handleCarDataResponse (a_obj) {
	
	if (POST['runtime'] != 0) {
		$E(leasingOptions.runtimeId).setFormValue(Number(POST['runtime']));
		leasingCalculator.setRuntime($E(leasingOptions.runtimeId).formValue());
		leasingRequest.setRuntime($E(leasingOptions.runtimeId).formValue());
		firstRun = false;
		delete POST['runtime'];
	}

	leasingRequest.removeEvent("success", handleCarDataResponse);
	leasingRequest.setDecliningBalanceType(a_obj.decliningBalanceId);
	
	var options = [];
	for (var i = Number(a_obj.minKilometers); i <= Number(a_obj.maxKilometers); i += Number(a_obj.step)) {
		var option = new Element ("option");
		option.innerHTML = i;
		option.value = i;
		options.push(option);
	}

	$E(leasingOptions.kmId).replaceOptions(options, 2);	
	leasingRequest.setKm(options[1].value);
	
	
	if ($E(leasingOptions.runtimeId).value() != 0) {
		if (firstRun == true) {
			firstRun = false;
		}
		else {
			getDecliningBalance("handleCarDataResponse");
		}
	}	
}

function handleDecliningBalanceResponse  (a_obj) {
	leasingRequest.removeEvent("success", handleDecliningBalanceResponse);
	leasingCalculator.setMinDecliningBalance($E(leasingOptions.priceId).numValue * Number (a_obj.minDecliningBalance)/100);
	leasingCalculator.setMaxDecliningBalance($E(leasingOptions.priceId).numValue * Number (a_obj.maxDecliningBalance)/100);
	leasingCalculator.setStandardDecliningBalance($E(leasingOptions.priceId).numValue * Number (a_obj.decliningBalance)/100);
		
	if ($E(leasingOptions.decliningBalanceKindId).value() != 1) {
		var decliningBalance = $E(leasingOptions.priceId).numValue * Number(a_obj.decliningBalance) / 100;
		leasingCalculator.setDecliningBalance(decliningBalance);
		$E(leasingOptions.decliningBalanceId).setNumValue(decliningBalance);
	}
	$('calculateButton').style.display = "inline";
	$E(leasingOptions.resultBox1Id).setVisibility(true);
}

function handleEffInterestResponse  () {
	leasingRequest.removeEvent("success", this);
}

function getDecliningBalance (a_caller) {
	leasingRequest.addEvent("success", handleDecliningBalanceResponse);
	setTimeout(function () {
		leasingRequest.getDecliningBalance();
	}, 200)
}

function setLeasingResults() {
	var nomInterest = LeasingInterest.getInterest($E(leasingOptions.carTypeId).formValue(), $E(leasingOptions.priceId).numValue, $E(leasingOptions.depositId).numValue);
	if (nomInterest) {
		var effInterest = Utilities.getEffInterest(nomInterest);
		$E(leasingOptions.nomInterestId).setValue(nomInterest.toFixed(2) + "%");
		$E(leasingOptions.effInterestId).setValue(effInterest.toFixed(2) + "%");
		leasingCalculator.setNomInterest(nomInterest);
	} else {
		leasingCalculator.setNomInterest(1.0);
	}
	leasingCalculator.setNomInterest(nomInterest);
	leasingCalculator.calculate();
}

function handleResults(){
	$E(leasingOptions.rateId).setNumValue(leasingCalculator.rate);
	$E(leasingOptions.rateInclPPIId).setNumValue(leasingCalculator.rateInclPPI);
	$E(leasingOptions.securityId).setNumValue(0);
	if ($E(leasingOptions.depositId).numValue == undefined || $E(leasingOptions.depositId).numValue == 0) {
		$E(leasingOptions.depositId).setNumValue (leasingCalculator.rateInclPPI);
	}
	$E(leasingOptions.resultBox2Id).setVisibility(true);
	$('continueButton').style.display = "inline";
}

function prepareSubmit () {
	
}

function handleError (a_obj) {
	switch (arguments[0]) {
		
		case "price":
			var error = TEXTS['Waehlen_Sie_einen_Wunschkredit'].replace("[param_1]", arguments[1]);
			error = error.replace("[param_2]", arguments[2]);
			break;
			
		case "runtime":
			var error = TEXTS['Waehlen_Sie_einen_Laufzeit'];
			break;
			
		case "decliningBalance":
			var error = String(TEXTS['Bitte_waehlen_Sie_einen_Restwert_zwischen']).replace("[param_1]", arguments[1]);
			error = error.replace("[param_2]", arguments[2]);
			break;
			
		case "deposit":
			var error = TEXTS['Die_erste_Rate_darf_nicht_hoeher'];
			break;
	}
	cmsAlert(TEXTS["Hinweis"], error ,TEXTS["Schliessen"]);
}

function initReadOnlys () {
	$E(leasingOptions.nomInterestId).setReadOnly(true);
	$E(leasingOptions.effInterestId).setReadOnly(true);
	$E(leasingOptions.rateId).setReadOnly(true);
	$E(leasingOptions.rateInclPPIId).setReadOnly(true);
	$E(leasingOptions.decliningBalanceId).setReadOnly(true);
	
}

function leasingInit () {
	window.removeEvent ("load", this);	
	addLeasingEvents();
	
	$('calculateButton').style.display = "none";
	$('continueButton').style.display = "none";

	
	leasingCalculator.addEvent("error", handleError);
	leasingCalculator.addEvent("success", handleResults);
	
	leasingRequest.addEvent("success", handleCarTypeResponse);
	leasingRequest.getCarType();
}

window.onload = leasingInit;

