/**
 * (C) Libra 2002 - http://www.libra.de
 */
var select = new Array();
var properties = ["programm", "laufzeitJahre", "zinsbindungsJahre", "tilgungsArt", "tilgungsFreieJahre","tilgungsperiode","beihilfe","kreditTyp"];
var actualCondition = new Condition();
//Beihilfe
var matrix=new Array();
	matrix[0]=new Array(new Array("A",0.75),new Array("B",1.0),new Array("C",1.4),new Array("D",1.7),new Array("E",2.2),new Array("F",2.8),new Array("J",5.1));
	matrix[1]=new Array(new Array("A",0.75),new Array("C",1.4),new Array("E",2.2),new Array("F",2.8),new Array("G",3.5),new Array("I",5.1),new Array("J",5.1));
	matrix[2]=new Array(new Array("B",1.0),new Array("E",2.2),new Array("H",4),new Array("H",4),new Array("I",5.1),new Array("K",7.4),null);

function Condition(programm, laufzeitJahre, zinsbindungsJahre, tilgungsArt, tilgungsFreieJahre,
	kreditTyp, abgabezinssatz, anzahlRaten, maxBeihilfe, beihilfeverordnung,fremdzuschuss,tilgungsperiode,bpbeginn,beihilfe)
{

	this.programm = programm;
	this.laufzeitJahre = laufzeitJahre;
	this.zinsbindungsJahre = zinsbindungsJahre;
	this.tilgungsArt = tilgungsArt;
	this.tilgungsFreieJahre = tilgungsFreieJahre;
	this.tilgungsperiode = tilgungsperiode;
	this.kreditTyp = kreditTyp;
	this.abgabezinssatz = abgabezinssatz;
	this.anzahlRaten = anzahlRaten;
	this.maxBeihilfe = maxBeihilfe;
	this.beihilfeverordnung = beihilfeverordnung;
	this.fremdzuschuss = fremdzuschuss;
	this.bpbeginn=bpbeginn;
	this.beihilfe=beihilfe;
}
function Condition_match(other)
{
	for (var i = 0; i < properties.length; i++)
	{
		if (this[properties[i]] == null)
			return true;
		else if (other[properties[i]] != this[properties[i]])
			return false;
	}
	return true;
}
function Condition_serialize()
{
	var state = "";
	for (var i = 0; i < properties.length; i++)
	{
		var value = "";
		if (actualCondition[properties[i]] != null)
			value = escape(actualCondition[properties[i]]);
		state += properties[i] + ":" + value + "&";
	}
	return state;
}
function Condition_deserialize(ser)
{
	if (ser == null)
		return;
	for (var i = 0; i < properties.length; i++)
	{
		var value = null;
		var pos = ser.indexOf(properties[i] + ":");
		if (pos != -1)
		{
			var start = pos + properties[i].length + 1;
			var end = ser.indexOf("&", start);
			if (end == -1)
				end = ser.length;
			value = ser.substring(start, end);
			value = unescape(value);
		}
		actualCondition[properties[i]] = value;
	}
}
Condition.prototype.match = Condition_match;
Condition.prototype.serialize = Condition_serialize;
Condition.prototype.deserialize = Condition_deserialize;

/**
 * called on body load
 */
function init()
{
	document.forms["Form"].elements["js"].value="1"; // hidden field
	// elements[0] capital input feld
	select [0] = document.forms["Form"].elements[1];
	select [1] = document.forms["Form"].elements[2];
	select [2] = document.forms["Form"].elements[3];
	select [3] = document.forms["Form"].elements[4];
	select [4] = document.forms["Form"].elements[5];
	select [5] = document.forms["Form"].elements[6];
	select [6] = document.forms["Form"].elements[7];

	restoreState();


	// focus to capital
	document.forms["Form"].elements[0].focus();
	updatePk();
}

/*
 * Ermitteln und anzeigen des max. Eknzinses für das gewählte Programm, die Bonitätsklasse und Besicherungsklasse
 */
