var MAX_ACCESS_SCALE_FACTOR = 0.3;

var MAP;
var LAST_CLICKED_MAX_ACCESS_PART;
var LAST_CLICKED_ATTACHMENT_POINT;

var heightLabels = new Array();
var showHeightLabels = false;
var heightTints = new Array();
var showHeightTints = false;
var heightKeys = new Array();
var legs = new Array();
var showLegs = false;
var autoAddedRails = new Array();

var toolTipText;
var showTooltip = false;
var showRemoveButton = false;

var height20Tint = "rgba(0,31,63,0.7)";
var height30Tint = "rgba(0,116,217,0.7)";
var height40Tint = "rgba(127,219,255,0.7)";
var height50Tint = "rgba(57,204,204,0.7)";
var height60Tint = "rgba(61,153,112,0.7)";
var height70Tint = "rgba(46,204,64,0.7)";
var height80Tint = "rgba(1,255,112,0.7)";
var height90Tint = "rgba(255,220,0,0.7)";
var height100Tint = "rgba(255,133,27,0.7)";
var height110Tint = "rgba(255,65,54,0.7)";

function MaxPart(data, attachmentPoint) {
  var container = new createjs.Container();
  if(attachmentPoint == null){
    container.partData = data;
    container.name = id;
    parts.push(container.name);
    id++;
    return container;
  }
  container.hasLegs = false;
  container.partData = data;
  container.noParent = false;
  container.mountPoint = attachmentPoint;
  container.parentPart = attachmentPoint.parent;
  attachmentPoint.filled = true;
  attachmentPoint.parent.attachmentSlotsUsed++;
  container.startingHeight = attachmentPoint.parent.height;
  container.attachmentSlotsUsed = 0;
  var attachmentPointMod = new createjs.Point(0,0);
  switch(attachmentPoint.rotOffset){
    case 0:
      attachmentPointMod = new createjs.Point(data.spriteAnchorOffset.x, data.spriteAnchorOffset.y);
      break;
    case 90:
      attachmentPointMod = new createjs.Point(-data.spriteAnchorOffset.y, data.spriteAnchorOffset.x);
      break;
    case -90:
      attachmentPointMod = new createjs.Point(data.spriteAnchorOffset.y, data.spriteAnchorOffset.x);
      break;
    case 180:
      attachmentPointMod = new createjs.Point(data.spriteAnchorOffset.x, -data.spriteAnchorOffset.y);
      break;
    default:
      break;
  }
  container.x = (container.parentPart.x/MAX_ACCESS_SCALE_FACTOR+attachmentPoint.x+attachmentPointMod.x)*MAX_ACCESS_SCALE_FACTOR;
  container.y = (container.parentPart.y/MAX_ACCESS_SCALE_FACTOR+attachmentPoint.y+attachmentPointMod.y)*MAX_ACCESS_SCALE_FACTOR;
  container.coordinates = attachmentPoint.coordinates;

  var sprite = new createjs.Bitmap(data.sprite);
  var spriteButtonHelper = new createjs.ButtonHelper(sprite);

  sprite.addEventListener("click", maxHandlePartClicked);
  sprite.addEventListener("mouseover", maxHandleMouseOver);
  sprite.addEventListener("mouseout", maxHandleMouseOut);
  sprite.name = container.name = id;
  id++;

  container.addChild(sprite);

  var center = new createjs.Shape();
  center.name = "CENTER";
  container.addChild(center);
  container.attachmentSlots = new Array();
  container.attachmentSlotIndices = new Array();
  var count=0;
  for(var i=0; i<data.attachmentSlots;i++) {
    if(data.platform || (i==0 && attachmentPoint.rotOffset == 0) || (i==1 && attachmentPoint.rotOffset == -90) || (i==2 && attachmentPoint.rotOffset == 90) || (i==3 && attachmentPoint.rotOffset ==180)){
      var f = new createjs.Shape();
      f.name = i;
      f.graphics.beginFill("#fff").setStrokeStyle(8,"round").beginStroke("rgba(255,192,0,1)").drawRect(-146,73,293,73);
      f.x = container.partData.attachmentPoints[i].x;
      f.y = container.partData.attachmentPoints[i].y;
      f.coordinates = new createjs.Point(container.partData.attachmentCoordinates[i].x + container.coordinates.x, container.partData.attachmentCoordinates[i].y + container.coordinates.y);
      f.visible = false;
      f.filled = false;
      switch(i){
        case 0:
          f.rotOffset = data.platform ? 0 : 0;
          break;
        case 1:
          f.rotOffset = data.platform ? -90 : 0;
          break;
        case 2:
          f.rotOffset = data.platform ? 90 : 0;
          break;
        case 3:
          f.rotOffset = data.platform ? 180 : 0;
          break;
        default:
        break;
      }
      if(data.ladder)
        f.rotation = f.rotOffset + attachmentPoint.rotOffset;
      else
        f.rotation = f.rotOffset;
      f.railsOnly = false;
      container.addChild(f);
      container.attachmentSlots[count] = f;
      var attachmentPointButtonHelper = new createjs.ButtonHelper(f);
      f.addEventListener("click", attachmentPointClicked);
      f.addEventListener("mouseover", maxHandleMouseOverAttachmentPoint);
      f.addEventListener("mouseout", maxHandleMouseOutAttachmentPoint);
      count++;
      container.attachmentSlotIndices.push(i);
    }
  }
  container.attachmentCount = count;

  var p = new createjs.Shape();
  p.name = "CONNECTOR";
  p.x = container.partData.anchorPoint.x;
  p.y = container.partData.anchorPoint.y;
  container.addChild(p);
  sprite.regX = data.bitmapCenter.x;
  sprite.regY = data.bitmapCenter.y;
  parts.push(sprite.name);
  container.highlight = new createjs.Shape();
  container.highlight.graphics.beginFill("rgba(255,192,0,0.8)").drawRect(-container.partData.bitmapCenter.x, -container.partData.bitmapCenter.y, 2*container.partData.bitmapCenter.x, 2*container.partData.bitmapCenter.y);
  container.addChild(container.highlight);
  container.highlight.visible = false;
  container.highlight.mouseEnabled = false;
  container.height = container.startingHeight + container.partData.heightMod;
  if(container.height != 0 && !container.partData.platform){
    if(container.partData.heightMod < 0)
      container.height += 10;
    else
      container.height -= 10;
  }
  if(data.platform){
    var heightText = new createjs.Text(container.height+"\"", "100px sans-serif", "#202020");
    heightText.x = -100;
    heightText.y = -100;
    heightText.visible = showHeightLabels;
    container.addChild(heightText);
    heightLabels.push(heightText);
    var heightTint = new createjs.Shape();
    switch(container.height){
      case 20:
        heightTint.graphics.beginFill(height20Tint).drawRect(-146,-146,293,293);
        break;
      case 30:
        heightTint.graphics.beginFill(height30Tint).drawRect(-146,-146,293,293);
        break;
      case 40:
        heightTint.graphics.beginFill(height40Tint).drawRect(-146,-146,293,293);
        break;
      case 50:
        heightTint.graphics.beginFill(height50Tint).drawRect(-146,-146,293,293);
        break;
      case 60:
        heightTint.graphics.beginFill(height60Tint).drawRect(-146,-146,293,293);
        break;
      case 70:
        heightTint.graphics.beginFill(height70Tint).drawRect(-146,-146,293,293);
        break;
      case 80:
        heightTint.graphics.beginFill(height80Tint).drawRect(-146,-146,293,293);
        break;
      case 90:
        heightTint.graphics.beginFill(height90Tint).drawRect(-146,-146,293,293);
        break;
      case 100:
        heightTint.graphics.beginFill(height100Tint).drawRect(-146,-146,293,293);
        break;
      case 110:
        heightTint.graphics.beginFill(height110Tint).drawRect(-146,-146,293,293);
        break;
      default:
        break;
    }
    container.addChild(heightTint);
    heightTint.mouseEnabled = false;
    heightTint.visible = showHeightTints;
    heightTints.push(heightTint);
  }
  else {
    container.highlight.rotation = sprite.rotation = attachmentPoint.rotOffset;
  }
  switch(attachmentPoint.rotOffset){
    case 0:
      for(var x=0;x<data.gridSize.x;x++){
        for(var y=0;y<data.gridSize.y;y++){
          if(y == 0){
            MAP[container.coordinates.x+x][container.coordinates.y-y][4].y = container.partData.length;
          }
          MAP[container.coordinates.x+x][container.coordinates.y-y][4].x = container.partData.width;
          MAP[container.coordinates.x+x][container.coordinates.y-y][0] = container.height;
          if(data.platform)
            MAP[container.coordinates.x+x][container.coordinates.y+y][1] = "P";
          if(data.ladder)
            MAP[container.coordinates.x+x][container.coordinates.y-y][1] = "L";
        }
      }
      break;
    case -90:
      for(var x=0;x<data.gridSize.x;x++){
        for(var y=0;y<data.gridSize.y;y++){
          if(y == 0){
            MAP[container.coordinates.x-y][container.coordinates.y-x][4].x = container.partData.length;
          }
          MAP[container.coordinates.x-y][container.coordinates.y-x][4].y = container.partData.width;
          MAP[container.coordinates.x-y][container.coordinates.y-x][0] = container.height;
          if(data.platform)
            MAP[container.coordinates.x-y][container.coordinates.y-x][1] = "P";
          if(data.ladder)
            MAP[container.coordinates.x-y][container.coordinates.y-x][1] = "L";
        }
      }
      break;
    case 180:
      for(var x=0;x<data.gridSize.x;x++){
        for(var y=0;y<data.gridSize.y;y++){
          if(y == 0){
            MAP[container.coordinates.x+x][container.coordinates.y+y][4].y = container.partData.length;
          }
          MAP[container.coordinates.x+x][container.coordinates.y+y][4].x = container.partData.width;
          MAP[container.coordinates.x+x][container.coordinates.y+y][0] = container.height;
          if(data.platform)
            MAP[container.coordinates.x+x][container.coordinates.y+y][1] = "P";
          if(data.ladder)
            MAP[container.coordinates.x+x][container.coordinates.y+y][1] = "L";
        }
      }
      break;
    case 90:
      for(var x=0;x<data.gridSize.x;x++){
        for(var y=0;y<data.gridSize.y;y++){
          if(y == 0){
            MAP[container.coordinates.x+y][container.coordinates.y-x][4].x = container.partData.length;
          }
          MAP[container.coordinates.x+y][container.coordinates.y-x][4].y = container.partData.width;
          MAP[container.coordinates.x+y][container.coordinates.y-x][0] = container.height;
          if(data.platform)
            MAP[container.coordinates.x+y][container.coordinates.y-x][1] = "P";
          if(data.ladder)
            MAP[container.coordinates.x+y][container.coordinates.y-x][1] = "L";
        }
      }
      break;
  }
  if(data.ladder)
  {
    startingText = new createjs.Text(container.startingHeight+"\"", "40px sans-serif", "#e17a0f");
    startingText.x = data.startTextPosition.x;
    startingText.y = data.startTextPosition.y;
    endText = new createjs.Text(container.height+"\"", "40px sans-serif", "#e17a0f");
    startingText.textAlign = "center";
    directionText = new createjs.Text("", "60px sans-serif", "#e17a0f");
    if(data.heightMod> 0)
      directionText.text = "UP";
    else{
      directionText.text = "DOWN";
      directionText.color = "#1e85f0";
      endText.color = "#1e85f0";
      startingText.color = "#1e85f0";
    }
    directionText.textAlign = "center";

    directionText.x = data.directionTextPosition.x;
    directionText.y = data.directionTextPosition.y;

    endText.x = data.endTextPosition.x;
    endText.y = data.endTextPosition.y;
    endText.textAlign = "center";
    var textContainer = new createjs.Container();
    textContainer.addChild(startingText);
    textContainer.addChild(endText);
    textContainer.addChild(directionText);
    container.addChild(textContainer);
    textContainer.rotation = sprite.rotation;
    if(sprite.rotation == 180){
      startingText.rotation = 180;
      startingText.y += 50;
      endText.y += 50;
      endText.rotation = 180;
      directionText.rotation = 180;
    }
    if(container.height == 0){
      MAP[container.coordinates.x][container.coordinates.y][3] = container.height - data.heightMod;
      switch(attachmentPoint.rotOffset){
      case 0:
        MAP[container.coordinates.x][container.coordinates.y][2] = 3;
        break;
      case -90:
        MAP[container.coordinates.x][container.coordinates.y][2] = 2;
        break;
      case 180:
        MAP[container.coordinates.x][container.coordinates.y][2] = 1;
        break;
      case 90:
        MAP[container.coordinates.x][container.coordinates.y][2] = 4;
        break;
      }
    }
    else {
      MAP[container.coordinates.x][container.coordinates.y][3] = 0 < data.heightMod ? (10-data.heightMod) : (-data.heightMod-10);
      switch(attachmentPoint.rotOffset){
        case 0:
          MAP[container.coordinates.x][container.coordinates.y][2] = 3;
          break;
        case -90:
          MAP[container.coordinates.x][container.coordinates.y][2] = 2;
          break;
        case 180:
          MAP[container.coordinates.x][container.coordinates.y][2] = 1;
          break;
        case 90:
          MAP[container.coordinates.x][container.coordinates.y][2] = 4;
          break;
      }
      switch(attachmentPoint.rotOffset){
        case 0:
          MAP[container.coordinates.x][container.coordinates.y-data.gridSize.y+1][2] = 1;
          MAP[container.coordinates.x][container.coordinates.y-data.gridSize.y+1][3] = 0;
          break;
        case -90:
          MAP[container.coordinates.x-data.gridSize.y + 1][container.coordinates.y][2] = 4;
          MAP[container.coordinates.x-data.gridSize.y + 1][container.coordinates.y][3] = 0;
          break;
        case 180:
          MAP[container.coordinates.x][container.coordinates.y+data.gridSize.y-1][2] = 3;
          MAP[container.coordinates.x][container.coordinates.y+data.gridSize.y-1][3] = 0;
          break;
        case 90:
          MAP[container.coordinates.x+data.gridSize.y - 1][container.coordinates.y][2] = 2;
          MAP[container.coordinates.x+data.gridSize.y - 1][container.coordinates.y][3] = 0;
          break;
      }
    }
  }
  container.scaleX = container.scaleY = MAX_ACCESS_SCALE_FACTOR;
  container.parentPartAttachmentPoint = attachmentPoint;
  updateMap();
  printMAP();
  for(var i=0;i<attachmentPoint.parent.attachmentCount;i++){
        attachmentPoint.parent.attachmentSlots[i].visible = false;
    }
  if(data.rails){
    var hitbox = new createjs.Shape();
    hitbox.rotation = attachmentPoint.rotOffset;
    hitbox.graphics.beginFill("rgba(255,255,255,0.01").drawRect(-125, -20, 250, 40);
    //sprite.hitArea = hitbox;
    var hitboxButtonHelper = new createjs.ButtonHelper(hitbox);

    hitbox.addEventListener("click", maxHandlePartClicked);
    hitbox.addEventListener("mouseover", maxHandleMouseOver);
    hitbox.addEventListener("mouseout", maxHandleMouseOut);
    hitbox.name = container.name;
    container.addChild(hitbox);
  }
  return container;
}

