////////////////////////////////////////////////////////////////////////////
//                                                                        //
//          Copyright (C) 2011 ANSYS Inc.  All rights reserved.           //
//     Unauthorized use, distribution or duplication is prohibited.      //
//                                                                        //
// This file contains proprietary software licensed from ANSYS Inc.       //
// This header must remain in any source code despite modifications or    //
// enhancements by any party.                                             //
//                                                                        //
////////////////////////////////////////////////////////////////////////////
//
// $Workfile: $
// $Revision: 744063 $
// $Date: 2014-06-13 02:46:08 -0400 (Fri, 13 Jun 2014) $
// $Author: ybaranwa $
//
// Decription: JScript for the AG (ANSYS Geometry) Workbench GUI
//             Implements preference settings
//
// All declared identifiers start with 'ag'
////////////////////////////////////////////////////////////////////////////

function agLoadPreferences (newOrStartup, clearFlag, unitPromptFlag, allowFolderPrompt)
{
  var prefChanged = false;
  
  // Turn the hourglass on
  agGUI_OnCursorWaitON();
  ++ag.processingPreferences;

// Preference setting in AGObject has been moved to GM.cpp file
 prefChanged = ag.m.LoadPreference(newOrStartup, clearFlag, allowFolderPrompt);
  
  // Number of digits
  if(ag.gui)
    ag.gui.setPrecision (agPrefInt("PID_Sig_Digits"));

  // Beta Features?
  agMode (ag.lastMode);  // calling agMode_betaFeatures();

  // Graphics
  if(ag.gui)
  {
    if(newOrStartup == false && allowFolderPrompt == true)
    {
      processPrefChangePrompt();
    }
  }
  if(ag.gb)
    ag.gb.DynamicViewing = agPrefInt("PID_Dynamic_Viewing");

  // Toolbar
  var showTexts = (agPrefInt("PID_Omit_Text") == 0);
  ag.showToolbarTexts = showTexts;
  try
    {
      for (var ix = 0; ix < ag.textTbrs.length; ix ++)
        ag.textTbrs[ix].DisplayButtonText = showTexts;
    }
  catch(e)
    { // Ignore: ag.textTbrs doesn't exist yet
    }

	//Check to see if any of the (customizable)feature toolbar button prefs have changed.
	//This way we do not rebuild the toolbar every time a change occurs occurs in the Control Panel.
	if (!newOrStartup)
    agCheckToolbarButtonPrefs ();

  // Unit setting -- WITH THE NEW Project Page THIS IS PRETTY MUCH DISABLED
  if(agLoadUnitSettings (newOrStartup, clearFlag, unitPromptFlag))
    prefChanged = true;

  //Grid/Axes default sizes (per each supported unit)
  if(ag.gui)
  {
    if(agLoadGridDefaults (newOrStartup))
      prefChanged = true;
  }

  // Dimensions animation preferences
  // Needs to be checked here, b/c Control Panel logic does not validate
  if(ag.gui)
  {
    var min = agPrefNum("DimensionAnimateMin");
    var max = agPrefNum("DimensionAnimateMax");
    if (min < max)
    {
      // Ok, set it
      ag.gui.setPrefValue ("SkDimAnimateMinFactor", min);
      ag.gui.setPrefValue ("SkDimAnimateMaxFactor", max);
    }
    else
    {
      //Reset min to old value
      min = ag.gui.getPrefValue ("SkDimAnimateMinFactor");
      max = ag.gui.getPrefValue ("SkDimAnimateMaxFactor");
      agSetPref ("DimensionAnimateMin", min);
      agSetPref ("DimensionAnimateMax", max);
      prefChanged = true;
    }
  }

  // When to delete Auto-save files? Check for valid value...
  if ((typeof(ag.prevLimitAutosaveDir) != "undefined") &&
      (agPrefInt("LimitAutosaveDir") < 1))
    {
      agSetPref ("LimitAutosaveDir", ag.prevLimitAutosaveDir);
      prefChanged = true;
    }

  // SpaceBall support
  if(!wb.Hidden)
    ag.gfx.Use3DMotionController = (agPrefInt("PID_SpaceBall") == 1);

  // Turn the hourglass off
  if(ag.gui)
    agGUI_OnCursorWaitOFF();

  // Commit to changes, if any
  if(prefChanged)
    agSetPrefSave ();
  --ag.processingPreferences;
}

