// Work out a couple of colours and convert to strings.
var gBGColVal    = artcam.GetSysColor(COLOR_BTNFACE);
var gDkGrayVal   = artcam.GetSysColor(COLOR_BTNSHADOW);
var gHalfGray    = GetColorShade(gBGColVal, 2, gDkGrayVal, 1);
var gHalfGrayStr = ColorToString(gHalfGray);

function WritePluginList(dir_path, libraryDiv, image_size)
{
   // Firstly we empty the libraryDiv
   libraryDiv.innerHTML = "";

   if(typeof(image_size)=='undefined')
      image_size = 50;

   // We need our filesystem object to check directories
   var fs = artcam.CreateFileSelector();
   if(fs == null)
   {
      artcam.Alert("WritePluginList::Unable to create FileSelector",0);
      return;
   }
   if(!fs.DirectoryExists(dir_path))
   {
      artcam.Alert("WritePluginList::The Folder '" + dir_path + "' does not exist",0);
      return;
   }
   
   // Create an Array for keeping all the strings for our HTML that we will write.
   var hArr = new Array();
   var col_index = 0;
   var column_count = 3;

   hArr.push("<table border=0 width=100% style='margin-left:1px;text-align:center;table-layout:fixed'>");
   hArr.push("<colgroup>");
   for(var index = 0;index<column_count;index++)
   {
      //hArr.push("<col width="+ 100/column_count +"%>");
      hArr.push("<col width=55>");
   }
   hArr.push("</colgroup>");
   //hArr.push("<col width=33%><col width=33%><col width=33%>");

   /* We loop through all the folders in this directory
   var dirList = artcam.CreateDirectoryList(dir_path);
   dirList.StartList("*"); // Enumerate ALL items. '*' wild card matches everything
   while( dirList.ItemIsValid() )
   {
      // If this is a directory we add it to the HTML array
      if( dirList.ItemIsDirectory() )
      {         
        col_index = BuildFolderInArray(fs, dirList.ItemPath, hArr, col_index, column_count, libraryDiv.toString, image_size);
      libraryDiv.innerHTML = hArr.join("\n");
      }

      // Move onto the next folder
      dirList.NextItem();
   }*/

   // We loop through all the folders in this directory and build a list
   var dirList = artcam.CreateDirectoryList(dir_path);
   var directory_list = new Array();
   dirList.StartList("*"); // Enumerate ALL items. '*' wild card matches everything
   while( dirList.ItemIsValid() )
   {
      // If this is a directory we add it to the list array
      if( dirList.ItemIsDirectory() )
      {         
         directory_list.push(dirList.ItemPath);
      }
      // Move onto the next folder
      dirList.NextItem();
   }
   // Bin the DirectoryList Object
   dirList=0;

   //Sort the list
   directory_list.sort();

   // Build HTML
   for(var index = 0;index<directory_list.length;index++)
   {
      col_index = BuildFolderInArray(fs, directory_list[index], hArr, col_index, column_count, libraryDiv.toString, image_size);
      libraryDiv.innerHTML = hArr.join("\n");
   }

   if(col_index <= column_count-1)
           hArr.push("</tr>");

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

   // If we didn't get any entries in our Array then there were no files 
   // to discover in the current directory. We just mark it all as empty
   // otherwise we join up the array, separated by newlines and set the innerText
   if( hArr.length == 0 )
      return;
   else
      libraryDiv.innerHTML = hArr.join("\n");
}

