var tileids = new Array('1-1-1','2-2-1','3-3-1',
                        '4-4-1','5-5-1','6-4-2',
                        '7-6-1','8-1-2','9-3-2',
                        '10-2-2','11-5-2','12-6-2');
var current = null;
var candidate = null;
var imgprefix = '/static/images/memory/';

function create_tile(numid) {
  id = 'tile-' + numid;
  return IMG({'src':imgprefix + id + '-back.gif',
                'onclick':"flip('" + id + "')",
                'class':'clickable ingame',
                'alt':'bricka',
                'id':id});
}

function init() {
  board_append = partial(appendChildNodes,"board");
  tiles = map(create_tile, tileids);
  map(board_append,tiles);
}

function lock_tile(tile) {
  setNodeAttribute(tile,'onclick','');
  removeElementClass(tile,'clickable');
}

function unlock_tile(tile) {
  setNodeAttribute(tile,'onclick', "flip('" + tile.id + "')");
  addElementClass(tile,'clickable');
}

function lock() {
  tiles = getElementsByTagAndClassName('img', 'ingame', 'board');
  map(lock_tile, tiles);
}

function unlock() {
  tiles = getElementsByTagAndClassName('img', 'ingame', 'board');
  map(unlock_tile, tiles);
}
function restore_tiles() {
  restore_tile(current);
  restore_tile(candidate);
  //  setNodeAttribute(current,'src',imgprefix + current.id+'-back.gif');
  //  setNodeAttribute(candidate,'src',imgprefix + candidate.id+'-back.gif');
  candidate = null;
  current = null;
  unlock();
}
function flip(id) {
  lock();
  tile = getElement(id);
  setNodeAttribute(tile,'src',imgprefix + id +'-front.gif');
  
  if (current == null) { 
    current = tile;
    unlock();
    lock_tile(tile);
  }
  
  else {
    if (match(tile, current)) {
      removeElementClass(tile,'ingame');
      removeElementClass(current,'ingame');
      current = null;
      unlock();
      if (getElementsByTagAndClassName('img','ingame', 'board').length == 0) {
        fadeinwin();
      }
    }
    else {
      candidate = tile;
      setTimeout("restore_tiles()",1000);
    }
  }
}


function match(tile1, tile2) {
  return tile1.id.split('-')[2] == tile2.id.split('-')[2]
}

function fadeinwin() {
  appear("memorypop", {'duration':0.5, 'to':0.8});
}
function fadeoutwin() {
  dropOut("memorypop");
  restart();
}

function restore_tile(tile) {
  setNodeAttribute(tile,'src',imgprefix + tile.id+'-back.gif');
}

function restart() {
  tiles = getElementsByTagAndClassName('img',null, 'board');
  map(restore_tile, tiles);
  map(unlock_tile, tiles);
  candidate = null;
  current = null;
}

addLoadEvent(init);

