function perRound(num, precision) {
	var precision = 6; //default value if not passed from caller, change if desired
	if (num > 1000000000) precision = 2;
	// remark if passed from caller
	precision = parseInt(precision); // make certain the decimal precision is an integer
	var result1 = num * Math.pow(10, precision);
	var result2 = Math.round(result1);
	var result3 = result2 / Math.pow(10, precision);
	return result3;
}

function netscapeKeyPress(e) {
    if (e.which == 13)
        myCon();
}

function microsoftKeyPress() {
//    if (window.event.keyCode == 13) myCon();
}

if (navigator.appName == 'Netscape') {
    window.captureEvents(Event.KEYPRESS);
    window.onKeyPress = netscapeKeyPress;
}

function setInnerHTML(id, str) {
	if(!document.getElementById) return; // Not Supported
	if(document.getElementById){
		document.getElementById(id).innerHTML = str;
	}
}

function stripBad_temp(string) {
    for (var i=0, output='', valid="eE-0123456789."; i<string.length; i++)
       if (valid.indexOf(string.charAt(i)) != -1)
          output += string.charAt(i)
    return output;
} 


function myCon_temp() {
  var FromVal, ToVal, FromName, ToName, v1;

  v1 = document.MainForm.what.value;
  v1 = stripBad_temp(v1);
  v1 = parseFloat(v1);
  if (isNaN(v1)) v1 = 0;
  document.MainForm.what.value = v1;
  
  FromVal = document.MainForm.from[document.MainForm.from.selectedIndex].value;

  ToVal = document.MainForm.to[document.MainForm.to.selectedIndex].value;
  FromName = document.MainForm.from.options[document.MainForm.from.selectedIndex].text;
  ToName = document.MainForm.to.options[document.MainForm.to.selectedIndex].text;

  var ConvertedTemp = get_fact(v1, FromVal, ToVal);
  if (ConvertedTemp == "Below Absolute Zero"){
    document.MainForm.answer.value = "Your input cannot be below absolute zero.";
  } else {
    document.MainForm.answer.value = v1 + " " + FromName + " = " + ConvertedTemp + " " + ToName;
  };

  for (var i=0; i< arr.length; i++) {
    ToVal = arr[i];
    setInnerHTML('value_'+i,get_fact(v1, FromVal, ToVal));
  };


 
}

function get_fact(ff,from_val,to_val){
 // first convert to kelvin
 if (from_val == 0){
   ff = ff + 273.15;
 } else if (from_val == 1){
   ff = ((ff - 32)/ 1.8) + 273.15;
 } else if (from_val == 2){
   ff = ff / 1.8;
 } else if (from_val == 3){
   ff = (ff * 1.25) + 273.15;
 }

 if (ff < 0){
   // Below absolute zero
   return "Below Absolute Zero";
 }

 // now convert kelvin to unit
 if (to_val == 0){
   ff = ff - 273.15;
 } else if (to_val == 1){
   ff = (1.8 * (ff -273.15)) + 32;
 } else if (to_val == 2){
   ff = ff * 1.8;
 } else if (to_val == 3){
   ff = (ff - 273.15) / 1.25;
 }
 
 // round it off
 if (Number.prototype.toFixed) {
   ff = ff.toFixed(7);
   ff = parseFloat(ff);
 }
 else {
   var leftSide = Math.floor(ff);
   var rightSide = ff - leftSide;
   ff = leftSide + Math.round(rightSide *10000000)/10000000;
 }

return ff;
}

function myXOR(a,b) {
  return ( a || b ) && !( a && b );
}


