var specialcase = ((navigator.userAgent.indexOf('Mac') != -1) || document.all);

var down = 0;
var startX = 0;
var startY = 0;
var endX = 0;
var endY = 0;
//var statesH = new Array();
var statesV = new Array();
var puzzleW = 0;
var puzzleH = 0;
var arrCells = new Array();
//var helper;
var opos = new Array();
var helperpos = new Array();
var tablepos = new Array();

var lastAns = 'y';
var lastRightClick = false;
var ResizeTimeout = false;

function init() {

	if (!(document.getElementById || document.all || document.layers)) return;
	document.getElementById("puzzleContainer").onselectstart = new Function ("return false");
	document.onselectstart = new Function ("return false");
	document.ondragstart = new Function ("return false");
	
	document.ondragstart = function() {return false};

  puzzleW = document.answerForm.w.value*1;
	puzzleH = document.answerForm.h.value*1;
  
  $('#puzzleContainer').mousedown(d);
  $('body').mousemove(mv);
  $('body').mouseup(u);
  
  //$('#puzzleContainer').click(c);
  document.onkeypress = kp;
  
	var sV = document.answerForm.ansV.value;
//	var sH = document.answerForm.ansH.value;
//  statesH = new Array();
  statesV = new Array();
  
  for (var i = 0; i < puzzleH; i++){
    for (var j = 0; j < puzzleW; j++){
      // has vertical
      if (statesV[i] == undefined) statesV[i] = new Array();
	    n = i * (1 * puzzleW) + (j * 1);
	    statesV[i][j] = sV.substr(n, 1);
      /*
      if (j < puzzleW - 1){
        // has vertical
        if (statesV[i] == undefined) statesV[i] = new Array();
		    n = i * (1 * puzzleW - 1) + (j * 1);
		    statesV[i][j] = sV.substr(n, 1);
      }
      if (i < puzzleH - 1){
        if (statesH[i] == undefined) statesH[i] = new Array();
        // has horizontal
		    n = n = i * puzzleW + j * 1;
		    statesH[i][j] = sH.substr(n, 1);
      }
      */
    }
  }
  //helper = $(document.createElement('div')).css({border:'1px dotted black'});
	timer();
  
}

function c(e){
  alert('x');
  d(e);
  u(e);
}
function g(id){
  return document.getElementById(id);
}
function setRedClass(el, pos, set){
  var i = 0;
  el = el[0];
  //el = el.index(0);
  var s = el.className;
  if (pos == 't') i = 1;
  if (pos == 'r') i = 2;
  if (pos == 'b') i = 3;
  if (pos == 'l') i = 4;
  if (!s){
    s = 'b0000';
  }
  var l = s.length;
	s = s.substr(0, i) + (set ? '1' : '0') + s.substr(i + 1, l);
  el.className = s;
}
var helperI1=0, helperI2=0, helperJ1=0, helperJ2=0;
var helperClass1, helperClass2;
function removeHelper(){
  if (helperI1 || helperJ1 || helperI2 || helperJ2){
    if (lastRightClick){
      $('#id_'+helperI1+'_'+helperJ1+' div')[0].className = helperClass1;
      $('#id_'+helperI2+'_'+helperJ2+' div')[0].className = helperClass2;
    } else {
      g('id_'+helperI1+'_'+helperJ1).className = helperClass1;
      g('id_'+helperI2+'_'+helperJ2).className = helperClass2;
    }
  }
}
function placeHelper(x1, y1, x2, y2){
  if (helperI1 == y1 && helperJ1 == x1 && helperI2 == y2 && helperJ2 == x2) return;
  removeHelper();
  helperI1 = y1; helperJ1 = x1; helperI2 = y2; helperJ2 = x2;
  if (lastRightClick){
    helperClass1 = $('#id_'+helperI1+'_'+helperJ1+' div')[0].className;
    helperClass2 = $('#id_'+helperI2+'_'+helperJ2+' div')[0].className;
    if (x1 != x2){
      setRedClass($('#id_'+helperI1+'_'+helperJ1+' div'), 'r', true);
      setRedClass($('#id_'+helperI2+'_'+helperJ2+' div'), 'l', true);
    }
    if (y1 != y2){
      setRedClass($('#id_'+helperI1+'_'+helperJ1+' div'), 'b', true);
      setRedClass($('#id_'+helperI2+'_'+helperJ2+' div'), 't', true);
    }
    
  } else {
    helperClass1 = g('id_'+helperI1+'_'+helperJ1).className;
    helperClass2 = g('id_'+helperI2+'_'+helperJ2).className;
    if (x1 != x2){
      g('id_'+helperI1+'_'+helperJ1).className = 'hl';
      g('id_'+helperI2+'_'+helperJ2).className = 'hr';
    }
    if (y1 != y2){
      g('id_'+helperI1+'_'+helperJ1).className = 'ht';
      g('id_'+helperI2+'_'+helperJ2).className = 'hb';
    }
  }
  
}

