/* base class extensions */
String.prototype.trim = function() {
  return this.replace(/^\s+/, '').replace(/\s+$/, '');
}
Array.prototype.indexOf = function(elem) {
  for (var i=0; i<this.length; i++) {
    if (this[i] == elem) return i;
  }
  return -1;
}

/* dom helpers */
function hasClass(elem, name) {
  var arr = elem.className.split(' ');
  if (arr.indexOf(name) != -1) {
    return true;
  }
  return false;
}
function addClass(elem, name) {
  var arr = elem.className.split(' ');
  if (arr.indexOf(name) == -1) {
    arr.push(name);
    elem.className = arr.join(" ");
  }
}

function removeClass(elem, name) {
  var arr = elem.className.split(' ');
  var arr2 = [];
  for (var i=0; i<arr.length; i++) {
    if (arr[i] != name) {
      arr2.push(arr[i]);
    }
  }
  elem.className = arr2.join(" ");
}

/* we want to touch the className only once
 yeah, it's not dry :p*/
function replaceClass(elem, old_class, new_class) {
  var arr = elem.className.split(' ');
  var arr2 = [];
  for (var i=0; i<arr.length; i++) {
    if (arr[i] != old_class) {
      arr2.push(arr[i]);
    }
  }
  arr2.push(new_class);
  elem.className = arr2.join(" ");
}

/* cookie helpers */
function setCookie(name, value, permanent) {
  var expires = '';
  var string = '';
  if (permanent) {
    expires = '; expires=' + (new Date()).toGMTString().replace(/20\d\d/, 2020);
  }
  string = name+"="+value+expires+"; path=/";
  document.cookie = string;
}

function getCookie(name) {
  var i, crumbs, crumb;
  crumbs = document.cookie.split(';');
  for (var i=0; i<crumbs.length; i++) {
    crumb = crumbs[i].trim();
    if (crumb.indexOf(name + "=") == 0) {
      return crumb.substring((name + "=").length);
    }
  }
  return '';
}

/* el customizer */
function loadPreferences() {
  var cookie = getCookie('skittlish');
  if (cookie == '') {
    cookie = 'fluid blue';
  }
  document.getElementsByTagName('body')[0].className = cookie;
}

/* Add a new row in the table*/

function add_row() {
    var tr;
    last_row = document.getElementById("last_row").value;
    last_row ++;
    document.getElementById("last_row").value = last_row;

    tr = document.getElementById("dynamic_table").getElementsByTagName("tr")[0];
    
    input_text = document.createElement("tr");
    td = document.createElement("td");
    td.innerHTML = "<input type = text name = 'variable_name_" + last_row + "' value = '' maxlength = 9 size = 9></input>";
    input_text.appendChild(td);
    td = document.createElement("td");
    td.innerHTML = "<select name = 'type_" + last_row + "'><option class = 'personal_link' value = 'A'>String</option><option class = 'personal_link' value = 'P'>Packed</option><option class = 'personal_link' value = 'U'>User</option><option class = 'personal_link' value = 'D'>Date</option></select>";
    input_text.appendChild(td);
    td = document.createElement("td");
    td.innerHTML = "<input type = text name = 'length_" + last_row + "' value = '1' maxlength = 3 size = 5></input>";
    input_text.appendChild(td);
    td = document.createElement("td");
    td.innerHTML = "<input type = text name = 'decimals_" + last_row + "' value = '' maxlength = 2 size = 5></input>";
    input_text.appendChild(td);
    td = document.createElement("td");
    td.innerHTML = "<input type = text name = 'heading_" + last_row + "' value = '' maxlength = 20 size = 7></input>";
    input_text.appendChild(td);
    td = document.createElement("td");
    td.innerHTML = "<input type = text name = 'display_" + last_row + "' value = '' maxlength = 25 size = 7></input>";
    input_text.appendChild(td);
    td = document.createElement("td");
    td.innerHTML = "<input type = text name = 'subfile_" + last_row + "' value = '' maxlength = 15 size = 7></input>";
    input_text.appendChild(td);
    td = document.createElement("td");
    td.innerHTML = "<input type = checkbox name = 'key_" + last_row + "'></input>";
    input_text.appendChild(td);
    td = document.createElement("td");
    td.innerHTML = "<input type = checkbox checked name = 'appear_subfile_" + last_row + "'></input>";
    input_text.appendChild(td);
    td = document.createElement("td");
    td.innerHTML = "<input type = checkbox name = 'blank_" + last_row + "'></input>";
    input_text.appendChild(td);
    if (tr.parentElement != null)
      tr.parentElement.appendChild(input_text);
    else
      tr.parentNode.appendChild(input_text);

    input_text = null;
    input_text = document.createElement("tr");
    td = document.createElement("td");
    td.innerHTML = "&nbsp;";
    input_text.appendChild(td);
    td = document.createElement("td");
    td.innerHTML = "<label for='f4_" + last_row + "'><b>Prompt capable</b></label>";
    td.colSpan = 2;
    input_text.appendChild(td);
    td = document.createElement("td");
    td.innerHTML = "<input type = 'checkbox' name = 'f4_" + last_row + "' id = 'f4_" + last_row + "'></input>";
    input_text.appendChild(td);
    td = document.createElement("td");
    td.innerHTML = "<b>Prompt program name</b>";
    td.colSpan = 2;
    input_text.appendChild(td);
    td = document.createElement("td");
    td.innerHTML = "<input type = 'text' name = 'f4program_" + last_row + "' value = '' maxlength = '10' size = '12'></input>";
    input_text.appendChild(td);

    if (tr.parentElement != null)
      tr.parentElement.appendChild(input_text);
    else
      tr.parentNode.appendChild(input_text);
      
}

