var debug = false;

// react on users' input via keyboard
function validateInput(e) {
   var cc;
   if (document.all) 
      cc=e.keyCode;  // IE ...
   else {
      // NS 	
      cc=e.which;
      if (e.keyCode) 
         return true;  // spezial key's: like DEL,Left-Arrow... in NS 6.*
   }
   if ((cc<45) || (cc==47) || (cc>57)) 
      return false;
   return true;
}

// validate users' input
function Validate(Value, Code) {
   if (isNaN(Value)) 
      return '';	
   if ((Value!='') && (Code!='')) 
      return eval(Value+'*'+Code);
   else 
      return '';
}

// calculation method
function Calculate(destField,sourceField,destCode,sourceCode) {
   var baseValue;
   if (sourceField.value!='') {
      baseValue=Validate(sourceField.value,sourceCode);
      destField.value=Validate(baseValue,destCode);
   } 
   else {
      destField.value='';
   }
}

// deletes all options of a drop-down field
function deleteOptions(dropDown) { 
   if(debug) alert("deleteOptions");
   while (dropDown.options.length>0) {
      deleteIndex = dropDown.options.length-1;
      dropDown.options[deleteIndex] = null;
   }
}  

// build up the drop-down fields for selecting the units
function buildUnits(dropDown, calc, calcDisplay, sourceORresult) {
   if(debug) alert("buildUnits");
   for (var j=1;j<=calc[calcDisplay][0][2];j++) {
      var newOption = new Option();
      newOption.text = calc[calcDisplay][j][0];
   
      if(sourceORresult == "source")
         newOption.value = calc[calcDisplay][j][1];
      else
         newOption.value = calc[calcDisplay][j][2];

      dropDown.options[dropDown.options.length] = newOption;	
   }
}  

// build up the drop-down fields for selecting the measurands
function buildMeasurands(dropDown, calc) {
   if(debug) alert("buildMeasurands");

   for (var j=0;j<=calc.length-1;j++) {
      var newOption = new Option();

      newOption.text = calc[j][0][0];
      newOption.value = j;

      dropDown.options[dropDown.options.length] = newOption;	
   }
   dropDown.options[0].selected = true;
}

// re-build the unit drop-down field when changing the measurand
function changeMeasurand(selectBox, calc) {
   if(debug) alert("changeMeasurand");
   var calcDisplay = selectBox.value;
  
   deleteOptions(document.selectUnitForm._sourceval);
   buildUnits(document.selectUnitForm._sourceval, calc, calcDisplay, "source");

   deleteOptions(document.selectUnitForm._destval);
   buildUnits(document.selectUnitForm._destval, calc, calcDisplay, "result");
  
   document.selectUnitForm._source.value = "";
   document.selectUnitForm._dest.value = "";
}

// reset the page when opening or reloading
function resetPage() {
  if(debug) alert("resetPage");
  document.selectMeasurandForm.reset();
  document.selectUnitForm.reset();
}	
