/* securityQuestions.js - Select a challenge/response pair randomly to
 *                        weed out form robots
 *  
 *  Requires jquery.validator
 *  Written for Jumping Jackrabbit Design by Joe Johnston <joe@jumpingjackrabbit.com>
 *
 *  The list of security challenges can be increased by added a question/answer pair
 *  to getQuestions()
 *
 *  Typical usage:
 *  <script>
 *    var challenge = getNewChallenge();
 *    $("input[name=captcha]").rules("add", {securityChallenge : [challenge["answer"]]}
      $("#captchaLabel").append(challenge["question"])
 *  </script>
 *  <form>
 *    <label id="captchaLabel"></label><input name="captcha" value="" />
 *  </form>
 */
function getQuestions() {
     return [
              ["How many letters are in GREEN?", "5"],
              ["What is 3+7?", "10"],
              ["What quacks, ducks or dogs?", "DUCKS"],
            ]
}

function getNewChallenge() {
    var questions = getQuestions();
    var choice = Math.floor(questions.length * Math.random());
    return { "question" : questions[choice][0],
             "answer"   : questions[choice][1]
            };
}

// Add a jquery.validator method, if loaded
if (typeof(jQuery.validator.addMethod) == "function") {
  jQuery.validator.addMethod("securityChallenge",
                             function(v,e,p) {
                                 if (p[0] == null || p[0].length == 0) {
                                     alert("No valid challenge answer provided");
                                     return false;
                                 }
                                 return v.toUpperCase()==p[0].toUpperCase();
                             },
                             "This is not the expected answer");
} else {
    alert("Please load securityQuestion.js after jquery validator");
}
