var maxRemoveButton;
var scrollbar;

function MaxSelectPartMenu(part, attachmentPoint, autoAddLadders, railsOnly, maxLength){
  refreshParts();
  selectPartMenu = new createjs.Container();
  selectPartMenu.originPart = part;
  selectPartMenu.attachmentPoint = attachmentPoint;
  originalPart = part;
  selectPartMenu.name = "SELECT_PART_MENU";
  if(partsMenuContainer.getChildByName("PART_BUTTONS_CONTAINER"))
  {
    partsMenuContainer.removeChild(partsMenuContainer.getChildByName("PART_BUTTONS_CONTAINER"));
  }
  var partButtonsContainer = new createjs.Container();
  partButtonsContainer.name = "PART_BUTTONS_CONTAINER";
  stage.getChildByName("PARTS_MENU_CONTAINER").addChild(partButtonsContainer);
  addMaxPartButtons(part, partButtonsContainer, attachmentPoint.parent.height, autoAddLadders, railsOnly, maxLength);

  if(partButtonsContainer.getNumChildren() > 0)
  {
    partsMenuContainerText.text = "Select a part to add";
    if(partButtonsContainer.getNumChildren() > 10)
      DrawScrollBar(partButtonsContainer);
  }
  else
  {
    partsMenuContainerText.text = "";
  }

  return selectPartMenu;
}

function addMaxRemoveButton(){
  maxRemoveButton = new createjs.Container();
  maxRemoveButton.x = 0;
  maxRemoveButton.y = 640;
  maxRemoveButton.name = "REMOVE_BUTTON";

  partsMenuContainer.addChild(maxRemoveButton);

  var removeButtonShape = new createjs.Shape();
  removeButtonShape.graphics.beginFill("#ff9e35").beginStroke("#e17a0f").drawRoundRect(0,0,260,60,5);

  maxRemoveButton.addChild(removeButtonShape);

  var removeButtonText = new createjs.Text("Remove Selected Part", "20px sans-serif", "#FFF");
  removeButtonText.textAlign = "center";
  removeButtonText.x = 130;
  removeButtonText.y = 20;

  maxRemoveButton.addChild(removeButtonText);

  var removeButtonHelper = new createjs.ButtonHelper(maxRemoveButton);
  maxRemoveButton.addEventListener("click", handleMaxRemoveClicked);
  maxRemoveButton.visible = showRemoveButton;
}