function InitialMaxPart(data) {
  partsMenuContainerText.text = "Select a part to build off of";
  toolTipText = new createjs.Text("Mouse over a part", "16px sans-serif", "#202020");
  toolTipText.name = "TOOL_TIP_TEXT";
  addMaxRemoveButton();
  stage.addChild(toolTipText);
  showTooltip = true;
  MAP = new Array();
  for(var x=0; x<40;x++){
    MAP[x] = new Array();
    for(var y=0; y<40;y++){
      MAP[x][y] = new Array();
      MAP[x][y].push(0);
      MAP[x][y].push("E");
      MAP[x][y].push(0);
      MAP[x][y].push(0);
      MAP[x][y].push(new createjs.Point(0,0));
    }
  }
  var container = new createjs.Container();
  container.partData = data;
  container.noParent = true;
  container.startingHeight = 0;
  container.attachmentSlotsUsed = 0;
  container.legsNeeded = data.legsNeeded;

  container.x = 0;
  container.y = 0;
  container.coordinates = new createjs.Point(20,20);

  var sprite = new createjs.Bitmap(data.sprite);

  var spriteButtonHelper = new createjs.ButtonHelper(sprite);
  sprite.addEventListener("click", maxHandlePartClicked);
  sprite.addEventListener("mouseover", maxHandleMouseOver);
  sprite.addEventListener("mouseout", maxHandleMouseOut);
  sprite.name = container.name = id;
  id++;
  if(!data.hiddenSprite)
    container.addChild(sprite);

  var center = new createjs.Shape();
  center.name = "CENTER";
  container.addChild(center);
  container.attachmentSlotIndices = new Array();
  container.attachmentSlots = new Array();
  var count = 0;
  for(var i=0; i<data.attachmentSlots;i++) {
    if(i==0)
    {
      var f = new createjs.Shape();
      f.name = i;
      f.graphics.beginFill("#fff").setStrokeStyle(8,"round").beginStroke("rgba(255,192,0,1)").drawRect(-146,73,293,73);
      f.x = container.partData.attachmentPoints[i].x;
      f.y = container.partData.attachmentPoints[i].y;
      f.coordinates = new createjs.Point(container.partData.attachmentCoordinates[i].x + container.coordinates.x, container.partData.attachmentCoordinates[i].y+container.coordinates.y);
      f.visible = false;
      f.filled = false;
      switch(i){
        case 0:
          f.rotOffset = 0;
          break;
        case 1:
          f.rotOffset = -90;
          break;
        case 2:
          f.rotOffset = 90;
          break;
        case 3:
          f.rotOffset = 180;
          break;
        default:
        break;
      }
      container.addChild(f);
      container.attachmentSlots[count] = f;
      var attachmentPointButtonHelper = new createjs.ButtonHelper(f);
      f.addEventListener("click", attachmentPointClicked);
      f.addEventListener("mouseover", maxHandleMouseOverAttachmentPoint);
      f.addEventListener("mouseout", maxHandleMouseOutAttachmentPoint);
      count++;
      container.attachmentSlotIndices.push(i);
    }
  }
  container.attachmentCount = count;

  var p = new createjs.Shape();
  p.name = "CONNECTOR";
  p.x = container.partData.anchorPoint.x;
  p.y = container.partData.anchorPoint.y;
  container.addChild(p);


  sprite.regX = data.bitmapCenter.x;
  sprite.regY = data.bitmapCenter.y;

  parts.push(sprite.name);



  container.highlight = new createjs.Shape();
  container.highlight.graphics.beginFill("rgba(255,192,0,0.8)").drawRect(-container.partData.bitmapCenter.x, -container.partData.bitmapCenter.y, 2*container.partData.bitmapCenter.x, 2*container.partData.bitmapCenter.y);
  container.addChild(container.highlight);
  container.highlight.visible = false;
  container.highlight.mouseEnabled = false;
  container.height = container.startingHeight + container.partData.heightMod;
  for(var x=0;x<data.gridSize.x;x++){
    for(var y=0;y<data.gridSize.y;y++){
      if(y == 0){
        MAP[container.coordinates.x+x][container.coordinates.y-y][4].y = container.partData.length;
      }
      MAP[container.coordinates.x+x][container.coordinates.y-y][0] = container.height;
      MAP[container.coordinates.x+x][container.coordinates.y-y][4].x = container.partData.width;
      if(data.platform)
        MAP[container.coordinates.x+x][container.coordinates.y-y][1] = "P";
      if(data.ladder)
        MAP[container.coordinates.x+x][container.coordinates.y-y][1] = "L";
    }
  }

  if(data.ladder)
  {
    startingText = new createjs.Text(container.startingHeight+"\"", "40px sans-serif", "#e17a0f");
    startingText.x = data.startTextPosition.x;
    startingText.y = data.startTextPosition.y;
    endText = new createjs.Text(container.height+"\"", "40px sans-serif", "#e17a0f");
    endText.x = data.endTextPosition.x;
    endText.y = data.endTextPosition.y;
    directionText = new createjs.Text("", "60px sans-serif", "#e17a0f");
    if(data.heightMod > 0)
      directionText.text = "UP";
    else{
      directionText.text = "DOWN";
      directionText.color = "#1e85f0";
      startingText.color = "#1e85f0";
      endText.color = "#1e85f0";
    }
    directionText.x = data.directionTextPosition.x;
    directionText.y = data.directionTextPosition.y;
    directionText.textAlign = startingText.textAlign = endText.textAlign = "center";
    container.addChild(directionText);
    container.addChild(startingText);
    container.addChild(endText);
    MAP[container.coordinates.x][container.coordinates.y-data.gridSize.y+1][2] = 1;
    if(container.height == 0)
      container.attachmentSlotsUsed = 0;
  }
  container.scaleX = container.scaleY = MAX_ACCESS_SCALE_FACTOR;
  updateMap();
  printMAP();
  return container;
}


