//=============================================================================
//
//@doc EXTERNAL
//
//@module templateModel.js |  Template Model code
//
// ----------------------------------------------------------------------------
// COPYRIGHT 2004 DELCAM PLC., BIRMINGHAM, ENGLAND. 
// ----------------------------------------------------------------------------
//
// History.
// Who When     What   
// --- -------- ---------------------------------------------------------------
// pah 14/06/04 Created
//-----------------------------------------------------------------------------

 // 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);

 var SharedImagesDir;

//=== BuildTemplateLibrary ====================================================
//
// Build template library - assumes that libraryDiv exists
//
// History
// Who When     What
// --- -------- ---------------------------------------------------------------
// pah 14/06/04 Written
//-----------------------------------------------------------------------------
function BuildTemplateLibrary(setOpenShutStates, libDir, extension)
{
   // Firstly we empty the libraryDiv
   libraryDiv.innerHTML = "";

   // We get the template directory and build up a list of all the
   // artcam models within it

   SharedImagesDir = artcam.HtmlRootDir + "../SharedImages";

   if( libDir == "" )
      return;

   // We need our filesystem object to check directories
   var fs = artcam.CreateFileSelector();
   if(fs == null)
   {
      artcam.MessageBox("Unable to create FileSelector, page will not work properly!");
      return;
   }
   if(!fs.DirectoryExists(libDir))
      return;
   
   // Create an Array for keeping all the strings for our HTML that we will write.
   // Each line will be written in as a string and then we will perform a join at the end
   // This is much quicker than simply doing string concatonation with the innerHTML or
   // a javascript string object, which reallocates and copies increasingly longer and
   // longer strings. With this method we allocate individual strings then use the Array
   // join method for throwing the entire array into one string.
   var hArr = new Array();

   // Add the files in the root folder before we do the subfolders
   BuildFolderInArray(fs, libDir, hArr, extension);

   // We loop through all the folders in this directory
   var dirList = artcam.CreateDirectoryList(libDir);
   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() )
         BuildFolderInArray(fs, dirList.ItemPath, hArr, extension);

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

   // 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 )
      SetErrorText(libDir);
   else
      libraryDiv.innerHTML = hArr.join("\n");

   //alert("div: " + libraryDiv.innerHTML );

   // Now setup all the open shut states of the folder bars
   // We do this from initialise so we can reload a page in it's last state
   if(setOpenShutStates)
      SetupOpenShutStates();
   else
   {
      // However when we change directory we want everything to be left open
      // for the user to close and we must synchronise this open state within artcam
      var count = document.images.length;
      for ( var img = 0; img < count; img++ )
      {
         imgDiv = document.images[img];
         if(imgDiv.childDiv != null)
            artcam.StoreString(window.document.title, imgDiv.id, "");
      }
   }
}



