var width = 30
var height = 34
var colour = "b"
var bodyClick = 1
var td = 0; //triangle direction. right = 0, left = 1;
var clicks = new Array()
var index = 0
var splashState = 1
var swatchOffset = 310
var swatchPath = "plain/"

function checkTriangle(a, b, c, p) { //checks a triangle to see if p is within it


  var v0 = [c[0] - a[0], c[1] - a[1]];
  var v1 = [b[0] - a[0], b[1] - a[1]];
  var v2 = [p[0] - a[0], p[1] - a[1]];

  var d00 = dot(v0, v0);
  var d01 = dot(v0, v1);
  var d02 = dot(v0, v2);
  var d11 = dot(v1, v1);
  var d12 = dot(v1, v2);

  var dots = (d00 * d11 - d01 * d01);

  if (dots !== 0) {
    var invDenom = 1.0 / (dots);
    var u = (d11 * d02 - d01 * d12) * invDenom;
    var v = (d00 * d12 - d01 * d02) * invDenom;

    if ((u > 0) && (v > 0) && (u + v < 1)) {
      return true;
    }
  }
  return false;
}

function storeClick(str) {

  clicks[index] = new Array( str, "" + td, "" + colour );
  index++;

}

function dot(a, b) { //computes the dot product of a and b
  var ans = 0.0;
  for(var i = 0; i < a.length; i++) {
    ans = ans + a[i] * b[i];
  }
  return ans;
}

function keyHandler(evt) { //handles key presses

  if (evt.keyCode==90) {
    colour = "b";
  } else if (evt.keyCode==88) {
    colour = "dg";
  } else if (evt.keyCode==67) {
    colour = "lg";
  } else if (evt.keyCode==86) {
    colour = "w";
  }
  redrawMenu();
}

function menuClick() { //tells the clickHandler not to draw a triangle while you click on a menu
  bodyClick = 0;
}

function windowHeight() {

  var myHeight = 0
  if( typeof( window.innerHeight ) == 'number' ) {
    //Non-IE
    myHeight = window.innerHeight
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myHeight = document.documentElement.clientHeight
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myHeight = document.body.clientHeight
  }
  return myHeight
}
  
function windowWidth() {

  var myWidth = 0
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth
    //myHeight = window.innerHeight
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth
    //myHeight = document.documentElement.clientHeight
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth
    //myHeight = document.body.clientHeight
  }
  return myWidth
}

function validate(str) {

  var objRegExp =  /(^[a-z]([a-z_\.]*)@([a-z_\.]*)([.][a-z]{3})$)|(^[a-z]([a-z_\.]*)@([a-z_\.]*)(\.[a-z]{3})(\.[a-z]{2})*$)/i
  
  return objRegExp.test(str)
}

function refresh() {

  bodyClick = 0
  var answer = confirm("Are you sure you want to start a new drawing?")
  if(answer){
    window.location.reload(false);
  }
}

function dragOn() {

  var swatch = document.all ? document.all["swatch"] : document.getElementById("swatch")
  var selector = document.all ? document.all["selector"] : document.getElementById("selector")
  Drag.init(swatch);
  Drag.init(selector);
  swatch.onDrag = function(x, y) { drawSelector(x, y); swatch.style.opacity = ".5" }
  selector.onDrag = function(x, y) { updateSwatch(x, y); selector.style.opacity = ".5" }
  swatch.onDragEnd = function(x, y) { swatch.style.opacity = ".85" }
  selector.onDragEnd = function(x, y) { selector.style.opacity = "1" }
}

function splashClick(splash) { //tells the clickHandler not to draw a triangle while you click on a menu
  bodyClick = 0
  splash.parentNode.removeChild(splash)
  dragOn()
  removeBlack()
  splashState = 0
}

function removeSaveLoad() {
  document.saveLoad.innerHTML = ""
  splashState = 0
}
function drawBlack() {
  splashState = 1
  document.getElementById("fullSize").style.visibility = "visible"
}
function removeBlack() {
  document.getElementById("fullSize").style.visibility = "hidden"
  splashState = 0
}

function saveloadClick(evt, obj) {

  bodyClick = 0
  var x = mouseX(evt)
  var y = mouseY(evt)
  var offsetY = parseInt(obj.style.top)
  var offsetX = parseInt(obj.style.left)
  if (y < 52 + offsetY) {
    if (x < 52 + offsetX) {
      obj.parentNode.removeChild(obj)
      //dragOn()
      removeSaveLoad()
      removeBlack()
    }
  } else if (y > 292 + offsetY) {
    if (y < 343 + offsetY) {
      if (x < 240 + offsetX) {
        if (x > 162 + offsetX) {
	  loadImage()
	}
      } else if (x > 553 + offsetX) {
        if (x < 630 + offsetX) {
          saveImage()
	}
      }
    }
  }
}

function drawHelp() {

  splashState = 1;
  var menu = document.all ? document.all["menu"] : document.getElementById("menu")
  menu.innerHTML += "<img id=\"help\" style=\"z-index: 3; visibility: hidden; position: absolute;\" src=\"help.png\" onclick=\"splashClick(this)\">"

  var help = document.getElementById("help")
 
  var div = document.getElementById("fullSize")
 
  help.style.top = 43;
  help.style.left = div.scrollWidth/2 - 339;
  help.style.visibility = "visible"
  div.style.visibility = "visible"
}

