/* $Id: xorcrypter.js,v 1.4.2.1 2004/12/22 15:07:16 jaris Exp $ */

/**
 * A class for decoding XOR crypted strings
 *
 * @author M. Muhonen
 * @version $Revision: 1.4.2.1 $
 * @copyright Ambientia Ltd. All Rights Reserved
 */
function XORCrypter(password)
{
  this.keyTraits = "abcdefghijklmnopqrstuvwxyz0123456789-";
  this.maxKeyTraits = this.keyTraits.length - 1;
  this.password = [];
  this.passwordLength = 0;

  /** Decodes the given string */
  this.decode = function(s)
  {
    var decoded = "", output = "";
    var escape = false;

    for (var i=0, j=0; i < s.length; i++, j++) {
      var ch = s.charAt(i);
      var input = this.keyTraits.indexOf(ch);

      if (j >= this.password.length)
        j = 0;

      if (input == -1)
        output = ch;
      else if (escape) {
        if (input == this.maxKeyTraits) {
          output = "\n";
          input = -1;
        } else if (input == "'") {
          output = '"';
          input = -1;
        } else
          input += this.maxKeyTraits;

        escape = false;
      } else if (input == this.maxKeyTraits) {
        output = '';
        input = -1;
        j--;
        escape = true;
      }

      if (input != -1)
        output = this.keyTraits.charAt(this.password[j] ^ input);

      decoded += output;
    }

    return decoded;
  }

  this.setPassword = function(p)
  {
    this.passwordLength = p.length;

    for (var i=0; i < this.passwordLength; i++)
      this.password[i] = this.keyTraits.indexOf(p.charAt(i));
  }

  this.setPassword(password);
}