/* pwtools */
$(document).ready(function(){
 if (window.rcmail) {
    rcmail.addEventListener('init', function(evt) {
      if(rcmail.pwtools){
        rcmail.register_command('plugin.pwtools-save', function() { 
          var input_enabled = $("[name='_pwtoolsenabled']");
          var input_question = $("[name='_pwtoolsquestion']");
          var input_answer = $("[name='_pwtoolsanswer']");
          var input_answerconfirm = $("[name='_pwtoolsanswerconfirm']");
          if(input_question.val() == ""){
            parent.rcmail.display_message(rcmail.gettext('pwtoolsquestionempty','pwtools'),'error');
            input_question.focus();
            return false;
          }
          if(input_answer.val() == ""){
            parent.rcmail.display_message(rcmail.gettext('pwtoolsanswerempty','pwtools'),'error');
            input_answer.focus();
            return false;
          }
          if(input_answer.val().toLowerCase() != input_answerconfirm.val().toLowerCase()){
            parent.rcmail.display_message(rcmail.gettext('pwtoolsanswernotmatch','pwtools'),'error');
            input_answerconfirm.focus();
            return false;
          }
          if(input_enabled.prop('checked')){
            parent.rcmail.display_message(rcmail.gettext('pwtoolsactive','pwtools'),'confirmation');
            document.forms.pwtoolsform.submit();
          }
          else{
            parent.rcmail.display_message(rcmail.gettext('pwtoolsinactive','pwtools'),'warning');
            setTimeout('document.forms.pwtoolsform.submit();', 6000);
          }
        }, true);
      }
    });
  }
});

function pwToolsValidate(){
  var input_answer = $("input[name='_pwtoolsanswer']");
  if(input_answer.val() == ""){
    rcmail.display_message(rcmail.gettext('pwtoolsanswerempty','pwtools'),'error');
    input_answer.focus();
    return false;
  }
  if(typeof captchaValidate == 'function'){
    var captcha = $("[name='captcha_input']");
    captchaValidate('pwToolsCallback()');
    return false;
  }
  else{
    pwToolsCallback();
    return true;
  }
}

function pwToolsCallback(){
  rcmail.set_busy(true, 'loading');
  document.forms.form.submit();
  return false;
}

function pwTools(){

  var input_user = $("[name='_user']");
  var input_host = $("[name='_host']");
  user = input_user.val();
  host = input_host.val();
  if(user == ""){
    rcmail.display_message(rcmail.gettext('pwtoolsuserempty','pwtools'),'error');  
  }
  else{
    if(user == 'undefined')
      document.location.href = "./";
    else{
      var append = '';
      if(host)
        append = "&_host=" + escape(host);
      document.location.href = "./?_task=settings&_action=plugin.pwtools_reset&_username=" + escape(user) + append;
    }
  }
}
