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

function plugin_main()
{
   // Check we have some closed vectors selected - we warn if open vectors were in the selection
   globalStore.selectedVectorArray = CreateSelectedClosedVectorArray();

   if(globalStore.selectedVectorArray.length == 0)
   {
      artcam.MessageBox(gNoVectorsSelected);
      OnBackButton();
      return;
   }

   if( globalStore.SelectionContainedOpenVectors )
      artcam.MessageBox(gOpenVectorsSelected);

   // Hide the library div
   HideAllLibraryDivs();
   write_params(paramsDiv);

   // Setup function references
   globalStore.OnCreateGem = OnCreateGem;
   globalStore.OnBackToColour = OnBackToColour;
   globalStore.MakeNewVectors_OnClick = MakeNewVectors_OnClick;

   globalStore.ActiveGem = new Gem();

   // Allow the params page to use the SizeFromVectorOption
   globalStore.ActiveGem.SizeFromVectorOption = true;

   globalStore.ActiveGem.TargetDiv = gemsDiv;
   globalStore.ActiveGem.CallingDiv = paramsDiv;
   globalStore.ActiveGem.CallbackFunction = GemCallback;
   globalStore.ActiveGem.WriteShapeSelectionHTML();

}

function write_params(targetDiv)
{
   targetDiv.innerHTML = "";
   var hArr = new Array();
   hArr.push("<table width='100%' border=0 cellspacing=0 style='margin-left:3px'>");
   hArr.push("<col width=40px><col width=30%><col width=70%>");


   hArr.push("<tr><td align=left><img src='" + globalStore.PluginImageSrc + "'></td><td colspan=2><b>" + gPluginName + "</b></td></tr>");
   hArr.push("<tr><td></td><td colspan=2><input type=checkbox id='MakeNewVectors' onclick='globalStore.MakeNewVectors_OnClick()' checked>"+gNewVectors+"</td></tr>");
   hArr.push("<tr><td></td><td id=DeleteOldVectorsRow colspan=2><input type=checkbox id='DeleteOldVectors' checked>"+gDeleteVectors+"</td></tr>");
   hArr.push("<tr><td></td><td><nobr>"+ gNameEdit + ":</nobr></td><td align=right><input type=edit id=GemNameEdit></td></tr>");
   hArr.push("</table>");

   // Add the back and forward button HTML to the array
   hArr.push("<div class='mouseOut' button_name='forward_button' id=ForwardButton targetFunction='globalStore.OnCreateGem' style='width=30px;float:right;'>");
   hArr.push("<img id=back_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='back_button' targetFunction='globalStore.OnBackToColour' 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>");
   // Bung all our HTML into the div and display it
   targetDiv.innerHTML += hArr.join("\n");

   globalStore.GemNameEdit = eval(GemNameEdit);
   globalStore.GemNameEdit.value = gGem;
   InitialiseButtonDivs();
   SubclassNumberEditControls();
}

function OnCreateGem()
{
   // We need to restore gPluginName as it will have been overridden whilst inside gemObject.js
   GetPluginTitle(artcam.HtmlRootDir + "JewelSmith/VectorToGem/VectorToGem.atext", false);

   // create a undo redo block from here on
   artcam.AddBatchUndoMarker(gPluginName, true );

   // Get the Gem Vector Layer index
   var layer_index = globalStore.ActiveGem.GetGemVectorLayer();

   // Find out whether we are making new vectors and deleting old ones.
   // We only allow the delete old vectors option if make_new_vectors is true
   var make_new_vectors = MakeNewVectors.checked;
   var delete_old_vectors = false;
   if( make_new_vectors )
      delete_old_vectors = DeleteOldVectors.checked;

   // We now need to loop through our Vector Array and store the Gem info in each of the vectors
   // (Creating and deleting vectors if neccessary)
   for(var index=0;index<globalStore.selectedVectorArray.length;index++)
   {
      var vector = globalStore.selectedVectorArray[index];

      // Set the size from the vector if requested
      if(globalStore.ActiveGem.SizeSetFromVector)
      {
         globalStore.ActiveGem.Width  = vector.MaxX - vector.MinX;
         globalStore.ActiveGem.Length = vector.MaxY - vector.MinY;
         globalStore.ActiveGem.Depth  = globalStore.ActiveGem.Width * 0.42; // This is close to a brilliant
      }

      // Need to override the height width if we are taking it from the vector
      globalStore.ActiveGem.Name = globalStore.GemNameEdit.value + " " + (index+1);
      globalStore.ActiveGem.InitialAngleReference = globalStore.ActiveGem.GetReferenceAngle(vector);
      globalStore.ActiveGem.StoreInfoInVectorObject(vector);

      // Make a new vector if requested
      if( make_new_vectors )
      {
         // Retrieve the info back from the current vector object.
         // This will ensure that XPosition etc is set for DrawVector
         globalStore.ActiveGem.RetrieveInfoFromVectorObject(vector);
         globalStore.ActiveGem.DrawVector();
         vector = artcam.GetVectorObjectWithId(globalStore.ActiveGem.VectorID);
      }

      // Move this vector to the gem layer
      if( typeof(vector) == 'object' && artcam.VectorLayers.IsValid(layer_index) )
         vector.Layer = layer_index;
   }

   // Delete the old vectors if requested
   if( delete_old_vectors )
      artcam.Drawing.DeleteVectors(globalStore.SelectedVectorID,true);

   // End a undo redo block here
   artcam.AddBatchUndoMarker(gPluginName, false );

   artcam.Refresh2dView();
   OnBackButton();
}

function GemCallback(completed)
{
   if(!completed)
   {
      OnBackButton();
      return;
   }
   globalStore.GemNameEdit.value = globalStore.ActiveGem.Shape + gGem;
}



function CreateSelectedClosedVectorArray()
{
   // Store the selection dtring for deleting later
   globalStore.SelectedVectorID = artcam.SelectedVectorID;

   // Create an Array of all vectors in the selection
   globalStore.SelectionContainedOpenVectors = false;
   var GemVectorArray = new Array();
   for(var index=0;index<artcam.VectorSelection.Count;index++)
   {
      var obj = artcam.VectorSelection.Item(index);
      AppendClosedVectorsToArray(obj, GemVectorArray);
   }
   return GemVectorArray;
}

function AppendClosedVectorsToArray(obj, array)
{
   if (obj.IsContour)
   {
      // Only add if this is a closed vector
      if( obj.IsOpen() )
         globalStore.SelectionContainedOpenVectors = true;
      else
         array.push(obj);
      return true;
   }
   else if (obj.IsGroup)
   {
      // this is a group - call ourselves recursively with each item in group
      var num_objs = obj.NumObjectsInGroup;
      for (var i = 0; i < num_objs; i++)
      {
         if (!AppendClosedVectorsToArray(obj.Item(i),array))
            return false;
      }
      return true;
   }
   // shoudnt reach here
   return false;
}


function MakeNewVectors_OnClick()
{
   // Disable the delete option if we are not making new vectors
   DeleteOldVectorsRow.disabled = !MakeNewVectors.checked;
}

function OnBackToColour()
{
   globalStore.ActiveGem.TargetDiv.innerHTML = "";
   globalStore.ActiveGem.WriteColourSelectionHTML();
}