function myCon() {
  var FromVal, ToVal, FromName, ToName, v1, Factor;

  v1 = document.MainForm.what.value;
  v1 = stripBad(v1);
  document.MainForm.what.value = v1;
  
  eval('v1 = parseFloat(' + v1 + ');');
  if (isNaN(v1)) {
	  v1 = 1;
	  document.MainForm.what.value = v1;
  }
  //v1 = Math.abs(v1);
  
  FromVal = document.MainForm.from[document.MainForm.from.selectedIndex].value;
  ToVal = document.MainForm.to[document.MainForm.to.selectedIndex].value;
  FromName = document.MainForm.from.options[document.MainForm.from.selectedIndex].text;
  ToName = document.MainForm.to.options[document.MainForm.to.selectedIndex].text;

	if ((FromVal == "") || (ToVal == "")){
		document.MainForm.answer.value = "";
		return;
	}

 
  if  ( (arr_b[document.MainForm.to.selectedIndex] == 1) ){
    Factor = eval("(" + ToVal + ")/(" + FromVal + ")");
  } else {
    Factor = eval("(" + FromVal + ")/(" + ToVal + ")");
  };

  if ( myXOR(arr_b[document.MainForm.from.selectedIndex],arr_b[document.MainForm.to.selectedIndex]) ){  
    document.MainForm.answer.value = space(v1) + " " + FromName + " = " + space(get_result(v1, Factor,1)) + " " + ToName;
  } else {
    document.MainForm.answer.value = space(v1) + " " + FromName + " = " + space(get_result(v1, Factor,0)) + " " + ToName;
  };

  for (var i=0; i< arr.length; i++) {
    Factor = 0;
    ToVal = arr[i];

    if ((FromVal == "") || (ToVal == "")){
	return;
    };

    if  ((arr_b2[i] == 1) ) {
      Factor = eval("(" + ToVal + ")/(" + FromVal + ")");
    } else {
      Factor = eval("(" + FromVal + ")/(" + ToVal + ")");
    };

    if  ( myXOR(arr_b2[i],arr_b[document.MainForm.from.selectedIndex]) ) {
      setInnerHTML('value_'+i,space(get_result(v1, Factor,1)));
    } else {
      setInnerHTML('value_'+i,space(get_result(v1, Factor,0)));
    };




  };

}

function myCon_volume() {
  var FromVal, ToVal, FromName, ToName, v1, Factor;

  v1 = document.MainForm.what.value;
  v1 = stripBad(v1);
  document.MainForm.what.value = v1;
  
  eval('v1 = parseFloat(' + v1 + ');');
  if (isNaN(v1)) {
	  v1 = 1;
	  document.MainForm.what.value = v1;
  }
  //v1 = Math.abs(v1);
  
  FromVal = document.MainForm.from[document.MainForm.from.selectedIndex].value;
  ToVal = document.MainForm.to[document.MainForm.to.selectedIndex].value;
  FromName = document.MainForm.from.options[document.MainForm.from.selectedIndex].text;
  ToName = document.MainForm.to.options[document.MainForm.to.selectedIndex].text;

  if ((FromVal == "") || (ToVal == "")){
    document.MainForm.answer.value = "";
    return;
  }


  Factor = eval("(" + FromVal + ")/(" + ToVal + ")"); 
  if ( myXOR(arr_b[document.MainForm.from.selectedIndex],arr_b[document.MainForm.to.selectedIndex]) ){  
    if  ( (arr_b[document.MainForm.from.selectedIndex] == 1) ){
      Factor *= document.MainForm.density[document.MainForm.density.selectedIndex].value;
    } else {
      Factor /= document.MainForm.density[document.MainForm.density.selectedIndex].value;
    };
  };

  document.MainForm.answer.value = space(v1) + " " + FromName + " = " + space(get_result(v1, Factor,0)) + " " + ToName;

  for (var i=0; i< arr.length; i++) {
    Factor = 0;
    ToVal = arr[i];

    if ((FromVal == "") || (ToVal == "")){
	return;
    };

    Factor = eval("(" + FromVal + ")/(" + ToVal + ")");

    if  ( myXOR(arr_b2[i],arr_b[document.MainForm.from.selectedIndex]) ) {
      if  ((arr_b2[i] == 1) ) {
        Factor /= document.MainForm.density[document.MainForm.density.selectedIndex].value;
      } else {
        Factor *= document.MainForm.density[document.MainForm.density.selectedIndex].value;
      };
    };
    setInnerHTML('value_'+i,space(get_result(v1, Factor,0)));
  };

}



