var server = "http://" + window.location.host;
var imgplus = server + "/img/toggle_plus.gif";
var imgminus = server + "/img/toggle_minus.gif";
var imgminus_dis = server + "/img/toggle_minus_dis.gif";
var titleplus = "Eingabefelder einblenden";
var titleminus = "Eingabefelder ausblenden";
var titleminus_dis = "";
var defaultWatchClass = "watchme";
var openInfoLayer = "";

// Automatically attach a listener to the window onload, 
// to show several elements only if JS is available
addEventS(window,"load",getToggleDivs);
addEventS(window,"load",disableCalculatedInputs);
addEventS(window,"load",disableCompression);

// Utility function to add an event listener
function addEventS(o,e,f){
  if (o.addEventListener){ o.addEventListener(e,f,false); return true; }
  else if (o.attachEvent){ return o.attachEvent("on"+e,f); }
  else { return false; }
}

// Utility function to remove an event listener
function removeEventS(o,e,f) {
  if (o.removeEventListener){ o.removeEventListener(e,f,false); return true; }
  else if (o.detachEvent){ o.detachEvent("on"+e,f); return true; }
  else { return false; }
} 

/* set classname of object O to toggle (mainly for IE's pseudohover) */
function toggleClass ( O, toggle, statusline ) {
  if ( O ) {
    O.className = toggle;
  }
  if (statusline) {
    window.status = statusline;
  }
}

// Removes the default value from an input field
function removeDefault( O, text ) {
  if ( O.value == text || O.value == roundx(text, 2))
    O.value = "";
  else if ( parseFloat(O.value) == parseFloat(text) )
    O.value = "";
  else if ( O.value == 0 ) // for konquerer+safari
    O.value = "";
}

// Sets the default value of an input field
function setDefault( O, text ) {
  if ( O != null && O.value == "" ) {
    // assume integer
    if ( text.indexOf('.') < 0 ) {
      O.value = text;
    } 
    // assume float
    else {
      O.value = roundx(text, 2);
    }
  }
}

// Sets the value of an input field 
function setInputValue(id, value, type) {
  var type = (type == null) ? "float" : type;
  
  El = document.getElementById(id);
  if ( El && !(value == (undefined || null)))
  {
    // First set the focus (race condition with removeDefault) 
    El.focus();
    if (type == "float")
    {
      El.value = roundx(value, 2);
    }
    else
    {
      El.value = Math.round(value);
    }
  }
  return false;
}

// Round a number to n digits 
function roundx(value, n) {
  if (n < 1 || n > 14) 
  {
    return false;
  }
  var e = Math.pow(10, n);
  var k = (Math.round(value * e) / e).toString();
  if (k.indexOf('.') == -1) 
  {
    k += '.';
  }
  k += e.toString().substring(1);
  return k.substring(0, k.indexOf('.') + n+1);
}

// Replace comma through points (required for pike calculation) 
function commaReplacer(input) {
  var temp = input.value;
  if(temp.indexOf(",")>=0) {
    // In case of commas and points, assume that the point is a thounsands delimiter and remove it/them.
    if(temp.indexOf(".")>=0) {
      temp = temp.replace(".","");
    }
    temp = temp.replace(",",".");
    if (!isNaN(temp)) {
      input.value = temp;
    }
  }
}

// Test if the pressure at the feed-in-point is higher than the threshold. 
// If so, enable the input fields for compression. If not, disable them. 
function checkPressure(O, threshold) {
  // Don't update if Object does not exist or view mode is enabled (O is disabled) 
  if ( O != null && O.disabled == 0 ) {
    if (parseFloat(O.value) >= parseFloat(threshold)) {
      // enable inputs
      $('calculated-value-investment-costs-compression').disabled = 0;
      $('calculated-value-operating-costs-compression').disabled = 0;
      if ($('calculated-value-investment-costs-compression').checked == 0) {
        $('investment-costs-compression').disabled = 0;
      }
      else {
        $('investment-costs-compression').value = $('default-investment-costs-compression-value').innerHTML;
      }
      if ($('calculated-value-operating-costs-compression').checked == 0) {
        $('operating-costs-compression').disabled = 0;
      }
      else {
        $('operating-costs-compression').value = $('default-operating-costs-compression-value').innerHTML;
      }
    }
    else {
      // disable inputs
      $('calculated-value-investment-costs-compression').disabled = 1;
      $('calculated-value-operating-costs-compression').disabled = 1;
      $('investment-costs-compression').disabled = 1;
      $('operating-costs-compression').disabled = 1;
      if ($('calculated-value-investment-costs-compression').checked == 0) {
        $('investment-costs-compression').value = "0.00";
      }
      if ($('calculated-value-operating-costs-compression').checked == 0) {
        $('operating-costs-compression').value = "0.00";
      }
    }
  }
}

