// Copyright 2000, 2001, 2002, 2003 Macromedia, Inc. All rights reserved.

//*************** GLOBAL CONSTANTS *****************
var helpDoc = MM.HELP_objFlashButton;
var TYPE_STR = "Flash Button";
var STYLE_EXT_STR = "swt";
var TYPE_PARAMETER = "dwType";
var BUTTON_TEXT_PARAMETER = "Button Text";
var BUTTON_URL_PARAMETER = "Button URL";
var BUTTON_TARGET_PARAMETER = "Button Target";
var BUTTON_FONT_PARAMETER = "Button Font";
var BUTTON_SIZE_PARAMETER = "Button Size";
var YIELD_PATH = "../Shared/MM/Images/yield.gif";
var DEFAULT_SIZE = 15;
var MAX_PREVIEW_WIDTH = 230;
var MAX_PREVIEW_HEIGHT = 50;
var MAX_FILE_LENGTH = 23;
//*************** GLOBAL VARIABLES *****************
// UI Elements
var MENU_FONTS, MENU_TARGET;
var LIST_STYLES;
var TEXT_LABEL, TEXT_LINK, TEXT_BG, TEXT_SAVEAS, TEXT_SIZE;
var COLORP_BG;
var SWF_SAMPLE;
var AREA_WARNING;
// other globals
var FILE_CONFIG_PATH = dw.getConfigurationPath();
var FILE_BUTTON_STYLES_PATH = FILE_CONFIG_PATH + "/Flash Objects/Flash Buttons";
var FILE_CURRENT_DOC_PATH;
var ARRAY_TARGET_STR = new Array("","_blank","_parent","_self","_top");
var REEDIT_SWF_PATH="";
var FLAG_OVERWRITE = new Object();
FLAG_OVERWRITE.state = false;
FLAG_OVERWRITE.reEdit = false;
var FILE_BUTTON_PREVIEW_PATH = FILE_CONFIG_PATH + "/Flash Objects/Flash Buttons Preview";
var LAST_SIZE=DEFAULT_SIZE;
//******************* API **********************
function commandButtons()
{
   return new Array( MM.BTN_OK,  "cmdOK(); "
                   , MM.BTN_Apply, "cmdApply();"
                   , MM.BTN_Cancel, "cmdCancel();"
                   , BTN_GetMoreStyles,'moreStyles();'
                   , MM.BTN_Help, 'displayHelp()');
}

function cmdOK()
{
  var done = insertButtonHTML();
  if (done)
    window.close();

  var objDOM = dreamweaver.getDocumentDOM();

  // check to see if accessibility option for media objects is turned on
  prefsAccessibilityOption = dw.getPreferenceString("Accessibility", "Accessibility Media Options", "");
  if(prefsAccessibilityOption == 'TRUE') {addAccessibility(objDOM);}
}

function cmdApply()
{
 var filename = document.saveAsField.getAttribute("value");
 insertButtonHTML();
 FLAG_OVERWRITE.state = true;
 FLAG_OVERWRITE.file = addExtention(filename, "swf");
}

function cmdCancel()
{
  window.close();
}

function moreStyles()
{
  dreamweaver.browseDocument(LABEL_MoreStylesURL);
  window.close();
}

function receiveArguments(swfPath)
{
  var fileName, fileObj;
  if (swfPath)
  {
    REEDIT_SWF_PATH = swfPath;
    fileObj = new File(REEDIT_SWF_PATH);
    fileName = fileObj.getName();
    FLAG_OVERWRITE.state = true;
    FLAG_OVERWRITE.reEdit = true;
    FLAG_OVERWRITE.file = fileName;
  }
}
//***************** LOCAL FUNCTIONS  ******************

