/* Mega Man 4 password generator / decoder
 * Copyright (C) 1992,2004 Joel Yliluoma (http://iki.fi/bisqwit/)
 * Written for http://tasvideos.org/PasswordGenerators.html
 * Permission to copy and modify is granted under the following terms:
 *   The copyright notice is kept unmodified
 *   No attempts are made to prevent anyone downloading the source code
 *
 * Reverse engineering by unknown, documentation from Protoman's site
 */
function mm4input(name)
{var tH=this,defs = {
    gel:  function(id)   { return document.getElementById(name+id) },
    id:   function(id)   { return tH.gel(id).selectedIndex },
    ch:   function(id)   { return tH.gel(id).checked },
    chs:  function(id,v) { tH.gel(id).checked=v>0 },
    view: function(id,v) { tH.gel(id).style.visibility = v?'visible':'hidden' },
    img:  function(id,v) { tH.gel(id).src = v },
  
    /* basic binary pattern: -- a- -b ab */
    grps: [[1*6+2, 2*6+1, 3*6+2, 1*6+1, 'TO','BR'],
           [1*6+3, 2*6+4, 3*6+3, 1*6+4, 'PH','DR'],
           [1*6+5, 2*6+6, 3*6+5, 2*6+5, 'RI','DU'],
           [4*6+1, 6*6+2, 5*6+1, 5*6+2, 'SK','DI'],
           [5*6+3, 4*6+4, 4*6+3, 6*6+3, 'WI','BA']],

    /* with counting */
    counts:[5*6+5, 1*6+6, 2*6+2, 2*6+3, 3*6+1,
           3*6+4, 3*6+6, 4*6+2, 5*6+4, 5*6+6, 6*6+1],

    status:[0,0,0,0,0,0,
            0,0,0,0,0,0,
            0,0,0,0,0,0,
            0,0,0,0,0,0,
            0,0,0,0,0,0,
            0,0,0,0,0,0],

  updatedots: function()
  {
    files = ['css/black.png', 'css/red.png']
    for(n=0;n<36;++n)
    {
      s = tH.status[n]
      tH.img('d'+n, files[s])
    }
  },
  
  decodehelper: function(n)
  {
    pos = tH.grps[n]
    
    a=-1
    for(n=0; n<4; ++n) if(tH.status[pos[n]-7]) { if(a==-1){a=n;}else{error=1;} }
    if(a==-1) error=1
    
    if(error) { return 15; }
    
    b = (a&2) ? 1 : 0
    a = (a&1)
    
    tH.chs(pos[4], a)
    tH.chs(pos[5], b)

    return a+b
  },
  encodehelper: function(n)
  {
    pos = tH.grps[n]
    
    a = 0
    n = 0
    
    if(tH.ch(pos[4])) { a+=1; n+=1; }
    if(tH.ch(pos[5])) { a+=2; n+=1; }
    
    tH.status[pos[a]-7] = 1
    
    return n
  },
  
  decode: function()
  {
    error = 0
    
    dotcount=0
    for(n=0; n<36; ++n) if(tH.status[n]) ++dotcount;
    if(dotcount != 6) error=1;

    count=0
    for(n=0;n<5;++n) count += tH.decodehelper(n)
    
    for(n=0; n<11; ++n)
    {
      shouldbe = (count==n?1:0)
      if(tH.status[tH.counts[n]-7] != shouldbe)
        error=1
    }
    
    tH.view('error', error)
  },
  hitdot: function(n)
  {
    s = (tH.status[n]+1) % 2
    tH.status[n]=s

    tH.updatedots()
    tH.decode()
  },
  
  setup: function()
  {
    for(n=0;n<36;++n) tH.status[n]=0
    
    count=0
    for(n=0;n<5;++n) count += tH.encodehelper(n)
    tH.status[tH.counts[count]-7] = 1

    tH.updatedots()
    tH.decode()
  }
}for(var i in defs) this[i]=defs[i]
}