// Event Handlers
function maxHandlePartClicked(event){
  var clicked = partsContainer.getChildByName(event.target.name);
  if(LAST_CLICKED_MAX_ACCESS_PART == clicked)
    return;
  if(LAST_CLICKED_MAX_ACCESS_PART != null){
    LAST_CLICKED_MAX_ACCESS_PART.highlight.visible = false;
    for(var i=0;i<LAST_CLICKED_MAX_ACCESS_PART.attachmentCount;i++){
        LAST_CLICKED_MAX_ACCESS_PART.attachmentSlots[i].visible = false;
    }
  }
  if(LAST_CLICKED_ATTACHMENT_POINT != null){
    LAST_CLICKED_ATTACHMENT_POINT.visible = false;
    LAST_CLICKED_ATTACHMENT_POINT = null;
  }

  if(partsMenuContainer.getChildByName("PART_BUTTONS_CONTAINER"))
  {
    partsMenuContainer.removeChild(partsMenuContainer.getChildByName("PART_BUTTONS_CONTAINER"));
  }
  if(scrollbar != null){
    scrollbar.removeAllChildren();
    partsMenuContainer.removeChild(scrollbar);
    scrollbar = null;
  }


  LAST_CLICKED_MAX_ACCESS_PART = clicked;
  if(clicked.height == 0){
    partsMenuContainerText.text = "Select a part to build off of";
    maxRemoveButton.visible = true;
    return;
  }
  if (clicked.attachmentSlotsUsed != clicked.partData.attachmentSlots){
    var updateText = false;
    for(var i=0;i<clicked.attachmentCount;i++){
      k = clicked.attachmentSlotIndices[i];
      if(MAP[clicked.coordinates.x+clicked.partData.attachmentCoordinates[k].x][clicked.coordinates.y+clicked.partData.attachmentCoordinates[k].y][0] == 0 && !clicked.attachmentSlots[i].filled && MAP[clicked.coordinates.x+clicked.partData.attachmentCoordinates[k].x][clicked.coordinates.y+clicked.partData.attachmentCoordinates[k].y][1] == "E"){
        clicked.attachmentSlots[i].visible = true;
        clicked.attachmentSlots[i].railsOnly = false;
        clicked.attachmentSlots[i].graphics.beginFill("#fff").setStrokeStyle(8,"round").beginStroke("rgba(255,192,0,1)").drawRect(-146,73,293,73);
        updateText = true;
      }
      else if((MAP[clicked.coordinates.x+clicked.partData.attachmentCoordinates[k].x][clicked.coordinates.y+clicked.partData.attachmentCoordinates[k].y][0] != clicked.height ||  MAP[clicked.coordinates.x+clicked.partData.attachmentCoordinates[k].x][clicked.coordinates.y+clicked.partData.attachmentCoordinates[k].y][1] != "P" && (clicked.noParent || (clicked.parentPart.coordinates.x != clicked.coordinates.x+clicked.partData.attachmentCoordinates[k].x ) && (clicked.parentPart.coordinates.y != clicked.coordinates.y+clicked.partData.attachmentCoordinates[k].y)) ) && !clicked.attachmentSlots[i].filled){
        clicked.attachmentSlots[i].visible = true;
        clicked.attachmentSlots[i].railsOnly = true;
        clicked.attachmentSlots[i].graphics.beginFill("#fff").setStrokeStyle(8,"round").beginStroke("rgba(255,192,0,1)").drawRect(-146,73,293,73);
        updateText = true;
      }
    }
    if(updateText){
      partsMenuContainerText.text = "Select an attachment point";
      toolTipText.text = "Mouse over an attachment point";
    }
  }
  else
    partsMenuContainerText.text = "Select a part to build off of";

  LAST_CLICKED_ATTACHMENT_POINT = null;
  if(!clicked.noParent && clicked.attachmentSlotsUsed == 0){
    maxRemoveButton.visible = true;
  }
  else
    maxRemoveButton.visible = false;
}