function kp(e){
  if (down){
    var kC  = (window.event) ?    // MSIE or Firefox?
               event.keyCode : e.keyCode;
    var Esc = (window.event) ?   
              27 : e.DOM_VK_ESCAPE // MSIE : Firefox
    if(kC==Esc){
       down = 0;
       removeHelper();
    }
  }

}

var downX, downY;
var startX, startY, endX, endY;

function Div(X, Y) { return Math.floor(X/Y); }
function prepareHelper(x, y){
  var tablepos = $('#DominosaTable').offset();
  var relX = (x-tablepos.left) % 22;
  var relY = (y-tablepos.top) % 22;
  var vertical = Math.min( relX, 22 - relX ) > Math.min( relY, 22 - relY );

  var cellX = Div (x-tablepos.left, 22);
  var cellY = Div (y-tablepos.top , 22);

  if (vertical){
    if (relY < 10){
      // up
      if ((cellY > 0) && (cellY < puzzleH) && (cellX >= 0) && (cellX < puzzleW)){
        placeHelper(cellX, cellY - 1, cellX, cellY);
      }
    } else {
      // down
      if ((cellY >= 0) && (cellY < puzzleH - 1) && (cellX >= 0) && (cellX < puzzleW)){
        placeHelper(cellX, cellY, cellX, cellY + 1);
      }
    }
  } else {
    if (relX < 10){
      // left
      if ((cellX > 0) && (cellX < puzzleW) && (cellY >= 0) && (cellY < puzzleH)){
        placeHelper(cellX - 1, cellY, cellX, cellY);
      }
    } else {
      // right
      if ((cellX >= 0) && (cellX < puzzleW - 1) && (cellY >= 0) && (cellY < puzzleH)){
        placeHelper(cellX, cellY, cellX + 1, cellY);
      }
    }
  }
}
/*
function findDuplicates(){
  var i, j, br, n;
  for (i = 0; i < arrPlacedDominoes.length; i++){
    for (j = 0; j < arrPlacedDominoes[j].length; j++){
      if (arrPlacedDominoes[i][j].length > 1){
        for (br = 0; br < arrPlacedDominoes[i][j].length; br++){
          n = arrPlacedDominoes[i][j][br];
          
        }
      }
    }
  }
}
*/
function setAns(i, j, ans){
	var s = document.answerForm.ansV.value;
	var n = i * (1 * puzzleW) + (j * 1);
	var l = s.length;
	if (ans == 'n'){
	  var Direction = s.substr(n, 1);
	} else {
	  var Direction = ans;
	}
	s = s.substr(0, n) + ans + s.substr(n + 1, l);
	document.answerForm.ansV.value = s;
  statesV[i][j] = ans;
  
  /*
  if (Direction == 'n'){
    return;
  }
  var d1 = arrTask[i][j];
  if (Direction == 'h'){
    var d2 = arrTask[i][j+1];
  } else if (Direction == 'v'){
    //alert (i+1);
    var d2 = arrTask[i+1][j];
  }
  
  
  var mn = Math.min(d1, d2);
  var mx = Math.max(d1, d2);
  var tmpArr = arrPlacedDominoes[mn][mx];
  var action = 'nop';
  if (ans == 'n'){
    var tmpBr = 0;
    for (var br = 0; br < tmpArr.length; br++){
      if (tmpArr[br] != n){
        arrPlacedDominoes[mn][mx][tmpBr] = tmpArr[br];
        tmpBr++;
      }
    }
    if (arrPlacedDominoes[mn][mx].length == 1) action = 'setOK';
  } else {
    arrPlacedDominoes[mn][mx][tmpArr.length] = n;
    if (arrPlacedDominoes[mn][mx].length > 1) action = 'setERR';
  }
  if (action == 'setERR' || action == 'setOK'){
    alert(action);
  }
  
  var newC = 'b';
  var i1, j1, i2, j2;
  if (action == 'setERR') newC = 'e';
  if (action == 'setERR' || action == 'setOK'){
    for (var br = 0; br < arrPlacedDominoes[mn][mx].length; br++){
      Direction = s.substr(arrPlacedDominoes[mn][mx][br], 1);
      i1 = Div(n, puzzleW);
      j1 = n % puzzleW;
      if (Direction == 'v'){
        g('id_'+i1+'_'+j1).className = newC + 't';
        g('id_'+(i1+1)+'_'+j1).className = newC + 'b';
      } else {
        g('id_'+i1+'_'+j1).className = newC + 'l';
        g('id_'+i1+'_'+(j1+1)).className = newC + 'r';
      }
    }
    
    //
  }
  */
  //g('debug').innerHTML = document.answerForm.ansV.value + '-' + ans;
}
function alterBorder(i, j, vertical, unset){
	var s = document.answerForm.ansH.value;
	if (vertical){
	  var n = i * (1 * puzzleW - 1) + (j * 1);
	} else {
	  var n = i * (1 * puzzleW) + (j * 1) + (puzzleW - 1) * puzzleH;
	}
	var l = s.length;
	var currentBorder = s.substr(n,1);
	//alert(currentBorder);
	s = s.substr(0, n) + ((currentBorder == 'x') || unset ? 'n' : 'x') + s.substr(n + 1, l);
	document.answerForm.ansH.value = s;
	return currentBorder == 'n';
  //if (ans != 'n')
  //g('debug').innerHTML = document.answerForm.ansH.value;
}
function clearPieces(i, j){
  if (statesV[i][j] == 'h'){
    g('id_'+i+'_'+(j+1)).className = '';
    setAns(i, j+1, 'n');
  }
  if (statesV[i][j] == 'v'){
    g('id_'+(i+1)+'_'+(j)).className = '';
    setAns(i+1, j, 'n');
  }
  if (j > 0 && statesV[i][j-1] == 'h'){
    g('id_'+i+'_'+(j-1)).className = '';
    setAns(i, j-1, 'n');
  }
  if (i > 0 && statesV[i-1][j] == 'v'){
    g('id_'+(i-1)+'_'+(j)).className = '';
    setAns(i-1, j, 'n');
  }
}
function placePiece(){
  if (!helperI1 && !helperJ1 && !helperI2 && !helperJ2) return;
	var vertical = (helperI1 != helperI2);
	if (  
	  (vertical && (statesV[helperI1][helperJ1] == 'v') && (statesV[helperI2][helperJ2] == 'n')) ||
	  (!vertical && (statesV[helperI1][helperJ1] == 'h') && (statesV[helperI2][helperJ2] == 'n'))
	){
	  // removing
    g('id_'+helperI1+'_'+helperJ1).className = '';
    g('id_'+helperI2+'_'+helperJ2).className = '';
    setAns(helperI1, helperJ1, 'n');
    setAns(helperI2, helperJ2, 'n');
	} else {
	  if (!lastRightClick){
      // placing
      clearPieces(helperI1, helperJ1);
      clearPieces(helperI2, helperJ2);
  
      if (vertical){
        var ans = 'v';
        g('id_'+helperI1+'_'+helperJ1).className = 'bt';
        g('id_'+helperI2+'_'+helperJ2).className = 'bb';
        alterBorder(helperI1, helperJ1, false, true);
        setRedClass($('#id_'+helperI1+'_'+helperJ1+' div'), 'b', false);
        setRedClass($('#id_'+helperI2+'_'+helperJ2+' div'), 't', false);
      } else {
        var ans = 'h';
        g('id_'+helperI1+'_'+helperJ1).className = 'bl';
        g('id_'+helperI2+'_'+helperJ2).className = 'br';
        alterBorder(helperI1, helperJ1, true, true);
        setRedClass($('#id_'+helperI1+'_'+helperJ1+' div'), 'r', false);
        setRedClass($('#id_'+helperI2+'_'+helperJ2+' div'), 'l', false);
      }
      setAns(helperI1, helperJ1, ans);
      setAns(helperI2, helperJ2, 'n');
    }
  }
  if (lastRightClick){
    ///
    if (helperJ1 != helperJ2){
      var set = alterBorder(helperI1, helperJ1, true);
      setRedClass($('#id_'+helperI1+'_'+helperJ1+' div'), 'r', set);
      setRedClass($('#id_'+helperI2+'_'+helperJ2+' div'), 'l', set);
    }
    if (helperI1 != helperI2){
      var set = alterBorder(helperI1, helperJ1, false);
      setRedClass($('#id_'+helperI1+'_'+helperJ1+' div'), 'b', set);
      setRedClass($('#id_'+helperI2+'_'+helperJ2+' div'), 't', set);
    }

  }
  helperI1 = helperI2 = helperJ1 = helperJ2 = 0;
}