function BuildFolderInArray(fs, currFolderPath, hArr, col_index, column_count, section, image_size)
{
   // This function finds all the files in a folder and adds HTML to display them to the array passed in.
   // Store whether or not we have written the header.
   // Create a path splitter object for cutting up pathnames
   var splitpath = artcam.CreateSplitPath(currFolderPath);
   if( splitpath == null )
      return; // If we can't create it we ignore this directory

   // First loop through all the JS files in this directory
   var dirList = artcam.CreateDirectoryList(currFolderPath);
   dirList.StartList("*.js"); // Enumerate js files, if there are any

   var js_list = new Array();
   while( dirList.ItemIsValid() )
   {
      js_list.push(dirList.ItemPath);
      dirList.NextItem();
   }
   js_list.sort();

   for(var index=0;index<js_list.length;index++)
   {
      splitpath.Path = js_list[index];

      if(splitpath.File == "MachineProject")
      {
         if(artcam.IsMachiningEnabled() == false)
            continue;
      }

      if(col_index == 0)
      {
         hArr.push("<tr id=" +section + "><td>");
      }
      else
      {
         hArr.push("<td>");
      }

      hArr.push("<div class='mouseOut'");
      hArr.push("button_name='" + js_list[index] + "' ");
      hArr.push("targetFunction = 'RunScriptFile' ");
      hArr.push("functionArgs ='" + js_list[index] + "'>");
      // First, if there is an associated gif or jpg we display that as a thumbnail
      splitpath.Extension = "";
      var img_filename = splitpath.Path;
      if( fs.FileExists(img_filename + ".jpg") )
         img_filename += ".jpg";
      else if( fs.FileExists(img_filename + ".gif") )
         img_filename += ".gif";
      else
         img_filename = null;
      
      if( img_filename != null )
         hArr.push("<img src='"+img_filename+"' align=absmiddle border=0 width="+image_size+" height="+image_size+"><br>");

      hArr.push(GetPluginTitle(splitpath.Path, false));

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

      if(col_index >= column_count-1)
      {
         hArr.push("</td></tr>");
         col_index=0;
      }
      else
      {
         hArr.push("</td>");
         col_index++;
      }
      return col_index;
   } 
   // Found no files - Look for subdirectories.
   dirList.StartList("*"); // Enumerate ALL items. '*' wild card matches everything

   var directory_list = new Array();
   while( dirList.ItemIsValid() )
   {
      if( dirList.ItemIsDirectory() )
      {
         directory_list.push(dirList.ItemPath);
      }
      dirList.NextItem();
   }
   dirList = 0;

   directory_list.sort();

   var header_created = false;
   for(var index=0;index<directory_list.length;index++)
   {
      // If it is a directory...
      // Create Foldup and re-parse the directory
         var baseID = GetSafeVariableName(currFolderPath);
         var section_name = baseID + "Section";
         var image_name = section_name + "Img";
         if(!header_created)
         {
            // Finish of current row
            if(col_index <= column_count-1)
            {
               hArr.push("</tr>");
               col_index=0;
            }
            hArr.push("<tr><td colspan=" + column_count + " ");
            hArr.push("     style='padding-left:5px;margin-bottom:4px;margin-top:5px;background-color:"+gHalfGrayStr+"'");
            hArr.push("     onclick='OnClickHeaderBar(" + section_name + "," + image_name + ")'>");
            hArr.push("  <img id='"+image_name+"'");
            hArr.push("       src='" + artcam.HtmlRootDir + "../SharedImages/close_up_small_grey.gif'");
            hArr.push("       align='right'");
            hArr.push(">");

            var title_text = GetPluginTitle(currFolderPath, true);

            hArr.push("  <b>"+title_text+"</b>");
            hArr.push("</td></tr>");
            header_created = true;
         }
         col_index = BuildFolderInArray(fs, directory_list[index], hArr, col_index, column_count, section_name, image_size);
   }
   return col_index;
}

function GetSafeVariableName(filepath)
{
   // tpb 22/06/06 Simply calls GetEndName which returns a simplified name, and makes a variable compatible name for JScript
   return "v_" + GetEndName(filepath).replace(/[^a-zA-Z0-9_]/g, ""); // Ensure variable is in correct JScript format with no bad characters
}

function GetEndName(filepath)
{
   var splitpath = artcam.CreateSplitPath(filepath);
   if( splitpath == null )
      return filepath;
   var basename = splitpath.File;
   if(basename.length == 0 )
      basename = filepath;
   return basename;
}

