// the player is correct
function correct() {
  g_body_el.style.backgroundColor='lime';
  setTimeout(play,2000);
}
// prepare two stacks with different top views
function deal() {
  g_arr1=Copy_array(g_arr0);
  Shuffle(g_arr1);
  g_arr2=Copy_array(g_arr0);
  var s=stack(g_arr1).join('');
  for (var i=0;i<500;i++) {
    Shuffle(g_arr2);
    if (stack(g_arr2).join('')!=s) break;
  }
}
// uses some fancy footwork to stack the discs
function drop(id) {
  var heights=[32,42,52,66,79]; // pixels
  var el=document.getElementById(id);
  el.style.marginTop='-'+g_margin+'vmin';
  el.style.zIndex=g_z++;
  el.style.visibility='visible';
  el.classList.add('move');
  g_margin+=Math.round(heights[id-10]*.13);
}
// opposite to show()
function hide() {
  Hide_class('left'); Hide_class('right');
  Hide_class('middle');
  Hide('larrow'); Hide('which'); Hide('rarrow');
}
// called when player clicks on left stack or arrow
function left() {
  if (g_ans=='left') correct(); else wrong();
}
// eg make('left',g_arr1);
function make(lr,arr) {
  var a=stack(arr).reverse();
  var z=1;
  var offset=0;
  if (lr=='right')offset=5;
  for (var i=0;i<a.length;i++) {
    var id=a[i]-1+offset;
    var el=document.getElementById(id);
    el.style.zIndex=z++;
  }
}
// drops the next disc if any left
function next1() {
  if (g_ind<5) {
    drop(g_arr[g_ind]+9);
    g_ind++;
  } else {
    show(); // reveal the choices
  }
}
// the main function
function play() {
  reset();
  deal();
  make('left',g_arr1);
  make('right',g_arr2);
  if (Random(2)==1) {
    g_arr=Copy_array(g_arr1);
    g_ans='left';
  } else {
    g_arr=Copy_array(g_arr2);
    g_ans='right';
  }
  g_arr.reverse();
  // didn't work without the Timeout!
  setTimeout(next1,100);
}
function reset() {
  g_body_el=document.getElementsByTagName('body')[0];
  g_body_el.style.backgroundColor='ivory';
  g_z=1; g_margin=0; g_ind=0;
  for (var i=0;i<10;i++) {
    var el=document.getElementById(i);
    el.style.zIndex=0;
  }
  for (var i=10;i<15;i++) {
    var el=document.getElementById(i);
    el.classList.remove('move');
    el.style.zIndex=0;
  }
  hide();
}
// called when player clicks on right stack or arrow
function right() {
  if (g_ans=='right') correct(); else wrong();
}
// called after the dropping complete
function show() {
  Show_class('left'); Show_class('right');
  Show('larrow'); Show('which'); Show('rarrow');
}
// eg 3 4 1 2 5 -> 3 4 5
// ie the top view
function stack(arr) {
  var big=0;
  var result=[];
  for (var i=0;i<arr.length;i++ ) {
    if (arr[i]>big) {
      big=arr[i]; result.push(big);
    }
  }
  return result;
}
// the player is wrong
function wrong() {
  g_body_el.style.backgroundColor='red';
  setTimeout(play,5000);
}
