// Calling page must have paramsDiv & libraryDiv objects for these functions
// show and manipulate

// History
// Who When     What
// --- -------- ---------------------------------------------------------
// bem 21/06/04 Added support for storing transforms so can edit
//              setting and have it return to the same place
// bem 05/07/04 Changed to 'unwrap' setting from top so that front
//              of setting is in the middle of the .art file
//-----------------------------------------------------------------------

function plugin_main()
{
   // Hide the library div
   HideAllLibraryDivs();
   Flush_write_params(paramsDiv);

   globalStore.ActiveGem = new Gem();
   globalStore.ActiveGem.TargetDiv = gemsDiv;
   globalStore.ActiveGem.CallingDiv = paramsDiv;
   globalStore.ActiveGem.ParentDiv = libraryDiv;
   globalStore.ActiveGem.CallbackFunction = GemCallback;
   globalStore.ActiveGem.WriteShapeSelectionHTML();
   globalStore.OnCreate = OnCreate;

   globalStore.OnBackFlush = OnBackFlush;
   globalStore.OnCreateTri = OnCreateTri;
   globalStore.OnRebuildSetting = OnRebuildSetting;
   globalStore.OnRebuildRelief = OnRebuildRelief;
   globalStore.OnFinish = OnFinish;
   globalStore.CreateReliefs = CreateReliefs;
   globalStore.CreateSettingVectors = CreateSettingVectors;
   globalStore.OnSettingDone = OnSettingDone;
   globalStore.EditSettings = EditSettings;
   globalStore.InstructionsDiv.style.display="none";
}

