var FIELDS = [
  ["Name", "name" ],
  ["Rank", "rank" ],
  ["Grade", "grade"],
  ["Job title", "job_title"],
  ["Social Security Account Number (SSAN)", "ssan"],
  ["Personnel Identifier (PID)", "pid", "*"],
  ["Employee Number", "empnum", "*"],
  ["Military occupational Specialty (MOS)", "mos"],
  ["Unit/Activity assigned to", "activity"]
];

var REQUIRED_FIELDS_EMPTY = "You should fill at least required fields";


function makeField (doc, name, title, required, type) 
{
  var text_fld;
  var tr = doc.createElement("tr");
  var td = tr.appendChild (doc.createElement ("td"));
  td.appendChild (doc.createTextNode(title));
  td.className = required ?  "title_required" : "title";
  
  td_input = doc.createElement ("td");
  td_input.className = "input";

  td = tr.appendChild (td_input);
  
  text_fld = doc.createElement ("input");
  text_fld.type = "text";
  text_fld.name = name;
  
  var input = td.appendChild (text_fld);
  input.style.width = "200";
  return tr;
}


function makeButton (doc, title, handler)
{
  var button = doc.createElement ("button");
  button.innerHTML = title;
  button.onclick = handler;
  return button;
}


function validResults (results)
{
  var pid = results['pid'];
  var empnum = results['empnum'];
  if (!pid || !empnum) {
    alert (REQUIRED_FIELDS_EMPTY);
    return false;
  }
  return true;
}


function closeOk()
{
  var results = new Object();
  var form = document.getElementById ("trainee_identification");

  var elms = form.elements;
  if (!elms || elms.length <= 0)
    alert (REQUIRED_FIELDS_EMPTY);
  
  for (var i=0; i < elms.length; ++i) {
    var input = elms.item(i);
    if (input.type == 'text' && input.value)
      results[input.name] = input.value;
  }     

  if (validResults (results)) {
    window.returnValue = results;
    window.close();
  }
}

function closeCancel()
{
  window.close();
}

function makeForm (doc)
{
  var form  = doc.createElement ("form");
  form.id = "trainee_identification";
  var table = form.appendChild (doc.createElement("table"));
  var tbody = table.appendChild(doc.createElement("tbody"));
  for (var i = 0; i < FIELDS.length; ++i) {
    var fld = FIELDS[i];
    tbody.appendChild (makeField (doc, fld[1], fld[0], fld[2] == '*', fld[3]));
  }
   
  var hr = form.appendChild(doc.createElement ("hr"));
  hr.style.height="4pt";
  var center = form.appendChild (doc.createElement ("center"));
  center.appendChild(makeButton (doc, "Create Report", closeOk));
  var span = center.appendChild(doc.createElement ("span"));
  span.style.width = "12pt";
  center.appendChild(makeButton (doc, "Cancel", closeCancel));

  doc.body.appendChild (form);
  form.elements[0].focus();
}