// Update the investment and operating costs (if necessary)
function updatePreparation() {
  // get elements respectively their values 
  var modellType = parseInt($('modell-type').value);
  var withLiquidgas = $('with-fluessiggas').checked;
  var capacity = $('site_capacity').value;
  var ref_iC = $('investment-costs-aufbereitung');
  var ref_oC = $('operating-costs-aufbereitung');

  var fIK1 = 1; 
  var fIK2 = 1; 
  var fOK1 = 1; 
  var fOK2 = 1; 

  
  if (withLiquidgas) modellType++;
  
  switch(modellType) {
    case 1: 
      fIK1 = 51947; 
      fIK2 = -0.5268; 
      fOK1 = 1.4539; 
      fOK2 = -0.5005; 
      break;
    case 2: 
      fIK1 = 51947; 
      fIK2 = -0.5268; 
      fOK1 = 1.2948; 
      fOK2 = -0.4541; 
      break;
    case 3: 
      fIK1 = 96542; 
      fIK2 = -0.662; 
      fOK1 = 1.6987; 
      fOK2 = -0.5274; 
      break;
    case 4: 
      fIK1 = 96542; 
      fIK2 = -0.662; 
      fOK1 = 1.6076; 
      fOK2 = -0.4912; 
      break;
  }
  
  var newIC = fIK1 * Math.pow(capacity, fIK2) * capacity; 
  var newOC = fOK1 * Math.pow(capacity, fOK2) * capacity * 8000; 
  
  if (newIC > 0) 
  {
    $('default-investment-costs-aufbereitung-value').innerHTML = roundx(newIC, 2);
    if($('calculated-value-investment-costs-aufbereitung').checked) 
    {
      ref_iC.value = roundx(newIC, 2); 
    }
  }
  if (newOC > 0) 
  {
    $('default-operating-costs-aufbereitung-value').innerHTML = roundx(newOC, 2);
    if($('calculated-value-operating-costs-aufbereitung').checked) 
    {
      ref_oC.value = roundx(newOC, 2); 
    }
  }
}
// Update the investment and operating costs (if necessary)
function updateBHKW() {
  // get elements respectively their values 
  var eff_th = parseFloat($('efficiency-th-bhkw').value);
  var eff_el = parseFloat($('efficiency-el').value);
  var required_heat = parseFloat($('required_heat').value);
  var required_power = 0; 
  var pBHKW = parseFloat($('power-bhkw').value);

  // sanity checks 
  if(isNaN(eff_th) || isNaN(eff_el) || isNaN(required_heat) || isNaN(pBHKW)) {
    return;
  }
  if (eff_th > 100) {
    eff_th = 100.00; 
    $('efficiency-th-bhkw').value = eff_th;
  }
  if (eff_el > 100) {
    eff_el = 100.00; 
    $('efficiency-el').value = eff_el;
  }

  if (eff_th > 0)
    required_power += required_heat / 8760 / (eff_th / 100);
  if (eff_el > 0)
    required_power += (required_heat / 0.6) * (eff_el / 100) / 8600;
  
  if (required_power > 0) {
    $('default-power-bhkw-value').innerHTML = roundx(required_power, 2);
  } else {
    $('default-power-bhkw-value').innerHTML = "-";
  }
  
  // re-calculate costs 
  var ic_bhkw = 4639 * Math.pow(pBHKW, -0.333) * pBHKW;
  var oc_bhkw = 4.9406 * Math.pow(pBHKW, -0.221) * pBHKW
  
  // update investment costs 
  $('default-investment-costs-bhkw-value').innerHTML = roundx(ic_bhkw, 2);
  if($('calculated-value-investment-costs-bhkw').checked) {
    $('investment-costs-bhkw').value = roundx(ic_bhkw, 2);
  }
  
  // update operating costs 
  $('default-operating-costs-bhkw-value').innerHTML = roundx(oc_bhkw, 2);
  if($('calculated-value-operating-costs-bhkw').checked) {
    $('operating-costs-bhkw').value = roundx(oc_bhkw, 2);
  }
}