function updateMap()
{
  for(var x=0; x<40;x++){
    for(var y=0; y< 40; y++){
      if(MAP[y][x][0]== " X "){
        MAP[y][x][0] = 0;
      }
      if(MAP[y][x][1] != "L"){
        MAP[y][x][2] = 0;
      }
    }
  }

  for(var i=0;i<legs.length;i++){
    if(parts.indexOf(legs[i].name)!= -1){
      parts.splice(parts.indexOf(legs[i].name), 1);
      partsContainer.removeChild(legs[i]);
    }
  }
  legs = new Array();


  for(var x=1; x<39;x++){
    for(var y=1; y< 39; y++){
      if(MAP[y][x][0]!= " X " && MAP[y][x][0]!= 0){
        continue;
      }
      var surroundingHeights = new Array();
      surroundingHeights.push(MAP[y-1][x][0]);
      surroundingHeights.push(MAP[y+1][x][0]);
      surroundingHeights.push(MAP[y][x-1][0]);
      surroundingHeights.push(MAP[y][x+1][0]);
      var uniq = new Array();
      for(var i=0; i<surroundingHeights.length;i++){
        if(surroundingHeights[i] == 0 || surroundingHeights[i] == " X ")
          continue;
        if(uniq.indexOf(surroundingHeights[i])==-1)
          uniq.push(surroundingHeights[i])
      }
      if(uniq.length > 1)
        MAP[y][x][0] = " X ";
    }
  }
  for(var i=0;i<1;i++){
  for(var x=0; x<40;x++){
    for(var y=0; y< 40; y++){
      if(MAP[x][y][1] == "P" && MAP[x][y][2] == 0){
        var leg1 = false;
        var leg2 = false;
        var leg3 = false;
        var leg4 = false;
        var p1 = false;
        var p2 = false;
        var p3 = false;
        var p4 = false;
        if(x > 0){
          if(MAP[x-1][y][1] != "E" && MAP[x-1][y][0] == MAP[x][y][0])
            p4 = true;
          if(MAP[x-1][y][2] == 0 || MAP[x-1][y][2] == 4){
            //No Nodes         
          }
          else if (MAP[x-1][y][2] == 2){
            //Left All Nodes
            leg1 = true;
            leg4 = true;
          }
          else if (MAP[x-1][y][2] == 3){
            //Bottom Left Node
            leg4 = true;
          }
          else if(MAP[x-1][y][2] == 1){
            //Top Left Node
            leg1 = true;
          }
        }
        if(x < 39){
          if(MAP[x+1][y][1] != "E" && MAP[x+1][y][0] == MAP[x][y][0])
            p2 = true;
          if(MAP[x+1][y][2] == 0 || MAP[x+1][y][2] == 2){
            //No Nodes         
          }
          else if (MAP[x+1][y][2] == 4){
            //Right All Nodes
            leg2 = true;
            leg3 = true;
          }
          else if (MAP[x+1][y][2] == 3){
            //Bottom Right Node
            leg3 = true;
          }
          else if(MAP[x+1][y][2] == 1){
            //Top Right Node
            leg2 = true;
          }
        }
        if(y > 0){
          if(MAP[x][y-1][1] != "E" && MAP[x][y-1][0] == MAP[x][y][0])
            p1 = true;
          if(MAP[x][y-1][2] == 0 || MAP[x][y-1][2] == 1){
            //No Nodes         
          }
          else if (MAP[x][y-1][2] == 4){
            leg1 = true;
            //Top Left Node
          }
          else if (MAP[x][y-1][2] == 2){
            leg2 = true;
            //Top Right Node
          }
          else if(MAP[x][y-1][2] == 3){
            leg1 = true;
            leg2 = true;
            //Top All Nodes
          }
        }
        if(y < 39){
          if(MAP[x][y+1][1] != "E" && MAP[x][y+1][0] == MAP[x][y][0])
            p3 = true;
          if(MAP[x][y+1][2] == 0 || MAP[x][y+1][2] == 3){
            //No Nodes         
          }
          else if (MAP[x][y+1][2] == 4){
            //Bottom Left Node
            leg4 = true;
          }
          else if (MAP[x][y+1][2] == 2){
            //Bottom Right Node
            leg3 = true;
          }
          else if(MAP[x][y+1][2] == 1){
            //Bottom All Nodes
            leg3 = true;
            leg4 = true;
          }
        }
        if(x > 0 && y > 0){
          if(MAP[x-1][y-1][2] == 0 || MAP[x-1][y-1][2] == 1 || MAP[x-1][y-1][2] == 4){
            //No Nodes         
          }
          else if (MAP[x-1][y-1][2] == 2 || MAP[x-1][y-1][2] == 3){
            // Top Left Node
            leg1 = true;
          }
        }
        if(x > 0 && y < 39){
          if(MAP[x-1][y+1][2] == 0 || MAP[x-1][y+1][2] == 3 || MAP[x-1][y+1][2] == 4){
            //No Nodes         
          }
          else if (MAP[x-1][y+1][2] == 2 || MAP[x-1][y+1][2] == 1){
            // Bottom Left Node
            leg4 = true;
          }
        }
        if(x < 39 && y > 0){
          if(MAP[x+1][y-1][2] == 0 || MAP[x+1][y-1][2] == 1 || MAP[x+1][y-1][2] == 2){
            //No Nodes         
          }
          else if (MAP[x+1][y-1][2] == 4 || MAP[x+1][y-1][2] == 3){
            // Top Right Node
            leg2 = true;
          }
        }
        if(x < 39 && y < 39){
          if(MAP[x+1][y+1][2] == 0 || MAP[x+1][y+1][2] == 3 || MAP[x+1][y+1][2] == 2){
            //No Nodes         
          }
          else if (MAP[x+1][y+1][2] == 4 || MAP[x+1][y+1][2] == 1){
            // Bottom Right Node
            leg3 = true;
          }
        }
        if(!leg1 && !leg2 && !leg3 && !leg4)    // 0
          if(!p1 && !p4 && !p3)
            MAP[x][y][2] = 4;
          else
            MAP[x][y][2] = 1;
        else if (leg1 && !leg2 && !leg3 && !leg4) // 1
          if(!p1 && p4 && p2 && p3)
            MAP[x][y][2] = 3;
          else
            MAP[x][y][2] = 2;
        else if (!leg1 && leg2 && !leg3 && !leg4)  // 2
          MAP[x][y][2] = 4;
        else if(leg1 && leg2 && !leg3 && !leg4) // 3
          MAP[x][y][2] = 3;
        else if (!leg1 && !leg2 && leg3 && !leg4)  // 4
          if(p4)
            MAP[x][y][2] = 1;
          else
            MAP[x][y][2] = 4;
        else if (leg1 && !leg2 && leg3 && !leg4) // 5
          MAP[x][y][2] = 1;
        else if (!leg1 && leg2 && leg3 && !leg4) //  6
          MAP[x][y][2] = 4;
        else if (leg1 && leg2 && leg3 && !leg4)  // 7
          MAP[x][y][2] = 0;
        else if (!leg1 && !leg2 && !leg3 && leg4)  // 8
          MAP[x][y][2] = 1;
        else if(leg1 && !leg2 && !leg3 && leg4)  //  9
          MAP[x][y][2] = 2; 
        else if (!leg1 && leg2 && !leg3 && leg4) // 10
          MAP[x][y][2] = 3;
        else if (leg1 && leg2 && !leg3 && leg4)  // 11
          MAP[x][y][2] = 0;
        else if (!leg1 && !leg2 && leg3 && leg4)  // 12
          MAP[x][y][2] = 1;
        else if (leg1 && !leg2 && leg3 && leg4)  // 13
          MAP[x][y][2] = 0;
        else if(!leg1 && leg2 && leg3 && leg4) //14
          MAP[x][y][2] = 1;
        else if (leg1 && leg2 && leg3 && leg4) // 15
          MAP[x][y][2] = 0;
      }
    }
  }
}
  for(var x=0; x<40;x++){
    for(var y=0; y< 40; y++){
      if(MAP[x][y][2] != 0){
        var legPart;
        var legHeight;
        if(MAP[x][y][1] == "P")
          legHeight = MAP[x][y][0];
        else
          legHeight = MAP[x][y][0] + MAP[x][y][3];
        switch(legHeight){
          case 20:
            legPart = MaxPart(UAP020(true), null);
            break;
          case 30:
            legPart = MaxPart(UAP030(true), null);
            break;
          case 40:
            legPart = MaxPart(UAP040(true), null);
            break;
          case 50:
            legPart = MaxPart(UAP050(true), null);
            break;
          case 60:
            legPart = MaxPart(UAP060(true), null);
            break;
          case 70:
            legPart = MaxPart(UAP070(true), null);
            break;
          case 80:
            legPart = MaxPart(UAP080(true), null);
            break;
          case 90:
            legPart = MaxPart(UAP090(true), null);
            break;
          case 100:
            legPart = MaxPart(UAP100(true), null);
            break;
          case 110:
            legPart = MaxPart(UAP110(true), null);
            break;
          default:
            break;
        }
        partsContainer.addChild(legPart);
        legs.push(legPart);
      }
    }
  }


}

