// basecmp extension for serverside validation with struts 2.1 and prototype

// convenience-function-shortcuts to validateWithPrototype
  function validateAndExecute(form) {
    validateWithPrototype(form, false);
  }
  function validateOnly(form) {
    validateWithPrototype(form, true);
  }

  // Ajax-Validierung via prototype 'on submit'.
  function validateWithPrototype(form, validateOnly) {

     var url = form.action;
     new Ajax.Request(
        url,
        {
            method: 'post',
            encoding: 'UTF-8',
            parameters: Form.serialize(form) + '&struts.enableJSONValidation=true&struts.validateOnly=' + validateOnly,
            evalJSON: false,
            onSuccess: function(response) { postValidation(response, form); },
            onException: handleException,
            on500: function() { alert("Serverside Error (Http-Responsecode 500) has occured!"); }
        }
     );

  }

  function handleException(response, e) {
    alert("JavaScript-Exception\n\t" + e);
  }

  function postValidation(response, form) {

     var text = response.responseText;

     // Note: Struts2-JSON-Validator sends JSON inside JS-Comments!
     //       That's why prototype cant do the job during Ajax-Request and evalJSON is set false!
     // so we test if request is a 'Struts-own-JSON-Response'
     //if(!text.match(/\/\*/)) {
     //  alert("The AJAX-Response seems invalid! Expected JSON-Content, got this:\n\t" + text);
     //}

     //get errors from response
     var errorsObject = StrutsUtils.getValidationErrors(text);
     //clear previous validation errors, if any
     StrutsUtils.clearValidationErrors(form);
     if(typeof clearGlobalError == 'function') {
         // execute only if 'clearGlobalError' is defined anyway
    	 clearGlobalError(form);
     }

     //show errors, if any
     if(errorsObject && errorsObject.fieldErrors) {

       StrutsUtils.showValidationErrors(form, errorsObject);
       if(typeof onInvalid == 'function') {
         // execute only if 'onInvalid' is defined anyway
         onInvalid(response, form);
       }

     } else if(errorsObject && errorsObject.errors) {

       if(typeof onGlobalError == 'function') {
         // execute only if 'onGlobalError' is defined anyway
         onGlobalError(form, errorsObject);
       }

     } else {

       if(typeof onValid == 'function') {
         // execute only if 'onValid' is defined anyway
         onValid(response, form);
       }

     }

  }