// Update the calculated value for the pipeline costs (if necessary) 
function updatePipelineCosts() {
  var soil_type = $('soil-type').value;
  var distance = parseFloat($('distance-feedin-point').value);
  var pressure = parseFloat($('pressure').value);
  var pipeline_costs = 0; 
  
  if(soil_type==1) {
    if(distance<=500) {
      if(pressure<=6) {
        pipeline_costs = 55;
      } else {
        if(pressure<=10) {
          pipeline_costs = 198;
        } else {
          pipeline_costs = 200;
        }
      }
    } else {
      if(distance<=1000) {
        if(pressure<=6) {
          pipeline_costs = 45;
        } else {
          if(pressure<=10) {
            pipeline_costs = 156;
          } else {
            pipeline_costs = 160;
          }
        }
      } else {
        if(pressure<=6) {
          pipeline_costs = 42;
        } else {
          if(pressure<=10) {
            pipeline_costs = 150;
          } else {
            pipeline_costs = 155;
          }
        }
      }
    }
  }
  else
  {
    if(distance<=500) {
      if(pressure<=6) {
        pipeline_costs = 100;
      } else {
        if(pressure<=10) {
          pipeline_costs = 232;
        } else {
          pipeline_costs = 234;
        }
      }
    } else {
      if(distance<=1000) {
        if(pressure<=6) {
          pipeline_costs = 80;
        } else {
          if(pressure<=10) {
            pipeline_costs = 190;
          } else {
            pipeline_costs = 194;
          }
        }
      } else {
        if(pressure<=6) {
          pipeline_costs = 75;
        } else {
          if(pressure<=10) {
            pipeline_costs = 184;
          } else {
            pipeline_costs = 189;
          }
        }
      }
    }
  }
  
  $('default-pipeline-costs-value').innerHTML = roundx(pipeline_costs, 2);
  if($('calculated-value-pipeline-costs').checked) {
    $('pipeline-costs').value = roundx(pipeline_costs, 2);
  }
}

// Update the default value of the feed-in-volume in step 3 
// aufbereitung (e.g. when the gas-loss is changed) 
function updateFeedInVolume(input, gas_available, methane_concentration) {
  var temp = parseFloat(input.value);
  if (temp > 100 || temp < 0) {
    input.value = "";
    return false;
  }
  var target = $('default-feedin-volume-h-value');
  var target2 = $('feedin-volume-h');
  var result = roundx(gas_available * methane_concentration / 100 * (1-temp/100) / 8760, 2);
  
  target.innerHTML = result;
  if ($('calc-value-feedin-volume-h').checked) {
    target2.value = result;
  }
}

// Toggle input field disabled, depending on the according checkbox value 
function toggleInputField (checkbox, input) {
  var O = $(input);
  
  // dis-/enable the input field 
  O.disabled = checkbox.checked; 
  
  // if we disabled the input field, also set the value 
  if (checkbox.checked) {
    var D = $('default-'+input+'-value');
    O.value = D.innerHTML;
  }
}

// Disables input fields if the according checkbox is ticked 
function disableCalculatedInputs() {
  var nodes = $A(document.getElementsByClassName('checkbox'));
  nodes.each(function(node){
    if (node.id.substring(0, 11)=="calc-value-" && node.value==1) {
      toggleInputField(node, node.id.substring(11));
    }
  });
}

// Disables input fields if the according checkbox is ticked 
function disableCompression() {
  var pressureObj = $('pressure');
  var pressure_thresholdObj = $('pressure_threshold');
  
  if (pressureObj && pressure_thresholdObj)
    checkPressure(pressureObj, pressure_thresholdObj.value);
}