function printMAP()
{
  for(var x=0; x<40;x++){
    var string = "|"
    for(var y=0; y< 40; y++){
      if(MAP[y][x]!= " X "){
        if(MAP[y][x] == 0)
          string +="0"
        if(MAP[y][x] < 100)
          string += "0"
      }
      string+= MAP[y][x] + "|"
    }
    console.log(string);
  }
}

function addHeightKeys()
{
  var height20key = new createjs.Container();
  height20key.x = 10;
  height20key.y = 700;
  stage.addChild(height20key);
  var height20keyBackground = new createjs.Shape();
  height20keyBackground.graphics.beginFill("rgba(200,200,200,0.90)").drawRect(0,0,120,40);
  //height20key.addChild(height20keyBackground);

  var height20keyBlock = new createjs.Shape();
  height20keyBlock.graphics.beginFill(height20Tint).drawRect(10,10,20,20);
  height20key.addChild(height20keyBlock);

  var height20keyText = new createjs.Text("20\" Height", "12px sans-serif", "#202020");
  height20keyText.y = 15;
  height20keyText.x = 40;
  height20key.addChild(height20keyText);
  height20key.visible = false;
  heightKeys.push(height20key);

  var height30key = new createjs.Container();
  height30key.x = 10;
  height30key.y = 660;
  stage.addChild(height30key);
  var height30keyBackground = new createjs.Shape();
  height30keyBackground.graphics.beginFill("rgba(200,200,200,0.90)").drawRect(0,0,120,40);
  //height30key.addChild(height30keyBackground);

  var height30keyBlock = new createjs.Shape();
  height30keyBlock.graphics.beginFill(height30Tint).drawRect(10,10,20,20);
  height30key.addChild(height30keyBlock);

  var height30keyText = new createjs.Text("30\" Height", "12px sans-serif", "#202020");
  height30keyText.y = 15;
  height30keyText.x = 40;
  height30key.addChild(height30keyText);
  height30key.visible = false;
  heightKeys.push(height30key);

  var height40key = new createjs.Container();
  height40key.x = 10;
  height40key.y = 620;
  stage.addChild(height40key);
  var height40keyBackground = new createjs.Shape();
  height40keyBackground.graphics.beginFill("rgba(200,200,200,0.90)").drawRect(0,0,120,40);
  //height40key.addChild(height40keyBackground);

  var height40keyBlock = new createjs.Shape();
  height40keyBlock.graphics.beginFill(height40Tint).drawRect(10,10,20,20);
  height40key.addChild(height40keyBlock);

  var height40keyText = new createjs.Text("40\" Height", "12px sans-serif", "#202020");
  height40keyText.y = 15;
  height40keyText.x = 40;
  height40key.addChild(height40keyText);
  height40key.visible = false;
  heightKeys.push(height40key);

  var height50key = new createjs.Container();
  height50key.x = 10;
  height50key.y = 580;
  stage.addChild(height50key);
  var height50keyBackground = new createjs.Shape();
  height50keyBackground.graphics.beginFill("rgba(200,200,200,0.90)").drawRect(0,0,120,40);
  //height50key.addChild(height50keyBackground);

  var height50keyBlock = new createjs.Shape();
  height50keyBlock.graphics.beginFill(height50Tint).drawRect(10,10,20,20);
  height50key.addChild(height50keyBlock);

  var height50keyText = new createjs.Text("50\" Height", "12px sans-serif", "#202020");
  height50keyText.y = 15;
  height50keyText.x = 40;
  height50key.addChild(height50keyText);
  height50key.visible = false;
  heightKeys.push(height50key);

  var height60key = new createjs.Container();
  height60key.x = 10;
  height60key.y = 540;
  stage.addChild(height60key);
  var height60keyBackground = new createjs.Shape();
  height60keyBackground.graphics.beginFill("rgba(200,200,200,0.90)").drawRect(0,0,120,40);
  //height60key.addChild(height60keyBackground);

  var height60keyBlock = new createjs.Shape();
  height60keyBlock.graphics.beginFill(height60Tint).drawRect(10,10,20,20);
  height60key.addChild(height60keyBlock);

  var height60keyText = new createjs.Text("60\" Height", "12px sans-serif", "#202020");
  height60keyText.y = 15;
  height60keyText.x = 40;
  height60key.addChild(height60keyText);
  height60key.visible = false;
  heightKeys.push(height60key);

  var height70key = new createjs.Container();
  height70key.x = 10;
  height70key.y = 500;
  stage.addChild(height70key);
  var height70keyBackground = new createjs.Shape();
  height70keyBackground.graphics.beginFill("rgba(200,200,200,0.90)").drawRect(0,0,120,40);
  //height70key.addChild(height70keyBackground);

  var height70keyBlock = new createjs.Shape();
  height70keyBlock.graphics.beginFill(height70Tint).drawRect(10,10,20,20);
  height70key.addChild(height70keyBlock);

  var height70keyText = new createjs.Text("70\" Height", "12px sans-serif", "#202020");
  height70keyText.y = 15;
  height70keyText.x = 40;
  height70key.addChild(height70keyText);
  height70key.visible = false;
  heightKeys.push(height70key);

  var height80key = new createjs.Container();
  height80key.x = 10;
  height80key.y = 460;
  stage.addChild(height80key);
  var height80keyBackground = new createjs.Shape();
  height80keyBackground.graphics.beginFill("rgba(200,200,200,0.90)").drawRect(0,0,120,40);
  //height80key.addChild(height80keyBackground);

  var height80keyBlock = new createjs.Shape();
  height80keyBlock.graphics.beginFill(height80Tint).drawRect(10,10,20,20);
  height80key.addChild(height80keyBlock);

  var height80keyText = new createjs.Text("80\" Height", "12px sans-serif", "#202020");
  height80keyText.y = 15;
  height80keyText.x = 40;
  height80key.addChild(height80keyText);
  height80key.visible = false;
  heightKeys.push(height80key);

  var height90key = new createjs.Container();
  height90key.x = 10;
  height90key.y = 420;
  stage.addChild(height90key);
  var height90keyBackground = new createjs.Shape();
  height90keyBackground.graphics.beginFill("rgba(200,200,200,0.90)").drawRect(0,0,120,40);
  //height90key.addChild(height90keyBackground);

  var height90keyBlock = new createjs.Shape();
  height90keyBlock.graphics.beginFill(height90Tint).drawRect(10,10,20,20);
  height90key.addChild(height90keyBlock);

  var height90keyText = new createjs.Text("90\" Height", "12px sans-serif", "#202020");
  height90keyText.y = 15;
  height90keyText.x = 40;
  height90key.addChild(height90keyText);
  height90key.visible = false;
  heightKeys.push(height90key);

  var height100key = new createjs.Container();
  height100key.x = 10;
  height100key.y = 380;
  stage.addChild(height100key);
  var height100keyBackground = new createjs.Shape();
  height100keyBackground.graphics.beginFill("rgba(200,200,200,0.90)").drawRect(0,0,120,40);
  //height100key.addChild(height100keyBackground);

  var height100keyBlock = new createjs.Shape();
  height100keyBlock.graphics.beginFill(height100Tint).drawRect(10,10,20,20);
  height100key.addChild(height100keyBlock);

  var height100keyText = new createjs.Text("100\" Height", "12px sans-serif", "#202020");
  height100keyText.y = 15;
  height100keyText.x = 40;
  height100key.addChild(height100keyText);
  height100key.visible = false;
  heightKeys.push(height100key);

  var height110key = new createjs.Container();
  height110key.x = 10;
  height110key.y = 340;
  stage.addChild(height110key);
  var height110keyBackground = new createjs.Shape();
  height110keyBackground.graphics.beginFill("rgba(200,200,200,0.90)").drawRect(0,0,120,40);
  //height110key.addChild(height110keyBackground);

  var height110keyBlock = new createjs.Shape();
  height110keyBlock.graphics.beginFill(height110Tint).drawRect(10,10,20,20);
  height110key.addChild(height110keyBlock);

  var height110keyText = new createjs.Text("110\" Height", "12px sans-serif", "#202020");
  height110keyText.y = 15;
  height110keyText.x = 40;
  height110key.addChild(height110keyText);
  height110key.visible = false;
  heightKeys.push(height110key);
}

