/*---------------------------------------------------------------------------*/

/* hash_pw
 * 
 * Hashes the password given in the specified document element id.
 */
function hash_pw(element_id)
{
  var ele;
  var orig;
  var str;

  ele = document.getElementById(element_id);
  orig = ele.value;
  str = hex_md5(orig);
  ele.value = str.substr(0,16);
  return true;
}
    
/*---------------------------------------------------------------------------*/

/* hash_pw_sess_id
 * 
 * Hashes the password given in the specified document element id.  Then
 * appends the session id, and hashes the result.  The result is then
 * stored in the password element id.
 *
 * Parameters:
 *
 *    pw_ele_id     The name of the element id that holds the password.
 *
 *    sid           A string containing the session id.
 */
function hash_pw_sess_id(pw_ele_id, sid)
{
  var ele;

  hash_pw(pw_ele_id);
  ele = document.getElementById(pw_ele_id);
  ele.value = ele.value + sid;
  hash_pw(pw_ele_id);
}

/*---------------------------------------------------------------------------*/

/* rc4
 *
 * Returns an rc4 encrypted string, given a key string and a plaintext string.
 *
 * Implemtation from http://shop-js.sourceforge.net/crypto.htm
 */
function rc4(key, text)
{
  var i, x, y, t, x2;
  var z= "";
  var s = new Array();

  /* Seed the sbox */
  for (i = 0; i < 256; i++)
  {
    s[i] = i;
  }

  /* Scramble the sbox with the key */
  y = 0;
  for (x = 0; x < 256; x++)
  {
    y = (key.charCodeAt(x % key.length) + s[x] + y) % 256;
    t = s[x];
    s[x] = s[y];
    s[y] = t;
  }

  /* Randomize the sbox by throwing out the first several values */
  for (x = 0; x < 2000; x++)
  {
    x2 = x % 256;
    y = (s[x2] + y) % 256;
    t = s[x2];
    s[x2] = s[y];
    s[y] = t;
  }

  /* Encrypt the text */
  for (x = 0; x < text.length; x++)
  {
    x2 = x % 256;
    y = (s[x2] + y) % 256;
    t = s[x2];
    s[x2] = s[y];
    s[y] = t;
    z += String.fromCharCode((text.charCodeAt(x) ^ s[(s[x2] + s[y]) % 256]));
  }
  return z
}

/*---------------------------------------------------------------------------*/

/* str2hex
 *
 * Converts a string composed of characters whose charCodeAt() values are
 * 0..255 into a hex encoded string (which is twice as long).
 */
function str2hex(str)
{
  var hex, i, conv, c;

  conv = "0123456789abcdef";

  hex = "";
  for (i = 0; i < str.length; i++)
  {
    c = str.charCodeAt(i);
    hex += conv.charAt((c >> 4) & 0xf);
    hex += conv.charAt(c & 0xf);
  }
  return hex;
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/