function BuildFolderInArray(fs, currFolderPath, hArr, ext)
{
   // 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.
   // We only write the header if we have found files inside
   var folderHeaderWritten = false;

   // 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

   // Get the name of this folder to be used later
   var currFolderName = splitpath.File;

   // Now loop through all the files in this directory
   var dirList = artcam.CreateDirectoryList(currFolderPath);
   dirList.StartList("*"); // Enumerate ALL items. '*' wild card matches everything
   while( dirList.ItemIsValid() )
   {
      // Ignore directories we just examine the files
      if( !dirList.ItemIsDirectory() )
      {
         // If it is the right extension, work on it
         splitpath.Path = dirList.ItemPath;
         var extension = splitpath.Extension;
         switch(extension.toLowerCase())
         {
         case ext:
            // If the folder hasn't been written and we have found an appropriate file
            // Then we write in the header
            if(!folderHeaderWritten)
            {
               folderHeaderWritten = true;
               var baseID = "foldBarDiv" + hArr.length; // We need a unique ID for the foldups
               hArr.push("<div id='"+baseID+"'");
               hArr.push("     style='padding-left:5px;margin-bottom:4px;margin-top:5px;background-color:"+gHalfGrayStr+"'");
               hArr.push("     onclick='OnToggleClick("+baseID+"Img)'>");
               hArr.push("  <img id='"+baseID+"Img'");
               hArr.push("       src= "+SharedImagesDir+"/close_up_small_grey.gif'");
               hArr.push("       align='right'");
               hArr.push("       childDiv='"+baseID+"Foldup'");
               hArr.push("       defaultDisplay=''>");
               hArr.push("  <b>"+currFolderName+"</b>");
               hArr.push("</div>");
               hArr.push("<div id="+baseID+"Foldup");
               hArr.push("     style='font-weight:bold;margin-left:10px;margin-right:10px;'>");
            }

            // Now add the file in the list
            hArr.push("<nobr>"); // Don't allow anything in this span to be put on a separate line
            hArr.push("<div class='mouseOut'");
            hArr.push("     onMouseOver='OnItemMouseOver()'");
            hArr.push("     onMouseOut='OnItemMouseOut()'");
            hArr.push("     onClick='OnItemClick()'");
            hArr.push("     filepath=\""+dirList.ItemPath+"\">");

            // 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=32 height=32>");
            hArr.push( GetSafeBaseName(dirList.ItemPath) );
            hArr.push("</div>");
            hArr.push("</nobr>");
            break;

         default:
            break;
         }
      }

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

   // If we wrote the folder header then we have to close of the dropdown div here
   if( folderHeaderWritten )
      hArr.push("</div>");
}

function SetErrorText()
{
}

function GetEventItem(ev)
{
   if(ev.srcElement.filepath != null)
      return ev.srcElement;
   if(ev.srcElement.parentElement.filepath != null)
      return ev.srcElement.parentElement;
   return null;
}

function OnItemMouseOver()
{
   var item = GetEventItem(event);
   if(item != null)
      item.className = "mouseOver";
}

function OnItemMouseOut()
{
   var item = GetEventItem(event);
   if(item != null)
      item.className = "mouseOut";
}

function OnItemClick()
{
   var item = GetEventItem(event);
   if(item == null)
   {
      alert("If you get this message, then the HTML tags are out of sync in this page\n\n" +
            "Timothy Buck in ArtCAM development should be able to help");
      return;
   }

   // We need to open the template in ArtCAM now
   artcam.OpenTemplateModel(item.filepath);
}


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


// ======================================================================================
// === O P E N S H U T   H A N D L E R S ===
// ======================================================================================
function OnToggleClick(imgDiv)
{
   var state;
   var childDiv = eval(imgDiv.childDiv);
   if(childDiv.style.display == "none")
   {
      childDiv.style.display = "";
      imgDiv.src = SharedImagesDir + "/close_up_small_grey.gif";
      // tpb 25/02/03 Ensure visible
      var obj = childDiv;//.offsetParent.offsetParent;
      var scrolltop = obj.offsetTop + obj.offsetHeight - document.body.offsetHeight;
      if( document.body.scrollTop < scrolltop )
         document.body.scrollTop = scrolltop;
      state = "";
   }
   else
   {
      childDiv.style.display = "none";
      imgDiv.src = SharedImagesDir + "/open_down_small_grey.gif";
      state = "none";
   }
   
   // Store current setting in ArtCAM
   artcam.StoreString(window.document.title, imgDiv.id, state);
}



function SetupOpenShutStates()
{
   // This function is called once by initialise
   // Go through all the images and use the ones that have the childDiv set
   var count = document.images.length;
   for ( var img = 0; img < count; img++ )
   {
      imgDiv = document.images[img];
      if(imgDiv.childDiv != null)
      {
         // If the childDiv is set, we evaluate it to the object and then change
         // the display states according to the string stored in ArtCAM
         var childDiv = eval(imgDiv.childDiv);
         var state = artcam.RetrieveString(document.title, imgDiv.id, imgDiv.defaultDisplay);
         childDiv.style.display = state;
         if( state == "none" )
            imgDiv.src = SharedImagesDir + "/open_down_small_grey.gif";
         else
            imgDiv.src = SharedImagesDir + "/close_up_small_grey.gif";
      }
   }
}