// HTML-Elemente beim Seitenaufruf initialisieren
/*
 * Auswahlbox Inbetriebnahme
 * erste Option entspricht dem aktuellen Jahr, die Anzahl der Optionen dem Wert des Parameters count_options
 *
 * @param int count_options
 */
function setStartup(count_options) {

    if (debug)
        alert("setStartup(" + count_options + ")");

    var now          = new Date();
    var basic_year   = 1900;
    var current_year = 0;
    var temp_year    = 1 * now.getYear();

    /* Microsoft ist ein Bug */
    if (temp_year < 1900)
        current_year += basic_year;

    current_year += 1 * temp_year;

    /* pruefen, nie ausprobiert */
    /*sStartup.prototype     = new upgradeSelect();
    sStartup.countoptions  = count_options;
    sStartup.indexselected = 0;
    sStartup.decimalplaces = 0;
    sStartup.startvalue    = 0;
    sStartup.starttext     = current_year;
    sStartup.step          = 1;

    createOptions(sStartup);*/

    var tmp_0       = document.createElement("option");
    tmp_0.value     = 1;
    tmp_0.text      = current_year;
    tmp_0.className = "tx_ibccalculator";
    tmp_0.selected  = true;
    
    var tmp_1       = document.createElement("option");
    tmp_1.value     = degression;
    tmp_1.text      = current_year + 1;
    tmp_1.className = "tx_ibccalculator";
    //tmp_1.selected  = true;

    sStartup.options.add(tmp_0);
    sStartup.options.add(tmp_1);

    /* nur das aktuelle Jahr anzeigen, Selectbox wird in standard.html ausgeblendet */
    document.getElementById('dis_ibccalculator_startup').value = sStartup.options[sStartup.selectedIndex].text;
}

/*
 * Auswahlbox Laufzeit
 *
 * @param int count_options
 */
function setDuration(count_options) {

    if (debug)
        alert("setDuration(" + count_options + ")");

    prepareOptions(sDuration, count_options, 1, 1, 1);
}

/*
 * Auswahlbox tilgungsfreie Jahre
 *
 * @param int count_options
 */
function setRedemption(count_options) {

    if (debug)
        alert("setRedemption(" + count_options + ")");

    prepareOptions(sRedemption, count_options, 0, 0, 1);
}

/*
 * Auswahlbox Erhoehung der Strombezugskosten
 *
 * @param int count_options
 */
function setIncreaseelectricity(count_options) {

    if (debug)
        alert("setIncreaseelectricity(" + count_options + ")");

    prepareOptions(sIncreaseelectricity, count_options, 0, 0, 0.5);
}

/*
 * Auswahlbox vorbereiten
 *
 * @param HTMLSelect selectbox
 * @param int        count_options
 * @param int        start_value
 * @param int        start_text
 * @param float      step
 */
function prepareOptions(selectbox, count_options, start_value, start_text, step) {

    if (debug)
        alert("prepareOptions(" + selectbox.id + ", " + count_options +  ", " + start_value + ", " + start_text + ", " + step + ")");

    selectbox.prototype     = new upgradeSelect();
    selectbox.countoptions  = count_options;
    selectbox.indexselected = data[selectbox.id][0] * 1
    selectbox.decimalplaces = data[selectbox.id][1] * 1;
    selectbox.startvalue    = start_value * 1;
    selectbox.starttext     = start_text * 1;
    selectbox.step          = step * 1;

    createOptions(selectbox);
}

/*
 * Auswahlbox bestuecken, Auswahl belegen
 *
 * @param HTMLSelect selectbox
 */
function createOptions(selectbox) {

    if (debug)
        alert("createOptions(" + selectbox.id + ")");

    for (var i = 0; i < selectbox.countoptions; i++) {

        var e       = document.createElement("option");
     	e.value     = (selectbox.startvalue + i) *  selectbox.step;
		e.text      = formatDigit((selectbox.starttext * 1 + i) * selectbox.step * 1, selectbox.decimalplaces);
		e.className = "tx_ibccalculator";
        selectbox.options.add(e);

        if (selectbox.options[i].value == selectbox.indexselected)
		     selectbox.options[i].selected = true;
    }
}

/*
 * input Elemente initialisieren
 */
function initInputElements() {

    if (debug)
        alert("initInputElements()");

    var inputs = document.getElementsByTagName("input");

    for (var i = 0; i < inputs.length; i++) {

        /* aktive nummerische Eingabefelder vom Typ Text und zusaetzlich die fuer die Bearbeitung gesperrten Eingabefelder fuer die Netzeinspeise-, und Eigenverbrauchsverguetung */
        if (inputs[i].type == "text" && (inputs[i].className == "tx_ibccalculator_numeric" || inputs[i].id == "compensation" || inputs[i].id == "owncompensation")) {

            var data_id       = inputs[i].id;
            var realvalue     = 0;
            var decimalplaces = 0;

            if (data_id == "compensation") {
                realvalue     = data['comp_roof_0_cur'][0] * 1;
                decimalplaces = data['comp_roof_0_cur'][1] * 1;

            } else if (data_id == "owncompensation") {
                realvalue     = data['comp_roof_0_cur'][0] * 1 - bonuspower + data['bonusquote_0'][0] * 1;
                decimalplaces = data['comp_roof_0_cur'][1] * 1;

            } else {
                realvalue     = data[data_id][0] * 1;
                decimalplaces = data[data_id][1] * 1;
            }

            inputs[i].prototype     = new upgradeNumericInput();
            inputs[i].value         = number2string(realvalue, decimalplaces);
            inputs[i].realValue     = realvalue;
            inputs[i].decimalplaces = decimalplaces;
//            alert(data_id + " = " + realvalue + " / " + decimalplaces);
        }
    }
}

