var superWidth = document.getElementById("superposition").clientWidth - 20;
var superposition = d3.select("#superposition").append("svg")
                                    .attr("width", superWidth)
                                    .attr("height", 200);

function drawRect(view, thisElementWidth, start, end, startHeight, endHeight, width, col){

    var startQuad = xoffset + Math.ceil(start);
    var endQuad = startQuad + Math.ceil(end*thisElementWidth+1);

    var quadPoints = (startQuad) + " " + (startHeight + width/2) + ", "
                        + (startQuad) + " " + (startHeight - width/2) + ", "
                        + (endQuad) + " " + (endHeight - width/2) + ", "
                        + (endQuad) + " " + (endHeight + width/2);

    view.append("polygon")
        .attr("fill", col)
        .attr("points", quadPoints); 
}

// Function for drawing glyphs of secondary structures
// Input:
// view - d3 svg canvas
// n - order of the protein chain
// i - position in the notAlignedSS
// thisElementWidth - width of one element in this svg canvas
// start - start x position in svg canvas
// gap - number of protein elements that ss consists of
// startHeight - start y position
// endHeight - end y position
// col - colour
// ss - type of ss
function drawSSglyph(view, n, i, thisElementWidth, start, gap, startHeight, endHeight, col, ss) {

  var ssStart = start + xoffset;

  var length = Math.ceil(gap*thisElementWidth);
  var newLength = Math.ceil(Math.sqrt(Math.pow(length, 2) + Math.pow(endHeight-startHeight, 2)));
  var angleDeg = Math.atan2(endHeight - startHeight, gap*thisElementWidth) * 180 / Math.PI;
  var newColor = (highlighted[n] >= i-gap && highlighted[n] <= i) ? "#66FF00" : col;

  var height = startHeight;

  var size = (thisElementWidth+5 > 10) ? 10 : thisElementWidth+5;
  //different size for helixes
  if(ss === 'H') size = (thisElementWidth+9 > 20) ? 20 : thisElementWidth+9;

  var ssGroup = view.append("g")
                       .on("mouseover", function handleMouseOverSS(nn, ii){

                          var viewWidth = view.node().getBBox().width;

                          var detailText = "";
                          var firstIndex = alignToNotAlign[n][i-gap+1];
                          var xPos = ssStart + newLength/2;

                          var textGroup = view.append("g");

                          //First position
                          var lastOne = textGroup.append("text")
                              .attr("x", xPos)
                              .attr("y", startHeight-12)
                              .attr('text-anchor', 'center')
                              .attr('opacity', 0.5)
                              .attr("class", "myDetail")
                              .style("fill", "grey")
                              .text(firstIndex);
                          xPos += lastOne.node().getBBox().width;

                          //Sequence of amino acids
                          for (var index = firstIndex; index < firstIndex+gap; index++) {
                            // detailText += " " + aminoAcids[n][index];
                            var op = (index % 2 === 0) ? 0.5 : 1.0;
                            lastOne = textGroup.append("text")
                              .attr("x", xPos)
                              .attr("y", startHeight-12)
                              .attr('text-anchor', 'center')
                              .attr('opacity', op)
                              .attr("class", "myDetail")
                              .style("fill", col)
                              .text(aminoAcids[n][index]);

                            xPos += lastOne.node().getBBox().width;

                          }

                          //Last position
                          lastOne = textGroup.append("text")
                              .attr("x", xPos)
                              .attr("y", startHeight-12)
                              .attr('text-anchor', 'center')
                              .attr('opacity', 0.5)
                              .attr("class", "myDetail")
                              .style("fill", "grey")
                              .text(firstIndex + gap - 1);

                          //Left overlapping
                          if ((textGroup.node().getBBox().x - textGroup.node().getBBox().width / 2) > 0) {
                            textGroup.attr("transform", "translate(" + textGroup.node().getBBox().width / -2 + "," + 0 + ")");
                          } else {
                            textGroup.attr("transform", "translate(" + textGroup.node().getBBox().x * -1 + "," + 0 + ")");
                          }

                          //Right overlapping
                          if((textGroup.node().getBBox().width / 2 + textGroup.node().getBBox().x) > viewWidth) {
                            var totalShift = (textGroup.node().getBBox().width / -2) + (viewWidth - (textGroup.node().getBBox().width/2 + textGroup.node().getBBox().x));
                            textGroup.attr("transform", "translate(" + totalShift + "," + 0 + ")");
                          }

                        })
                       .on("mouseout", function handleMouseOutSS(nn, ii){
                          d3.selectAll(".myDetail").remove();
                        })
                       .on("click", function(){
                          highlighted[n] = (highlighted[n] === i) ? 9999 : i;
                          redrawD3();
                          (highlighted[n] === 9999) ? (resetViewerSelection(n)) : highlightPV(n, alignToNotAlign[n][i]);
                        });


  if(ss === 'E') drawArrow(ssGroup, size, newLength, ssStart, height, newColor, startHeight, endHeight, angleDeg);
  if(ss === 'H') drawHelix(ssGroup, size, newLength, ssStart, height, newColor, startHeight, endHeight, angleDeg);

}