function Flush_write_params(targetDiv)
{
   targetDiv.innerHTML = "";
   var hArr = new Array();
   // Add the back button HTML to the array

   hArr.push("<div id='SettingsDiv'>");
   hArr.push("<table width='100%' border=0 cellspacing=0 style='margin-left:3px;table-layout:fixed'>");
   hArr.push("<col width=40px><col width=30%><col width=30%><col width=40%>");
   hArr.push("<tr HELPTAG style='display:none'><td colspan=4><img align=left src='" + artcam.HtmlRootDir + "../SharedImages/help.gif'>&nbsp;" + gFormHelp + "</td></tr>");
   hArr.push("<tr><td colspan=4 align=center><img src='ProjectAssistant/Blanks/RotaryFlush/Images/SettingParams.gif'></td></tr>");

   hArr.push("<tr><td></td><td>"+ gName + ":</td><td colspan=2 align=right><input type=edit id=SettingNameEdit></td></tr>");
   hArr.push("<tr><td></td><td colspan=2>"+ gTopAllowance + " <b>(A)</b>:</td><td align=right><input type=edit size=5 maxLength=6 number dp='3' value=0.1 id=TopAllowanceEdit></td></tr>");
   hArr.push("<tr><td></td><td colspan=2>"+ gBottomAllowance + " <b>(B)</b>:</td><td align=right><input type=edit size=5 maxLength=6 number dp='3' value=0.5 id=BottomAllowanceEdit></td></tr>");
   hArr.push("<tr><td></td><td colspan=2>"+ gThickness + " <b>(C)</b>:</td><td align=right><input type=edit size=5 maxLength=6 number dp='3' value=0.5 id=ThicknessEdit></td></tr>");
   hArr.push("<tr><td></td><td colspan=2>"+ gWallAngle + " <b>(D)</b>:</td><td align=right><input type=edit size=5 maxLength=6 number dp='3' value=80 id=WallAngleEdit></td></tr>");
   hArr.push("<tr><td></td><td colspan=3>"+ gPosition + "&nbsp;<input type=checkbox id=PositionCheck checked></td></tr>");

   hArr.push("</table>");

   hArr.push("</div>");

   hArr.push("<div id='InstructionsDiv'");
   hArr.push("<tr><td colspan=3>" + gInstructions + "</td></tr>");
   hArr.push("</div>");

   hArr.push("<div class='mouseOut' button_name='forward_button' id=ForwardButton targetFunction='globalStore.OnCreate' style='width=30px;float:right'>");
   hArr.push("<img alt =" + gAcceptButtonAlt + " id=forward_img src ='" + artcam.HtmlRootDir + "../SharedImages/forward.gif' align=absmiddle border=0 width=30 height=30>");
   hArr.push("</div>");

   hArr.push("<div class='mouseOut' button_name='rebuild_button' id=RebuildButton targetFunction='globalStore.OnRebuildSetting' style='width=30px;float:right;display:none'>");
   hArr.push("<img alt =" + gRebuildButtonAlt + " id=rebuild_img src ='" + artcam.HtmlRootDir + "../SharedImages/rebuild.gif' align=absmiddle border=0 width=30 height=30>");
   hArr.push("</div>");

   hArr.push("<div class='mouseOut' button_name='back_button' id=BackButton targetFunction='globalStore.OnBackFlush' style='width=30px;float:right'>");
   hArr.push("<img alt =" + gBackButtonAlt + " id=back_img src ='" + artcam.HtmlRootDir + "../SharedImages/back.gif' align=absmiddle border=0 width=30 height=30>");
   hArr.push("</div>");

   targetDiv.innerHTML += hArr.join("\n");

   globalStore.SettingTopAllowanceEdit = eval(TopAllowanceEdit);
   globalStore.SettingBottomAllowanceEdit = eval(BottomAllowanceEdit);
   globalStore.SettingThicknessEdit = eval(ThicknessEdit);
   globalStore.SettingWallAngleEdit = eval(WallAngleEdit);

   globalStore.RebuildButton = eval(RebuildButton);
   globalStore.ForwardButton = eval(ForwardButton);
   globalStore.BackButton = eval(BackButton);
   globalStore.back_img = eval(back_img);
   globalStore.forward_img = eval(forward_img);
   globalStore.SettingNameEdit = eval(SettingNameEdit);
   globalStore.SettingNameEdit.value= gPluginName;
   globalStore.PositionCheck = eval(PositionCheck);
   globalStore.SettingsDiv = eval(SettingsDiv);
   globalStore.InstructionsDiv = eval(InstructionsDiv);
   
   // Bung all our HTML into the div and display it
   InitialiseButtonDivs();
   SubclassNumberEditControls();

   RetrieveParams();
}

function OnCreate()
{
   SaveParams();
   OnCreateModel();
   CreateSettingVectors();
   CreateReliefs();
   // bem 05/07/04 ensure we have a greyscale view
   if (artcam.CurrentModel != null)
      {
      current_2d_view = artcam.CurrentModel.ActiveView;
      if (current_2d_view != null)
         {
         // cant have bitmap and greyscale on at same time - switch off bitmap
         current_2d_view.DisplayBitmap = false;
         current_2d_view.DisplayGreyscale = true;
         current_2d_view.Refresh();
         }
       current_2d_view = null;
       }

   OnCreateTri();
//   globalStore.ForwardButton.targetFunction = 'globalStore.OnFinish';
   globalStore.ForwardButton.targetFunction = 'globalStore.OnSettingDone';
//   globalStore.forward_img.src = artcam.HtmlRootDir + "../SharedImages/accept.gif";
}

function OnBackFlush()
{
   globalStore.ActiveGem.WriteColourSelectionHTML();
}

