﻿var ascii = new Array(' ','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8','9',',','?','-',"'",'','`');
var morse = new Array('/','.-','-...','-.-.','-..','.','..-.','--.','....','..','.---','-.-','.-..','--','-.','---','.--.','--.-','.-.','...','-','..-','...-','.--','-..-','-.--','--..','-----','.----','..---','...--','....-','.....','-....','--...','---..','----.','.-.-.-','--..--','..--..','-....-','.----.','.----.');

function ascii2morse() {
  var testo = document.getElementById('asciiTA').value.toString().replace(/\s/g,' ').replace(/ +/g,' ');
  var risp = '';
  var thischar,lastchar = '';
  for (var i=0; i<testo.length; i++) {
    thischar = testo.substr(i,1);
    risp += thischar == lastchar ? '' : charA2M(thischar);
    lastchar = thischar;
  }
  risp = risp.toString().replace(/ \/ \/ /g, " / ");
  thischar =  document.getElementById('morseTA');
  thischar.value = risp;
  thischar.focus();
  thischar.select();
}
function charA2M(thechar) {
  thechar=thechar.toUpperCase();
  for(var i=0; i<ascii.length; i++) if(thechar == ascii[i])return (i>26 ? '/ ' : '')+morse[i]+' ';
  return (document.getElementById('unknownMarkBox').checked ? '? ' : '');
}

function morse2ascii() {
  var testo = document.getElementById('morseTA').value.toString().replace(/\//g, " / ").replace(/\s/g, " ").replace(/…/g, ".").replace(/_/g, "-");
  testo += ' ';
  testo = testo.replace(/ +/g, " ");
  var charm = '';
  var thischar,risp = '';
  for (var i=0; i<testo.length; i++) {
    thischar = testo.substr(i,1);
    if (thischar == ' ') {
      risp += charM2A(charm);
      charm = '';
    } else {
      charm += thischar;
    }
  }
  thischar = document.getElementById('asciiTA');
  thischar.value = risp;
  thischar.focus();
  thischar.select();
}
function charM2A(thechar) {
  for(var i=0; i<morse.length; i++) if(thechar == morse[i]) return ascii[i];
  return '';
}

window.onload = function() {
  var x = '&copy; 2005 by <a href="mail'+'to:balestra';
  x += '@mac.com (Marco Balestra)">Marco Balestra<'+'/a>';
  document.getElementById('copyDiv').innerHTML = x;
  document.getElementById('asciiTA').focus();
  document.getElementById('asciiTA').select();
}
