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

//---------------   GLOBAL VARIABLES   ---------------

var helpDoc = MM.HELP_objAnchor;


//---------------    LOCAL FUNCTIONS   ---------------

function initializeUI() 
{
  var curDOM = dw.getDocumentDOM();
  if (curDOM)
  {
    var curSel = dw.getSelection();  //get selection
    if (curSel && curSel.length>1 && curSel[1]>curSel[0]) //if selection exists
    {
      var curText = (curDOM.documentElement.outerHTML.slice(curSel[0],curSel[1]));  //get selection string
      if (curText && curText.search(/[a-zA-Z]\w*/)==0) //if selection starts with word (must begin w/ letter
      {
        var wordArray = curText.match(/[a-zA-Z]\w*/);  //get first word
        document.theform.anchorname.value = unescape(wordArray[0]);  //preload text into UI
      }
    }
  }

  document.theform.anchorname.focus();
  document.theform.anchorname.select();
}


//---------------     API FUNCTIONS    ---------------

function canAcceptCommand()
{
  var enabled= dw.getFocus() != 'browser' && dw.getDocumentDOM() != null &&
			 dw.getDocumentDOM().getParseMode() == 'html' && 
			 !(dw.getDocumentDOM().getCCSharedSetting_TextOnlyInNonTemplates())

  return enabled;
}

function commandButtons()
{
   return new Array("PutButtonsOnBottom", "OkButton", MM.BTN_OK, "createAnchorString()", "CancelButton", MM.BTN_Cancel, 
                    "window.close()", "PutButtonOnLeft", MM.BTN_Help, "displayHelp()");
}


function createAnchorString()
{
  var anchorString =  document.forms[0].anchorname.value;

  var errorStr = CheckNewAnchor( anchorString );
  
  if (!errorStr)
  { 
    var curDOM = dw.getDocumentDOM();
    anchorString = dw.doURLEncoding(anchorString);  //URL encode to avoid problem with hi-ascii & double-byte

    var idStr = ''
    if (curDOM.getIsXHTMLDocument())
	  idStr = ' id="' + anchorString + '"'

    dw.showInvisibles();

    var htmlStr = "";
    if (dw.getFocus(true) == 'html' || dw.getFocus() == 'textView')
      htmlStr ='<a name="' + anchorString + '"' + idStr + '></a>';
    else
      htmlStr ='<a name="' + anchorString + '"' + idStr + '>';

    var curSel = dw.getSelection();  //get selection
    if (curSel && curSel.length>1) //if selection exists
    {
      curDOM.setSelection(curSel[0],curSel[0]);  //put IP prior to selection so inserts before
    }
    curDOM.insertHTML( htmlStr , false);
    window.close();
  }

  else
  {
    alert (errorStr);
    document.theform.anchorname.focus();
    document.theform.anchorname.select();
  }
}