function updatePk() {
	var f1=document.getElementById("besicherungsklasse");
	var f2=document.getElementById("bonitaetsklasse");
	var eknzins;
	var condition = new Condition();
	condition["programm"]=select[0].options[select[0].selectedIndex].value;
	condition["laufzeitJahre"]=select[1].options[select[1].selectedIndex].value;
	condition["zinsbindungsJahre"]=select[2].options[select[2].selectedIndex].value;
	condition["tilgungsArt"]=select[3].options[select[3].selectedIndex].value;
	condition["tilgungsFreieJahre"]=select[4].options[select[4].selectedIndex].value;
	condition["tilgungsperiode"]=select[5].options[select[5].selectedIndex].value;
	condition["beihilfe"]=select[6].options[select[6].selectedIndex].value;
	if (matrix[f1.options.selectedIndex][f2.options.selectedIndex] !=null) {
		for (var i = 0; i < table.length; i++)
		{
			var row = table[i];
			if (condition.match(row))
			{
				eknzins=parseFloat(row["abgabezinssatz"])-parseFloat(row["fremdzuschuss"])+parseFloat(matrix[f1.options.selectedIndex][f2.options.selectedIndex][1]);
				document.getElementById("bpbeginn").innerHTML=row["bpbeginn"];
				break;
			}
		}
		document.getElementById("preisklasse").innerHTML=matrix[f1.options.selectedIndex][f2.options.selectedIndex][0]+" / "+formatNumber(eknzins)+" % *";
	} else {
		document.getElementById("preisklasse").innerHTML="";
	}
}

/**
 * called on body unload
 */
function unload()
{
	storeState();
}

/**
 * reloads recursively all select boxes starting with initial index
 */
function reloadSelectBox (index)
{
	// debug:
	//document.forms[0].elements["debug"].value += "\nreloadSelectBox"
	//	+ "(" + index + ")";
	if (index >= select.length) { // end condition for recursion
		return; // no more select box to reload
	}

	var condition = new Condition();
	for (var i = 0; i < properties.length; i++)
	{
		if (i < index)
		{
			var selectedOption = select[i].options[select[i].selectedIndex];
			condition[properties[i]] = selectedOption.value;
		}
		else
		{
			condition[properties[i]] = null;
		}
	}
	select[index].options.length = 0;

	var options = new Array();
	var maxBeihilfe;
	var beihilfeverordnung;
	for (var i = 0; i < table.length; i++)
	{
		var row = table[i];
		if (condition.match(row))
		{
			var value = row[properties[index]];
			options[options.length] = new Option(value, value);
			maxBeihilfe=row["maxBeihilfe"];
			beihilfeverordnung=row["beihilfeverordnung"];
		}
	}
	options = format(index, options);
	options = condense(options);
	// fill select box
	var selectedIndex = 0;
	var matchOption = null;
	if (actualCondition != null)
		matchOption = actualCondition[properties[index]];
	for (var i = 0; i < options.length; i++)
	{
		select[index].options[select[index].options.length] = options[i];
		if (options[i].value == matchOption)
			selectedIndex = i;
	}
	// select option
	if (select[index].options.length > 0)
	{
		select[index].selectedIndex = selectedIndex;
	}
	// reload dependent recursively
	if (index + 1 < select.length)
		reloadSelectBox(index + 1);
}

function formatNumber(str)
{
	var i=(+str);
	if (i<=0)
		return "-";
	var nf = new NumberFormat(i);
	nf.setPlaces(2);
	nf.setSeparators(true, nf.PERIOD, nf.COMMA);
	return nf.toFormatted();
}

function sortOptions(select1, select2){
	var i = 0;
	if (isNaN(select1.text)||isNaN(select2.text)){
		if (select1.text==select2.text){
			i==0;
		} else if (select1.text<select2.text){
			i=-1;
		} else {
			i=1;
		}
	} else {
		i=parseInt(select1.text)-parseInt(select2.text);
	}
	return i;
}

/**
 * make options unique
 */
function condense(options)
{
	/* create a new array which contains no duplicate options */
	var newOptions = new Array();
	for (var i = 0; i < options.length; i++)
	{
		var option = options[i];
		var match = false;
		for (var j = 0; j < newOptions.length; j++)
		{
			if (option.value == newOptions[j].value)
			{
				match = true;
				break;
			}
		}
		if (!match)
			newOptions[newOptions.length] = option;
	}
	newOptions.sort(sortOptions);
	return newOptions;
}
/**
 * format options 
 * @param index - n'th property
 * @param options - array of option objects
 * @return array of option objects
 */
