/**
 * Puzzle - a PHP/Javascript jigsaw puzzle
 *
 * Copyright (C) 2006 David Eder <david@eder,us>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * @author David Eder <david@eder.us>
 * @copyright 2004 David Eder
 * @package puzzle
 * @version .1
 *
 *  rhd27Jan08 - rework to separate javascript and php components
 */

  var cluster = new Array();

  function init_puzzle()  // init cluster array and scatter pieces
  {
   for(r = 0; r < rows_js; r++)
   {
    for(c = 0; c < cols_js; c++)
    {
      id = 't_' + r + '_' + c;
      obj = dd.elements[id];
      obj.moveTo(xinc_js * Math.round(Math.random() * 800 / xinc_js), yinc_js * Math.round(Math.random() * 600 / yinc_js));
      obj.row = r;
      obj.col = c;
      obj.cluster = id;
      cluster[id] = new Array();
      cluster[id][id] = id;
    }
   }
  }

  function merge_cluster(a, b)
  {
    for(i in cluster[b])
    {
      obj = dd.elements[cluster[b][i]];
      cluster[a][obj.name] = obj.name;
      obj.cluster = a;
    }
  }

  function align_cluster(a)
  {
    for(i in cluster[a])
    {
      obj = dd.elements[cluster[a][i]];
      obj.moveTo(xinc_js * Math.round(obj.x / xinc_js), yinc_js * Math.round(obj.y / yinc_js));
    }
  }

  function my_DragFunc()
  {
    for(i in cluster[dd.obj.cluster])
    {
      obj = dd.elements[cluster[dd.obj.cluster][i]];
      if(obj.name != dd.obj.name)
      {
        ox = dd.obj.x + (obj.col - dd.obj.col) * vw_js;
        oy = dd.obj.y + (obj.row - dd.obj.row) * vh_js;
        obj.moveTo(ox, oy);
      }
    }
  }

  function my_DropFunc()
  {
    align_cluster(dd.obj.cluster);

    for(r = -1; r <= 1; r++)
    {
      for(c = -1; c <= 1; c++)
      {
        if(c != 0 || r != 0)
        {
          obj = dd.elements['t_'+(dd.obj.row + r)+'_'+(dd.obj.col + c)];
          if(obj)
          {
            if(dd.obj.x + c * vw_js == obj.x && dd.obj.y + r * vh_js == obj.y)
            {
              merge_cluster(dd.obj.cluster, obj.cluster);
            }
          }
        }
      }
    }    

  }