function agCheckToolbarButtonPrefs ()
{
  var id, name, pref, button;
  var tbrnames = agToolbarNames();
  for (var j = 0; j < tbrnames.length; j++) 
  {
    var tbr = ag.menu.ToolBars.Item(tbrnames[j]);
    if (!tbr) continue;
    for (var i = 0; i < ag.controlledButtons.length; i++) 
    {
      name = ag.controlledButtons[i].Name;

      // This is ugly, but necessary for drop down menus in the toolbar
			if (name == "Mn3dFBlend" || name == "Mn3dVBlend")
				id = "3dBlend";
			else if (name == "3dLineFromPoints" || name == "3dLineFromSketch" ||
               name == "3dLineFromEdges"  || name == "3dLineSplit" ||
               name == "3dSurfFromLines")
				id = "MnConcept";
			else if (name == "CS_RECT" || name == "CS_QUAD" || name == "CS_CSOLID" ||
               name == "CS_CTUBE" || name == "CS_CHANNEL" || name == "CS_IBEAM" ||
               name == "CS_ZEE" || name == "CS_ELL" || name == "CS_TEE" ||
               name == "CS_HAT" || name == "CS_HREC" || name == "CS_ASEC" ||
               name == "CS_USER")
        id = "MnCrossSections";
      else if (name == "MnPrimitiveSphere" || name == "MnPrimitiveBox" ||
               name == "MnPrimitiveParallelepiped" || name == "MnPrimitiveCylinder" ||
               name == "MnPrimitiveCone" || name == "MnPrimitivePrism" ||
               name == "MnPrimitivePyramid" || name == "MnPrimitiveBend")
				id = "MnPrimitives";
      else if (name == "MnShellPrimitiveTEnd" || name == "MnShellPrimitiveSEnd" ||
               name == "MnShellPrimitiveEEnd" || name == "MnShellPrimitivePEnd" ||
               name == "MnShellPrimitiveCYShell" || name == "MnShellPrimitiveCOShell" ||
               name == "MnShellPrimitiveSPShell" || name == "MnShellPrimitivePicking")
				id = "MnShellPrimitives";
		  else if(name == "ID_RepairSlivers" || name == "ID_RepairSpikes" || 
		          name == "ID_RepairHoles" || name == "ID_RepairEdges" ||
		          name == "ID_RepairFaces" || name == "ID_RepairSeams" ||
		          name == "ID_RepairSharpAngles" || name == "ID_RepairFillets" ||
                  name == "ID_RepairBodies")
		    id = "MnRepair";
		  else if (name == "ID_AT_DistanceFinder" || name == "ID_EntityInfo" ||
		          name == "ID_BoundingBox" || name == "ID_MassProperty" ||
		          name == "ID_FaultDetect" || name == "ID_SmallEntitySearch" ||
              name == "ID_BodyClashSearch" || name == "ID_OverlappingRegionSearch")
		    id = "ID_AnalysisTools";
		  else if (name == "MnIceSimplify" || name == "MnIceFan" || name == "MnIceGrille" ||
		          name == "MnIceOpening" || name == "MnElectronicsTools" ||
		          name == "MnDisplayBodiesEligibleForExport" || name == "MnDisplayBodiesNotEligibleForExport" ||
		          name == "MnDisplayRevertView")
		    id = "MnElectronics";
      else if (name == "MnTransformationMove" || name == "MnTransformationTranslation" ||
               name == "MnTransformationRotate" || name == "MnTransformationMirror" ||
               name == "MnTransformationScale")
          id = "MnTransformation";
            
      else
  			id = name;

      // Check if the preference has changed
      pref = agPrefInt(id);
      button = tbr.Buttons.Item(id);
      if ((button && (pref == 0)) || (!button && (pref == 1))) 
      {
        ag.BuildFeatureToolbar = true;
        break;
      }
    }
  }
	agCreateFeatureBar();
}

