// Max number of slice planes allowd. 
var g_MaxSlicePlanes = 6;

//Horizontal Text Alignment
var TE_HTA_LEFT   = 0;
var TE_HTA_RIGHT  = 1;
var TE_HTA_CENTER = 2;

//cell check kind
var DGC_CK_NONE = 0;
var DGC_CK_CHECKBOX = 1;
var DGC_CK_RADIOBUTTON = 2;

//cell check style
var DGC_CS_3D = 0;
var DGC_CS_FLAT = 1;

function sectionPlaneObj(id, name, checkState)
{
    this.id = id;
    this.name = name;
    this.checkState = checkState;
}

function initSectionPlanesPane()
{
    initCommandContainer();
    initSectionPaneListView();
  }

var ID_ADD					= 2001;
var ID_DELETE				= 2002;
var ID_RENAME				= 2003;
var ID_REDISPLAY			= 2004;
var ID_HIDE                 = 2005;
var ID_ELEMENTS             = 2006;
var ID_EDIT                 = 2007;

ag.duringAddPlane = false;
ag.singleSelectedEditableId = 0; //unset

function SectionPaneObjects()
{
    this.toolbar = null;
    ag.btnAdd = null;
    ag.btnEdit = null;
    ag.btnDelete = null;
    this.btnRename = null;
    this.btnRedisplay = null;
    this.btnHide = null;
    this.itemClicked = null;
    this.bItemChecked = false;

    this.SectionPane_Add = function sectionPane_Add(sender, args) {
      agUncheckAllGraphicsButtons();
      doAddSectionPlane();
      this.RefreshToolbar();
    }
    this.SectionPane_Edit = function sectionPane_Edit(sender, args) {
      agUncheckAllGraphicsButtons();
      if (ag.gb.DragMode == ag.c.DragCutPlane)
        sectionPlaneHandler(113); // turn OFF
      else
        sectionPlaneHandler(113); // turn ON
      this.RefreshToolbar();
    }
    this.SectionPane_Delete = function sectionPane_Delete(sender, args) 
    {
        doDeleteSectionPlane();
        this.RefreshToolbar();
    }
    
    this.SectionPane_OnItemClick = function sectionPane_OnItemClick(sender, args)
    {
        this.itemClicked = args.ListItem;
        this.bItemChecked = args.ListItem.Checked;
    }
    this.SectionPane_OnItemCheck = function sectionPane_OnItemCheck(sender, args) 
    {
        var slice = ag.gb.SliceTool;
        var item = args.ListItem;
        var camMode = ag.gb.DragMode;

        this.itemClicked = args.ListItem;
        this.bItemChecked = args.ListItem.Checked;

        // no check logic during addplane
        if (camMode == ag.c.DefineCutPlane)
        {
            return;
        }

        slice.Enabled(this.itemClicked.Tag.id) = this.itemClicked.Checked;

        if (!ag.duringAddPlane)
          ag.gb.Redraw(ag.c.RedrawAll);
    }
    
    this.SectionPane_OnDisplayContextMenu = function sectionPane_OnDisplayContextMenu(sender, args)
    {
        //WBScript.Out("SectionPane_OnDisplayContextMenu Not Implemented",true);
    }

    this.SectionPane_OnMouseDown = function sectionPane_OnMouseDown(sender, args) {
      var slice = ag.gb.SliceTool;
      var item = args.ListItem;
      var camMode = ag.gb.DragMode;

      if (this.itemClicked != null) {
        // user clicked check box
        if (this.bItemChecked != this.itemClicked.Checked) {/*Do Nothing?*/}
        // user clicked list item
        else if (this.itemClicked.Checked == true) {
          if (camMode == ag.c.DefineCutPlane) sectionPlaneHandler(112); // turn OFF DefineCutPlane mode
          slice.ActivePlane = this.itemClicked.Tag.id;
          var activeSlices = ag.gb.EnableActiveSlices;
          if (!activeSlices)
            slice.RetainPlane();
          ag.gb.Redraw(ag.c.RedrawAll);
          var hitNum;
          hitNum = slice.HitDetectLabels(-1, -1);
        }
        else if (this.itemClicked.Checked == false) {
          if (camMode == ag.c.DragCutPlane)
            sectionPlaneHandler(113); // turn OFF
        }
      }
      this.itemClicked = null;
      this.RefreshToolbar();
    }
    
    function doAddSectionPlane() {
		  if (ag.gb.DragMode == ag.c.DefineCutPlane)
		  {
			  sectionPlaneHandler( 112 );	// turn OFF  DefineCutPlane mode
		  }
		  else
		  {
		    if (ag.gb.DragMode == ag.c.DragCutPlane) sectionPlaneHandler(113); // turn OFF DragCutPlane mode
			  sectionPlaneHandler( 112 );	// turn ON  DefineCutPlane mode
		  }
	      pvUnselectAllItems();
    }
    
    function doDeleteSectionPlane()
    {
		  var sliceTool  = ag.gb.SliceTool;
		  if (sliceTool == null)
			  return;
	    if (ag.gb.DragMode == ag.c.DragCutPlane)		
		    sectionPlaneHandler( 113 );	// turn off
		  for (i = ag.sectionPaneListView.ListItems.Count; i >=1 ; i--)
		  {
			  var item = ag.sectionPaneListView.ListItems.Item(i);
			  if (item != null && item.Selected)
        {
			    var id = item.Tag.id;
          sliceTool.DeletePlane(id);
			  }
		  }
	    ag.gb.Redraw(ag.c.RedrawAll);
	    pvUnselectAllItems();
    }

    this.RefreshToolbar = function refreshToolbar() 
    {
      ag.singleSelectedEditableId = 0;
      var numSelectedItems = 0;
      var numSelectedEditable = 0;
      for (i = ag.sectionPaneListView.ListItems.Count; i >= 1; i--) {
        var item = ag.sectionPaneListView.ListItems.Item(i);
        if (item != null && item.Selected) {
          numSelectedItems++;
          if (item.Checked == true) {
            numSelectedEditable++;
            if (numSelectedEditable == 1)
              ag.singleSelectedEditableId = item.Tag.id;
            else
              ag.singleSelectedEditableId = 0;
          }
        }
      }
      if (ag.singleSelectedEditableId == 0 && ag.gb.DragMode == ag.c.DragCutPlane)
        sectionPlaneHandler(113); // turn off

      if (canCreateSlice())
        ag.btnAdd.Enabled = true;
      else
        ag.btnAdd.Enabled = false;

      ag.btnEdit.Enabled = numSelectedEditable == 1;
      if (ag.gb.DragMode == ag.c.DragCutPlane)
        ag.btnEdit.Check = true;
      else
        ag.btnEdit.Check = false;

      ag.btnDelete.Enabled = numSelectedItems > 0;

      if (ag.gb.DragMode == ag.c.DefineCutPlane) {
        ag.bSectionPlane.Check = true;
        ag.btnAdd.Check = true;
      }
      else {
        ag.bSectionPlane.Check = false;
        ag.btnAdd.Check = false;
      }
    } //end this.RefreshToolbar
} // end func SectionPlaneObjects()