function initializeUI()
{
  var i, fileObj, filterFunction, targetArray,currentSwfPath, swfButtonParams;
  var fileName, filesArray, fontArray;
  FILE_CURRENT_DOC_PATH = dw.getDocumentPath("document");
      //Global UI Controls
  LIST_STYLES = new ListControl("stylesList");
  MENU_TARGET = new ListControl("targetMenu");
  MENU_FONTS = new ListControl("fontMenu");
  TEXT_SIZE = document.sizeField;
  TEXT_LABEL = document.labelField;
  TEXT_LINK = document.linkField;
  TEXT_BG = document.bgColorField;
  TEXT_SAVEAS = document.saveAsField;
  COLORP_BG = document.bgColorPicker;
  SWF_SAMPLE = document.swfPreview;
  AREA_WARNING = document.warningMsg;
    // set the Styles list
  fileObj = new File(FILE_BUTTON_STYLES_PATH);
  filterFunction =  new Function("x", "return x.isFile() && (x.getExtension().toLowerCase()=='swt');");
  filesArray = fileObj.listFolder(filterFunction);
  if (filesArray.length>0)
    LIST_STYLES.setAll(getMenuList(filesArray),filesArray);
  else
  {
    alert(MSG_NoTemplatesFound);
    window.close();
    return "";
  }
  // set font menu
  fontArray = filterFonts(dw.getSystemFontList("TrueType"));
  if (!fontArray)
  {
    alert(MSG_NoFontsInstalled);
    window.close();
    return "";
  }
  else
    MENU_FONTS.setAll(fontArray,fontArray);
  TEXT_SIZE.value = DEFAULT_SIZE;
    // set the Preview field
  updateUI("stylesList");
    // set target menu
  docFrames = dw.getDocumentDOM().getFrameNames();
  targetArray = ARRAY_TARGET_STR;
  if (docFrames)
   targetArray = targetArray.concat(docFrames);
  MENU_TARGET.setAll(targetArray, targetArray);
    // set the default file name
  TEXT_SAVEAS.setAttribute("value",createUniqueFilename("button", getDocumentDir(FILE_CURRENT_DOC_PATH),MAX_FILE_LENGTH));
  if (REEDIT_SWF_PATH)
  {
    REEDIT_SWF_PATH =File.getFullUrl(REEDIT_SWF_PATH, FILE_CURRENT_DOC_PATH);  // modify button does not pass in full path
    swfButtonParams = SWFFile.readFile(REEDIT_SWF_PATH);
    swfButtonParams.unshift("templatePath");
//    if (navigator.platform != "Win32")
    if (!hasDoubleByteChar(swfButtonParams[1]))
      swfButtonParams[1] = unescape(swfButtonParams[1]);
    if (swfButtonParams.length % 2 != 0) // if last parameter has no value array is odd
      swfButtonParams.push("");
    populateUI(swfButtonParams,absoluteToRelativeURL(REEDIT_SWF_PATH, FILE_CURRENT_DOC_PATH,true));
  }

  TEXT_LABEL.focus();
  TEXT_LABEL.select();
  return "";
}