function add_validation_file(){
    vld_file_cnt = document.getElementById("vld_file_cnt").value;
    vld_file_cnt ++;
    document.getElementById("vld_file_cnt").value = vld_file_cnt;

    tr = document.getElementById("vld_file_dyn_table").getElementsByTagName("tr")[0];;
    input_text = document.createElement("tr");
    td = document.createElement("td");
    
     td.innerHTML = 	 
      "<div class = 'underline'></div>" +
      "<div class = 'somespace'></div>" +  
      "<b>Key & File validation " + vld_file_cnt + ":</b>" +
      "<ul>" +
      "<li>Are any fields validated against a file? Provide the file name and the fields to be validated:<br />" +
      "<table class = 'no_margin'><tr>" +
      "<td>file name:</td><td><input type = 'text' name = 'key_file_name_" + vld_file_cnt + "' value = '' maxlength = 10/></td>" +
      "</tr><tr>" +
      "<td>fields:</td><td><input type = 'text' name = 'key_validated_fields_" + vld_file_cnt + "' value = '' maxlength = 100/></td>" +
      "<td>(comma separated list; eg: FL1,FL2,FL3)</td>" +
      "</tr>" +
      "</table>" +
      "</li>" +
      "<li>Is a description in the file that must appear in the screen? Provide its details:<br />" +
      "<table cellspacing = 10 class = 'no_margin'>" +
      "<tr>" +
      "<td>File field name</td>" +
      "<td>Variable name</td>" +
      "<td>Type</td>" +
      "<td>Length</td>" +
      "<td>Decimals</td>" +
      "<td>Display name</td>" +
      "<td>Subfile name</td>" +
      "<td>Appear in the subfile:</td>" +
      "</tr>" +
      "<tr>" +
      "<td><input type='text' name='key_variable_file_name_" + vld_file_cnt + "' value='' maxlength = 10 size = 7></input></td>" +
      "<td><input type = 'text' name = 'key_variable_name_" + vld_file_cnt + "' value = '' maxlength = 9 size = 5></input></td>" +
      "<td><select name = 'key_type_" + vld_file_cnt + "'><option class = 'personal_link' value = 'A'>String</option><option class = 'personal_link' value = 'P'>Packed</option><option class = 'personal_link' value = 'S'>Signed</option></select></td>" +
      "<td><input type = 'text' name = 'key_length_" + vld_file_cnt + "' value = '' maxlength = 3 size = 5></input></td>" +
      "<td><input type = 'text' name = 'key_decimals_" + vld_file_cnt + "' value = '' maxlength = 2 size = 5></input></td>" +
      "<td><input type = 'text' name = 'key_display_" + vld_file_cnt + "' value = '' maxlength = 25 size = 7></input></td>" +
      "<td><input type = 'text' name = 'key_subfile_" + vld_file_cnt + "' value = '' maxlength = 15 size = 7></input></td>" +
      "<td><input type = 'checkbox' name = 'key_appear_subfile_" + vld_file_cnt + "' ></input></td>" +
      "</tr>" +
      "</table>" +
      "</li>" +
      "<li>" +
      "<input type = 'checkbox' name = 'key_is_near_field_" + vld_file_cnt + "' >&nbsp;Position near field:&nbsp;&nbsp;</input>" +
      "<input type = 'text' name = 'key_near_field_" + vld_file_cnt + "' value = '' maxlength = 6 size = 5 />" +
      " (if left unchecked the field will be displayed as the last one)" + 
      "</li>" +
      "</ul>";

    input_text.appendChild(td);

    if (tr.parentElement != null)
      tr.parentElement.appendChild(input_text);
    else
      tr.parentNode.appendChild(input_text);
}