function OnCreateModel()
{
   var diameter = globalStore.ActiveGem.Width > globalStore.ActiveGem.Length ? globalStore.ActiveGem.Length/4 : globalStore.ActiveGem.Width/4;
   var thickness = (globalStore.ActiveGem.Width + globalStore.ActiveGem.Length)/4;
   var width = globalStore.SettingTopAllowanceEdit.getValue() +
      globalStore.ActiveGem.Depth +
      globalStore.SettingBottomAllowanceEdit.getValue() +
      globalStore.SettingThicknessEdit.getValue();

   var resolution = 400 / (width * 2);

   artcam.ProjectAssembly.SetFlag("BuildingFlag", CreateRotaryModel(diameter, thickness, width * 2, resolution));
   if(false == artcam.ProjectAssembly.GetFlag("BuildingFlag", false))
   {
      return false;
   }

   artcam.CurrentModel.Rename(globalStore.SettingNameEdit.value, false);

   StoreTransformForComponentType("RotarySetting");
   artcam.CurrentModel.SetString("Ring_creation_page_name", "RotaryAxisSetting");
   artcam.CurrentModel.SetString("Ring_component_type", "Setting");

   return true;
}

function CreateSettingVectors()
{
   DeleteConstructionVectors();

   globalStore.MainGemID = globalStore.ActiveGem.DrawVector();

   var silhouette_centre_x = GetRingSilhouetteCentre("x", true);
   var silhouette_centre_y = GetRingSilhouetteCentre("y", true);
   artcam.VectorSelection.Selection = globalStore.MainGemID;
   artcam.MoveVectors(
      silhouette_centre_x ,//double x,
      silhouette_centre_y//double y
      );

   var ring_designer = artcam.CreateRingDesigner();
   SetRingDesignerInfoFromModel(ring_designer);
   globalStore.OuterVectorsLayer = artcam.VectorLayers.Create(-1,"Outer Vectors");
   globalStore.InnerVectorsLayer = artcam.VectorLayers.Create(-1,"Inner Vectors");

   artcam.VectorLayers.selectedIndex = globalStore.OuterVectorsLayer;

   var rad_angle = (90 - globalStore.SettingWallAngleEdit.getValue()) * (Math.PI / 180.0);

   var outer_height = globalStore.SettingTopAllowanceEdit.getValue() +
      globalStore.ActiveGem.Depth +
      globalStore.SettingBottomAllowanceEdit.getValue()/* +
      globalStore.SettingThicknessEdit.getValue()*/;

   var inner_height = outer_height/* - globalStore.SettingThicknessEdit.getValue()*/;

   var outer_width_at_girdle = (globalStore.ActiveGem.Width/2) + globalStore.SettingThicknessEdit.getValue();

   var adjacent = outer_height - globalStore.SettingTopAllowanceEdit.getValue();
   var opposite = Math.tan(rad_angle) * adjacent;

   var base_half_width = outer_width_at_girdle - opposite;
   var offset = (globalStore.ActiveGem.Width/2) - base_half_width;

   artcam.VectorSelection.Selection = globalStore.MainGemID;
   if(offset<0)// Positive value - offset outwards...
      artcam.OffsetSelectedVectors(true,offset,2,5,false);
   else// Otherwise offset inwards
      artcam.OffsetSelectedVectors(false,offset,2,5,false);
   globalStore.BottomID = artcam.VectorSelection.Selection;
   globalStore.BottomIDUnwrapped = ring_designer.UnWrapSelectedVectorFromTop();

   // Offset inwards for azure
   artcam.VectorLayers.selectedIndex = globalStore.InnerVectorsLayer;
   artcam.OffsetSelectedVectors(false,globalStore.SettingThicknessEdit.getValue(),2,5,false);
   globalStore.BottomIDInner = artcam.VectorSelection.Selection;
   globalStore.BottomIDUnwrappedInner = ring_designer.UnWrapSelectedVectorFromTop();

   artcam.VectorLayers.selectedIndex = globalStore.OuterVectorsLayer;

   adjacent = outer_height;
   opposite = Math.tan(rad_angle) * adjacent;

   var top_half_width = opposite + base_half_width;
   var offset = top_half_width - (globalStore.ActiveGem.Width/2);

   artcam.VectorSelection.Selection = globalStore.MainGemID;
   if(offset>0)// Positive value - offset outwards...
      artcam.OffsetSelectedVectors(true,offset,2,5,false);
   else// Otherwise offset inwards
      artcam.OffsetSelectedVectors(false,offset,2,5,false);
   globalStore.TopID = artcam.VectorSelection.Selection;
   globalStore.TopIDUnwrapped = ring_designer.UnWrapSelectedVectorFromTop();

   artcam.VectorLayers.selectedIndex = globalStore.InnerVectorsLayer;
   // Offset inwards for azure
   artcam.OffsetSelectedVectors(false,globalStore.SettingThicknessEdit.getValue(),2,5,false);
   globalStore.TopIDInner = artcam.VectorSelection.Selection;
   globalStore.TopIDUnwrappedInner = ring_designer.UnWrapSelectedVectorFromTop();

   artcam.VectorLayers.selectedIndex = globalStore.OuterVectorsLayer;
   globalStore.total_setting_height = outer_height;

   DrawRails();

   globalStore.RebuildButton.style.display="";
   return true;
}