// Navigations- und Eingabemaskenfunktionen
/*
 * Steuerung fuer Maskenwechsel bzw. Wirtschaftlichkeitsberechnung starten,
 *
 * @param string p_id
 */
function pressTab(p_id) {

    if (debug)
        alert("pressTab(" + p_id + ")");

    /* Navigation nicht gesperrt */
    if (navi) {
        /* checkStrings entfernt unzulaessige Zeichen aus den Eingabeformularfeldern */
    	if (p_id == 'submit') {
    	   checkStrings();

    	   /*
    	    * checkValues gibt aktuell immer true zurueck
    	    * dort koennen noch spezielle Pruefungen fuer die Eingabefelder eingebunden werden
    	    */
    	   if(checkValues()) {
    	       dPeriod.disabled              = false;
    	       dCompensation.disabled        = false;
    	       dOwncompensation.disabled     = false;
    	       dOwncompensationrate.disabled = false;
    	       sIscompany.disabled           = false;

    	       /* keine lokalisierten und formatierten Ziffernzeichenfolge uebergeben */
    	       dOwncompensationrate.value = string2number(dOwncompensationrate.value, 2);

    	       var inputs = document.getElementsByTagName("input");

    	       for (var i = 0; i < inputs.length; i++) {

    	           if (inputs[i].type == "text" && (inputs[i].className == "tx_ibccalculator_numeric" || inputs[i].id == "compensation" || inputs[i].id == "owncompensation")) {
    	               setValuesByValue(inputs[i]);
    	               inputs[i].value = inputs[i].realValue;
    	           }
    	       }

    	       submitForm();
    	       //document.forms['tx_ibccalculator_form'].submit();
    	   }
    	} else {

    	   if (input_mask)
    	       setEquity();
               //getCredit();

    	   changeLayer(p_id);
        }
    }
}

/*
 * angewaehlte Maske ein- und alle anderen Masken ausblenden
 * Navigationsmenu der aktiven und inaktiven Maske formatieren
 *
 * @param string p_id
 */
function changeLayer(p_id) {

    if (debug)
        alert("changeLayer(" + p_id + ")");

    var end = pages.length;

    if (input_mask)
        end = 3;

	for (var i = 0; i < end; i++){

  		if(p_id == pages[i]) {
  			document.getElementById('tx_ibccalculator_content' + p_id).style.display = "";
  			document.getElementById('tx_ibccalculator_menu' + p_id).className = "tx_ibccalculator_menuactive" + p_id;

  			if (document.getElementById('div_ibccalculator_content' + p_id))
  			    document.getElementById('div_ibccalculator_content' + p_id).style.display = "";

  		} else {
  			document.getElementById('tx_ibccalculator_content' + pages[i]).style.display = "none";
  			document.getElementById('tx_ibccalculator_menu' + pages[i]).className = "tx_ibccalculator_menuinactive" + pages[i];

  			if (document.getElementById('div_ibccalculator_content' + pages[i]))
  			    document.getElementById('div_ibccalculator_content' + pages[i]).style.display = "none";
  		}
    }
}

/*
 * hoover Effekt fuer Navigationstabs
 *
 * @param object e
 * @param string classname
 * @param string p_id
 */
function hooverTab(e, classname, p_id) {

    if (debug)
        alert("hooverTab(" + e.id + ", " + classname + ", " + p_id + ")");

    if (document.getElementById('tx_ibccalculator_content' + p_id).style.display == "none")
        e.className = classname;
}

/*
 * Einspeiseveguetung in Abhaengigkeit des gewaehlten Inbetriebnahmejahres setzen
 */
function changeCompensation() {

  if(debug)
    alert('changeCompensation()');

  dCompensation.realValue = getCompensation();
  setValuesByRealValue(dCompensation);

  /* Erlaeuterungen Konversions- sonstige Freiflaechen / notwendige Eingabefelder fuer Eigenverbrauchsauswahl ein- bzw. ausblenden */
  if (sType.options[sType.selectedIndex].value == 3) {
      document.getElementById('area_adaptive').style.display         = "";
      document.getElementById('area_other').style.display            = "none";
      document.getElementById('row_owncompensation_0').style.display = "none";
      setLblAccumulator(0);
      rOwnCompensationNo.checked                                     = true;
      ownCompensation(false);

  } else if (sType.options[sType.selectedIndex].value == 4) {
      document.getElementById('area_adaptive').style.display         = "none";
      document.getElementById('area_other').style.display            = "";
      document.getElementById('row_owncompensation_0').style.display = "none";
      setLblAccumulator(0);
      rOwnCompensationNo.checked                                     = true;
      ownCompensation(false);
  } else {
      document.getElementById('area_adaptive').style.display         = "none";
      document.getElementById('area_other').style.display            = "none";
      document.getElementById('row_owncompensation_0').style.display = "";

      if(vPowerout.realValue > 500) {
        ownCompensation(false);
      } else {
        dOwncompensation.realValue = calculateOwnCompensation();
        setValuesByRealValue(dOwncompensation);
      }
  }
}

/*
 * Eigenverbrauchseinspeiseverguetung und - zeitraum zum Bearbeiten freischalten
 *
 * @param boolean own
 */
