$(function() {
  var canvas = $('#canvasCLEM');
  var ctx = canvas[0].getContext("2d");

  $('#CLEMimg').on('change', function CLEMmap() { //画像を選択時に呼び出される

    if (window.File) { //FileAPIを未対応ブラウザではアラート

      var files = $('#CLEMimg')[0].files[0];
      var reader = new FileReader();
      var img = new Image();

      reader.onload = function(evt) {
        img.onload = function() {
          //  参考  https://qiita.com/PG0721/items/599ba2921b8339700fe3
          var imgAspect = img.width / img.height;
          ctx.clearRect(0, 0, 512, 512);
          if (imgAspect >= 1) { //画像が横長
            left = 0;
            width = ctx.canvas.width;
            height = ctx.canvas.height / imgAspect;
            to = (ctx.canvas.height - height) / 2;
          } else { //画像が縦長
            to = 0;
            width = ctx.canvas.width * imgAspect;
            height = ctx.canvas.height;
            left = (ctx.canvas.width - width) / 2;
          }
          ctx.drawImage(img, 0, 0, img.width, img.height, left, to, width, height); //画像をアスペクト比を維持して中心に表示
        }
        img.src = evt.target.result;
      }
      reader.readAsDataURL(files);
    } else {
      window.alert("本ブラウザではFile APIが使えません");
    }
  }); //END   CLEMmap()

  $('#setClemButton').on('click', function setClem() {
    var tbody = document.getElementById("listCoord");
    var rowlen = tbody.rows.length; //行数
    //      LM X Y EM X Y Mov Del
    //cells 0 1 2  3 4 5  6   7

    if (rowlen >= 2) {

      var LmVec = new Array();
      var EmVec = new Array();
      var rad = 0;
      for (var i = 0; i < (rowlen - 1); i++) {
        LmVec[i] = new Object();

        LmVec[i].x = tbody.rows[i+1].cells[1].innerText - tbody.rows[0].cells[1].innerText;
        LmVec[i].y = tbody.rows[i+1].cells[2].innerText - tbody.rows[0].cells[2].innerText;
        //  alert(LmVec[i].x+"  , "+LmVec[i].y);
        EmVec[i] = new Object();
        EmVec[i].x = tbody.rows[i+1].cells[4].innerText - tbody.rows[0].cells[4].innerText;
        EmVec[i].y = tbody.rows[i+1].cells[5].innerText - tbody.rows[0].cells[5].innerText;
        //  alert(EmVec[i].x+"  , "+EmVec[i].y);
        var dist = Math.sqrt(LmVec[i].x * LmVec[i].x + LmVec[i].y * LmVec[i].y) * Math.sqrt(EmVec[i].x * EmVec[i].x + EmVec[i].y * EmVec[i].y);
        if (dist == 0) {
          alert("座標をセットし直して下さい");
        } else {
          var cos = (LmVec[i].x * EmVec[i].x + LmVec[i].y * EmVec[i].y) / dist;
          var sin = (LmVec[i].x * EmVec[i].y - LmVec[i].y * EmVec[i].x) / dist;

          //alert("cos:"+cos+"   sin:"+sin);
          var rad1 = Math.acos(cos);
          var rad2 = Math.asin(sin);

          //alert("rad1:"+rad1+"   rad2:"+rad2);
          if (cos >= 0 && sin >= 0) { //0<rad<pi/2
            rad += (-1) * rad1;
          } else if (cos >= 0 && sin < 0) { //-2/pi<rad<0
            rad += (-1) * rad2;
          } else if (cos < 0 && sin >= 0) { //pi/2<rad<pi
            rad += (-1) * rad1;
          } else { // -pi<rad<-pi/2
            rad += rad1;
          }
        }
      }
      rad = rad / (rowlen - 1);
      alert(rad * 180 / Math.PI + " 度");

      ctx.clearRect(0, 0, 512, 512);
      ctx.translate(256, 256);
      ctx.rotate(-1 * rad);
      ctx.translate(-256, -256);
      $('#CLEMimg').change();
      /*for(i=0;i<rowlen;i++){
        var temp={x:0,y:0};
      temp.x=tbody.rows[i].cells[1].innerText*Math.cos(rad)-tbody.rows[i].cells[2].innerText*Math.sin(rad);
      temp.y=tbody.rows[i].cells[1].innerText*Math.sin(rad)+tbody.rows[i].cells[2].innerText*Math.cos(rad);
      temp.x=Math.round(temp.x);
      temp.y=Math.round(temp.y);
      tbody.rows[i].cells[1].innerHTML=temp.x;
      tbody.rows[i].cells[2].innerHTML=temp.y;
      alert(temp.x+"  ,  "+temp.y);
      }*/

    }
  }); //END setClem()

}); //END $(function(){


