If I understand your problem correctly, you can "walk" in x-direction either directly from x1 to x2 (abs(x1 - x2)
steps), or wrap around in increasing x-direction (size + x2 - x1
steps) or in decreasing x-direction (x1 - x2 + size
steps).
Therefore the difference in x-direction is
dx = min ( abs(x1 - x2) , size + x2 - x1, x1 - x2 + size)
and similarly
dy = min ( abs(y1 - y2) , size + y2 - y1, y1 - y2 + size)
and finally the Manhattan distance
dist = dx + dy
Update: Another way to look at it is that the distance in x-direction is
either abs(x2-x1)
if you don't wrap around, or size - abs(x2-x1)
if you wrap around.
Therefore
dx = min ( abs(x2 - x1) , size - abs(x2 - x1) )
which is a more symmetric way of expressing it.
Update: Final JavaScript Function:
function getToroidManhattanDistance( node1, node2, size )
{
var dx = Math.min( Math.abs( node1.x - node2.x ), size - Math.abs( node2.x - node1.x ) );
var dy = Math.min( Math.abs( node1.y - node2.y ), size - Math.abs( node2.y - node1.y ) );
return dx + dy;
}