function ownCompensation(own) {

    if (debug)
        alert("ownCompensation(" + own + ")");

    /* Nennleistung groesser 500 kWp */
    if((vPowerout.realValue > 500)) {
        document.getElementById('errPowerout').style.visibility = "visible";
        rOwnCompensationNo.checked                              = true;
        own = false;
        //alert("kein Eigenverbrauch - Nennleistung zu gross");
    /* kein Eigenverbrauch gewaehlt */
    } else if (!own) {
        document.getElementById('errPowerout').style.visibility = "hidden";
        rOwnCompensationNo.checked                              = true;
        //alert("kein Eigenverbrauch - gewaehlt");
    /* Eigenverbrauch gewaehlt Nennleistung bis 500 kWp */
    } else {
        document.getElementById('errPowerout').style.visibility = "hidden";
        rOwnCompensationYes.checked                             = true;
        //alert("Eigenverbrauch - gewaehlt");
    }

    /* evtl. Fehlermeldung kein Eigenverbrauch da Nennleistung zu gross nach Anlagentyp ausblenden */
    if(sType.options[sType.selectedIndex].value > 2)
        document.getElementById('errPowerout').style.visibility = "hidden";

    /* notwendige Eingabefelder fuer Eigenverbrauch ein- bzw. ausblenden */
    initOwnCompensationRows();

    dOwncompensation.realValue = calculateOwnCompensation();
    setValuesByRealValue(dOwncompensation);
}

/*
 * Eigenverbrauchseingabfelder ein- bzw. ausblenden
 */
function initOwnCompensationRows() {

    if (rOwnCompensationYes.checked == true) {

      document.getElementById('row_owncompensation_1').style.display = "";
      document.getElementById('row_owncompensation_2').style.display = "";
      document.getElementById('row_owncompensation_3').style.display = "";
      document.getElementById('row_owncompensation_4').style.display = "";
      document.getElementById('row_owncompensation_5').style.display = "";
      document.getElementById('row_owncompensation_6').style.display = "";
      document.getElementById('row_owncompensation_7').style.display = "";
    } else {

      document.getElementById('row_owncompensation_1').style.display = "none";
      document.getElementById('row_owncompensation_2').style.display = "none";
      document.getElementById('row_owncompensation_3').style.display = "none";
      document.getElementById('row_owncompensation_4').style.display = "none";
      document.getElementById('row_owncompensation_5').style.display = "none";
      document.getElementById('row_owncompensation_6').style.display = "none";
      document.getElementById('row_owncompensation_7').style.display = "none";
   }
}

/*
 * effektiver Zinssatz vs. nominaler Zinssatz
 */
function switchAnnualrateLabel() {

    if(debug)
		alert("switchAnnualrateLabel()");

    if (vDisbursement.realValue >= 100.00) {
	    document.getElementById('annualrate_nominal').style.display = "none"
	    document.getElementById('annualrate_effective').style.display = ""
	} else {
	    document.getElementById('annualrate_effective').style.display = "none"
	    document.getElementById('annualrate_nominal').style.display = ""
	}
}

// Berechnungen
/*
 * Einspeiseverguetung ermitteln
 */
function getCompensation() {

    if(debug)
        alert('getCompensation()');

    if (sType.options[sType.selectedIndex].value == 3)
        return data['comp_outdoor_cur'][0] * sStartup.value;

    else if (sType.options[sType.selectedIndex].value == 4)
        return data['comp_other_cur'][0] * sStartup.value;

    return calculateCompensation();
}

/*
 * durchschnittliche Einspeiseverguetung fuer Dach- oder Fassadenanlage ueber 30 kWp Nennleistung berechnen
 *
 */
function calculateCompensation() {

    if(debug)
        alert('calculateCompensation()');

    var power = 1 * vPowerout.realValue;

    /* keine Berechnung bis 30.00 kWp Anlagenleistung */
    if (power < 30.01)
        return compensation_rate[sType.options[sType.selectedIndex].value][0] * sStartup.value;

    var start     = 1 * sStartup.value;
    var adv_comp  = 0;
    var advantage = "";
    var power_0   = 30;
    var power_1   = 70;
    var power_2   = 900;
    var power_3   = 0;

    if (power < 1000)
      power_2 = power - power_0 - power_1;
    else
      power_3 = power - power_0 - power_1 - power_2;

    if (power < 100) {
      power_1 = power - power_0;
      power_2 = 0;
    }

    adv_comp  = power_0 * compensation_rate[sType.options[sType.selectedIndex].value][0] * sStartup.value;
    adv_comp += power_1 * compensation_rate[sType.options[sType.selectedIndex].value][1] * sStartup.value;
    adv_comp += power_2 * compensation_rate[sType.options[sType.selectedIndex].value][2] * sStartup.value;
    adv_comp += power_3 * compensation_rate[sType.options[sType.selectedIndex].value][3] * sStartup.value;
    adv_comp  = adv_comp / power;
    advantage = " " + adv_comp + " ";
    advantage = trim(advantage);

    return advantage;
}

/*
 * durchschnittliche Einspeiseverguetung fuer Eigenverbrauch berechnen
 * gewerblich genutzt
 *
 * @param int power
 */