function validate_project() {
  var err_no;
  var error_msg;
  var previous_key = true;
  var page_errors;
  var catg_errors;
  var subfile_index;
  
  err_no = 0; 
  page_errors = new Array();
  catg_errors = new Array();

  /*clear the error screens*/
  document.getElementById("error_page").innerHTML = "";
  document.getElementById("errors_0").innerHTML = "";
  document.getElementById("errors_1").innerHTML = "";
  document.getElementById("errors_2").innerHTML = "";


  /*validate general project data*/

  if (document.getElementById("application_name").value.trim().length != 6)
    catg_errors[err_no++] = 'Application name must have 6 chars.';
  if (document.getElementById("application_title").value.trim().length == 0)
    catg_errors[err_no++] = 'Application title must not be blank.';
  if (document.getElementById("application_text").value.trim().length == 0)
    catg_errors[err_no++] = 'Module text must not be blank.';

  if (catg_errors.length != 0)
    page_errors[0] = catg_errors;
    
  /*validate fields data*/

  err_no = 0; 
  previous_key = true;
  catg_errors = new Array();
  subfile_index = 6;
  
  for (var i=1; i<=document.getElementById("last_row").value; i++)
  { 
    if (document.forms[0]['variable_name_' + i].value.trim() != '')
    {
      if (isNaN(document.forms[0].elements["length_".concat(i)].value) || document.forms[0].elements["length_".concat(i)].value.trim() == '')
        catg_errors[err_no++] = 'The <i>Length</i> column must contain numbers and must not be blank. See variable ' + document.forms[0]['variable_name_' + i].value.trim() + '.';
      if (document.forms[0].elements["decimals_".concat(i)].value.trim() != '' && document.forms[0].elements['type_' + i].value == 'A')
        catg_errors[err_no++] = 'For string fields the <i>Decimals</i> column should be left blank. See variable ' + document.forms[0]['variable_name_' + i].value.trim() + '.';
      if ((document.forms[0].elements["decimals_".concat(i)].value.trim() == '' || isNaN(document.forms[0].elements["decimals_".concat(i)].value)) && document.forms[0].elements['type_' + i].value == 'P')
        catg_errors[err_no++] = 'For numeric fields the <i>Decimals</i> column must contain numbers and must not be blank. See variable ' + document.forms[0]['variable_name_' + i].value.trim() + '.';
      if (document.forms[0].elements['type_' + i].value == 'U' && (document.forms[0].elements["length_".concat(i)].value.trim() != "10" || document.forms[0].elements["decimals_".concat(i)].value.trim() != ""))
        catg_errors[err_no++] = 'For User type fields the <i>Length</i> field must be 10 and the <i>Decimals</i> field must be blank. See variable ' + document.forms[0]['variable_name_' + i].value.trim() + '.';
      if (document.forms[0].elements['type_' + i].value == 'U' && document.forms[0].elements["key_".concat(i)].checked)
        catg_errors[err_no++] = 'For User type fields the <i>Key</i> field must be unchecked. See variable ' + document.forms[0]['variable_name_' + i].value.trim() + '.';
      if (document.forms[0].elements['type_' + i].value == 'D' && (document.forms[0].elements["length_".concat(i)].value.trim() != "14" || document.forms[0].elements["decimals_".concat(i)].value.trim() != "0"))
        catg_errors[err_no++] = 'For Date type fields the <i>Length</i> field must be 14 and the <i>Decimals</i> field must be 0. See variable ' + document.forms[0]['variable_name_' + i].value.trim() + '.';
      if (document.forms[0].elements['type_' + i].value == 'D' && document.forms[0].elements["key_".concat(i)].checked)
        catg_errors[err_no++] = 'For Date type fields the <i>Key</i> field must be unchecked. See variable ' + document.forms[0]['variable_name_' + i].value.trim() + '.';
      if (previous_key && !document.forms[0].elements["key_".concat(i)].checked)
        previous_key = false;
      if (i == 1 && !previous_key)
        catg_errors[err_no++] = 'At least the first variable must be key. See variable ' + document.forms[0]['variable_name_' + i].value.trim() + '.';
      if (!previous_key && document.forms[0].elements["key_".concat(i)].checked)
        catg_errors[err_no++] = 'The key fields must be declared in order. See variable ' + document.forms[0]['variable_name_' + i].value.trim() + '.';
      if (document.forms[0].elements["key_".concat(i)].checked && !document.forms[0].elements["appear_subfile_".concat(i)].checked)
        catg_errors[err_no++] = 'At least until now :p, if you check the key option you must check also the appear subfile option. See variable ' + document.forms[0]['variable_name_' + i].value.trim() + '.';
      if (document.forms[0].elements["appear_subfile_".concat(i)].checked && !isNaN(document.forms[0].elements["length_".concat(i)].value) && document.forms[0].elements["subfile_".concat(i)].value.trim().length  > Number(document.forms[0].elements["length_".concat(i)].value) + 1)
        catg_errors[err_no++] = 'You provided for the variable ' + document.forms[0]['variable_name_' + i].value.trim() + ' a subfile name (\'' + document.forms[0].elements["subfile_".concat(i)].value.trim() + '\') with a length of ' + document.forms[0].elements["subfile_".concat(i)].value.trim().length + ' and the space to fill that in in the subfile is maximum the length of the field plus one (' + document.forms[0].elements["length_".concat(i)].value + ' + 1 = ' + (Number(document.forms[0].elements["length_".concat(i)].value) + 1) + ').';
      if (document.forms[0].elements["f4_".concat(i)].checked && document.forms[0].elements["f4program_".concat(i)].value.trim() == '')
        catg_errors[err_no++] = 'If you check the <i>Prompt capable</i> checkbox you must also type in a program name. See variable ' + document.forms[0]['variable_name_' + i].value.trim() + '.';
      if (document.forms[0].elements["appear_subfile_".concat(i)].checked && !isNaN(document.forms[0].elements["length_".concat(i)].value))
      {
        subfile_index += Number(document.forms[0].elements["length_".concat(i)].value);
        if (subfile_index >= 80)
          catg_errors[err_no++] = 'The fields displayed in the subfile add up to a total > 80 chars. Please uncheck for some of them the <i>Appear subfile</i> checkbox. See variable ' + document.forms[0]['variable_name_' + i].value.trim() + '.';
        subfile_index += 2;
      }  

    }

      
  }


  if (catg_errors.length != 0)
    page_errors[1] = catg_errors;


  /*validate external key fields data*/

  err_no = 0; 
  catg_errors = new Array();


  for (var i=1; i<=document.getElementById("vld_file_cnt").value; i++)
  { 
    if (document.forms[0]['key_file_name_' + i].value.trim() != '')
    {
      /*if (document.forms[0].elements["key_variable_file_name_".concat(i)].value.trim() == '') 
        catg_errors[err_no++] = '"File field name" column, for file ' + document.forms[0]['key_file_name_' + i].value.trim() + ', must not be blank.';*/
      if ((isNaN(document.forms[0].elements["key_length_".concat(i)].value) || document.forms[0].elements["key_length_".concat(i)].value.trim() == '') && (document.forms[0].elements["key_variable_file_name_".concat(i)].value.trim() != ''))
        catg_errors[err_no++] = 'The <i>Length</i> column must contain numbers and must not be blank. See file ' + document.forms[0]['key_file_name_' + i].value.trim() + '.';
      if (document.forms[0].elements["key_decimals_".concat(i)].value.trim() != '' && document.forms[0].elements['key_type_' + i].value == 'A')
        catg_errors[err_no++] = 'For string fields the <i>Decimals</i> column should be left blank. See file ' + document.forms[0]['key_file_name_' + i].value.trim() + '.';
      if ((document.forms[0].elements["key_decimals_".concat(i)].value.trim() == '' || isNaN(document.forms[0].elements["key_decimals_".concat(i)].value)) && document.forms[0].elements['key_type_' + i].value == 'P')
        catg_errors[err_no++] = 'For numeric fields the <i>Decimals</i> column must contain numbers and must not be blank. See file ' + document.forms[0]['key_file_name_' + i].value.trim() + '.';
      if (document.forms[0].elements['key_type_' + i].value == 'P' && !isNaN(document.forms[0].elements["key_decimals_".concat(i)].value) && !isNaN(document.forms[0].elements["key_length_".concat(i)].value) && Number(document.forms[0].elements["key_decimals_".concat(i)].value) >= Number(document.forms[0].elements["key_length_".concat(i)].value))
        catg_errors[err_no++] = 'For numeric fields the <i>Decimals</i> field must be smaller than <i>Length</i> field. See file ' + document.forms[0]['key_file_name_' + i].value.trim() + '.';
      if (document.forms[0].elements["key_is_near_field_".concat(i)].checked && document.forms[0].elements["key_near_field_".concat(i)].value.trim().length == 0) 
        catg_errors[err_no++] = 'If "Position near field", for file ' + document.forms[0]['key_file_name_' + i].value.trim() + ', was checked, please make sure that also the field column is filled in.';
    }
  }




  if (catg_errors.length != 0)
    page_errors[2] = catg_errors;


  /*final check before submision */
  
  if (page_errors.length == 0) document.forms[0].submit();
  else
  {
    
    error_msg = '';
    if (page_errors[0] != null)
    {
      for (var i=0; i<page_errors[0].length; i++)
        error_msg += page_errors[0][i] + '<br />';
      document.getElementById("errors_0").innerHTML = error_msg;
    }

    error_msg = '';
    if (page_errors[1] != null)
    {
      for (var i=0; i<page_errors[1].length; i++)
        error_msg += page_errors[1][i] + '<br />';
      document.getElementById("errors_1").innerHTML = error_msg;
    }

    error_msg = '';
    if (page_errors[2] != null)
    {
      for (var i=0; i<page_errors[2].length; i++)
        error_msg += page_errors[2][i] + '<br />';
      document.getElementById("errors_2").innerHTML = error_msg;
    }

  
    document.getElementById("error_page").innerHTML = '<p>You have some errors in your form. Please review them and try again.</p>';
  }
  return;
}