function drawSave() {
  splashState = 1
  var div = document.getElementById("fullSize")

  var saveLoad = document.saveLoad;
  //var saveLoad = document.getElementById("saveLoad")
  saveLoad.innerHTML += "<img id=\"save\" style=\"z-index: 3; position: absolute;\" src=\"save.png\" onclick=\"saveloadClick(event, this)\">"
  saveLoad.innerHTML += "<input id=\"lName\" type=\"text\" style=\"background-color: #FBB03B; position: absolute; z-index:4; width:183; height:29\" />"
  saveLoad.innerHTML += "<input id=\"lEmail\" type=\"text\" style=\"background-color: #FBB03B; position: absolute; z-index:4; width:183; height:29\" />"
  saveLoad.innerHTML += "<input id=\"sName\" type=\"text\" style=\"background-color: #FFFFFF; position: absolute; z-index:4; width:183; height:29\" />"
  saveLoad.innerHTML += "<input id=\"sEmail\" type=\"text\" style=\"background-color: #FFFFFF; position: absolute; z-index:4; width:183; height:29\" />"
  //var save = document.saveLoad.save
  var save = document.getElementById("save")
  var lName = document.getElementById("lName")
  var sName = document.getElementById("sName")
  var lEmail = document.getElementById("lEmail")
  var sEmail = document.getElementById("sEmail")
  var fullSize = windowWidth()
  var fullHeight = windowHeight()
  var saveTop = fullHeight/2 - 200;
  //save.style.top = 70
  save.style.top = saveTop
  //save.style.left = div.scrollWidth/2 - 395
  save.style.left = fullSize/2 - 395
  
  lName.style.top = saveTop + 220
  //lName.style.left = div.scrollWidth/2 - 230
  lName.style.left = fullSize/2 - 230
  sName.style.top = saveTop + 221
  //sName.style.left = div.scrollWidth/2 + 158
  sName.style.left = fullSize/2 + 158
  lEmail.style.top = saveTop + 255
  //lEmail.style.left = div.scrollWidth/2 - 230
  lEmail.style.left = fullSize/2 - 230
  sEmail.style.top = saveTop + 256
  //sEmail.style.left = div.scrollWidth/2 + 158
  sEmail.style.left = fullSize/2 + 158
  //div.style.height  = screen.height
  //div.style.width  = screen.width
  div.style.visibility = "visible"
  splashState = 1
}

function clickHandler(evt) { //event handlder

    var mx = mouseX(evt);
    var my = mouseY(evt);
    if (splashState == 0) {
      if (bodyClick == 1) {
        drawer(mx, my) 
        storeClick(mx + "," + my);
      } else {
        bodyClick = 1;    
        swatchClick(my, mx);
      }
      redrawMenu();
    }
}

function changeSwatch() {
  drawBlack()
  saveClick()
  loadState(document.form.session.value)
  redrawMenu()
}

function swatchClick(y, x) { //handles clicking on a swatch

  var swatch = document.getElementById("swatch");
  var offsetY = parseInt(swatch.style.top);
  var offsetX = parseInt(swatch.style.left);
  if (x < offsetX) {
    return;
  }
  if (y < 89 + offsetY) {
    colour = "b";
  } else if (y < 156 + offsetY) {
    colour = "dg";
  } else if (y < 223 + offsetY) {
    colour = "lg";
  } else if (y < 290 + offsetY) {
    colour = "w";
  } else if (y < 336 + offsetY) {
    if (y >  300 + offsetY) {
      if((x > 25 + offsetX) && (x < 60 + offsetX)) {
        swatchPath = "plain/"
        changeSwatch()
      }
      if((x >= 60 + offsetX) && (x < 95 + offsetX)) {
        swatchPath = "wood/"
        changeSwatch()
      }
      if((x >= 95 + offsetX) && (x < 130 + offsetX)) {
        swatchPath = "primary/"
        changeSwatch()
      }
      if((x >= 130 + offsetX) && (x < 155 + offsetX)) {
        swatchPath = "sherbert/"
        changeSwatch()
      }
    }
  } else if (y < 382 + offsetY) {
    if (y > 342 + offsetY) {
      if ((x > 20 + offsetX) && (x < 64 + offsetX)) {
        drawSave();
      } else if ((x > 73 + offsetX) && (x < 113 + offsetX)) {
        drawHelp();
      }
    }
  }
}