function calculateOwnCompensation() {

    if(debug)
        alert('calculateOwnCompensation()');

    //var start     = 1 * sStartup.value;
    var power     = vPowerout.realValue;
    var crate     = 1 * dOwncompensationrate.value.replace(decimalpoint, "\.");
    var adv_comp  = 0;
    var advantage = "0";

    /* Berechnung Nennleistung bis 30.00 kWp und Eigenverbrauchsanteil bis 30 % */
    if (power < 30.01 && crate < 30.01)
        return data['comp_roof_0_cur'][0] * sStartup.value - bonuspower + data['bonusquote_0'][0] * 1;

    /* Nennleistung wird nur bis 500 kWp beruecksichtigt */
    if(power > 500.00)
        power = 500.00;

    var power_0 = 30;
    var power_1 = 70;
    var power_2 = 0;

    /* Nennleistungsanteil zwischen 100 und 500 kWp ermitteln */
    if(power > 100)
        power_2 = power - 100;

    /* Nennleistungsanteil zwischen 30 und 100 kWp ermitteln */
    if(power < 100)
        power_1 = power - 30;

    if(power <= 30) {
        power_1 = 0;
        power_0 = power;
    }

    /* Eigenverbrauchsanteile ermitteln */
    var crate_30  = 30;
    var crate_100 = 0;

    if(crate < 30)
        crate_30 = crate;
    else
        crate_100 = crate - 30;

    var tmp_comp = new Array();
    tmp_comp.push(power_0 * (data['comp_roof_0_cur'][0] * sStartup.value - bonuspower + data['bonusquote_0'][0] * 1));
    tmp_comp.push(power_1 * (data['comp_roof_1_cur'][0] * sStartup.value - bonuspower + data['bonusquote_0'][0] * 1));
    tmp_comp.push(power_2 * (data['comp_roof_2_cur'][0] * sStartup.value - bonuspower + data['bonusquote_0'][0] * 1));
    tmp_comp.push(power_0 * (data['comp_roof_0_cur'][0] * sStartup.value - bonuspower + data['bonusquote_1'][0] * 1));
    tmp_comp.push(power_1 * (data['comp_roof_1_cur'][0] * sStartup.value - bonuspower + data['bonusquote_1'][0] * 1));
    tmp_comp.push(power_2 * (data['comp_roof_2_cur'][0] * sStartup.value - bonuspower + data['bonusquote_1'][0] * 1));

    var adv_comp_1 = (tmp_comp[0] + tmp_comp[1] + tmp_comp[2]) / power;
    var adv_comp_2 = (tmp_comp[3] + tmp_comp[4] + tmp_comp[5]) / power;

    adv_comp  = ((adv_comp_1 * crate_30) + (adv_comp_2 * crate_100)) / (crate_30 + crate_100);
    advantage = " " + adv_comp + " ";
    advantage = trim(advantage);

    return adv_comp;
}


/*
 * Anschaffungskosten und Haushaltsverbrauch in Abhaengigkeit der Speicherloesungen ermitteln
 */
function setPurchasecosts() {

    if (debug)
        alert("setPurchasecosts()");

    var currentprofile        = sAccumulator.value;
    vPurchasecosts.realValue += load_profile[currentprofile] * 1 - load_profile[lastprofile] * 1;
    lastprofile               = currentprofile;

    setValuesByRealValue(vPurchasecosts);
    displayPurchasecosts();
    getOwnCompensationRate();
}

/*
 * Warnungen ein- bzw. ausblenden
 *
 * @param string value
 * @param string id
 * @param int    limit
 * @param string message
 */
function displayError(value, id, limit, message) {

    if (debug)
        alert("displayError(" + value + ", " + id + ", " + limit + ")");

    var e   = document.getElementById(id);
    var br0 = new RegExp("<br />", "g");
    message = message.replace(br0, " ");

    if (value > limit) {
      /*
       * alert wenn Fehlermeldung noch nicht eingeblendet verhindert Seitenwechsel ohne Warnung
       * Button: naechster Schritt => nach Eingabe eines Wertes > limit
       */
      if (e.style.visibility != "visible") {

          /* keine Popupfehlermeldung Nennleistung/Eigenverbrauch fuer Dach- / Fassadenanlagen */
          //if(id != "errPowerout")
            alert(unescape(message));
      }

      /* nur Popupfehlermeldung bei Nennleistung groesser 30,00 kWp - komplett abgeklemmt im standard.html
      if (id != "errPowerout")*/
        e.style.visibility = "visible";

    } else {
        e.style.visibility = "hidden";
    }
}

/*
 * Validierung Wertebereiche, Festlegung Pflichtfelder
 * Rueckgabewert false verhindert das Abschicken des Formulars
 *
 * @todo   keine Konzeptvorgaben fuer Pflichtfelder oder weiterer Validierung vorhanden
 * @return boolean
 */
function checkValues() {

    if (debug)
        alert("checkValues()");

    var roger          = true;
    /*var powerout       = vPowerout;
    var ework          = vEwork;
    var operatingcosts = vOperatingcosts;
    var increasecosts  = vIncreasecosts;
    var disbursement   = vDisbursement;
    var annualrate     = vAnnualrate;
    var email          = tEmail;*/

    /* ToDo: alternative Wertebereichspruefung vor dem Submit, z.B. gueltige E-Mailadresse abfragen */
    //roger = isEmail(email);

    return roger;
}

// Formularfunktionalitaeten

/*
 * Anschaffungskosten von Maske 1100 auf Maske 1200 uebertragen
 */
function displayPurchasecosts() {

    if (debug)
        alert("displayPurchasecosts()");

    document.getElementById('dis_purchasecosts').value = vPurchasecosts.value;
}

/*
 * bei privater Nutzung des eigenverbrauchten Stroms wird der Wert der Auswahlbox "Firma" auf der Eingabemaske "Persoenliche Daten"
 * auf "nein" gesetzt, bzw. bei gewerblicher Nutzung auf "ja"
 *
 * @param boolean is_private
 */