function RunScriptFile(filename)
{
   var fso = artcam.CreateFileSelector();
   if(fso == null)
   {
      artcam.Alert("RunScriptFile::Unable to Create FileSystemObject",0);
      return;
   }
   if(!fso.FileExists(filename))
   {
      artcam.Alert("RunScriptFile::The file '" + filename + "' does not exist",0);
      return;
   }
   gFileCode = fso.ReadTextFile(filename);

   var splitpath = artcam.CreateSplitPath(filename);
   splitpath.Extension = "atext";
   globalStore.PreviousFormHelp = gFormHelp;
   EvalJewelSmithAtextFile(splitpath);

   splitpath.Extension = "gif";
   var ImageSrc = splitpath.Path;

   globalStore = new Object();
   splitpath.File = "";
   splitpath.Extension = "";
   globalStore.ComponentPath = splitpath.Path;
   globalStore.PluginImageSrc = ImageSrc;
   if(typeof(parent.header)!='undefined')
   {
      globalStore.PreviousImageSrc = parent.header.titleImage.src;
      globalStore.PreviousPageTitle = parent.header.titleText.innerHTML;
      SetHeaderTitle(gPluginName,globalStore.PluginImageSrc);
   }
   else
   {
      globalStore.PreviousImageSrc = "";
      globalStore.PreviousPageTitle = "";
   }
   eval(gFileCode);
   eval("plugin_main()");
	// if help is NOT visible turn it off
   SetHelpSpanVisibility();
}

function AddBackButtonHTML(hArr)
{
   hArr.push("<div class='mouseOut' button_name='back_button' targetFunction='OnBackButton' 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>");
}

function OnBackButton()
{ 
   // If there is an Active Gem need to do extra tidying up
   if (globalStore.ActiveGem != null)
   {
      globalStore.ActiveGem.OnClose();
   }

   if(globalStore.PreviousPageTitle!=undefined && globalStore.PreviousPageTitle!="" )
   {
      SetHeaderTitle(globalStore.PreviousPageTitle,globalStore.PreviousImageSrc);
   }

   if(artcam.ProjectAssemblyExists && artcam.ProjectAssembly.FlagExists("BuildingFlag"))
   {
      if(artcam.ProjectAssembly.GetFlag("BuildingFlag", false) != false)
      {
         artcam.ProjectAssembly.SetFlag("BuildingFlag", false);
      }
   }

   gFormHelp = globalStore.PreviousFormHelp;

   SetHelpSpanVisibility();

   globalStore = new Object(); // Will cause everything to be deleted, but leaves the globalStore ready to accept new members
   ShowAllLibraryDivs();
   paramsDiv.style.display="none";
}

function OnClickHeaderBar(section, image)
{
   var row_collection = eval(section);
   var image_object = eval(image);
   
   // Check if there is more than one row
   if(typeof(row_collection.length) == 'undefined')
   {
      // Single row
      if(row_collection.style.display == "none")
      {
         row_collection.style.display = "";
         image_object.src = artcam.HtmlRootDir + "../SharedImages/close_up_small_grey.gif";
         // tpb 25/02/03 Ensure visible
         var obj = row_collection;//.offsetParent.offsetParent;
         var scrolltop = obj.offsetTop + obj.offsetHeight - document.body.offsetHeight;
         if( document.body.scrollTop < scrolltop )
            document.body.scrollTop = scrolltop;
      }
      else
      {
         row_collection.style.display = "none";
         image_object.src = artcam.HtmlRootDir + "../SharedImages/open_down_small_grey.gif";
      }
      
   }
   else
   {
      for(var index=0;index<row_collection.length;index++)
      {
         if(row_collection[index].style.display == "none")
         {
            row_collection[index].style.display = "";
            image_object.src = artcam.HtmlRootDir + "../SharedImages/close_up_small_grey.gif";
            // tpb 25/02/03 Ensure visible
            var obj = row_collection[index];//.offsetParent.offsetParent;
            var scrolltop = obj.offsetTop + obj.offsetHeight - document.body.offsetHeight;
            if( document.body.scrollTop < scrolltop )
               document.body.scrollTop = scrolltop;
         }
         else
         {
            row_collection[index].style.display = "none";
            image_object.src = artcam.HtmlRootDir + "../SharedImages/open_down_small_grey.gif";
         }
      }
   }
}