function drawer(x, y) { //draws the triangles (top level)

  var x1, x2, y1, y2, cd;
  cd = 0; //column direction
  x1 = 0;
  y1 = 0;

  for (var i = 1; i*width < x; i++) {
    x1 = (i)* width;
    if ((i % 2) === 0) {
      cd = 0;
    } else {
      cd = 1;
    }
  }
  x2 = x1 + width;
  for (i = 1; i*height < y; i++) {
    y1 = (i)* height;
  }
  y2 = y1 + height;

 
  var p1 = [x1, y1];
  var p2 = [x2 + 1, y1];
  var p3 = [x2, y1 + (height/2)];
  var p4 = [x1, y2];
  var p5 = [x2 + 1, y2];

  var p6 = [x2, y1 - (height/2)];
  var p7 = [x2, y2 + (height/2)];

  if (cd == 0) {
    if (checkTriangle(p1, p3, p4, [x, y])) {
      td = 0;
      drawTriangle(p1,"r");
    } else if (checkTriangle(p1, p2, p3, [x, y])) {
      td = 1;
      p6 = [x1 - 1, y1 - (height/2)];
      drawTriangle(p6,"l");
    } else {
      td = 1;
      p3 = [x1 - 1, y1 + (height/2)];
      drawTriangle(p3,"l");
    }
  } 
  if (cd == 1) {
    p3 = [x1, y1 + (height/2)];
    p6 = [x1, y1 - (height/2)];
    p7 = [x1, y2 + (height/2)];

    if (checkTriangle(p2, p3, p5, [x, y])) {
      td = 1;
      p1 = [x1 - 1, y1];
      drawTriangle(p1,"l");
    } else if (checkTriangle(p1, p2, p3, [x, y])) {
      td = 0;
      drawTriangle(p6,"r");
    } else {
      td = 0;
      drawTriangle(p3,"r");
    }
  } 

}

function drawTriangle(p1, d) { //should be replaced by placeGif
  
  placeGif(p1[0], p1[1], swatchPath + "" + colour + "" + d + ".png");

}

function redrawMenu() { //needs updating, redraws the selector around the swatch
  var swatch = document.getElementById("swatch");
  swatch.src = swatchPath + "gui.png"
  swatchX = swatch.style.left;
  swatchY = swatch.style.top;
  drawSelector(parseInt(swatchX), parseInt(swatchY));
  
}

function updateSwatch (sx ,sy) { //redraws the swatch based on the selector coordinates (sx, sy)
  var swatch = document.getElementById("swatch");
  x = getSwatchX(sx);
  y = getSwatchY(sy);
  swatch.style.top = y;
  moveObject(x, y, swatch);

}

function moveObject(x, y, obj) {
  obj.style.left = x;
  obj.style.top = y;

}

function getSelectorX(x) { //x is swatch.style.left
  return x;
}

function getSwatchX(x) { //x is selector.style.left
  sx = x;
  return sx
}

function getSwatchY(y) { //y is selector.style.top
  if (colour == "b") {
    sy = y + 67;
  } else if (colour == "dg") {
    sy = y;
  } else if (colour == "lg") {
    sy = y - 67;
  } else {
    sy = y - 134;
  }
  return sy;
}

function getSelectorY(y) { //y is swatch.style.top
  if (colour == "b") {
    y = parseInt(y);
  } else if (colour == "dg") {
    y = parseInt(y) + 67;
  } else if (colour == "lg") {
    y = parseInt(y) + 134;
  } else {
    y = parseInt(y) + 201;
  }
  return y;
}


function drawSelector(swatchX, swatchY) {

  if (document.getElementById("selector") !== null) {
    obj = document.getElementById("selector");
  }
  x = getSelectorX(swatchX);
  y = getSelectorY(swatchY);

  moveObject(x, y, obj)
}

function cycleColour() {
  if (colour == "b") {
    colour = "lg";
  } else if (colour == "lg") {
    colour = "dg";
  } else if (colour == "dg") {
    colour = "w";
  } else {
    colour = "b";
  }
}

function placeGif(x, y, img) {


  if (document.getElementById("" + x + "" + y) !== null) {
    obj = document.getElementById("" + x + "" + y);
    if(colour == "w") {
      obj.parentNode.removeChild(obj);
    } else {
      obj.src = img
    }
  } else if (colour != "w") {
    if(document.getElementById(x) == null) {
      document.getElementById("testSpan").innerHTML += "<span id=\"" + x + "\"></span>"
    }
    document.getElementById(x).innerHTML += "<img id=\"" + x + "" + y + "\" style=\"z-index: 0; left: " + x + "px; top: " + y + "px; position: absolute\" src=\"" +img+ "\">";
  }
/*
  if (document.getElementById("" + x + "" + y) !== null) {
    obj = document.getElementById("" + x + "" + y);
    obj.parentNode.removeChild(obj);
  }
  if (colour != "w") {
    document.getElementById("testSpan").innerHTML += "<img id=\"" + x + "" + y + "\" style=\"z-index: 0; left: " + x + "px; top: " + y + "px; position: absolute\" src=\"" +img+ "\">";
  }
*/
}

function mouseX(evt) {
  if (evt.pageX) return evt.pageX;
  else if (evt.clientX)
    return evt.clientX + (document.documentElement.scrollLeft ?
    document.documentElement.scrollLeft :
    document.body.scrollLeft);
  else return null;
}

function mouseY(evt) {
  if (evt.pageY) return evt.pageY;
  else if (evt.clientY)
    return evt.clientY + (document.documentElement.scrollTop ?
    document.documentElement.scrollTop :
    document.body.scrollTop);  
  else return null;
}