function setIsCompany(is_private) {

    if (debug)
        alert("setIsCompany(" + is_private + ")");

    if (is_private) {
        sIscompany.selectedIndex = 1;
        document.getElementById('label_oc_commercial').style.display  = "none";
        document.getElementById('label_oc_private').style.display = "";
    } else {
        sIscompany.selectedIndex = 0;
        document.getElementById('label_oc_commercial').style.display  = "";
        document.getElementById('label_oc_private').style.display = "none";
    }
}

/*
 * zusaetzliche Anschaffungskosten fuer Speicherloesung ein-, bzw. ausblenden
 *
 * @param int modus
 */
function setLblAccumulator(modus) {

    if (debug)
        alert("setLblAccumulator(" + modus + ")");

    if(modus == 0) {
        document.getElementById('purechasecosts_accu').style.display  = "none";
        resetAccumulator();

    } else {
        document.getElementById('purechasecosts_accu').style.display  = "";
    }
}

/*
 * Auswahlbox Speicherloesung zuruecksetzen
 *
 */
function resetAccumulator() {

    if (debug)
        alert("resetAccumulator()");


    for(var i = 0; i < sAccumulator.options.length; i++) {

        if(i == 0)
            sAccumulator.options[i].selected = true;
        else
            sAccumulator.options[i].selected = false;
    }
}

/*
 * bei privater Nutzung des eigenverbrauchten Stroms wird die Auswahlbox "Firma" auf der Eingabemaske "Persoenliche Daten"
 * fuer Aenderungen gesperrt
 *
 * @param boolean disable
 */
function disableIsCompany(disable) {

    if (debug)
        alert("disableIsCompany()");

    if (disable) {
        sIscompany.disabled     = true;
        sIscompany.style.cursor = "default";
    } else {
        sIscompany.disabled     = false;
        sIscompany.style.cursor = "pointer";
    }

    setIsCompany(document.getElementById('owncompensation_private').checked);
}

/*
 * bei privater Nutzung des eigenverbrauchten Stroms wird die Mehrwertsteuer automatisch addiert, bei gewerblicher Nutzung subtrahiert
 *
 * @param boolean is_private
 */
function calculateElectricityTax(is_private) {

    if (debug)
        alert("calculateElectricityTax(" + is_private + ")");

    var val = vElectricity.realValue;

    if (is_private) {
        vElectricity.realValue = val * (1 + taxrate);
        vElectricity.limitMax *= (1 + taxrate);
    } else {
        vElectricity.realValue = val / (1 + taxrate);
        vElectricity.limitMax /= (1 + taxrate);
    }

    setValuesByRealValue(vElectricity);
}

/*
 * Hoehe des Kredits ermitteln
 */
function getCredit() {

    if (debug)
	    alert ("getCredit()");

	getEquity();

    var investment = document.getElementById('investment').value * 1;
    var subp       = vSubvention.realValue * vPowerout.realValue;
    var diff       = vPurchasecosts.realValue + investment - vEquity.realValue - subp;

    if (diff > 0) {
        //vCredit.realValue = diff;
        setEquity();
        setValuesByRealValue(vCredit);
    }

    //alert("diff = " + diff + ", investment = " + investment + ", subvention = " + vSubvention.realValue  * vPowerout.realValue + ", Anschaffungskosten = " + vPurchasecosts.realValue + ", Eigenkapital = " + vEquity.realValue);
}

/*
 * Hoehe des Eigenkapitals gleicht die Kreditkondition Auszahlung aus
 */
function getEquity() {

    if (debug)
	    alert ("getEquity()");

	var totalPurchase = vPurchasecosts.realValue + document.getElementById('investment').value * 1;
	var actualFinance = vCredit.realValue * vDisbursement.realValue / 100 + vEquity.realValue + vSubvention.realValue * vPowerout.realValue;

	if (totalPurchase > actualFinance) {
        //vEquity.realValue += vCredit.realValue * (100 - vDisbursement.realValue) / 100;
        vEquity.realValue += totalPurchase - actualFinance;
        setValuesByRealValue(vEquity);

	} else if (totalPurchase < actualFinance) {
	    //vEquity.realValue -= vCredit.realValue * (100 - vDisbursement.realValue) / 100;
	    vEquity.realValue -= actualFinance - totalPurchase;
        setValuesByRealValue(vEquity);
	}
}

/*
 * nach manueller Eingabe der Hoehe des Eigenkapitals den Kredit anpassen
 */
function setEquity() {

    if (debug)
	    alert ("setEquity()");

	var totalPurchase = vPurchasecosts.realValue + document.getElementById('investment').value * 1;
	var actualFinance = vEquity.realValue + vSubvention.realValue * vPowerout.realValue;

	vCredit.realValue = (totalPurchase - actualFinance) * 100 / vDisbursement.realValue;
	setValuesByRealValue(vCredit);
}

/*
 * nummerische Felder validieren und Ausgabewert formatieren
 *
 * @param Input element
 * @param int   decimalplaces
 */
function formatNumber(element) {

	if (debug)
		alert ("formatNumber(" + element.id + ")");

	element.value = formatDigit(element.realValue, element.decimalplaces);
}

/*
 * Zahl formatieren
 *
 * @param string digit
 * @param int    decimalplaces
 */
