// Content of this file must correspond to captcha.xsl file
// JS-library prototype.js is required
function PM_CaptchaClass(inputId, imgId, errorAreaId){
  this.inputId = inputId;
  this.imgId = imgId;
  this.errorAreaId = errorAreaId;

  this.result = false;

  this.positiveResult = function(){
    this.result = true;
    $(this.errorAreaId).hide();
  }
  this.negativeResult = function(){
    $(this.errorAreaId).show();
    $(this.inputId).activate();
    this.reset();
  }
  this.reset = function(){
    this.result = false;
    $(this.inputId).clear();
    $(this.imgId).setAttribute('src', '/jcaptcha'+'?anticache='+Math.random());
  }

  this.validate = function(onValidationSuccess){
    if(this.result){
      if(onValidationSuccess){
        onValidationSuccess();
      }
      return;
    }
    var _this = this;
    var url = '/jcaptcha'
              +'?operation=ajax-validation'
              +'&j_captcha_response='+encodeURIComponent($(this.inputId).getValue());
    new Ajax.Request(url, {
      method: 'post',
      onSuccess: function(transport) {
        if(('true'==transport.responseText)){
          _this.positiveResult();
          if(onValidationSuccess){
            onValidationSuccess();
          }
        }else{
          _this.negativeResult();
        }
      },
      onFailure: function(transport) {
        alert('Captcha validation failure!');
        _this.reset();
      }
    });
  }// end validate

  // Method isn't ready to use!
  // It works bad. Onsubmit validation procedures executes two times.
  this.wireupToSubmit = function(form){
    var _this = this;
    Event.observe(window, 'load', function() {
      if(!form){
        form = document.forms[0];
      }
      Event.observe(form, 'submit', function(event) {
        _this.validate(function(){
          // It works bad. Onsubmit validation procedures executes two times.
          if($(form).onsubmit){
            if($(form).onsubmit()){
              $(form).submit();
            }
          }else{
            $(form).submit();
          }
        });
        Event.stop(event);
      });
    });
  }// end wireupToSubmit

}// end PM_CaptchaClass


// Stub for the case when captcha is disabled.
function PM_CaptchaDisabledClass(){
  this.validate = function(onValidationSuccess){
    if(onValidationSuccess){
      onValidationSuccess();
    }
  }
}// end PM_CaptchaDisabledClass
