// For each form(element) a request will be done to the 'wmpformclientsideframework'-servlet.
// It will add the corresponding formState object to the WebmanagerFormStateRegistry.
var WebmanagerFormStateRegistry = {};

$(document).ready(function(event) {
  // initial hide
  $('.hide').each(function() {
      $(this).hide();
  });

  //
  // Set a change event on all inputs: we can determine clientside if other fields needs to be shown
  //
  $('.wmpform').find(':input').change(function() {
      var formId = $(this).parents('form:first').attr("id");

      if (formId != 'undefined' && formId != '') {
          var formState = WebmanagerFormStateRegistry[formId];

          if (typeof formState != 'undefined' && formState != '' ) {

              attr = $(this).attr("name");
              if (typeof attr != 'undefined' && attr != '') {
                checkField(formState, $(this));
              }
          }
      }
  });

  //
  // logic which is executed when the form is submitted:
  //  - each fragment is check for clientside validations
  //
  $(".wmpform").submit(function(event) {
      hasError = false;
      var formId = $(this).attr("id");

      // This js only supports the non ajax variant
      $('#clientsideRouting').val("false");

      if (formId != 'undefined' && formId != '') {
        // get the formState
        var formState = WebmanagerFormStateRegistry[formId];

        if (typeof formState != 'undefined' && formState != '' ) {
          // loop over the inputs to check the validations
          $(':input').each(function() {
            // skip the hidden inputs
            if ($(this).attr("type") != 'hidden') {

              inputName = $(this).attr("name");
              obj = $('#error_' + inputName.replace('.','_'));
              if (obj.length > 0 && isVisible(obj)) {

                fr_error = "";

                value = getValue($(this));
                
                // get the validation errors
                arr = formState.validateAndReturnMessage(inputName,value);
                
                // build a list of fragment errors
                for(var item in arr) {
                  hasError = true;
                  var value = arr[item];
                  fr_error += '<li>' + value + '</li>';
                }
                if (fr_error != '') {
                  fr_error = '<ul>' + fr_error + '</ul>';
                }
                
                // Show all fragment errors
                obj.html(fr_error);
                obj.show();
              }
            }
          });

          // If there is an error: don't submit the form
          if (hasError) {
              event.preventDefault();
          }
        }
      }
  });

  // Get the value(s) for an object. This implementation differs per input type
  function getValue(obj) {
    value = obj.val();

    // for checkboxes we pass the array of values
    if (obj.attr("type") == 'radio') {
      value = $('input[name=' + obj.attr("name") + ']:checked').val();
    }
    if (obj.attr("type") == 'checkbox') {                      
      values = $('input:checkbox[name=' + obj.attr("name") + ']:checked') || [];
      value = new Array();

      i=0;
      values.each(function() {
        value[i] = obj.val();
        i++;
      });
    }
    return value;    
  }

  // Check if an input has to be shown or not
  function checkField(formState, obj) {
    // If the input is not visible, the value is unknown so other input can also disappear
    if (isVisible(obj)) {
      value = getValue(obj);
    } else {
      value = 'unknown';
    }
    
    // Get the changes: input which needs to be shown or hide
    changes = formState.setFragmentValue(obj.attr("name"),value);

    for (var i = 0; i < changes.length; i++) {
      // Change object contains the identifier and a value if the input needs to be shown or hide
      var change = changes[i];
      identifier = change.identifier.replace('.','_');

      if (change.value == 'show') {
        $('#' + identifier).show();
      } else {
        $('#' + identifier).hide();            
      }
      // We need to go recursive because hiding an input can have an effect on other inputs
      showObj = $('input:[name=' + identifier + ']');

      if (showObj.length > 0) {
        checkField(formState, showObj);
      }

    }    
  }

  // checks if the object is visible
  function isVisible(obj) {
    visible = true;
    obj.parents().each(function() {
      if ($(this).css("display") == 'none') {
        visible = false;
        return false;      
      }
    });
    return visible;
  }

  // List entries for debugging in FX.
  // for (entry in WebmanagerFormStateRegistry) {
  //     window.console.log(entry + ': %o', WebmanagerFormStateRegistry[entry]);
  // }
});