function formatDigit(digit, decimalplaces) {

	if (debug)
		alert ("formatDigit(" + digit + ", " + decimalplaces + ")");

    var tmp    = " " + digit;
	var svalue = "";
	var fak    = Math.pow(10, decimalplaces);
	tmp        = tmp.replace(decimalpoint, "\.");
    tmp        = trim(tmp);

	// runden auf Nachkommastellen
	tmp = Math.floor(tmp * fak + 0.5) / fak;
	tmp = " " + tmp;
	tmp = tmp.replace(/\./g, decimalpoint);
	tmp = tmp.substr(1);

	if (tmp == "")
	    tmp = "0";

	if (decimalplaces == "0" || decimalplaces == 0) {
	    svalue = tmp;

	} else {

    	var dp = decimalpoint;

    	if (dp == ".")
    	   dp = "\.";

    	var p = new RegExp("^[0-9]{1,}[" + dp + "]{0,1}[0-9]{0," + decimalplaces + "}$");

    	if (!p.test(trim(tmp)))
    	   tmp = "0";

    	if (tmp.indexOf(decimalpoint) == -1)
    	    tmp += decimalpoint;

    	var x = tmp.indexOf(decimalpoint);
    	var s = tmp.substr(0, x);
    	var e = tmp.substr(x);

    	while (e.length < decimalplaces + 1)
    	   e += "0";

    	svalue = s + e.substr(0, decimalplaces + 1);
	}

	if (debug)
	   alert(tmp + " - " + p + " = " + p.test(trim(tmp)) + ", stringvalue = " + svalue);

	return svalue;
}

/* allgemeine Funktionen */

/*
 * Leerzeichen trimmen
 *
 * @param  string value
 * @return string
 */
function trim(value) {

    if (debug)
        alert("trim(" + value + ")");

    return value.replace(/^\s*|\s*$/g, "");
}

/*
 * formatierten Zifferstring in Zahl umwandeln
 *
 * @param  string value
 * @param  int    decimalplaces
 * @return float
 */
function string2number(value, decimalplaces) {

    if (debug)
		alert ("string2number(" + value + ", " + decimalplaces + ")");

	var dp = decimalpoint;
    var tp = thousandpoint;

	if (dp == ".")
	   dp = "\.";

	if (tp == ".")
       tp = "\\.";

    var rp = new RegExp(tp, "g");

    var values = value.split(dp);

    /* Ganzzahl */
    if (values.length == 1)
        return value.replace(rp, "") * 1;

    var faktor = Math.pow(10, decimalplaces);
    var result = Math.round((values[0].replace(rp, "") + "." + values[1].replace(rp, "")) * faktor);

	return result / faktor;

}

/*
 * Zahl in formatierten Zifferstring umwandeln
 *
 * @param  int value
 * @param  int decimalplaces
 * @return float
 */
function number2string(value, decimalplaces) {

    if (debug)
		alert ("number2string(" + value + ", " + decimalplaces + ")");

    //return formatDigit(value, decimalplaces);
	return setThousandpoint(formatDigit(value, decimalplaces));
}

/*
 * unzulaessige Zeichen aus Texteingaben eliminieren
 *
 */
function checkStrings() {

    if (debug)
	   alert("checkStrings()");

    var e_input = document.getElementsByTagName('input');
    var input = "";

      for (var i = 0; i < e_input.length; i++) {
    	  var e = e_input[i];

        if (e.id.substr(0, 3) == "txt"){
           input  += e.value + "\t";
           e.value = e.value.replace(/</g, "");
           e.value = e.value.replace(/>/g, "");
           e.value = e.value.replace(/=/g, "");
           input  += e.value + "\n";
        }
	}

	if (debug)
	   alert(unescape(input));
}

/*
 * uebergebenen String auf Email-Format pruefen
 *
 * @param  Input element
 * @return boolean
 */
function isEmail(element) {

	 if(debug)
	   alert("isEmail(" + element.value + ")");

	 /* Format pruefen */
  	var emailname  = "([a-zA-Z0-9][a-zA-Z0-9_.-]*|\"([^\\\\\x80-\xff\015\012\"]|\\\\[^\x80-\xff])+\")";
    var domainname = "([a-zA-Z0-9][a-zA-Z0-9._-]*\\.)*[a-zA-Z0-9][a-zA-Z0-9._-]*\\.[a-zA-Z]{2,5}";
    var pattern    = "^" + emailname + "\@" + domainname + "$";
    var rex        = new RegExp(pattern);
    var res        = rex.test(element.value);

    if (!res)
    	element.value = "";

    return res;
}

/*
 * Tausenderpunkt setzen
 *
 * @param  int value
 * @return string
 */
function setThousandpoint(value) {

    if (debug)
        alert("setThousandpoint(" + value + ")");

    var dp = decimalpoint;

    if (dp == ".")
       dp = "\.";

    var vals = value.split(dp);
    var end  = vals[0].length - 1;
    var tmp  = new Array();
    var a    = 1;

    for (var i = end; i >= 0 ; i--) {
        tmp.push(vals[0].substr(i, 1));

        if (a % 3 == 0 && i > 0 && vals[0].substr(i, 1) != "-")
            tmp.push(thousandpoint);

        a++;
    }

    var val = "";
    end     = tmp.length - 1;

    for (var j = end; j >= 0; j--)
        val += tmp[j];

    val += dp + vals[1];
    return val;
}

// ajax functions

/*
 * Intialisierung des XMLHttpRequest
 */
function initRequest() {

   if (debug)
        alert("initRequest()");

   if (window.ActiveXObject) {
        try {
           // IE 6 and higher
           xhttp = new ActiveXObject("MSXML2.XMLHTTP");
        } catch (e) {
            try {
                // IE 5
                xhttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
                req = false;
            }
        }
    }
    else if (window.XMLHttpRequest) {
        try {
            // Mozilla, Opera, Safari ...
            xhttp = new XMLHttpRequest();
        } catch (e) {
            req = false;
            alert("execption: " + e);
        }
    }
}