function updateUI(itemName)
{
  var currentStyle, browseURL, colorCP, colorF,previewFile, theLink, sizeArray;
  switch(itemName)
  {
    case "stylesList":
    {
      currentStyle = LIST_STYLES.getValue();
      stylePath = FILE_BUTTON_STYLES_PATH + "/"+ currentStyle;
      previewFile = currentStyle.replace(/.swt/,".swf");
      if (DWfile.exists(FILE_BUTTON_PREVIEW_PATH+"/"+previewFile))
      {
        // [gc] read in default settings from swf preview file
        var defaultParams = SWFFile.readFile(FILE_BUTTON_PREVIEW_PATH+"/"+previewFile);
        defaultParams.unshift("templatePath");
        if (defaultParams.length % 2 != 0) // if last parameter has no value array is odd
        defaultParams.push("");
        var theFont = getValueFromParameters(BUTTON_FONT_PARAMETER, defaultParams);
		theFont		= getDefaultSystemFont(theFont);
        var theSize = getValueFromParameters(BUTTON_SIZE_PARAMETER, defaultParams);
        if (!REEDIT_SWF_PATH && theFont )
        {
          if ( !MENU_FONTS.pickValue(theFont) )
          {
            var warnMsg = MSG_DefaultFontDoesNotExist;
            warnMsg = warnMsg.replace(/%s/,theFont);
            AREA_WARNING.innerHTML = createWarningMsgHTML(warnMsg, YIELD_PATH);
          }
          else
            AREA_WARNING.innerHTML = "";
        }
        if (!REEDIT_SWF_PATH && theSize)
          TEXT_SIZE.value = theSize/20;
        sizeArray = SWFFile.getNaturalSize(FILE_BUTTON_PREVIEW_PATH+"/"+previewFile);
        SWF_SAMPLE.setAttribute("SRC",FILE_BUTTON_PREVIEW_PATH+"/"+previewFile);
      }
      else
      {
        if (AREA_WARNING.innerHTML != "")
          AREA_WARNING.innerHTML = "";
        sizeArray = SWFFile.getNaturalSize(stylePath);
        SWF_SAMPLE.setAttribute("SRC",stylePath);
      }
     // resize preview area to natural size of template
      if (sizeArray)
      {
        SWF_SAMPLE.setAttribute("WIDTH",sizeArray[0] > MAX_PREVIEW_WIDTH ? MAX_PREVIEW_WIDTH : sizeArray[0]);
        SWF_SAMPLE.setAttribute("HEIGHT",sizeArray[1] > MAX_PREVIEW_HEIGHT ? MAX_PREVIEW_HEIGHT : sizeArray[1]);
      }
      break;
    }
    case "sizeField":
    {
      if (!isInteger(TEXT_SIZE.value))
      {
        TEXT_SIZE.value = LAST_SIZE;
      }
      else
        LAST_SIZE = TEXT_SIZE.value
    }
    case "linkField":
    {
      theLink = TEXT_LINK.value;
      if (isSiteRelative(theLink))
        AREA_WARNING.innerHTML = createWarningMsgHTML(MSG_SiteRelLinkWarning, YIELD_PATH);
      else if (theLink.indexOf("file:///")!=-1)
        AREA_WARNING.innerHTML = createWarningMsgHTML(MSG_LocalURLLinkWarning, YIELD_PATH);
      else
        AREA_WARNING.innerHTML = "";
      break;
    }
    case "saveAsField":
    {
//    if (TEXT_LINK.value)
//      document.targetMenu.setAttribute("disabled", "false");
//    else
//      document.targetMenu.setAttribute("disabled", "true");
      theLink = TEXT_LINK.value;
      theSaveLoc = TEXT_SAVEAS.value;
      if (theSaveLoc.indexOf('/') != -1){
        if (isSiteRelative(theLink)){
          AREA_WARNING.innerHTML = createWarningMsgHTML(MSG_SiteRelLinkWarning, YIELD_PATH);
          TEXT_LINK.focus();
          TEXT_LINK.select();
        }else if (isDocRel(theLink) && theLink!="#"){
          AREA_WARNING.innerHTML = createWarningMsgHTML(MSG_DocRelLinkWarning, YIELD_PATH);
          TEXT_LINK.focus();
          TEXT_LINK.select();
        }else if (theLink.indexOf("file:///")!=-1){
          AREA_WARNING.innerHTML = createWarningMsgHTML(MSG_LocalURLLinkWarning, YIELD_PATH);
          TEXT_LINK.focus();
          TEXT_LINK.select();
        }else{
          AREA_WARNING.innerHTML = "";
        }
      }
      break;
    }
    case "linkButton":
    {
      browseURL = dreamweaver.browseForFileURL("select",LABEL_Select, false, true);
      if (browseURL)
        TEXT_LINK.setAttribute("value", browseURL);
      updateUI("linkField");
      break;
    }
    case "bgColorPicker":
    {
      updateColorPicker("colorPicker",COLORP_BG,TEXT_BG);
      break;
    }
    case "bgColorField":
    {
      updateColorPicker("colorField",COLORP_BG,TEXT_BG);
      break;
    }
    case "saveAsButton":
    {
      browseURL = dreamweaver.browseForFileURL("save",LABEL_Select, false, true);
      browseURL = absoluteToRelativeURL(browseURL, FILE_CURRENT_DOC_PATH,false);
      if (browseURL)
        TEXT_SAVEAS.setAttribute("value", browseURL);
      break;
    }
  }
}