function d(e){
  down = 1;
  e.preventDefault();
	var rightclick = (e.which == 3 || e.ctrlKey || e.shiftKey || e.metaKey);
  lastRightClick = rightclick;
  //downX = e.pageX;
  //downY = e.pageY;
  //if (lastRightClick){
  //} else {
    prepareHelper(e.pageX, e.pageY);
  //}
}
function mv(e){
  if (down){
    //if (lastRightClick){
    //} else {
      prepareHelper(e.pageX, e.pageY);
    //}
  }
}
function u(e){
  if (down){
    removeHelper();
    placePiece();
  }
  down = 0;
}

function highlightNumber(){
  /*
  $(".select").each(function(i, selected){     
    selected.className = '';
  });
  */
  var val = $("#selectNumber").val();
  var valG = $("#selectNumberG").val();
  var kids;
  for (var i = 0; i < puzzleH; i++){
    for (var j = 0; j < puzzleW; j++){
      if (task[i][j] == val){
        document.getElementById('id_'+i+'_'+j).firstChild.firstChild.className = 'select';
        //$('#id_'+i+'_'+j).firstChild.firstChild.className = 'select';
      } else if (task[i][j] == valG){
        document.getElementById('id_'+i+'_'+j).firstChild.firstChild.className = 'selectG';
      } else {
        document.getElementById('id_'+i+'_'+j).firstChild.firstChild.className = '';
      }
    }
  }

}

function getstatus(s){
	var ar = new Array();
	ar = s.split('/');
	return ar[ar.length-1].charAt(2);
}
function getdirection(s){
	var ar = new Array();
	ar = s.split('_');
	return ar[0];
}
function getXY(s){
	var ar = new Array();
	ar = s.split('_');
	return new Array(ar[1], ar[2]);
}



 

var xh = new Image();
xh.src = '/dh.gif';
var xv = new Image();
xv.src = '/dv.gif';
var yh = new Image();
yh.src = '/dho.gif';
var yv = new Image();
yv.src = '/dvo.gif';