function attachmentPointClicked(event){
  var point = event.target;
  if(point == LAST_CLICKED_ATTACHMENT_POINT)
    return;
  if(LAST_CLICKED_MAX_ACCESS_PART != null)
    LAST_CLICKED_MAX_ACCESS_PART.highlight.visible = false;
  for(var i=0;i<point.parent.attachmentCount;i++){
    point.parent.attachmentSlots[i].graphics.beginFill("#fff").setStrokeStyle(8,"round").beginStroke("rgba(255,192,0,1)").drawRect(-146,73,293,73);
  }
  partsMenuContainerText.text = "Select a part to attach";
  toolTipText.text = "Select a part from the menu on the right";
  point.graphics.beginFill("rgba(255,192,0,1)").drawRect(-146,73,293,73);
  var spaces = calculateGridSpace(point);
  stage.addChild(MaxSelectPartMenu(point.parent, point,((spaces!=0) && point.parent.partData.platform), (spaces==0 && point.parent.partData.platform), spaces ));
  LAST_CLICKED_MAX_ACCESS_PART.highlight.visible = false;
  LAST_CLICKED_ATTACHMENT_POINT = point;
  maxRemoveButton.visible = false;
}

function maxHandleMouseOver(event){
  var target = partsContainer.getChildByName(event.target.name);
  target.highlight.visible = true;
  if(LAST_CLICKED_MAX_ACCESS_PART != target)
    toolTipText.text = "Click to select this part";
}