// Add a toggle button to every div.toggle
function getToggleDivs() {
  var button = '<a href="#" onclick="toggleDiv(this.parentNode); return false;" title="' + titleminus_dis + '" class="togglebutton"><img src="' + imgminus_dis + '" alt="' + titleminus_dis + '" /></a>';
  var nodes = $A(document.getElementsByClassName('toggle'));
  nodes.each(function(node){
    legend = node.getElementsByTagName("legend")[0];
    new Insertion.After(legend, button);
    toggleDiv(node);
  });
}

// Performs the toggling, but watches if input field values of a 
// given class (default: watchMe) are greater than 0
function toggleDiv(El, watchClass) {
  var watchClass = (watchClass == null) ? defaultWatchClass : watchClass;
  var watchedPositive = false;
  var Img;
  var nodes = $A(document.getElementsByClassName(watchClass,El));
  var toggleNodes;
  
  nodes.each(function(node){
    if(!isNaN($F(node)) && $F(node)>0) {
      watchedPositive = true;
      Anc = El.getElementsByTagName("a")[0];
      Img = Anc.getElementsByTagName("img")[0];
      Img.setAttribute("src",imgminus_dis);
      Anc.title=titleminus_dis;
      Img.alt=titleminus_dis;
    }
  });
  
  if(watchedPositive == false) {
    toggleDivHelper(El);
    toggleImg(El.getElementsByTagName("a")[0]);
  }
}

// Performs the actual toggling
function toggleDivHelper(El) {
  toggleNodes = $A(El.getElementsByTagName("div"));
  toggleNodes.each(function(node){
    Element.toggle(node);
  });
}

// Toggle [+] and [-] images
function toggleImg(Anc) {
  Img = Anc.getElementsByTagName("img")[0];
    
  if(Img.src==imgplus) {
    Img.setAttribute("src",imgminus);
    Anc.title=titleminus;
    Img.alt=titleminus;
  } else {
    Img.setAttribute("src",imgplus);
    Anc.title=titleplus;
    Img.alt=titleplus;
  }
}

// Toggle fieldset->fieldset on radio-select
function showSelect(elId,len) {
  var nodes = $A(document.getElementsByTagName("fieldset"));
  nodes.each(function(node){
    if(node.id=="tog"+elId) {
      Element.show(node);
    } else if (node.id.search("tog")==0) {
      Element.hide(node);
    }
  });
}

function showInfo(El) {
	Element.addClassName(El, "showinfo");
}

function hideInfo(El) {
  Element.removeClassName(El, "showinfo");
}

function showOrgValueInfo(El) {
  if ( openInfoLayer ) {
    closeInfoLayer(openInfoLayer);
  }
  Element.addClassName(El, "orgval-info-show");
  openInfoLayer = El;
}

function hideOrgValueInfo(El) {
  Element.removeClassName(El, "orgval-info-show");
}

function showHelp(El,e,button) {
  if ( openInfoLayer ) {
    closeInfoLayer(openInfoLayer);
  }
  var cX = 0; var cY = 0;
  
  var elX = 0; var elY = 0;
  var posEl = Position.cumulativeOffset($(button));
  elX = posEl[0];
  elY = posEl[1]-150;

  $(El).style.top = (elY) + "px";
  Element.addClassName(El, "help-info-show");

  openInfoLayer = El;
  
  var anchor = $(El).getElementsByTagName("a")[0];
  anchor.focus();
  
  return false;
}

function hideHelp(El, ElInput) {
  Element.removeClassName(El, "help-info-show");
  $(ElInput).focus();
  return false;
}

function closeInfoLayer (El) {
  Element.removeClassName(El, "help-info-show");
  Element.removeClassName(El, "orgval-info-show");
  openInfoLayer = "";
}

function showHelpKontext(El) {
  Element.addClassName(El, "eingabeactive");
}

function hideHelpKontext(El) {
  Element.removeClassName(El, "eingabeactive");
}


function mouseX(evt) {
  if (evt.pageX) {
    return evt.pageX;
  }
  else {
    if (evt.clientX) {
      return evt.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
    }
    else {
      return null;
    }
  }
}

function mouseY(evt) {
  if (evt.pageY) {
    return evt.pageY;
  }
  else {
    if (evt.clientY) {
      return evt.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
    }
    else {
      return null;
    }
  }
}