function addMaxPartButtons(part, mselectPartMenu, cheight, autoAddLadders, railsOnly, maxLength){
  var x = y = 0;
  if(railsOnly == true){
    newPart = UAPHR1(true);
    var partButton = new createjs.Container();
    partButton.part = newPart;
    partButton.x = 10;
    partButton.y = 20;
    mselectPartMenu.addChild(partButton);

    var partButtonShape = new createjs.Shape();
    partButtonShape.graphics.beginFill("#FFF").beginStroke("#e17a0f").drawRoundRect(0,0,100,90,5);
    partButton.addChild(partButtonShape);

    var partButtonText = new createjs.Text(newPart.name, "12px sans-serif", "#444");
    partButtonText.textAlign = "center";
    partButtonText.x = 50;
    partButtonText.y = 92;
    partButton.addChild(partButtonText);

    var partImg = new createjs.Bitmap(newPart.sprite);
    partImg.regX = newPart.bitmapCenter.x;
    partImg.regY = newPart.bitmapCenter.y;
    partImg.scaleX = partImg.scaleY = 0.15;
    partImg.x = 50;
    partImg.y = 30;
    partButton.addChild(partImg);

    mselectPartMenu.addChild(partButton);

    var partButtonHelper = new createjs.ButtonHelper(partButton);
    partButton.addEventListener("click", handleMaxPartSelected);
  }
  else {
    var possibleParts;
    if(autoAddLadders){
      possibleParts = part.partData.connectableParts.concat(MA_LADDERS(cheight));
    }
    else
      possibleParts = part.partData.connectableParts;
    for(var i=0; i < possibleParts.length; i++){

      newPart = PARTS[possibleParts[i]];
      if(!newPart.platform && !newPart.rails && newPart.gridSize.y > maxLength-1)
        continue;

      var partButton = new createjs.Container();
      partButton.part = newPart;
      partButton.x = x*125 + 10;
      partButton.y = y*135 + 25;
      mselectPartMenu.addChild(partButton);

      var partButtonShape = new createjs.Shape();
      partButtonShape.graphics.beginFill("#FFF").beginStroke("#e17a0f").drawRoundRect(0,0,100,90,5);
      partButton.addChild(partButtonShape);

      var partButtonText = new createjs.Text(newPart.name, "12px sans-serif", "#444");
      partButtonText.textAlign = "center";
      partButtonText.x = 50;
      partButtonText.y = 100;
      partButton.addChild(partButtonText);

      var partImg = new createjs.Bitmap(newPart.sprite);
      partImg.regX = newPart.bitmapCenter.x;
      partImg.regY = newPart.bitmapCenter.y;
      partImg.scaleX = partImg.scaleY = (0.15/newPart.gridSize.y);
      partImg.x = 50;
      partImg.y = 50;
      partButton.addChild(partImg);

      mselectPartMenu.addChild(partButton);
      mselectPartMenu.setChildIndex(partButton, 0);

      var partButtonHelper = new createjs.ButtonHelper(partButton);
      partButton.addEventListener("click", handleMaxPartSelected);
      partButton.addEventListener("mouseover", handleMaxPartOver);
      partButton.addEventListener("mouseout", handleMaxPartOut);
      x++;
      if (x == 2){
        x = 0;
        y++;
      }
    }
  }
  partsMenuContainer.setChildIndex(mselectPartMenu, 1);
  partsMenuContainer.setChildIndex(upperPartsMenuClip, partsMenuContainer.getNumChildren());
  partsMenuContainer.setChildIndex(partsMenuContainerText, partsMenuContainer.getNumChildren());
}

function DrawScrollBar(partButtonsContainer){
  if(scrollbar != null){
    scrollbar.removeAllChildren();
    partsMenuContainer.removeChild(scrollbar);
    scrollbar = null;
  }
  scrollbar = new createjs.Container();
  var scrollbarOutline = new createjs.Shape();
  scrollbarOutline.graphics.beginStroke("#e17a0f").drawRoundRect(-2,10,15,690,5);
  scrollbar.addChild(scrollbarOutline);

  var scrollbarBar = new createjs.Shape();
  scrollbarBar.name = "scrollbarBar";
  scrollbarBar.graphics.beginFill("#444").drawRoundRect(0,12,11,300,5);
  scrollbar.addChild(scrollbarBar);

  scrollbarBar.on("mousedown", function(evt){
    this.offset = {x:this.x-evt.stageX, y:this.y-evt.stageY};
  });

  scrollbarBar.on("pressmove", function(evt) {
        this.y = evt.stageY + this.offset.y;
        this.y = (Math.min(Math.max(0,this.y), 386));
        partButtonsContainer.y = -this.y;
      });



  scrollbar.x = 245;
  partsMenuContainer.setBounds(0,0,100,700);
  partsMenuContainer.addChild(scrollbar);

}

// Event Handlers
function handleMaxRemoveClicked(event){
  removePart(LAST_CLICKED_MAX_ACCESS_PART, true)
}