function maxHandleMouseOut(event){
  var target = partsContainer.getChildByName(event.target.name);
  if(LAST_CLICKED_MAX_ACCESS_PART != target || LAST_CLICKED_ATTACHMENT_POINT != null)
    target.highlight.visible = false;
  if(((LAST_CLICKED_MAX_ACCESS_PART == null || !LAST_CLICKED_MAX_ACCESS_PART.highlight.visible) && LAST_CLICKED_ATTACHMENT_POINT == null) || LAST_CLICKED_MAX_ACCESS_PART.attachmentSlotsUsed == LAST_CLICKED_MAX_ACCESS_PART.attachmentCount)
    toolTipText.text = "Mouse over a part";
  else if(LAST_CLICKED_ATTACHMENT_POINT == null)
    toolTipText.text = "Mouse over an attachment point";
  else
    toolTipText.text = "Select a part from the menu on the right";
}

function maxHandleMouseOverAttachmentPoint(event){
  if(LAST_CLICKED_ATTACHMENT_POINT != event.target)
  toolTipText.text = "Click to select this attachment point";
}

function maxHandleMouseOutAttachmentPoint(event){
  if(LAST_CLICKED_ATTACHMENT_POINT == null)
    toolTipText.text = "Mouse over an attachment point";
  else
    toolTipText.text = "Select a part from the menu on the right";
}