/*
 * Haushaltsverbrauchquote einlesen
 */
function getOwnCompensationRate() {

    if (debug)
        alert("getOwnCompensationRate()");

    if (!req) {
        alert(error);
        return; // exit
    }

    var consumption = document.getElementById('household').realValue;

    try {
        xhttp.open("POST", url, true);
        xhttp.onreadystatechange = getOwnCompensationRate_callback;
        xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhttp.send("tx_ibccalculator_mode=quota&tx_ibccalculator_pi1[consumption]=" + consumption + "&tx_ibccalculator_pi1[powerout]=" + vPowerout.realValue + "&tx_ibccalculator_pi1[ework]=" + vEwork.realValue + "&tx_ibccalculator_pi1[loadprofile]=" + sAccumulator.value);
    } catch (e) {
        alert("execption: " + e);
    }
}

/*
 * AJAX Antwort Haushaltsverbrauchsanteil verarbeiten
 */
function getOwnCompensationRate_callback() {

    if (debug)
        alert("getOwnCompensationRate_callback()");

    if (xhttp.readyState == 4 && xhttp.status == 200){

        var result = trim(xhttp.responseText);

        // Fehler abfangen
        //alert(result);
        dOwncompensationrate.value = number2string(result, 2);
        changeCompensation();
    }
}

/*
 * Berechnung durchfuehren
 */
function submitForm() {

    if (debug)
        alert("submitForm()");

    navi                = false;
    tableOutput.innerHTML = "";
    var params            = "";

    for (var i = 0; i < document.forms['tx_ibccalculator_form'].length; i++) {

        if (document.forms['tx_ibccalculator_form'][i].name) {

            if (document.forms['tx_ibccalculator_form'][i].type == "radio" && document.forms['tx_ibccalculator_form'][i].checked)
                params += document.forms['tx_ibccalculator_form'][i].name + "=" + document.forms['tx_ibccalculator_form'][i].value + "&";
            else if (document.forms['tx_ibccalculator_form'][i].type != "radio")
                params += document.forms['tx_ibccalculator_form'][i].name + "=" + document.forms['tx_ibccalculator_form'][i].value + "&";
        }
    }

    var end = params.lastIndexOf("&");
    params  = params.substring(0, end);

    if (!req) {
        alert(error);
        return; // exit
    }

    try {
        submitButton.style.cursor = 'wait';
        tableInput.style.cursor   = 'wait';
        xhttp.open("POST", url, true);
        xhttp.onreadystatechange = submitForm_callback;
        xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhttp.send(params);
    } catch (e) {
        submitButton.style.cursor = 'pointer';
        tableInput.style.cursor   = 'default';
        navi                    = true;
        alert("execption: " + e);
    }
}

/*
 * AJAX Antwort Berechnungen verarbeiten
 */
function submitForm_callback() {

    if (debug)
        alert("getOwnCompensationRate_callback()");

    if (xhttp.readyState == 4 && xhttp.status == 200){

        var result = trim(xhttp.responseText);

        // Fehler abfangen
        // alert(result);
        navi                      = true;
        input_mask                = false;
        tableOutput.innerHTML     = result;
        tableInput.style.display  = 'none';
        tableOutput.style.display = '';
        tableInput.style.cursor   = 'default';
        submitButton.style.cursor = 'pointer';
        changeLayer("_004");
    } else if (xhttp.readyState == 4 && xhttp.status == 500) {
        //alert("statusText: " + xhttp.statusText + ", status: " + xhttp.status);
        alert(error);
        javascript:location.reload(true);
    }
}

/*
 * Berechnung variieren
 */
function changeCalculation() {

    if (debug)
        alert("changeCalculation()");

    input_mask                    = true;
    dPeriod.disabled              = true;
    dCompensation.disabled        = true;
    dOwncompensation.disabled     = true;
    dOwncompensationrate.disabled = true;
    disableIsCompany(rOwnCompensationYes.checked);

    /* Ziffernzeichenfolgen formatieren */
    dOwncompensationrate.value = number2string(dOwncompensationrate.value, 2);

    var inputs = document.getElementsByTagName("input");

    for (var i = 0; i < inputs.length; i++) {

       if (inputs[i].type == "text" && (inputs[i].className == "tx_ibccalculator_numeric" || inputs[i].id == "compensation" || inputs[i].id == "owncompensation")) {

           setValuesByRealValue(inputs[i]);

           if (debug)
               alert(inputs[i].name + ": value / realValue = " + inputs[i].value + " / " + inputs[i].realValue);
       }
    }

    changeLayer("_001");
    tableOutput.style.display = 'none';
    tableInput.style.display  = '';
    getOwnCompensationRate();
}

// HTML Elemente erweitern

/*
 * <input type=text> mit Zahlen erweitern
 */
function upgradeNumericInput() {

    if (debug)
        alert("upgradeNumericInput()");

    this.realValue     = null;
    this.decimalplaces = null;
    this.limitMax      = null;
    this.limitMin      = null;
}

/*
 * Auswahlboxen mit nummerischen Optionen erweitern
 */
function upgradeSelect() {

    if (debug)
        alert("upgradeNumericInput()");

    this.countoptions  = null;
    this.decimalplaces = null;
    this.startvalue    = null;
    this.starttext     = null;
    this.step          = null;
}

// Eventhandler ausser Navigation
/*
 * Nennleistung
 */
