/*
 * File controler.js
 * Copyright 2003 Wolfgang Kuehn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *       http://www.apache.org/licenses/LICENSE-2.0 
 */

// The field representing the temperature.
var T;
// The field representing the dew point temperature.
var DPT;
// The field representing the accuracy of the dew point temperature.
var deltaDPT;

/*
 * Called once when the page is loaded.
 * Initializes all input fields and computes the output fields.
 */
function init() {
  var form = document.FORM;
  
  this.T = new Temperature(20, CELSIUS, form.T);
  this.DPT = new Temperature(0, CELSIUS, form.DPT);
  this.deltaDPT = new TemperatureChange(20, CELSIUS, form.deltaDPT);
  
  document.FORM.TScale[1].checked=true;
  document.FORM.RH.value = 50;
  document.FORM.DELTARH.value = 3;

  compute();
}

/*
 * From the input temperatue and relative humidity, computes dew 
 * point temperature and Saturation Vapor Pressure.
 */
function compute () {
  var t = T.getKelvin();
  
  // Check temperature in range.
  if (t<minT || t>maxT) {
    alert("Ambient temperature out of range [" + minT + ".." + maxT +"] Deg.Kelvin.");
    return;
  }
  
  // Check 
  var RH = stringToFloat(document.FORM.RH.value);
  if (isNaN(RH) || RH<=0 || RH>100) {
    alert("Relative humidity out of range (0..100].");
    return;
  }
  
  // Check relative humidity in range.
  var deltaRH = stringToFloat(document.FORM.DELTARH.value);
  if (deltaRH<0 || deltaRH>100) {
    alert("Accuracy of relative humidity out of range [0..100].");
    return;
  }

  // Compute dew point temperature.
  var Tdp;
  try {
    Tdp = dewPoint(RH,t);
  } catch (e) {
    alert("Dewpoint below valid range.");
    return;
  }

  // Compute dew point temperature accuracy.
  var deltaTdp = Math.abs(Tdp-dewPoint(RH+deltaRH,t));
  
  // Display temperature.
  DPT.setKelvin(Tdp);
  // Display accuracy.
  deltaDPT.setKelvin(deltaTdp);
  // Display saturation vapor pressure
  document.FORM.PVS.value = truncate(PVS(t)/1000, 5, RELATIVE);
}