// Copyright 2000 Macromedia, Inc. All rights reserved.

//*************** GLOBALS *****************
var FILE_CONFIG_PATH = dw.getConfigurationPath();
var FILE_CUSTOM_SET = FILE_CONFIG_PATH + "/Menus/Custom Sets";

//******************* API **********************
function commandButtons()
{
   return new Array( BTN_OK,  "cmdOK()"
                   , BTN_Cancel, "cmdCancel()");
}

function cmdOK()
{
  var newSetName, facSetArray = new Array(), custSetArray = new Array();
  var canWrite = true;
  var oldFileName = MM.commandArgument;
  
  if (getExtension(oldFileName) != "xml")
    oldFileName += ".xml";
  newSetName = document.renameSetNameField.getAttribute("value");
  if (newSetName.lastIndexOf(".xml") != newSetName.length-4) 
    newSetName += ".xml";
  if (isSet(newSetName, "factory"))   // check to see if name used by factory set
  {
    alert(errMsg(MSG_NameUsedByFactorySet, newSetName));
	canWrite = false;
  }
  else if (isSet(newSetName, "custom"))
  { 
    if (oldFileName == newSetName)
	{
	  alert(MSG_SetNameIsTheSame);
	  canWrite = false;
	}
    else if (!confirm(errMsg(MSG_ShortcutSetAlreadyExists,newSetName)))
	  canWrite = false;
  }
  if (canWrite)
  {
    if (!DWfile.copy(FILE_CUSTOM_SET +"/"+ oldFileName, FILE_CUSTOM_SET+"/"+newSetName))
	  alert(errMsg(MSG_InvalidFileNameCannotSave, newSetName));
	else
	{
	  DWfile.remove(FILE_CUSTOM_SET +"/"+ oldFileName);
	  MM.commandReturnValue = getSimpleName(newSetName);
	  window.close();
	}
  }
}

function cmdCancel()
{
  window.close();
}
//***************** LOCAL FUNCTIONS  ******************

function initializeUI()
{ 
  var origSetName; // orig Set Name should be passed in 
  
  origSetName = MM.commandArgument;
  document.renameSetNameField.setAttribute("value", origSetName);
  document.renameSetNameField.focus();
  document.renameSetNameField.select();
}

function getCustomSetList(setType)
{
  var fileObj, filterFunction;
  fileObj = new File(FILE_CUSTOM_SET);
  if (setType == "factory")
    filterFunction =  new Function("x", "return (x.isFile()) && (x.getAttributes() == 'R') && (x.getExtension()== 'xml');");
  else
    filterFunction =  new Function("x", "return (x.isFile()) && (x.getAttributes() != 'R') && (x.getExtension()== 'xml');");
  return fileObj.listFolder(filterFunction);
}

function isSet(setName, setType)
{
  var facSetArray = new Array(), i, retVal = false;
  facSetArray = getCustomSetList(setType);
  for (i=0; i<facSetArray.length; i++)
  {
    if (facSetArray[i] == setName)
	{
	  retVal = true;
	  break;
	}
  }
  return retVal;
}

function getExtension(fileName)
{
  var retVal = "", index;
    
  index = fileName.lastIndexOf(".");
  if (index != -1)
    retVal = fileName.substring(index+1);
  return retVal;
}

function getSimpleName(fileName)
{
  var index; retVal = fileName;
  
  index = fileName.lastIndexOf(".");
  if (index != -1)
    retVal = fileName.substring(0,index);
  return retVal;
}