function agLoadUnitSettings (newOrStartup, clearFlag, unitPromptFlag) {
  var prefChanged = false;
  //debugger;
  if ((ag.gui) && newOrStartup && !clearFlag && unitPromptFlag)
  {
    var lenUnit = (agPrefInt("LengthUnit") == 8) ? ag.m.Interop.ProjLengthUnit : agPrefInt ("LengthUnit");
    var angUnit = (agPrefInt("AngleUnit") == 2) ? ag.m.Interop.ProjAngleUnit : agPrefInt("AngleUnit");
    var lmsFlag = agPrefInt ("LargeModOn");
    try
    {
      // LMS can ONLY be enabled with meter or feet unit
      if (lmsFlag && (lenUnit != 1) && (lenUnit != 7)) {
        var disablePopups = ag.m.EnvVarActive("TB_DISABLE_POPUP_IN_DM");
        if (!disablePopups) {
          agWarning(agString("AW_INCOMPATIBLE_LMS"));
        }
        lmsFlag = 0;
      }

      ag.gui.setUnits(lenUnit, angUnit, lmsFlag);
    }
    catch (error)
    {
      // Catch any other kind of errors
      agWarning(agString("AW_UNITS_SET_FAILURE"));
      ag.gui.setUnits(1 /*meter*/, 0/*degree*/, 0/*LMS off*/);
    }
  }
  else if ((agPrefInt("LargeModOn") != ag.prevLargeModOnSetting) && !clearFlag && !ag.WB2)
  {
    agSetPref("largeModOn", 1);
    prefChanged = true;
  }

  return prefChanged;
}