function format(index, options)
{
	
	if (properties[index] == "laufzeitJahre")
	{
		for (var i = 0; i < options.length; i++)
		{
			var parts = options[i].text.split(".", 2);
			var fraction = parts[1];
			var nonZero = false;
			for (var j = 0; j < fraction.length; j++)
			{
				if (fraction.charAt(j) != '0')
				{
					nonZero = true;
				}
			}
			
			var text;
			if (nonZero == true)
			{
				// decimalSeparator is a global whose value is set by the jsp page
				text = options[i].text.replace(".", decimalSeparator);
			}
			else
			{
				text = parts[0];
			}
			options[i].text = text; 
			// we do not format the option value - otherwise we would not find a match in js table for current selection
			 
		}
	} else if (properties[index] == "tilgungsperiode"){
		for (var i = 0; i < options.length; i++){
			if (options[i].value == "3"){
				options[i].text = "vierteljährlich"; 
			} else if (options[i].value == "6"){
				options[i].text = "halbjährlich";
			} else if (options[i].value == "12"){
				options[i].text = "jährlich";
			} else if (options[i].value == "99"){
				options[i].text = "endfällig";
			}
		}
	} else if (properties[index] == "beihilfe"){
		for (var i = 0; i < options.length; i++){
			if (options[i].value == "true"){
				options[i].text = "Ja"; 
			} else if (options[i].value == "false"){
				options[i].text = "Nein";
			}
		}
	}

	return options;

}


/**
 * store "state" (i.e. state of select boxes) into session cookie
 * server will delete cookie through http header
 * -> cookie will not be used when full server cycle but trown away
 * -> cookie will be used only on restore when "back button"
 *		was pressed
 */
function storeState()
{
	// actualCondition was set at unload Event from select boxes

	var path = location.pathname;
	//var end = path.indexOf("/", 1); // skip first
	//if (end != -1)
	//	path = path.substring(0, end); // trim to context name
	path = "/"; // context is too fragile for deployment, we take root

	var cookie = new Cookie("state", path);
	cookie.actualCondition = actualCondition.serialize();
	cookie.store();

}
function restoreState()
{
	// debug:
	//document.forms[0].elements["debug"].value = "restoreState()"

	var cookie = new Cookie("state"); // we do no store it here
		// so we do not need a path
	var loaded = cookie.load();
	

	if (loaded)
	{
		actualCondition.deserialize(cookie.actualCondition);
		reloadSelectBox(0);
	}
	else
	{
		// this should happen in a full server cycle
		// page was set up correcty in JSP
		reloadSelectBox(0);
	}
	for (var i = 0; i < properties.length; i++)
	{
		if (select[i] != null && select[i].selectedIndex  && select[i].selectedIndex >= 0)
		{
			var selectedOption = select[i].options[select[i].selectedIndex].value;
			actualCondition[properties[i]] = selectedOption;
		}
	}

	// debug:
	//document.forms[0].elements["debug"].value += "loaded="
	//	+ loaded;
	//document.forms[0].elements["debug"].value += "\ndocument.cookie="
	//	+ document.cookie;

}

/**
 * changeHandler is EventHandler for both
 * "onchange" and "onunload" Event for SelectBoxes
 * it sets the global actualCondition
 * and triggers reload of dependent select boxes
 */
function changeHandler(index)
{
	// set actual condition (all "lower" properties with values
	// all "higher" properties with null)
	for (var i = 0; i < properties.length; i++)
	{
		if (i <= index)
		{
			var selectedOption = select[i].options[select[i].selectedIndex].value;
			actualCondition[properties[i]] = selectedOption;
		}
		else
		{
			actualCondition[properties[i]] = null;
		}
	}
	reloadSelectBox(index+1); // reload all dependent
	updatePk(); // Preisklasse und max. EKN-Zins aktualisieren
	return true;

}

function Cookie(name, path)
{
	this.$name = name;
	if (path)
		this.$path = path;
}
Cookie.prototype.store = function()
{
	var cookieval = "";
	for (var property in this)
	{
		if ((property.charAt(0) == '$') || ((typeof this[property]) == 'function'))
			continue;
		cookieval += property + ":" + escape(this[property]) + "&";
	}
	var cookie = this.$name + "=" + cookieval;
	if (this.$path)
		cookie += "; path=" + this.$path;
	document.cookie = cookie;
}
Cookie.prototype.load = function()
{
	var allCookies = document.cookie;
	if (allCookies == "")
		return false;

	var start = allCookies.indexOf(this.$name + "=");
	if (start == -1)
		return false;

	start += this.$name.length + 1;
	var end = allCookies.indexOf(";", start);
	if (end == -1)
		end = allCookies.length;
	var cookieval = allCookies.substring(start, end);

	if (cookieval.length == 0)
		return false; // there is a cookie - but empty

	var ar = cookieval.split("&");
	for (var i = 0; i < ar.length; i++)
	{
		var pair = ar[i].split(":");
		this[pair[0]] = unescape(pair[1]);
	}
	return true;
}