function calcClemCoord(event) { //CLEM画像のポインター位置の座標を返す

  //参考  https://lab.syncer.jp/Web/JavaScript/Snippet/12/
  var clickX = event.pageX;
  var clickY = event.pageY;

  // 要素の位置を取得
  var clientRect = document.getElementById("canvasCLEM").getBoundingClientRect();
  var positionX = clientRect.left + window.pageXOffset;
  var positionY = clientRect.top + window.pageYOffset;

  // 要素内におけるクリック位置を計算
  // 要素の中心を0にする
  var cod = new Object();
  cod.x = clickX - positionX - 255;
  cod.y = clickY - positionY - 255;
  return cod;
}
/*
document.getElementById("canvasSimplePhoto").addEventListener('mousemove', function( event ) {//EM画像にマウスオーバー時
  var coordinate=document.getElementById("EMcoordinate");
  var cod = calcEmCoord(event);
  coordinate.childNodes[0].data= "X:"+cod.x+"  ,  Y:"+cod.y;
 });
*/
document.getElementById("canvasCLEM").addEventListener('mousemove', function(event) { //CLEM画像にマウスオーバー時
  var coordinate = document.getElementById("CLEMcoordinate");
  var cod = calcClemCoord(event);
  coordinate.childNodes[0].data = "X:" + cod.x + "  ,  Y:" + cod.y;
});

function setLmCoordinate(innerTd) {

  var tr = innerTd.parentNode.parentNode; //tr
  tr.cells[0].innerHTML = '<input type="button" value="Set" onclick="cancelSetLmCoordinate(this)" style="background-color:red;" />'
  tr.cells[0].state = "on";

  document.getElementById("canvasCLEM").addEventListener('click', function(event) {
    if (tr.cells[0].state == "on") {
      var cod = calcClemCoord(event);
      tr.cells[1].innerHTML = cod.x;
      tr.cells[2].innerHTML = cod.y;
      tr.cells[0].innerHTML = '<input type="button" value="Set" onclick="setLmCoordinate(this)" />';
      tr.cells[0].state = "off";
    }
  });


}

function cancelSetLmCoordinate(innerTd) {
  var tr = innerTd.parentNode.parentNode; //tr
  tr.cells[0].innerHTML = '<input type="button" value="Set" onclick="setLmCoordinate(this)" />';
  tr.cells[0].state = "off";
}

document.getElementById("addList").addEventListener('click', function addList(event) {

  // tbody要素に指定したIDを取得し、変数「tbody」に代入
  var tbody = document.getElementById("listCoord");
  var row = tbody.insertRow(-1); //tr
  var cellLM0 = row.insertCell(-1); //td0
  cellLM0.state = "off";
  var cellLMX = row.insertCell(-1); //td1
  var cellLMY = row.insertCell(-1); //td2
  var cellEM0 = row.insertCell(-1); //td3
  var cellEMX = row.insertCell(-1); //td4
  var cellEMY = row.insertCell(-1); //td5
  var cellMoveButton = row.insertCell(-1); //td6
  var cellDelButton = row.insertCell(-1); //td7
  var SetLmButton = '<input type="button" value="Set" onclick="setLmCoordinate(this)" />';
  var DelButton = '<input type="button" value="Delete" onclick="deleteList(this)" />';
  var SetButton = '<input type="button" value="Set" onclick="setEmCoordinate(this)" />';
  var MoveButton = '<input type="button" value="Move" onclick="moveEmCoordinate(this)" />';
  cellLM0.innerHTML = SetLmButton;
  cellDelButton.innerHTML = DelButton;
  cellEM0.innerHTML = SetButton;
  cellMoveButton.innerHTML = MoveButton;
  //      LM X Y EM X Y Mov Del
  //cells 0 1 2  3 4 5  6   7
});

function deleteList(innerTd) {
  var tr = innerTd.parentNode.parentNode; //tr
  tr.parentNode.deleteRow(tr.sectionRowIndex);
}

function setEmCoordinate(innerTd) {
  var movexr = $("#movex").val();
  var moveyr = $("#movey").val();
  var tr = innerTd.parentNode.parentNode; //tr
  cellEMX = tr.cells[4];
  cellEMY = tr.cells[5];
  cellEMX.innerHTML = parseInt(movexr);
  cellEMY.innerHTML = parseInt(moveyr);
}