function generateParametersArray()
{
  var retVal = new Array();
  var theLink = TEXT_LINK.value;
  if (!theLink)
    theLink = "javascript:;";   // this fixes the crash on netscape when getURL=""
  retVal[0] = TYPE_PARAMETER;
  retVal[1] = TYPE_STR;
  retVal[2] = BUTTON_TEXT_PARAMETER;
  retVal[3] = TEXT_LABEL.value;
  retVal[4] = BUTTON_URL_PARAMETER;
  retVal[5] = theLink;
  retVal[6] = BUTTON_TARGET_PARAMETER;
  retVal[7] = MENU_TARGET.get();
  retVal[8] = BUTTON_FONT_PARAMETER;
  retVal[9] = MENU_FONTS.get();
  retVal[10] = BUTTON_SIZE_PARAMETER
  retVal[11] = convertPtToTwip(TEXT_SIZE.value);
  return retVal;
}

function createFlashTag(swfURL)
{
  var retVal= new Array();
  var theLink = TEXT_LINK.value;
  var docRelURL = absoluteToRelativeURL(swfURL, FILE_CURRENT_DOC_PATH,true);
  var sizeArray = SWFFile.getNaturalSize(swfURL);
  var width, height;
  var bgcolor = TEXT_BG.value;

  if (sizeArray)
  {
    width = sizeArray[0];
    height = sizeArray[1];
  }
  else
  {
    width = 32;
    height = 32;
  }
  retVal.push('<OBJECT CLASSID="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"');
  retVal.push(' CODEBASE="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0"');
  retVal.push(' WIDTH="' + width + '" HEIGHT="'+ height + '">\n');
  retVal.push('<PARAM NAME="movie" VALUE="' + docRelURL + '"> <PARAM NAME="quality" VALUE="high">\n' );
  if (bgcolor)
    retVal.push('<PARAM NAME="bgcolor" VALUE="' + bgcolor + '">\n');
  retVal.push('<EMBED SRC="' + docRelURL +'"');
  retVal.push(   ' QUALITY="high" PLUGINSPAGE="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" ' +
         'TYPE="application/x-shockwave-flash" ');
  retVal.push('WIDTH="' + width + '" HEIGHT="'+ height +'" ');
  if (bgcolor)
    retVal.push('BGCOLOR="' + bgcolor + '"');
  retVal.push('>' +'</EMBED>\n' + '</OBJECT>');
  return  retVal.join("");
}

function insertButtonHTML()
{
  var data, outputFilePath,templateFile,currentStyle, canCreateFile=false;
  var success=false, createFileMsg;
  var theLink = TEXT_LINK.value;
  var fileName = TEXT_SAVEAS.value;
  var dom = dw.getDocumentDOM();
  var selectedNode,wasPlaying, temp1, temp2;
  if (dom.canStopPlugin())
  {
    dom.stopPlugin();
    wasPlaying = true;
  }
  if (fileName.charAt(0) == " ")
  {
    alert(MSG_FilenameStartWithSpace);
    return false;
  }
  if (!fileName)
    alert(MSG_SaveAsFieldIsEmpty);
  else if ((outputFilePath = resolveFilePath(fileName,FILE_CURRENT_DOC_PATH,"swf")) == "")
    alert(errMsg(MSG_InvalidFileName,fileName));
  else
  {
    outputFilePath = truncateFileName(MAX_FILE_LENGTH, outputFilePath);
    if (!checkLink(theLink,outputFilePath,FILE_CURRENT_DOC_PATH))
      return false;
    if (DWfile.exists(outputFilePath) && DWfile.getAttributes(outputFilePath)=="R")
    {
      alert(errMsg(MSG_ReadOnlyFile,outputFilePath));
      return false;
    }
    if (!DWfile.exists(outputFilePath) || (FLAG_OVERWRITE.state == true && FLAG_OVERWRITE.file == addExtention(fileName, "swf")))
      canCreateFile=true;
    else if (confirm(errMsg(MSG_FileAlreadyExists, outputFilePath)))
      canCreateFile=true;
    if (canCreateFile==true)
    {
      data = generateParametersArray();
      currentStyle = LIST_STYLES.getValue();
      templateFile = FILE_BUTTON_STYLES_PATH + "/" + currentStyle;
      MM.setBusyCursor();
      
      resolvedTemplatePath = resolveConfigPath(templateFile);
      if (navigator.platform == "Win32")
        createFileMsg = SWFFile.createFile(resolvedTemplatePath,data,outputFilePath);
      else{
        temp1 = (hasDoubleByteChar(templateFile)) ?   resolvedTemplatePath : escape(resolvedTemplatePath);
        temp2 = (hasDoubleByteChar(outputFilePath)) ?   outputFilePath : escape(outputFilePath);
        createFileMsg = SWFFile.createFile(temp1,data,temp2);
      }
      MM.clearBusyCursor();
      if (createFileMsg=="noError")
      {
        if (!FLAG_OVERWRITE.reEdit){
          dom.insertHTML(createFlashTag(outputFilePath), FLAG_OVERWRITE.state);
		}
        else
        {
          selectedNode = dom.getSelectedNode();
          editButtonAttribute(outputFilePath,currentStyle,selectedNode);
// **** next line is a hack that needs to be removed when setSelectedNode bug fixed
          selectedNode.outerHTML = selectedNode.outerHTML;
//        dom.setSelectedNode(selectedNode);
        }
        dom.notifyFlashObjectChanged();
        success = true;
      }
      else
        alert(generatorErrorMsg(createFileMsg,fileName));
    }
  }
  if (wasPlaying)
    dom.playPlugin();
  return success;
}

