Line 53:
gid = layer.tileGIDs[row][col] - 1;
does not take into account multiple tilesets so "- 1" is accurate only for the first tileset. In other cases we need to offset it by firstGID field of the appropriate tileset instead. The code I came up with is (replacing the line above):
// find proper tileset for this gid
var firstGID = 1;
for (t in map.tilesets)
if (gid >= t.firstGID)
firstGID = t.firstGID;
gid -= firstGID;