ag.g_sectionPaneObjects = new SectionPaneObjects();

function initCommandContainer()
{
    var cmdCont = ag.spPane.CommandContainer;
    ag.spPane.CommandContainerVisible = true;
    
	var TBT_BUTTON					= 101;
	var TBT_SEPARATOR				= 102;
	var TBT_DROPDOWNBUTTON			= 103;
	var TBT_CHECKBOX				= 104;
	var TBT_BUTTON_DROPDOWN			= 105;
	
	with (ag.g_sectionPaneObjects)
	{
	    toolbar = cmdCont.ToolBars.Add("Standard_toolbar");
	    
	    var imageList = CreateActiveXObject(GenWBProgId("WBControls.WBImageList"));
	    imageList.Create();
	    imageList.Add(wb.NoLocaleInstallDir("AGApplet") + GetPathSeparator() + "images");
	    var ImagesDir = wb.AISOLCommonFile + str_CommonPages + GetPathSeparator() + str_images;
	    imageList.Add(ImagesDir);
	    toolbar.ImageList = imageList;

	    ag.btnAdd = agTbrButton(toolbar, ID_ADD, "ID_NewSectionPlane", "NewSectionPlane", false);
	    ag.btnAdd.OnClick.AddCOM(ag.g_sectionPaneObjects, "SectionPane_Add");

	    ag.btnEdit = agTbrButton(toolbar, ID_EDIT, "ID_EditSectionPlane", "EditSectionPlane", false);
	    ag.btnEdit.OnClick.AddCOM(ag.g_sectionPaneObjects, "SectionPane_Edit");

	    ag.btnDelete = agTbrButton(toolbar, ID_DELETE, "ID_DeleteSectionPlane", "delete", false);
	    ag.btnDelete.OnClick.AddCOM(ag.g_sectionPaneObjects, "SectionPane_Delete");

	    eventCallback = wb.OnEvent;
	    eventCallback.AddCOM(this, "applet_onEventDelegate");

	}
}

