var maxLength = 500;

// check our recommendation feedback forms, do text counter and also check we have selected a radio button
function check_feedback(form) {
  textCounter(form.frm_feedback,form.remLen,maxLength);
  
  if (!form.frm_progressing) return;  // no radios on this form, don't check em
  
  if (!check_feedback_radios(form.frm_progressing) || !check_feedback_radios(form.frm_involvement) || !check_feedback_radios(form.frm_priority)) {
    alert('Before providing feedback please answer the 3 questions to the left with the radio buttons provided.');
  }
}

function textCounter(field, countfield, maxlimit) {
    if (field.value.length > maxlimit) // if too long...trim it!
        field.value = field.value.substring(0, maxlimit);
        // otherwise, update 'characters left' counter
    else
        countfield.value = maxlimit - field.value.length;
}

// make sure we have a radio option selected in the passed radio element and return true or false based on that
function check_feedback_radios(radio) {
  var i;
  for (i = 0; i < radio.length; i++) {
    if (radio[i].checked == true) return true;
  }
  return false;
}

// check occupation level drop downs if current level has a value enable next level, otherwise disable
function occ_lvl_check(lvl) {
  var obj = document.getElementById('select_occupation' + lvl);
  var nextLvl = lvl * 1 + 1;
  var objNext = document.getElementById('select_occupation' + nextLvl);
  
  if (objNext) {
    if (obj.value == 0) objNext.disabled = true;
    else objNext.disabled = false;
    
    // if we are an interested community member, don't allow further levels of occupation
    if (lvl == 1 && obj.value == 1) {
      document.getElementById('frm_pcode_work').disabled = true;
      while (objNext) {
        objNext.disabled = true;
        nextLvl = nextLvl * 1 + 1;
        objNext = document.getElementById('select_occupation' + nextLvl);
      }
    }
    else document.getElementById('frm_pcode_work').disabled = false; 
  }
}

function submitFeedback(form) {
  if (!form.frm_progressing) form.submit();  // no radios on this form, don't check em
  
  if (!check_feedback_radios(form.frm_progressing) || !check_feedback_radios(form.frm_involvement) || !check_feedback_radios(form.frm_priority)) {
    alert('Please answer all 3 questions with the radio buttons provided to submit feedback.');
    return false;
  }
  form.submit();
}

window.onload = function() {
  var i = 1;
  var occ_levels = 4; // number of levels of occupations we process in forms
  for (i = 1; i <= occ_levels; i++) {
    occ_lvl_check(i);
  }
}