function DrawRails()
{
   var width_of_pixel = artcam.CurrentModel.RealWidth / artcam.CurrentModel.PixelWidth;
   var height_of_pixel = artcam.CurrentModel.RealHeight / artcam.CurrentModel.PixelHeight;
   var halfwidth = (artcam.CurrentModel.RealWidth + width_of_pixel) / 2;

   artcam.VectorLayers.selectedIndex = globalStore.OuterVectorsLayer;

   var rail_y2 = globalStore.total_setting_height / 2;
   var rail_y1 = -rail_y2;

   var rail_vector = artcam.Vectors.CreateVector();
   rail_vector.MoveTo(-halfwidth,rail_y1);
   rail_vector.LineTo(-halfwidth,rail_y2);
   artcam.Vectors.AddVectorToArtcam(rail_vector);
   globalStore.Rail1ID = rail_vector.VectorID;

   rail_vector = artcam.Vectors.CreateVector();
   rail_vector.MoveTo(halfwidth,rail_y1);
   rail_vector.LineTo(halfwidth,rail_y2);

   artcam.Vectors.AddVectorToArtcam(rail_vector);
   globalStore.Rail2ID = rail_vector.VectorID;

   artcam.VectorLayers.selectedIndex = globalStore.InnerVectorsLayer;

   // Make the inner rails slightly larger than the outer ones to
   // prevent rounding errors causing problems.
   rail_y2 += height_of_pixel;
   rail_y1 = -rail_y2;

   rail_vector = artcam.Vectors.CreateVector();
   rail_vector.MoveTo(-halfwidth,rail_y1);
   rail_vector.LineTo(-halfwidth,rail_y2);

   artcam.Vectors.AddVectorToArtcam(rail_vector);
   globalStore.Rail1IDInner = rail_vector.VectorID;

   rail_vector = artcam.Vectors.CreateVector();
   rail_vector.MoveTo(halfwidth,rail_y1);
   rail_vector.LineTo(halfwidth,rail_y2);

   artcam.Vectors.AddVectorToArtcam(rail_vector);
   globalStore.Rail2IDInner = rail_vector.VectorID;
}

function DeleteConstructionVectors()
{
   var ids = new Array();

   if (globalStore.MainGemID != undefined) ids.push(globalStore.MainGemID);
   if (globalStore.Azure_ID != undefined)  ids.push(globalStore.Azure_ID);
   if (globalStore.BottomID != undefined)  ids.push(globalStore.BottomID);
   if (globalStore.TopID != undefined)     ids.push(globalStore.TopID);

   if (0 == ids.length) return;

   artcam.VectorSelection.Selection = ids.join(",");
   artcam.DeleteSelection();

   globalStore.MainGemID = undefined;
   globalStore.Azure_ID  = undefined;
   globalStore.BottomID  = undefined;
   globalStore.TopID     = undefined;
}