// The following function become obsolate as part of removing Units dialog (US67259).
function agLoadUnitSettings_Old (newOrStartup, clearFlag, unitPromptFlag)
{
  //debugger;
  var prefChanged = false;
  var usePopUp = false;
  if (ag.wb.AppletList.WBApplet("StartPage").InMemory || ag.WB2)
    usePopUp = true;
    
  if(newOrStartup && !clearFlag && unitPromptFlag)
    {
      // Take out 'usePopUp' to activate the unit pop-up permanently
      if (agPrefInt("UnitsBoxOn") == 1 && usePopUp)
        {
          var dlg = CreateActiveXObject(GenWBProgId("WBControls.WBHTMLDialog"));
          var unitsBox = CreateActiveXObject(GenWBProgId("WBControls.DlgArgs"));
          unitsBox("wb") = wb;
          unitsBox("ag") = ag;
          unitsBox("title") = agString("UnitsBoxTitle");
          unitsBox("unit1") = agString("Meter");
          unitsBox("unit2") = agString("Centimeter");
          unitsBox("unit3") = agString("Millimeter");
          unitsBox("unit4") = agString("Micron");
          unitsBox("unit5") = agString("Nanometer");
          unitsBox("unit6") = agString("Inch");
          unitsBox("unit7") = agString("Foot");
          unitsBox("ShowBox1") = agString("ShowUnitsBoxText1");
          unitsBox("ShowBox2") = agString("ShowUnitsBoxText2");
          unitsBox("ShowBox3") = agString("ShowUnitsBoxText3");
          //Onyx 83967 - a new option is added to the units option dialog
          //1.Always use proj schematic unit - use the units selected in WB2
          //2.Always use selected unit - will use the user selected unit next time DM opens.
          unitsBox("UseProjSchCheckBoxVal") = 1; 
          unitsBox("UseSelectUnitsCheckBoxVal") = 1;
          unitsBox("ProjSchUnit") = agPrefInt("LengthUnit");
          if(agPrefInt("DMLengthUnit") == 8)//UseProjSch
          {
            unitsBox("unit") = agPrefInt("LengthUnit");
          }
          else
            unitsBox("unit") = agPrefInt("DMLengthUnit");

          var largeModSuppDefault = agPrefInt("LargeModOn");
          unitsBox("UseLargeModCheckBoxVal") = largeModSuppDefault;
          ag.m.Busy = 1;

          // Note the window height below is actually a bit larger than we
          // need for en-us, but some foreign languages require an extra
          // line of text. Hence I'm adding a bit more of a cushion. - jmg
          var ret = dlg.DoDialog(wb.hWnd, ag.pagesDirNoLocale +
                                 "/html/agUnitsBox.htm", unitsBox,
                                 false, 250 /*Width*/, 270 /*Height*/,
                                 5, ag.wb.Title);

          ag.m.Busy = 0;
          // Evaluate the result
          if(unitsBox("UseProjSchCheckBoxVal") == 1)
          {
            agSetPref("DMLengthUnit", 8);
            ag.gui.setUnits (agPrefInt("LengthUnit"), 0, unitsBox("UseLargeModCheckBoxVal"));
            agSetPref("UnitsBoxOn", 0);
            prefChanged = true;
          }
          else if(unitsBox("UseSelectUnitsCheckBoxVal") == 1)
          {
            agSetPref("DMLengthUnit", unitsBox("unit"));
            
            agSetPref("UnitsBoxOn", 0);
            prefChanged = true;
            
            ag.gui.setUnits(unitsBox("unit"), 0, unitsBox("UseLargeModCheckBoxVal"));
            var currentUnit = ""
            switch (unitsBox("unit"))
            {
              case "1": currentUnit = "m"; break;
              case "3": currentUnit = "cm"; break;
              case "4": currentUnit = "mm"; break;
              case "6": currentUnit = "in"; break;
              case "7": currentUnit = "ft"; break;
              case "9": currentUnit = "um"; break;
              default : currentUnit = "";
            }
            agGUI_OnUpdateUnitStatus();
          }
          else
          {
            ag.gui.setUnits(unitsBox("unit"), 0, unitsBox("UseLargeModCheckBoxVal"));
            var currentUnit = ""
            switch (unitsBox("unit"))
            {
              case "1": currentUnit = "m"; break;
              case "3": currentUnit = "cm"; break;
              case "4": currentUnit = "mm"; break;
              case "6": currentUnit = "in"; break;
              case "7": currentUnit = "ft"; break;
              case "9": currentUnit = "um"; break;
              default : currentUnit = "";
            }
            // Since parameters are published as dimensionless
            // there is no need to push DM unit to addin
            // DEC 2008, PZOPE - Re-enable on Jan 22, 2013 by John T
            //agInteropSetDMUnitInAddin(currentUnit);
          }
          
          if(unitsBox("UseLargeModCheckBoxVal") != largeModSuppDefault)
          {
            agSetPref("LargeModOn", unitsBox("UseLargeModCheckBoxVal"));
            prefChanged = true;
          }
          agGUI_OnUpdateUnitStatus();
        }
      else
        {
          if(ag.gui)
          {
            if(agPrefInt("DMLengthUnit") == 8)//UseProjSch
            {
              ag.gui.setUnits (agPrefInt("LengthUnit"), 0, agPrefInt("LargeModOn"));
            }
            else
              ag.gui.setUnits (agPrefInt("DMLengthUnit"), 0, agPrefInt("LargeModOn"));
            agGUI_OnUpdateUnitStatus();
          }
        }
    }
    else if ((agPrefInt("LengthUnit") != ag.prevLengthUnitDefaultSetting) && !clearFlag && !ag.WB2)
    {
    
      // Who is T.User?? 
      // This code should be dead!
      
      // NOTE: in the above 'ag.gui.getLengthUnit()' is NOT necessarily
      // the same as 'ag.prevUnitDefaultSetting' -- see agMenuControlPanel().
      // Indeed, the C.P. setting for the default may be different, b/c
      // T.User just File>Opened an AGDB with units other than the default
      // -epm

      // Notify T.User that update only on file new or next start-up
      var ync;
      if (ag.WB2)
        ync = agYesNoCancel (agString("FileNewToChangeUnits?"));
      else
        {
          // Changing the unit system from the Control Panel is not supported
          ync = 0;
        }
      if (ync == 1) // Yes
        {
          ag.gb.Redraw(ag.c.RedrawAll);
          agMenuFileNew();
        }
      else if (ync == -1) // Cancel
        {
          // Undo the the change in the unit default settings
          agSetPref("LengthUnit", ag.prevLengthUnitDefaultSetting);
          prefChanged = true;
        }
    }
  else if ((agPrefInt("LargeModOn") != ag.prevLargeModOnSetting) && !clearFlag && !ag.WB2)
  {
    agSetPref("largeModOn", 1);
  }
    return prefChanged;
}