function initSectionPaneListView()
{
  var lvwReport = 3;
	ag.sectionPaneListView.View = 2;
	ag.sectionPaneListView.Checkboxes = true;
	ag.sectionPaneListView.GridLines = false;
	ag.sectionPaneListView.FullRowSelect = true;
	ag.sectionPaneListView.MultiSelect = true;
	ag.sectionPaneListView.HideSelection = false;
	ag.sectionPaneListView.HideColumnHeaders = false;
	
	var ccDefault = 0;
	ag.sectionPaneListView.MousePointer = ccDefault;
	
	var lvwAutomatic = 0;
  var lvwManual = 1;
  ag.sectionPaneListView.LabelEdit = lvwManual;
	
  var ccNone = 0;
  var ccFixedSingle = 1;
  ag.sectionPaneListView.BorderStyle = ccFixedSingle;
	
  var ccFlat = 0;
  var cc3D = 1;
  ag.sectionPaneListView.Appearance = ccFlat;

  ag.sectionPaneListView.OnItemClick.AddCOM(ag.g_sectionPaneObjects, "SectionPane_OnItemClick");
  ag.sectionPaneListView.OnDisplayContextMenu.AddCOM(ag.g_sectionPaneObjects, "SectionPane_OnDisplayContextMenu");
  ag.sectionPaneListView.OnMouseDown.AddCOM(ag.g_sectionPaneObjects, "SectionPane_OnMouseDown");
  ag.sectionPaneListView.OnItemCheck.AddCOM(ag.g_sectionPaneObjects, "SectionPane_OnItemCheck");
}

function setColumnHeaders()
{
    var indexRow = 1;
    var indexCol = 1;
    var cell = sppGrid.Cell(indexRow, indexCol);
    cell.Text = "Active";
    cell.HorizontalTextAlignment = TE_HTA_CENTER;
    indexCol++;
    cell = sppGrid.Cell(indexRow, indexCol);
    cell.Text = "Name";
    cell.HorizontalTextAlignment = TE_HTA_LEFT;
}

function setColumnWidths()
{
    sppGrid.ColumnWidth(1) = 40;
    sppGrid.ColumnWidth(2) = 200;
}

function RefreshSectionPlaneListView() 
{
  ag.sectionPaneListView.ListItems.Clear();
  var slice = ag.gb.SliceTool;
  if (!slice)
    return;
  var count = slice.Count;
  var i = 0;
  var id = 0;
  for (i = 0; i < count; i++) {
    // id corresponds to the internal SP id
    // i is the number of the SP in the listview. +1 so we get from 1->6
    id = slice.GetPlaneId(i);
    cpt_OnAddPlane(id, i+1); 
  }
  pvUnselectAllItems();
  ag.g_sectionPaneObjects.RefreshToolbar();
}

function deleteAllSectionPlanes()
{
  var sliceTool  = ag.gb.SliceTool;
  if (sliceTool == null)
    return;
  if (ag.gb.DragMode == ag.c.DragCutPlane)		
    sectionPlaneHandler( 113 );	// turn off
  for (i = ag.sectionPaneListView.ListItems.Count; i >=1 ; i--)
  {
    var item = ag.sectionPaneListView.ListItems.Item(i);
    if (item != null)
    {
      var id = item.Tag.id;
      sliceTool.DeletePlane(id);
    }
  }
  ag.gb.Redraw(ag.c.RedrawAll);
  pvUnselectAllItems();
}


// Function gets called from C++ as well; do not change its names.
function RedefineSlicePlanes()
{
  pvRedefineSlicePlanes(false); // no need to invoke redraw from here
  RefreshSectionPlaneListView();
}

function agSlicePlane_OnAddPlaneDelegate(sender, args) {
  // Determine if SP List needs reordered. 
  // If the newest ID is less than the current count, reorder the list and add it
  // Otherwise, add the newest SP at the end.
  if (args.ID < args.Count)
    RefreshSectionPlaneListView();
  else 
  {
    cpt_OnAddPlane(args.ID, args.Count);
  }
}

function cpt_OnAddPlane(id, count) {
  ag.duringAddPlane = true;
	var bCheckedState = true;
	var slice   = ag.gb.SliceTool;
	if (slice)
	{
		if (slice.Enabled( id ) == 0) bCheckedState = false;
  }
  var lstItem = ag.sectionPaneListView.ListItems.Add(null, null, agString("ID_SectionPlane") + count);
  var spObj = new sectionPlaneObj(id, count, bCheckedState);
  lstItem.Tag = spObj;
  lstItem.Checked = bCheckedState;
	lstItem.Selected = false;
	if (ag.gb.DragMode == ag.c.DefineCutPlane || ag.gb.DragMode == ag.c.DragCutPlane)	
	{
		lstItem.Selected = true;	// select newly defined cut plane
		ag.g_sectionPaneObjects.RefreshToolbar();
  }
  ag.duringAddPlane = false;
  syncButtons(1);
}

function agSlicePlane_OnDeletePlaneDelegate(sender, args)
{
    cpt_OnDeletePlane(args.ID);
}