function onblurPowerout(message) {

    if (debug)
        alert("onblurPowerout()");

    setValuesByValue(vPowerout);

    if (sType.value == 1)
        displayError(vPowerout.realValue, 'errPowerout', 500, message);

    changeCompensation();
    getOwnCompensationRate();
    //getCredit();
}

/*
 * Anschaffungskosten
 */
function onblurPurchasecosts() {

    if (debug)
        alert("onblurPurchasecosts()");

    setValuesByValue(vPurchasecosts);
    displayPurchasecosts();
    setEquity();
    //getCredit();
}

/*
 * elektrische Arbeit
 */
function onblurEwork() {

    if (debug)
        alert("onblurEwork()");

    setValuesByValue(vEwork);
    getOwnCompensationRate();
}

/*
 * Inbetriebnahme
 */
function onchangeStartup() {

    if (debug)
        alert("onchangeStartup()");

    changeCompensation();
}

/*
 * Anlagenart
 */
function onchangeType() {

    if (debug)
        alert("onchangeType()");

    changeCompensation();
    setPurchasecosts();
}

/*
 * Berechnung mit Eigenverbrauch
 *
 * @param boolean own
 */
function onclickOwnCompensation(own) {

    if (debug)
        alert("onclickOwnCompensation(" + own + ")");

    ownCompensation(own);
    disableIsCompany(own);

    if (!own) {

        setLblAccumulator(0);
        setPurchasecosts();
    }
}

/*
 * Haushaltsverbrauch
 */
function onblurHousehold() {

    if (debug)
        alert("onblurHousehold()");

    setValuesByValue(vHousehold);
    getOwnCompensationRate();
}

/*
 * Speicherloesung
 *
 * @param int    accumulator
 * @param string message
 */
function onchangeAccumulator(accumulator, message) {

    if (debug)
        alert("onchangeAccumulator(" + accumulator + ", " + message + ")");

    if (accumulator > 0 && document.getElementById('purechasecosts_accu').style.display  == "none")
        alert(unescape(message));

    if (accumulator > 0)
        vPurchasecosts.focus();

    setPurchasecosts();
    setLblAccumulator(accumulator);
    changeCompensation();
    setEquity();
}

/*
 * Nutzung des Eigenverbrauchs privat vs. gewerblich
 *
 * @param boolean usePrivate
 */
function onclickUseOwnCompensation(usePrivate) {

    if (debug)
        alert("onclickUseOwnCompensation(" + usePrivate + ")");

    if (usePrivate)
        document.getElementById('owncompensation_private').checked = true;
    else
        document.getElementById('owncompensation_commercial').checked = true;

    setIsCompany(usePrivate);
    calculateElectricityTax(usePrivate);
    setValuesByValue(vElectricity);
    changeCompensation();
}

/*
 * Strombezugskosten
 */
function onblurElectricity() {

    if (debug)
        alert("onblurElectricity()");

    setValuesByValue(vElectricity);
}

/*
 * Betriebskostenpauschale
 */
function onblurOperatingcosts(message) {

    if (debug)
        alert("onblurOperatingcosts()");

    setValuesByValue(vOperatingcosts);
    displayError(vOperatingcosts.realValue, 'errOperatingcosts', 2, message);
}

/*
 * Teuerung der Betriebskosten
 */
function onblurIncreasecosts() {

    if (debug)
        alert("onblurIncreasecosts()");

    setValuesByValue(vIncreasecosts);
}

/*
 * Eigenkapital
 */
function onblurEquity() {

    if (debug)
        alert("onblurEquity()");

    setValuesByValue(vEquity);
    setEquity();
}

/*
 * Kredit
 */
function onblurCredit() {

    if (debug)
        alert("onblurCredit()");

    setValuesByValue(vCredit);
    getCredit();
}

/*
 * Auszahlung
 */
function onblurDisbursement() {

    if (debug)
        alert("onblurDisbursement()");

    setValuesByValue(vDisbursement);
    getCredit();
    switchAnnualrateLabel();
}

/*
 * Zinssatz
 */
function onblurAnnualrate() {

    if (debug)
        alert("onblurAnnualrate()");

    setValuesByValue(vAnnualrate);
}

/*
 * Solarkonto Habenzinssatz
 */
function onblurPlusrate() {

    if (debug)
        alert("onblurPlusrate()");

    setValuesByValue(vPlusrate);
}

/*
 * Solarkonto Sollzinssatz
 */
function onblurMinusrate() {

    if (debug)
        alert("onblurMinusrate()");

    setValuesByValue(vMinusrate);
}

/*
 * sonstige Finanzierung
 */
function onblurSubvention() {

    if (debug)
        alert("onblurSubvention()");

    setValuesByValue(vSubvention);
    getCredit();
}

/*
 * Abgleich zwischen der eingegebenen formatierten Ziffer und dem dazugehoerigen Zahlenwert
 *
 * @param HTML-Inputelement element
 */
function setValuesByValue(input) {

    if(debug)
    	alert("setValuesByValue(" + input.id + ")");

    input.realValue = string2number(input.value, input.decimalplaces);

    if (input.realValue < input.limitMin) {
        input.realValue = input.limitMin;
    }

    if (input.realValue > input.limitMax) {
        input.realValue = input.limitMax;
    }

    input.value = number2string(input.realValue, input.decimalplaces);
}

/*
 * Abgleich zwischen berechneten Wert und angezeigtem formatierten Zahlenwert
 *
 * @param HTML-Inputelement element
 */
function setValuesByRealValue(input) {

    if(debug)
    	alert("setValuesByRealValue(" + input.id + ")");

    input.value = number2string(input.realValue, input.decimalplaces);
    setValuesByValue(input);
}