function agLoadGridDefaults (newOrStartup)
{
  var prefChanged = false;
  var aux = new Object();
  aux.major = ag.gui.getPrefValue("SkGridMajorDist");
  aux.minor = ag.gui.getPrefValue("SkGridMinorLines");
  aux.minsnaps = ag.gui.getPrefValue("SkGridSnapMinor");
  aux.lengthUnit = ag.m.GetCurrentLengthUnit();
  agLoadUnitPrefsHelper (aux, 1,  0.0,  0, 101, 0, 1001); //m
  agLoadUnitPrefsHelper (aux, 3,  0.0,  0, 101, 0, 1001); //cm
  agLoadUnitPrefsHelper (aux, 4,  0.0,  0, 101, 0, 1001); //mm

  agLoadUnitPrefsHelper (aux, 6,  0.0,  0, 101, 0, 1001); //in
  agLoadUnitPrefsHelper (aux, 7,  0.0,  0, 101, 0, 1001); //ft
  agLoadUnitPrefsHelper (aux, 9,  0.0,  0, 101, 0, 1001); //micrometer
  agLoadUnitPrefsHelper (aux, 10,  0.0,  0, 101, 0, 1001); //nanometer


  aux.show = agPrefInt("GridShow1");  // 1:yes, 0:no
  aux.snap = agPrefInt("GridSnap1");  // 1:yes, 0:no
  ag.m.Defaults.GridShow = aux.show;
  ag.m.Defaults.GridSnap = aux.snap;

  aux.forCurrent = agPrefInt("ApplyToActive1");  // 1:yes, 0:no

  //Set Grid values for current part if requested
  if ((aux.forCurrent == 1) && (newOrStartup == false))
    {
      // Ok, user requested setting current plane values
      ag.gui.setPrefValue ("SkGridOn", aux.show);
      ag.gui.setPrefValue ("SkGridSnapOn", aux.snap);
      ag.gui.setPrefValue ("SkGridMajorDist", aux.major);
      ag.gui.setPrefValue ("SkGridMinorLines", aux.minor);
      ag.gui.setPrefValue ("SkGridSnapMinor", aux.minsnaps);
    }

  // Turn the switch back to No (per each unit)
  if (aux.forCurrent == 1)
  {
    agSetPref("ApplyToActive1", 0);
    prefChanged = true;
  }
  return prefChanged;
}

function agLoadUnitPrefsHelper (aux, i, majorLower,
                                minorLower, minorUpper,
                                snapsLower, snapsUpper)
{
  var majorID = "GridMajor" + i;
  var minorID = "GridMinor" + i;
  var snapsID = "GridSnaps" + i;

  ag.m.SetAxisLengthForUnit (i, agPrefNum("AxisDefaultSize" + i));

  var major = agPrefNum(majorID); // double > majorLower?
  var minor = agPrefInt(minorID);   // interger > minorLower, < ipper?
  var minsnaps = agPrefInt(snapsID);   // interger > snapsLower, < ipper?
  if ((major > majorLower) &&
      (minor > minorLower) &&
      (minor < minorUpper) &&
      (minsnaps > snapsLower) &&
      (minsnaps < snapsUpper))
    {
      ag.m.Defaults.SetGridMajorDist (i, major);
      ag.m.Defaults.SetGridMinorSteps (i, minor);
      ag.m.Defaults.SetGridSnapMinor (i, minsnaps);
      if (aux.lengthUnit == i)
      {
        aux.major = major;
        aux.minor = minor;
        aux.minsnaps = minsnaps;
      }
    }
  else
    {
      agSetPref(majorID, ag.m.Defaults.GetGridMajorDist(i));
      agSetPref(minorID, ag.m.Defaults.GetGridMinorSteps(i));
      agSetPref(snapsID, ag.m.Defaults.GetGridSnapMinor(i));
    }
}