function OnFinish()
{
   var component_type = "Head";

   SaveArtFile(component_type, globalStore.SettingNameEdit.value);

   StoreCreationFilePathInAssembly(globalStore.Setting_assembly);
   globalStore.Setting_assembly.Name = globalStore.SettingNameEdit.value;
   artcam.ProjectAssembly.AppendChild(globalStore.Setting_assembly);
   artcam.ProjectAssembly.UpdateAssemblyMonitor();
   artcam.ProjectAssembly.InDisplayList=true;
   globalStore.Setting_assembly.InDisplayList=false;

   artcam.ProjectAssembly.SetFlag("BuildingFlag", false);
   FileCheck();

   OnClose();
//   OnCloseAndGotoAssistantTab();
   OnBackButton();
}

function CreateReliefs()
{
   artcam.Relief.MakeFrontReliefCurrent();
   artcam.Relief.SetName("Front Relief");

   var temp_relief = artcam.CreateEmptyRelief();
   temp_relief.CopyFromCurrent();
   temp_relief.BaseHeight = artcam.Relief.BaseHeight;

   var sweep_info = artcam.CreateTwoRailSweepData();
   sweep_info.SetRail1(globalStore.Rail1ID);
   sweep_info.SetRail2(globalStore.Rail2ID);

   sweep_info.AddCrossSection(globalStore.BottomIDUnwrapped,0,0,0,0,false);
   sweep_info.AddCrossSection(globalStore.TopIDUnwrapped,1,1,0,0,false);
   artcam.TwoRailSweep(sweep_info, temp_relief);
   temp_relief.MergeHighestWithCurrent();

   artcam.Relief.MakeBackReliefCurrent();
   artcam.Relief.SetName("Back Relief");

   temp_relief.SetAllHeights(artcam.Relief.BaseHeight);
   sweep_info.SetRail1(globalStore.Rail1IDInner);
   sweep_info.SetRail2(globalStore.Rail2IDInner);
   sweep_info.DeleteAllCrossSections();
   sweep_info.AddCrossSection(globalStore.BottomIDUnwrappedInner,0,0,0,0,false);
   sweep_info.AddCrossSection(globalStore.TopIDUnwrappedInner,1,1,0,0,false);
   artcam.TwoRailSweep(sweep_info, temp_relief);

   temp_relief.MergeHighestWithCurrent();

   artcam.Relief.MakeFrontReliefCurrent();

   return true;
}


function OnRebuildSetting()
{
//   alert("OnRebuildSetting");
   if (true == artcam.ProjectAssembly.GetFlag("BuildingFlag", false))
   {
      artcam.ProjectAssembly.SetFlag("BuildingFlag", false);
      artcam.CurrentModel.RemoveFromProject();
      artcam.ForceModelClose();
   }

//   OnCreateTri();
//   globalStore.ForwardButton.targetFunction = 'globalStore.OnFinish';

   OnCreate();
}

function OnRebuildRelief()
{
//   alert("OnRebuildRelief!");
   OnCreateTri();
}


function OnCreateTri()
{
   var head_mesh = CreateWrappedMeshFromCurrentModel(0.01, true);
   if(head_mesh==null)
      return;

   head_mesh.Name = globalStore.SettingNameEdit.value;

   globalStore.ActiveGem.ZPosition = head_mesh.MaxZ - globalStore.SettingTopAllowanceEdit.getValue();
   globalStore.ActiveGem.Name = globalStore.SettingNameEdit.value + "Gem";

   globalStore.ActiveGem.CreateModel();
   globalStore.ActiveGem.GemModel.Transform(
               0,0,0,
               1,1,1,
               0,0,90,
               0,0,0,
               true,false);

   globalStore.Setting_assembly = artcam.CreateAssembly(globalStore.SettingNameEdit.value);

   globalStore.Setting_assembly.InDisplayList=true;

   if(globalStore.Setting_assembly!=null)
   {
      globalStore.Setting_assembly.Append3dModel(head_mesh);
      head_mesh.InDisplayList=false;
      if(typeof(gBezelMesh)=='object')
      {
         globalStore.Setting_assembly.Append3dModel(gBezelMesh);
         globalStore.BezelMesh.InDisplayList=false;
         globalStore.BezelMesh = null;
      }

      if(globalStore.ActiveGem.GemModel!=null)
      {
         globalStore.Setting_assembly.AppendGemSet(globalStore.ActiveGem.GemModel);
         globalStore.ActiveGem.GemModel.InDisplayList=false;
      }

      if(globalStore.PositionCheck.checked)
      {
         var shankobject = new Shank();
         if(shankobject.RetrieveSettings())
         {
            var radius = shankobject.Diameter/2;
            var displacement = radius - globalStore.Setting_assembly.MinZ;
            globalStore.Setting_assembly.Transform(0,0,displacement,1,1,1,0,0,0,0,0,0,false,false);
            artcam.CurrentModel.SetString
                                (
                                "_js_AutoAssemblyTransform2",
                                "0 0 " + displacement +
                                " 1 1 1 0 0 0 0 0 0 false"
                                );
         }
      }
   }
}

