// 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 != '') {
                var done = new Array();

                checkField(formState, $(this), done);
              }
          }
      }
  });


  //
  // Set a click event on all radio inputs and pipe it to the onChange
  // this to avoid problems in IE6/IE7/IE8 that have a different event model
  //
  $('.wmpform').find(':input:radio').click(function() {
    $(this).change();
  }); 

  //
  // 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
          var doneFragments = new Array();
          var formObj = $(this);
          $(':input', $(this)).each(function() {
            // skip the hidden inputs
            var inputName = $(this).attr("name");

            if ($(this).attr("type") != 'hidden' && !doneFragments.contains(inputName)) {

              doneFragments.push(inputName);
              if (isVisible($(this))) {
                var obj = $('#error_' + inputName.replace('.','_'));
                // Skip the clientside validation if there is no div to show the error message
                if (obj.length > 0) {

                  var fr_error = "";
                  var value = getValue($(this));
                  
                  // get the validation errors
                  var arr = formState.validateAndReturnMessage(inputName,value);

                  // build a list of fragment errors
                  for(var item in arr) {
                    hasError = true;
                    fr_error += '<li>' + arr[item] + '</li>';
                  }
                  if (fr_error != '') {
                    fr_error = '<ul>' + fr_error + '</ul>';
                  }

                  // Show all fragment errors
                  obj.html(fr_error);
                  obj.show();
                }
              } else {
                // make the value empty to prevent to be routed to the same step
                // issue: http://jira.gxdeveloperweb.com/jira/browse/GXWMF-626
                switch(this.type) {
                    case 'password':
                    case 'select-multiple':
                    case 'select-one':
                    case 'text':
                    case 'textarea':
                      $(this).val('');
                      break;
                    case 'checkbox':
                    case 'radio':
                      $('input[name=' + $(this).attr("name") + ']').removeAttr("checked");  
                      // add an empty input type="hidden": this because the browser doesn't send an empty radio
                      formObj.append('<input type="hidden" name="' + inputName + '" value="" />');
                }
              }
            }
          });
          
          // 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.push($(this).val());
        i++;
      });
    }
    return value;    
  }

  // Check if an input has to be shown or not
  function checkField(formState, obj, done) {
    // If the input is not visible, the value is unknown so other input can also disappear
    var fvalue = 'unknown';
    if (isVisible(obj)) {
      fvalue = getValue(obj);
    }

    done.push(obj.attr("id"));

    // Get the changes: input which needs to be shown or hide
    var changes = formState.setFragmentValue(obj.attr("name"),fvalue);

    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];
      var 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) {
        if (fvalue != 'unknown' && showObj.attr("id") != '' && !done.contains(showObj.attr("id"))) {
           checkField(formState, showObj, done);
        }
      }

    }
  }

  // checks if the object is visible
  function isVisible(obj) {
    var visible = true;
    obj.parents().each(function() {
      if ($(this).css("display") == 'none') {
        visible = false;
        return false;      
      }
    });
    return visible;
  }

});