function moveEmCoordinate(innerTd) {
  var tbody = document.getElementById("listCoord");
  var rowlen = tbody.rows.length //行数
  var s = 0;
  var t = 0;
  //      LM X Y EM X Y Mov Del
  //cells 0 1 2  3 4 5  6   7

  if (rowlen >= 3) {
    var target = {
      x: innerTd.parentNode.parentNode.cells[1].innerText - tbody.rows[0].cells[1].innerText,
      y: innerTd.parentNode.parentNode.cells[2].innerText -tbody.rows[0].cells[2].innerText
    };
    var goal = {
      x: 0,
      y: 0
    };
    var LmVec = new Array();
    var EmVec = new Array();
    var rad = 0;

    alert("init  x:" + goal.x + "  ,y:" + goal.y);
    for (var i = 0; i < (rowlen - 2); i++) {
      LmVec[i] = new Object();

      LmVec[i].x = tbody.rows[i+1].cells[1].innerText - tbody.rows[0].cells[1].innerText;
      LmVec[i].y = tbody.rows[i+1].cells[2].innerText - tbody.rows[0].cells[2].innerText;
      //  alert(LmVec[i].x+"  , "+LmVec[i].y);
      EmVec[i] = new Object();
      EmVec[i].x = tbody.rows[i+1].cells[4].innerText - tbody.rows[0].cells[4].innerText;
      EmVec[i].y = tbody.rows[i+1].cells[5].innerText - tbody.rows[0].cells[5].innerText;
    }

    //target.x=LmVec.x*s+LmVec.y*t   p=ax+by
    //target.y=EmVec.x*s+EmVec.y*t   q=cx+dy
    for (var i = 0; i < (rowlen - 3); i++) { //解法：クラメルの公式

      alert("a:"+LmVec[0].x +"   d:"+ LmVec[i + 1].y +"   b:"+ LmVec[0].y +"   c:"+LmVec[i + 1].x);
      var Det = LmVec[0].x * LmVec[i + 1].y - LmVec[0].y * LmVec[i + 1].x; //ad-bc
      alert("det:" + Det);
      if (Det == 0) {
        //解が一位に定まらない
      } else {
        alert("target.x:"+target.x+"target.y:"+target.y);
        var s = (target.x * LmVec[i + 1].y - LmVec[0].y * target.y) / Det;  //ed-fb/det
        var t = (LmVec[0].x * target.y - target.x * LmVec[i + 1].x) / Det;  //af-ec/det
        alert("s:" + s + "  ,t:" + t);
        goal.x += s * EmVec[0].x + t * EmVec[i + 1].x;
        goal.y += s * EmVec[0].y + t * EmVec[i + 1].y;
      }
    }



    goal.x = goal.x / (rowlen - 3);
    goal.y = goal.y / (rowlen - 3);

    alert("x:" + goal.x + "  ,y:" + goal.y+"   rowlen:"+(rowlen-3));
    alert("x0:" +tbody.rows[0].cells[4].innerText+ "  ,y0:" + tbody.rows[0].cells[5].innerText);
    goal.x=goal.x+parseInt(tbody.rows[0].cells[4].innerText);
    goal.y=goal.y+parseInt(tbody.rows[0].cells[5].innerText);
    goal.x = Math.round(goal.x);
    goal.y = Math.round(goal.y);
    alert("x:" + goal.x + "  ,y:" + goal.y+"   rowlen:"+(rowlen-3));

    var movexr = $("#movex").val();
    var moveyr = $("#movey").val();
    var movezr = $("#movez").val();
    console.log("movex="+movexr);
    console.log("movey="+moveyr);
    movexr = goal.x;
    moveyr = goal.y;
    innerTd.parentNode.parentNode.cells[4].innerHTML=goal.x;
    innerTd.parentNode.parentNode.cells[5].innerHTML=goal.y;
    $("#movex").val(String(movexr));
    $("#movey").val(String(moveyr));

    $.ajax({
      type:"GET",
      url:"http://" +UrlElement['sendIpAddress']+
      ":"+UrlElement['sendPortNumber']+"/"+UrlElement['sendManufacturer']+
      "/set/stagea?x="+encodeURIComponent(movexr)+
      "&y="+encodeURIComponent(moveyr)+
      "&z="+encodeURIComponent(movezr)+
      "&a="+encodeURIComponent(movezr),
      success: function(data){
        console.log(data);//string型
      }

    });

  } else {
    alert("LM座標を3つ、EM座標を2つ以上指定して下さい");
  }
} // END moveEmCoordinate(innerTd);


//var txt=document.createTextNode("X:"+cod.x+"  ,  Y:"+cod.y);
//first.appendChild(txt);
//coordinate.removeChild();
//  var txt=document.createTextNode();
//  coordinate.appendChild(txt);