function agLimitAutosaveDir (d)
{
  // Remove all files in the AutoSave directory that are older then d days old
  var today = new Date();
  var temp_path = ag.m.TempDir;
  temp_path = ag.fs.BuildPath(temp_path, "agptmp");
  var strver = GenWBProgId("");
  temp_path = temp_path + strver.slice(1);
  var auto_path = ag.fs.BuildPath(temp_path, "AutoSave");

  /********************************************
    This version asks the user whether files should be deleted
    THIS IS CURRENTLY DISSABLED!
  var listing = "";
  if (ag.fs.FolderExists (auto_path))
  {
    var i = 0, expiredFiles = false;
    var dir = ag.fs.GetFolder (auto_path);
    var iter = new Enumerator (dir.Files);
    var oldIter = new Enumerator (dir.Files);
    for (; !iter.atEnd(); iter.moveNext())
    {
      var file = iter.item();
      if (agFileIsOlderThan (file, d, today) && (i <= 20))
      {
        if (i < 20)
          listing += "\n" + file.DateCreated + ":\t" + file.Name;
        else if (i = 20)
          listing += "\n" + "etc...";
        i++;
        expiredFiles = true;
      }
    }

    if (expiredFiles)
    {
      var msg = agString("DeleteAutoSave1") + " " + d + " "
              + agString("DeleteAutoSave2") + "\n" + listing;
      var deleteFiles = agYesNo(msg);
      if (deleteFiles)
      {
        for (; !oldIter.atEnd(); oldIter.moveNext())
        {
          var file2 = oldIter.item();
          if (agFileIsOlderThan (file2, d, today))
            ag.fs.DeleteFile(file2);
        }
      }
    }
  }
  *******************************************/

  // The enabled version simply deletes all files older than d days
	try
	{
  	var dir = ag.fs.GetFolder (auto_path);
  	var iter = new Enumerator (dir.Files);
  	for (; !iter.atEnd(); iter.moveNext())
  	{
  	  var file = iter.item();
  	  if (agFileIsOlderThan (file, d, today))
  	    ag.fs.DeleteFile(file);
  	}
	}
	catch(e)
	{

	}
}

function agFileIsOlderThan (file, days, today)
{
  // 86400000 is the number of milliseconds in a day
  return (file.DateCreated + (days * 86400000) < today.getTime());
}

function agPrefStr (id)
{
  // Returns a string
  return agPref (id);
}

function agPrefInt (id)
{
  // Should return an int, but also returns a string (lazy me, I don't care :)
  return agPref (id);
}

function agPrefNum (id)
{
  // Returns a floating-point number
  // We need to make sure that we handel the localized decimal point properly!

  var str = agPref (id);
  var num = ag.m.StringToDouble (str);
  return num;
}

function agPref (id)
{
  // Original query function for preferences, returning a string!
  // DO NO LONGER CALL THIS DIRECTLY; CALL agPrefStr|Int|Num(.) INSTEAD!
  //
  // Queries the Control Panel / User Preferences; or: the Registry over-write!
  var rg, from_rg = true;
  try
    {
      rg = ag.wbAnsRegHelper.RegRead (ag.appletPrefsRP + id);
    }
  catch(e)
    {
      from_rg = false;
    }
  try
    {
      var pr = ag.wb.PreferenceMgr.Preference(id);
      if (typeof(pr) == "undefined")
        {
          throw "No preference";
        }
      else if (from_rg)
        {
          if (pr != rg)
            agSetPref (id, rg);
          return rg;
        }
      else
        return pr;
    }
  catch(e)
    {
      if (from_rg)
        return rg;
      else
        {
          // agError ("No value for agPref(\"" + id + "\"");
          return 0;
        }
    }
}

function agSetPref (id, value)
{
  // Used in the above, to over-write the Control Panel setting
  // NOTE: this is only saved to disk once agSetPrefSave() is called
  var pm = ag.wb.PreferenceMgr;
  var pg = pm.PreferencesCategories.Item("CATNAME_DesignModeler").PreferencesGroups;
  var n = pg.Count;
  for (var i = 1; i <= n; i++)
    {
      var group = pg.Item(i);
      var prefs = group.Preferences;
      var m = prefs.Count;
      for (var j = 1; j <= m; j++)
        {
          var p = prefs.Item(j);
          if (p.PreferenceID == id)
            {
              p.Value = value;
              return;
            }
        }
    }
}

function agSetPrefSave()
{
  ag.wb.PreferenceMgr.Save();
}