function GemCallback(completed)
{
   if(completed)
   {
      globalStore.SettingNameEdit.value = globalStore.ActiveGem.Shape + gFlush;
   }
   else
   {
      OnBackButton();
   }
}

function RetrieveParams()
{
   globalStore.SettingTopAllowanceEdit.setValue(artcam.RetrieveDouble("RotaryFlush", "TopAllowance", 0.5));
   globalStore.SettingBottomAllowanceEdit.setValue(artcam.RetrieveDouble("RotaryFlush", "BottomAllowance", 2.0));
   globalStore.SettingThicknessEdit.setValue(artcam.RetrieveDouble("RotaryFlush", "WallThickness", 0.8));
   globalStore.SettingWallAngleEdit.setValue(artcam.RetrieveDouble("RotaryFlush", "WallAngle", 76.0));
   globalStore.PositionCheck.checked = artcam.RetrieveString("RotaryFlush", "PositionOnRing", "checked")
}

function SaveParams()
{
   artcam.StoreDouble("RotaryFlush", "TopAllowance", globalStore.SettingTopAllowanceEdit.getValue());
   artcam.StoreDouble("RotaryFlush", "BottomAllowance", globalStore.SettingBottomAllowanceEdit.getValue());
   artcam.StoreDouble("RotaryFlush", "WallThickness", globalStore.SettingThicknessEdit.getValue());
   artcam.StoreDouble("RotaryFlush", "WallAngle", globalStore.SettingWallAngleEdit.getValue());
   artcam.StoreString("RotaryFlush", "PositionOnRing", globalStore.PositionCheck.checked ? "checked" :  "");
}

function OnModelClosed()
{
   if (true == artcam.ProjectAssembly.GetFlag("BuildingFlag", false))
   {
      OnClose();
   }
}

function OnSettingDone()
{
   globalStore.SettingsDiv.style.display="none";
   globalStore.InstructionsDiv.style.display="";
   globalStore.RebuildButton.style.display="";  
   globalStore.RebuildButton.targetFunction = 'globalStore.OnRebuildRelief';
   globalStore.ForwardButton.targetFunction = 'globalStore.OnFinish';
   globalStore.forward_img.src = artcam.HtmlRootDir + "../SharedImages/accept.gif";
   globalStore.ForwardButton.targetFunction = 'globalStore.OnFinish';
   globalStore.BackButton.targetFunction = 'globalStore.EditSettings';
}

function EditSettings()
{
   globalStore.InstructionsDiv.style.display = "none";
   globalStore.SettingsDiv.style.display="";
   globalStore.RebuildButton.targetFunction = 'globalStore.OnRebuildSetting';
   globalStore.ForwardButton.targetFunction = 'globalStore.OnSettingDone';
   globalStore.BackButton.targetFunction = 'globalStore.OnBackFlush';
   globalStore.forward_img.src = artcam.HtmlRootDir + "../SharedImages/forward.gif";
}