function HideAllLibraryDivs()
{
  var tags = document.all.tags("div");
  var idx, tag;
  var count = tags.length;
  for( idx = 0; idx < count; idx ++ )
  {
    tag = tags[idx];
    if( tag.library != null)
    {
       tag.style.display="none";
    }
  }
}

function ShowAllLibraryDivs()
{
  var tags = document.all.tags("div");
  var idx, tag;
  var count = tags.length;
  for( idx = 0; idx < count; idx ++ )
  {
    tag = tags[idx];
    if( tag.library != null)
    {
       tag.style.display="";
    }
  }
}

function EvalJewelSmithAtextFile(splitpath)
{
   var fs = artcam.CreateFileSelector();
   if(fs == null)
   {
      artcam.Alert("EvalJewelSmithAtextFile::Unable to create FileSelector",0);
      return;
   }

   var filepath = artcam.HtmlLangDir + "JewelSmith\\" + splitpath.File + "." + splitpath.Extension;
   //Check for translation first
   if(!fs.FileExists(filepath))
   {
      filepath = splitpath.Path;
   }

   if(fs.FileExists(filepath))
   {
      eval(fs.ReadTextFile(filepath));
   }
}

function GetPluginTitle(plugin_path, is_directory)
{
      var atextpath = artcam.CreateSplitPath(plugin_path);

      if(is_directory)
      {
         // Directory
         var indexed_name = atextpath.File;
         var split_array = indexed_name.split("_");
         if(split_array.length>1)
            non_indexed_name = split_array[1];
         else
            non_indexed_name = atextpath.File;
         
         atextpath.Path = atextpath.Path + "\\" + non_indexed_name;
      }

      gPluginName = "";
      atextpath.Extension = "atext";
      EvalJewelSmithAtextFile(atextpath);
      if(gPluginName == "")
         return GetEndName(plugin_path);
      else
         return gPluginName;
}



//=== GetCorrectedVectorLayer ==============================================
//
// Returns the Vector layer for the Corrected vectors. Creates it if it doesn't exist.
//
// History
// Who When     What
// --- -------- ---------------------------------------------------------
// tpb 01/07/04 Written
//-----------------------------------------------------------------------

function GetCorrectedVectorLayer()
{
   // See if we have a corrected vector layer
   var vl = artcam.VectorLayers;
   for(var layer_index = vl.FindFirst();                                          // Loop from first layer
       vl.IsValid(layer_index) && vl.GetLayer( layer_index ).name != gCorrectedVectors; // Break if we have found it
       layer_index = vl.FindNext(layer_index) );                                  // Move to next layer

   // If we haven't found one, create it
   if(!vl.IsValid(layer_index))
   {
      // Remember the current layer first and set it back afterwards
      var selIdx = vl.selectedIndex;
      layer_index = vl.Create(-1, gCorrectedVectors);
      vl.selectedIndex = selIdx;
   }

   // If we have a layer, set it's colour to be a ruby colour, ensure it is visible and return the index
   if(vl.IsValid(layer_index))
   {
      var layer = vl.GetLayer(layer_index);
      layer.color = 0x008800; // (0xbbggrr)
      layer.visibility = 100;
   }

   // Now return the index which may or may not be valid
   return layer_index;
}

function WriteFormHelpSection(hArr)
{
   hArr.push("<table width='100%' border=0 cellspacing=0 style='table-layout:auto'>");
   hArr.push("<tr style='display:none' HELPTAG><td><img align=left src='" + artcam.HtmlRootDir + "../SharedImages/help.gif'>" + gFormHelp + "</td></tr>");
   hArr.push("</table>");
}