function drawArrow(ssGroup, size, newLength, ssStart, height, newColor, startHeight, endHeight, angleDeg){

    var triangleLength = (newLength > size) ? size : newLength;

    ssGroup.append("rect")
        .attr("height", size)
        .attr("width", newLength - triangleLength + 2)
        .attr("x", ssStart)
        .attr("y", height-size/2)
        .style("fill", newColor);

    var trianglePoints = (ssStart + newLength) + " " + (height) + ", " 
            + (ssStart + newLength - triangleLength) + " " + (height + size) + ", " 
            + (ssStart + newLength - triangleLength) + " " + (height - size) ; 

    ssGroup.append("polygon")
              .attr("fill", newColor)
              .attr("points", trianglePoints);  

    var middle = (endHeight<startHeight) ? -((Math.abs(endHeight-startHeight))/2) : ((Math.abs(endHeight-startHeight))/2);

    ssGroup.attr("transform", "rotate("+angleDeg+"," + (ssStart+(length/2)) + "," + (startHeight+middle) + 
                    ") translate (0, " + (middle) + ")" );
}

function drawHelix(ssGroup, size, newLength, ssStart, height, newColor, startHeight, endHeight, angleDeg){
  
  var firstShade = (ssStart) + " " + (height - size/2) + ", "
                        + ((i+size/2>ssStart+newLength) ? ssStart+newLength : ssStart+size/2) + " " + (height - size/2) + ", "
                        + (ssStart) + " " + (height+size/2) + ", "
                        + (ssStart - size/4) + " " + (height + size/2) + ", "
                        + (ssStart - size/4) + " " + (height);

  ssGroup.append("polygon")
        .attr("fill", newColor)
        .attr("opacity", 0.3)
        .attr("points", firstShade);


  for (var i = ssStart; i < ssStart+newLength; i+=size) {
      var quadPoints = (i) + " " + (height - size/2) + ", "
                        + (i+size/2) + " " + (height - size/2) + ", "
                        + (i+size) + " " + (height + size/2) + ", "
                        + (i+size/2) + " " + (height + size/2);

      if (i+10 > ssStart+newLength) quadPoints = (i) + " " + (height - size/2) + ", "
                                                + (i+size/2) + " " + (height - size/2) + ", "
                                                + (i+3*size/4) + " " + (height) + ", "
                                                + (i+3*size/4) + " " + (height + size/2) + ", "
                                                + (i+size/2) + " " + (height+size/2);

  ssGroup.append("polygon")
          .attr("fill", newColor)
          .attr("points", quadPoints);    

  }

  for (var i = ssStart+size/2; i < ssStart+newLength; i+=size) {
      var quadPoints = (i) + " " + (height + size/2) + ", "
                        + (i+size/2) + " " + (height + size/2) + ", "
                        + (i+size) + " " + (height - size/2) + ", "
                        + (i+size/2) + " " + (height - size/2);

      if (i+10 > ssStart+newLength) quadPoints = (i) + " " + (height + size/2) + ", "
                                                + (i+size/2) + " " + (height + size/2) + ", "
                                                + (i+3*size/4) + " " + (height) + ", "
                                                + (i+3*size/4) + " " + (height - size/2) + ", "
                                                + (i+size/2) + " " + (height-size/2);

  ssGroup.append("polygon")
          .attr("fill", newColor)
          .attr("opacity", 0.5)
          .attr("points", quadPoints);    

  }

  var middle = (endHeight<startHeight) ? -((Math.abs(endHeight-startHeight))/2) : ((Math.abs(endHeight-startHeight))/2);

  ssGroup.attr("transform", "rotate("+angleDeg+"," + (ssStart+(length/2)) + "," + (startHeight+middle) + 
                  ") translate (0, " + (middle) + ")" );
}

function drawSuperposition(n){

  var startAA = globalZoom[0];
  var endAA = globalZoom[1];
  var thisElementWidth = (superWidth-100)/(endAA-startAA);

  var globalI = 0;
  var lastHeight = 0;

  for (var i = startAA; i < endAA - 1; i++) {
      var ss = alignedSS[n].charAt(i);
      var initHeight = 75 ;
      var endHeight = 75 ;

      var start = i;
      while (alignedSS[n].charAt(i+1) === ss) i++;
      var gap = i - start + 1;

      if(n!==reference && (ss == 'H' || ss == 'E')) {
        if(alignedSS[reference].charAt(start) == '-') {
          initHeight -= 15;
        } else {
          //console.log(atomDiffs[n][start]);
          initHeight -= (15 < atomDiffs[n][start])? 15 : atomDiffs[n][start];
        } 
        if(alignedSS[reference].charAt(i) == '-') {
          endHeight -= 15;
          lastHeight = endHeight;
        } else {
          endHeight -= (15 < atomDiffs[n][i]) ? 15 : atomDiffs[n][i];
          lastHeight = endHeight;
        }
      }

      if(n!==reference && ss == 'C') {
          if(lastHeight !== 0) initHeight = lastHeight;
          if (alignedSS[n].charAt(i+1) === 'H' || alignedSS[n].charAt(i+1) === 'E') {
            if(alignedSS[reference].charAt(i+1) == '-') {
              endHeight -= 15;
            } else {
              endHeight -= (15 < atomDiffs[n][i+1]) ? 15 : atomDiffs[n][i+1];
            }
          } else {
            lastHeight = 0;
          }
      }

      if(n!==reference && ss == '-') lastHeight = 0;

      if (ss === 'E') drawSSglyph(superposition, n, i, thisElementWidth, globalI, gap, initHeight, endHeight, colorMolecule[n], ss);
      if (ss === 'H') drawSSglyph(superposition, n, i, thisElementWidth, globalI, gap, initHeight, endHeight, colorMolecule[n], ss);
      if (ss === '-') drawRect(superposition, thisElementWidth, globalI,  gap, initHeight, endHeight, 3, "lightgray");
      if (ss === 'C') drawRect(superposition, thisElementWidth, globalI,  gap, initHeight, endHeight, 3, colorMolecule[n]);

      globalI += Math.round( gap * thisElementWidth);
  }

  addSelection(superposition, n, thisElementWidth, 45);

}