/*
   New Perspectives on HTML, XHTML, and DHTML
   Tutorial 15
   Review Assignment

   Filename: makepuzzle.js

   Functions List:
   setUpBoard()
      Sets up the background images for the 24 tiles in the sliding block puzzle

   scramble()
      Scrambles the tiles in the 5x5 sliding block puzzle. A check
      is made to ensure that the resulting tile layout is solveable,
      if not the tiles are rescrambled until the layout is
      solveable. Used in the puzzle.htm file.

   colorPiece(object,z, color)
      Sets the z-index value of the object to z and sets the border color
      of the object to "color".

*/

function setUpBoard() {
   for (i=0;i<=23;i++) {
      document.getElementsByTagName("div")[i].style.backgroundImage="url(image"+(i+1)+".jpg)";
   }
}

function scramble() {
  var x = new Array();
  for (i=0;i<=23;i++) {x[i]=i;}

  for (i=0;i<=23;i++) {
     ri=Math.floor(Math.random()*(24-i))+i;
     temp=x[ri];
     x[ri]=x[i];
     x[i]=temp;
   }
 
   nSum=0;
   for (i=0; i<=23;i++) {for (j=i; j<=23; j++) {if (x[j] < x[i]) nSum++;}}
   
   if (Math.floor(nSum/2) != nSum/2) scramble(); // check if puzzle is solveable
   else {
     for (i=0;i<=23;i++) {
        document.getElementsByTagName("div")[i].style.backgroundImage="url(image"+(x[i]+1)+".jpg)";
     }
   }
}

function colorPiece(object,z,color) {
   object.style.zIndex=z;
   object.style.borderColor=color;
}