function autoAddRails(all){
  var preExistingParts = new Array();
  for(var i =0; i < partsContainer.getNumChildren(); i++){
    if(partsContainer.getChildAt(i).partData.platform && (all || partsContainer.getChildAt(i).height >=50)){
      preExistingParts.push(partsContainer.getChildAt(i));
    }
  }
  for(var i = 0; i< preExistingParts.length; i++){
    var platform = preExistingParts[i];
    if(platform.attachmentSlotsUsed == platform.attachmentCount)
      continue;
    for(var k=0; k < platform.attachmentCount; k++){
      if(platform.attachmentSlots[platform.attachmentSlotIndices[k]].filled)
        continue;
      if(MAP[platform.attachmentSlots[platform.attachmentSlotIndices[k]].coordinates.x][platform.attachmentSlots[platform.attachmentSlotIndices[k]].coordinates.y][1]=="E"){
        var newPart = MaxPart(UAPHR1(false), platform.attachmentSlots[platform.attachmentSlotIndices[k]]);
        partsContainer.addChild(newPart);
        autoAddedRails.push(newPart);
      }
    }
  }
  console.log("*********")
  console.log(autoAddedRails)
  angularUpdate(parts);
}

function removeAutoAddedRails(){
  console.log("HIT")
  console.log(autoAddedRails.length)
  for(var i=0; i<autoAddedRails.length; i++){
    removePart(autoAddedRails[i],false);
  }
  autoAddedRails = new Array();
  console.log(autoAddedRails)
}

function calculateGridSpace(attachmentPoint){
  var startPoint = attachmentPoint.coordinates;
  var openSpaces = 0;
  var xCount = 0;
  var x = startPoint.x;
  var y = startPoint.y;
  switch(attachmentPoint.rotOffset){
    case 0:
      while (y>-1){
        if((MAP[x][y][0]==0 && MAP[x][y][1]=="E") || (MAP[x][y][0]==" X " && xCount == 0)){
          openSpaces++;
          if(MAP[x][y][0]==" X ")
            xCount++;
        }
        else if((MAP[x][y][0]==0 && MAP[x][y][1] == "L") || MAP[x][y][0] != attachmentPoint.parent.height){
          openSpaces--;
          break;
        }
        else
          break;
        y--;
      }
      break;
    case -90:
      while (x>-1){
        if((MAP[x][y][0]==0 && MAP[x][y][1]=="E") || (MAP[x][y][0]==" X " && xCount == 0)){
          openSpaces++;
          if(MAP[x][y][0]==" X ")
            xCount++;
        }
        else if((MAP[x][y][0]==0 && MAP[x][y][1] == "L") || MAP[x][y][0] != attachmentPoint.parent.height){
          openSpaces--;
          break;
        }
        else
          break;
        x--;
      }
      break;
    case 90:
      while (x<MAP.length){
        if((MAP[x][y][0]==0 && MAP[x][y][1]=="E") || (MAP[x][y][0]==" X " && xCount == 0)){
          openSpaces++;
          if(MAP[x][y][0]==" X ")
            xCount++;
        }
        else if((MAP[x][y][0]==0 && MAP[x][y][1] == "L") || MAP[x][y][0] != attachmentPoint.parent.height){
          openSpaces--;
          break;
        }
        else
          break;
        x++;
      }
      break;
    case 180:
      while (y<MAP[x].length){
        if((MAP[x][y][0]==0 && MAP[x][y][1]=="E") || (MAP[x][y][0]==" X " && xCount == 0)){
          openSpaces++;
          if(MAP[x][y][0]==" X ")
            xCount++;
        }
        else if((MAP[x][y][0]==0 && MAP[x][y][1] == "L") || MAP[x][y][0] != attachmentPoint.parent.height){
          openSpaces--;
          break;
        }
        else
          break;
        y++;
      }
      break;
    default:
      break;
  }
  if ((openSpaces == 1 && xCount == 1) || openSpaces < 0)
    return 0;
  else if (openSpaces == 2 && xCount == 1)
    return 1;
  else
    return openSpaces;
}

function updateTooltipPosition(){
  if(stage.mouseInBounds && stage.getChildIndex(maxTopDownView) == -1 && !stage.getChildByName("RAILS_POPUP")){
    toolTipText.visible = true;
    toolTipText.x = stage.mouseX+10;
    toolTipText.y = stage.mouseY+10;
  }
  else
    toolTipText.visible = false;
}