function populateUI(paramArray, fileName)
{
  var templatePath = getValueFromParameters("templatePath", paramArray);
  var textLabel = getValueFromParameters(BUTTON_TEXT_PARAMETER, paramArray);
  var theLink = getValueFromParameters(BUTTON_URL_PARAMETER, paramArray);
  var theTarget = getValueFromParameters(BUTTON_TARGET_PARAMETER, paramArray);
  var theFont = getValueFromParameters(BUTTON_FONT_PARAMETER, paramArray);
  var theSize = getValueFromParameters(BUTTON_SIZE_PARAMETER, paramArray);
  var tempFile = new File(templatePath);
  var styleName = tempFile.getName();
  var docDOM = dw.getDocumentDOM('document');
  var bgcolor = getSelectedNodeAttr("BGCOLOR",docDOM);

  FLAG_OVERWRITE.style = tempFile.getSimpleName();
  FLAG_OVERWRITE.width = getSelectedNodeAttr("WIDTH",docDOM);
  FLAG_OVERWRITE.height = getSelectedNodeAttr("HEIGHT",docDOM);
  if (!LIST_STYLES.pickValue(styleName))
  {
    if (!confirm(errMsg(MSG_TemplateNotFound, styleName)))
    window.close();
  }
  if (!MENU_FONTS.pickValue(theFont))
  {
    if (!confirm(errMsg(MSG_FontDoesNotExist,theFont)))
    window.close();
  }
  updateUI("stylesList");
//  if (textLabel)
    TEXT_LABEL.value = textLabel;
  if (theLink && theLink !="javascript:;")
    TEXT_LINK.value = theLink;
  if (theTarget)  // ***** check to see if target exists
    if (!MENU_TARGET.pickValue(theTarget))
      {
        if (!confirm(errMsg(MSG_FrameNotFound, theTarget)))
          window.close();
      }
  TEXT_SAVEAS.value = fileName;
  TEXT_SIZE.value = theSize/20;
  if (bgcolor)
    TEXT_BG.value = bgcolor;
  updateUI('bgColorField');
  return true;
}

function generatorErrorMsg(createFileMsg,currentStyle,fileName)
{
  var generatorMsgArray = new Array("invalidData","initGeneratorFailed","outOfMemory","unknownError");
  var returnMsgArray;
  if ( "macos" == DWfile.getPlatform() )
    returnMsgArray = new Array(MSG_InvalidData,MSG_InitGeneratorFailedMac,MSG_OutOfMemory,MSG_UnknownError);
  else
    returnMsgArray = new Array(MSG_InvalidData,MSG_InitGeneratorFailed,MSG_OutOfMemory,MSG_UnknownError);
  var retVal = "";
  if (createFileMsg == "invalidTemplateFile")
    retVal = errMsg(MSG_InvalidButtonStyle,currentStyle);
  else if (createFileMsg == "invalidOutputFile")
    retVal = errMsg(MSG_InvalidFileName,fileName);
  else
  {
    for (var i=0;i<generatorMsgArray.length;i++)
    {
      if (createFileMsg == generatorMsgArray[i])
      {
        retVal = returnMsgArray[i];
        break;
      }
    }
  }
  return retVal;
}