window.onload = function() {
  var o = document.getElementById("options");
  var lis = o.getElementsByTagName("LI");

  for (var i=0; i< lis.length; i++) {
    li = lis[i];
    parts = li.id.split("_");
    li.title = parts[1] + ": " + parts[2];

    
    li.onclick = function() {
      var body = document.getElementsByTagName('BODY')[0];
      var new_option_group = this.id.split("_")[1];
      var new_option = this.id.split("_")[2];
      if (new_option_group == 'size') {
        if (new_option == 'fluid') {
          replaceClass(body, 'fixed', 'fluid');
        } else {
          replaceClass(body, 'fluid', 'fixed');
        }
      } else {
        var colors = 'blue,cyan,green,orange,pink,red,violet'.split(',');
        var current_color = '';
        for (var i=0; i<colors.length; i++) {
          if (hasClass(body, colors[i])) {
            current_color = colors[i];
            break;
          }
        }
        if (new_option != current_color) {
          replaceClass(body, current_color, new_option);
        }
      }
      setCookie('skittlish', body.className, true);
      return false;
    }

  }

}

function toggle_external_val(){
    var ele = document.getElementById("External_keys");
	if(ele.style.display == "none") {
    		ele.style.display = "block";
		    document.getElementById("ExpandButton").style.display = "none";
  	}

}