function cpt_OnDeletePlane(id)
{
	for (i = 1; i <= ag.sectionPaneListView.ListItems.Count; i++)
	{
		var item = ag.sectionPaneListView.ListItems.Item(i);
		if (item.Tag.id == id)
		{
			ag.sectionPaneListView.ListItems.Remove(i);
			break;
		}
  }

  syncButtons(2);
}

function syncButtons(flag) {
  if (flag == 1) // Add
  {
    ag.bSectionPlane.Check = false; // uncheck toolbar button
    ag.btnAdd.Check = false; // uncheck listview button
    if (!canCreateSlice()) ag.bSectionPlane.Enabled = false; // if sliceCount = 6, disable toolbar btn
  }  
  else if (flag == 2) // Delete
  {
    if (canCreateSlice() && ag.bSectionPlane.Enabled == false) // reenable toolbar button once slices < 6
      ag.bSectionPlane.Enabled = true;
  }
  else if (flag == 3) // Section Plane Mode Turned Off
  {
    ag.bSectionPlane.Check = false; // Toolbar Button
    ag.btnAdd.Check = false; // Listview ADD button
  } 

  // the following is exactly what is set when the "rotate" toolbar btn is clicked
  // we want to enable the same thing here
  ag.gb.BrowserMode = 1;
  ag.gb.DragMode = 4; // turn ON rotation mode
  ag.gui.SetViewFlag(1, 1); // turn ON dynamic rotation (status message)
  ag.bZoom.Check = ag.bBZoom.Check = ag.bPan.Check = false; // turn off all graphics buttons
  ag.pointPick.Check = ag.edgePick.Check = ag.facePick.Check = ag.bodyPick.Check = false; // Turn off all selection buttons
  ag.bRot.Check = true; // turn ON rotate toolbar btn
}

function pvNumActivePlanes()
{
	var numActive = 0;
	
    for (var i = 1; i <= ag.sectionPaneListView.ListItems.Count; i++)
    {
        if (ag.sectionPaneListView.ListItems.Item(i).Checked)
            numActive++;
    }
    return numActive;
}

function pvRedefineSlicePlanes(bRedraw)
{
	var slice = ag.gb.SliceTool;
	if (!slice) return;

	if (pvNumActivePlanes() == 0) return;

	var redraw		= 0;
	var mode		= ag.gb.DragMode;
	var activePlane = slice.ActivePlane;
	if (mode == ag.c.DragCutPlane)	sectionPlaneHandler( 113 );	// turn OFF
	
	for (var i = 1; i <= ag.sectionPaneListView.ListItems.Count; i++)
    {
		var item = ag.sectionPaneListView.ListItems.Item(i);
		slice.ActivePlane = item.Tag.id;
		redraw = 1;
    }
	if (mode == ag.c.DragCutPlane)	
	{	
		slice.RetainPlane();
		sectionPlaneHandler( 113 );	// turn ON
		redraw = 0;
	}
	slice.ActivePlane = activePlane;
    var activeSlices = ag.gb.EnableActiveSlices;
    if (!activeSlices)
        slice.RetainPlane ();

    // If redraw is needed, and redraw is asked.
    if (redraw && bRedraw)
      ag.gb.Redraw(ag.c.RedrawAll);
}

function pvUnselectAllItems()
{
	for (i = 1; i <= ag.sectionPaneListView.ListItems.Count; i++)	// unselect all items
	{
		var item = ag.sectionPaneListView.ListItems.Item(i);
		item.Selected = false;
	}
}

function doTurnOffSliceModes()
{
	if		(ag.gb.DragMode == ag.c.DefineCutPlane)	sectionPlaneHandler( 112 );	// turn OFF
	else if (ag.gb.DragMode == ag.c.DragCutPlane)		sectionPlaneHandler( 113 );	// turn OFF
}

function setActiveSectionPlane() 
{
    if (ag.gb.DragMode == ag.c.DragCutPlane) 
    {
      var slice = ag.gb.SliceTool;
        if(slice)
        slice.ActivePlane = ag.singleSelectedEditableId;
    }
}

function canCreateSlice()
{
    var slice = ag.gb.SliceTool;
    if (!slice)
        return false;

    var count = slice.Count;
    if (count >= g_MaxSlicePlanes)
        return false;

    return true;
  }

function applet_onEventDelegate(sender, args)
{
    applet_onEvent(args.Name, args.Value);
}

function applet_onEvent(vParam1, vParam2) 
{
  if (vParam2 == ag.spPane.ID && ag.gb) 
  {
    if (isSectionPlaneWindowVisible() == false) 
    {
      // turn OFF section plane define/drag mode if user turns OFF window via "X"
      doTurnOffSliceModes()
      ag.bSectionPlane.Check = false; ag.mSectionPlane.Check = false;
    }
  }
}