function removePart(part, updateText) {
  partsContainer.removeChild(partsContainer.getChildByName(part.name));
  parts.splice(parts.indexOf(part.name), 1);
  if(part.partData.platform){
    for(var x=0;x<part.partData.gridSize.x;x++){
      for(var y=0;y<part.partData.gridSize.y;y++){
        MAP[part.coordinates.x+x][part.coordinates.y-y][0] = 0;
        MAP[part.coordinates.x+x][part.coordinates.y-y][1] = "E";
      }
    }
  }
  else if (part.partData.ladder){
    console.log(part)
    switch(part.mountPoint.rotation){
      case 0:
        for(var x=0;x<part.partData.gridSize.x;x++){
          for(var y=0;y<part.partData.gridSize.y;y++){
            MAP[part.coordinates.x+x][part.coordinates.y-y][0] = 0;
            MAP[part.coordinates.x+x][part.coordinates.y-y][1] = "E";
          }
        }
        break;
      case -90:
        for(var x=0;x<part.partData.gridSize.x;x++){
          for(var y=0;y<part.partData.gridSize.y;y++){
            MAP[part.coordinates.x-y][part.coordinates.y-x][0] = 0;
            MAP[part.coordinates.x-y][part.coordinates.y-x][1] = "E";
          }
        }
        break;
      case 90:
        for(var x=0;x<part.partData.gridSize.x;x++){
          for(var y=0;y<part.partData.gridSize.y;y++){
            console.log(y)
            MAP[part.coordinates.x+y][part.coordinates.y-x][0] = 0;
            MAP[part.coordinates.x+y][part.coordinates.y-x][1] = "E";
          }
        }
        break;
      case 180:
        for(var x=0;x<part.partData.gridSize.x;x++){
          for(var y=0;y<part.partData.gridSize.y;y++){
            MAP[part.coordinates.x+x][part.coordinates.y+y][0] = 0;
            MAP[part.coordinates.x+x][part.coordinates.y+y][1] = "E";
          }
        }
        break;
      default:
        break;
    }
  }
  for(var i=0;i<part.parentPartAttachmentPoint.parent.attachmentCount;i++){
    var k = part.parentPartAttachmentPoint.parent.attachmentSlotIndices[i];
    if(part.parentPartAttachmentPoint.parent.attachmentSlots[i] == part.parentPartAttachmentPoint)
      part.parentPartAttachmentPoint.parent.attachmentSlots[i].filled = false;
  }
  part.parentPartAttachmentPoint.parent.attachmentSlotsUsed--;
  updateMap();
  printMAP();
  updateZOrder();
  angularUpdate(parts);
  if(updateText){
    maxRemoveButton.visible = false;
    partsMenuContainerText.text = "Select a part to build off of";
    toolTipText.text = "Mouse over a part";
    if(scrollbar != null){
      scrollbar.removeAllChildren();
      partsMenuContainer.removeChild(scrollbar);
      scrollbar = null;
    }
    LAST_CLICKED_ATTACHMENT_POINT = null;
    LAST_CLICKED_MAX_ACCESS_PART = null;
  }
}

function handleMaxPartSelected(event){
  newPart = (MaxPart(event.target.parent.part, selectPartMenu.attachmentPoint));
  partsContainer.addChild(newPart);
  if(partsMenuContainer.getChildByName("PART_BUTTONS_CONTAINER"))
  {
    partsMenuContainer.removeChild(partsMenuContainer.getChildByName("PART_BUTTONS_CONTAINER"));
  }
  if(scrollbar != null){
    scrollbar.removeAllChildren();
    partsMenuContainer.removeChild(scrollbar);
    scrollbar = null;
  }
  var partButtonsContainer = new createjs.Container();
  angularUpdate(parts);
  partsMenuContainerText.text = "Select a part to build off of";
  toolTipText.text = "Mouse over a part";
  LAST_CLICKED_ATTACHMENT_POINT = null;
  LAST_CLICKED_MAX_ACCESS_PART = null;
}

function handleMaxPartOver(event){
  toolTipText.text = "Click to add this part";
}

function handleMaxPartOut(event){
  if(LAST_CLICKED_ATTACHMENT_POINT != null)
    toolTipText.text = "Select a part from the menu on the right";
}

function scrollPartsBar(delta){
  if(scrollbar != null && scrollbar.getChildByName("scrollbarBar") != null){
    bar = scrollbar.getChildByName("scrollbarBar");
    bar.y = (Math.min(Math.max(0,(bar.y-(25*delta))), 386));
    scrollbar.parent.getChildByName("PART_BUTTONS_CONTAINER").y = -bar.y;
  }
}