function resetanswer() {
  document.MainForm.answer.value = "";
}

function get_result(ff,factor,operation){

 if (operation == 1){
   ff = factor/ff;
 } else {
   ff *= factor;
 };           


 var s = ff.toString(), first, last = '';
 var i = s.indexOf('e');
 if (i != -1)
 {
	 first = perRound(s.substring(0, i));
	 last = parseInt(s.substring(i + 1));
	 while (first >= 10)
	 {
		 first /= 10;
		 last++;
	 }
	 if (last > 0)
		 last = '+' + last;
	 last = 'e' + last;
	 if (first.toString().indexOf('.') == -1)
		first += '.0';
 }
 else
	 first = perRound(s);

 return first + last;
}


function stripBad(string) {
	// If a space is next to two numbers, change to a + sign, for fractions
	while (string.match(/(\d) (\d)/)){
		string = string.replace(/(\d) (\d)/, "$1\+$2");
	}

    for (var i=0, output='', valid="eE+/*-0123456789.()"; i<string.length; i++)
       if (valid.indexOf(string.charAt(i)) != -1)
          output += string.charAt(i)
    return output;
} 

function space (num)
{
	num = num + '';
	// exit if scientific notation
	if (num.indexOf('e') > -1){ return num; }

	var dec = num.indexOf('.');

	var left, right = '';
	if (dec >= 0)
	{
		left = num.substring(0, dec);
		right = num.substring(dec + 1);
	}
	else
		left = num;

	var new_left = '', new_right = '';
	for (var i = 0; i < right.length; i++)
	{
		new_right += right.charAt(i);
		if (i % 3 == 2 && i != right.length - 1)
			new_right += ' ';
	}
	for (var i = left.length - 1; i >= 0; i--)
	{
		new_left = left.charAt(i) + new_left;
		if ((left.length - 1 - i) % 3 == 2 && i != 0)
			new_left = ' ' + new_left;
	}

	return (dec >= 0) ? new_left + '.' + new_right : new_left;
}


function helpQty(){
	var myMessage = '';
	myMessage = "- Conversion Help -\n\n";
	myMessage += "This is the amount of the 'From' unit you want to convert to the 'To' unit.\n\n";
	myMessage += "You can enter a basic quantity value, such as\n10\n100\n1267.9874\n\n";
	myMessage += "To enter fractions, seperate fractions from whole numbers with a + sign.\n7/8\n2+3/4\n1+1/2\n\n";
	myMessage += "Or you may enter formulas, such as\n100+37+99\n33 * 56 + (100-23) * 17\n93*56-13*4\n\n";
	myMessage += "To enter numbers in scientific notation, be sure to use the 'e' style of notation. For example\n";
	myMessage += "1.0e-15\n9.3478e+23\n1.0e+18";

	alert(myMessage);
	return;
}

function helpResult(){
	var myMessage = '';
	myMessage = "- Conversion Help -\n\n";
	myMessage += "This is the result of your conversion, suitable for copy and paste as needed. ";
	myMessage += "Select the text you wish to copy and press Ctrl-C to copy then press Ctrl-V to paste it into the application of your choice.";
	myMessage += "\n\nThe format used follows the international standard called the SI standard. ";
	myMessage += "Digits are separated by spaces in groups of three, this makes them easier to read. ";
	myMessage += "Some countries use the comma as a separator which may be confused with the period so the SI standard is preferred.";
	myMessage += "\n\nScientific notation is displayed in the 'e' format, such as 1.0e-18 or 1.0e+24";

	alert(myMessage);
	return;
}