function editButtonAttribute(outputFilePath,currentStyle,selectedNode)
{
  var sizeArray = SWFFile.getNaturalSize(outputFilePath);
  var bgcolor = TEXT_BG.value;
  var width = sizeArray[0];
  var height = sizeArray[1];
  var theLink = TEXT_LINK.value;
  var docRelURL = absoluteToRelativeURL(outputFilePath, FILE_CURRENT_DOC_PATH,true);
  var tagsToAdd = new Array();
  if (outputFilePath != REEDIT_SWF_PATH)
  {
    setFlashAttribute("PARAM","MOVIE",docRelURL,selectedNode,tagsToAdd);
    setFlashAttribute("EMBED","SRC",docRelURL,selectedNode);
  }

  var currentStyleName = currentStyle;
  var index = currentStyleName.lastIndexOf(".");
  if (index != -1)
    currentStyleName = currentStyleName.substring(0,index);
  if (currentStyleName != FLAG_OVERWRITE.style)
  {
    setFlashAttribute("OBJECT","WIDTH",width,selectedNode);
    setFlashAttribute("OBJECT","HEIGHT",height,selectedNode);
    setFlashAttribute("EMBED","WIDTH",width,selectedNode);
    setFlashAttribute("EMBED","HEIGHT",height,selectedNode);
  }
  setFlashAttribute("EMBED","BGCOLOR",bgcolor,selectedNode);
  setFlashAttribute("PARAM","BGCOLOR",bgcolor,selectedNode,tagsToAdd);
  
  if (tagsToAdd.length>0)
    selectedNode.innerHTML = tagsToAdd.join("") + selectedNode.innerHTML;
}

function getMenuItemNames(fileURL)
{
  var dom = dreamweaver.getDocumentDOM(fileURL);
  var menuitemArray = new Array();
  var retArray = new Array();

  menuitemArray = dom.getElementsByTagName("menuitem");
  for (var i=0; i<menuitemArray.length; i++)
  {
    retArray[menuitemArray[i].getAttribute("FILE")] = menuitemArray[i].getAttribute("NAME");
  }
  return retArray;
}

function getMenuList(fileList)
{
  var menuFile = FILE_CONFIG_PATH + "/Commands/Flash Button.xml"
  var fileLabelHash = getMenuItemNames(menuFile);
  var retArray = new Array();
  var label,index;
  for (var i=0; i<fileList.length;i++)
  {
    label = fileLabelHash[fileList[i]];
    if (!label)
    {
      index = fileList[i].lastIndexOf(".");
      if (index != -1)
        label = fileList[i].substring(0, index);
      else
        label = fileList[i];
    }
    retArray.push(label);
  }
  return retArray;
}

// get the system default font for Asian languages
function getDefaultSystemFont(theFont)
{
	// set the default to relavant font for Double-byte languages
	if ( dreamweaver.appVersion && ( dreamweaver.appVersion.indexOf('ja') != -1 || 
					 dreamweaver.appVersion.indexOf('ko') != -1 || 
					 dreamweaver.appVersion.indexOf('zh') != -1) ) {
		if ( "macos" == DWfile.getPlatform() )
			return LABEL_DefaultSystemFontMac;
		else
			return LABEL_DefaultSystemFontWin;
	}
	else 
		return theFont;
}

///////////////////////////////////////////////////////////////////
//  addAccessibility: called when Accessibility Option is turned on
//  
// receives: current document object
// returns : nothing
//
//  Flash Options.htm dialog collects the attributes.

function addAccessibility(objDom) {
   var cmdFile = dreamweaver.getConfigurationPath() + "/Commands/Flash Options.htm";
   var cmdDOM = dreamweaver.getDocumentDOM(cmdFile);
   
   cmdDOM.parentWindow.setFormItem(objDom);
   dreamweaver.popupCommand("Flash Options.htm");

}
