<?xml version="1.0"?>
<!-- ***** BEGIN LICENSE BLOCK *****
   - Version: MPL 1.1/GPL 2.0/LGPL 2.1
   -
   - The contents of this file are subject to the Mozilla Public License Version
   - 1.1 (the "License"); you may not use this file except in compliance with
   - the License. You may obtain a copy of the License at
   - http://www.mozilla.org/MPL/
   -
   - Software distributed under the License is distributed on an "AS IS" basis,
   - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
   - for the specific language governing rights and limitations under the
   - License.
   -
   - The Original Code is Verbosio XML editor.
   -
   - The Initial Developer of the Original Code is
   - Alexander J. Vincent <ajvincent@gmail.com>.
   - Portions created by the Initial Developer are Copyright (C) 2007
   - the Initial Developer. All Rights Reserved.
   -
   - Contributor(s):
   -
   - Alternatively, the contents of this file may be used under the terms of
   - either the GNU General Public License Version 2 or later (the "GPL"), or
   - the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
   - in which case the provisions of the GPL or the LGPL are applicable instead
   - of those above. If you wish to allow use of your version of this file only
   - under the terms of either the GPL or the LGPL, and not to allow others to
   - use your version of this file under the terms of the MPL, indicate your
   - decision by deleting the provisions above and replace them with the notice
   - and other provisions required by the LGPL or the GPL. If you do not delete
   - the provisions above, a recipient may use your version of this file under
   - the terms of any one of the MPL, the GPL or the LGPL.
   -
   - ***** END LICENSE BLOCK ***** -->
<!DOCTYPE window [
  <!ENTITY % commonDTD SYSTEM "chrome://verbosio/content/verbosio.dtd">
  %commonDTD;
]>
<?xml-stylesheet type="text/css"
                 href="chrome://xulwidgets/skin/"
                ?>
<?xml-stylesheet type="text/css"
                 href="chrome://verbosio/content/template.css"
                ?>
<window xmlns="&XUL_NS;"
        style="background-color: #ffff7f;">
  <commandset>
    <command id="cancelFloatBox"
             oncommand="clearPanel();"
            />
    <command id="acceptFloatBox"
             oncommand="acceptChanges();"
            />
  </commandset>

  <!-- Hidden boxes which we reuse later appear here. -->
  <box hidden="true">
    <!-- XXX ajvincent Localize! -->
    <vbox id="newTemplatePanel"
          menulabel="(create new template)">
      <hbox><button label="Open new template"/></hbox>
    </vbox>
  </box>

  <hbox id="dialog-buttons-box">
    <spacer flex="1"/>
    <!-- XXX ajvincent Localize! -->
    <button label="Ok"
            command="acceptFloatBox"
           />
    <!-- XXX ajvincent Localize! -->
    <button label="Cancel"
            command="cancelFloatBox"
           />
  </hbox>

  <script type="&JS_TYPE;"
          src="resource://app/res/ecma-debug.js"
         />
&namespaces.script;
  <script type="&JS_TYPE;"><![CDATA[
const s = new XMLSerializer();

function resetTemplates(aOrigNode, aTemplateSet) {
  assert(aTemplateSet, "No template set?");
  var menudeck = document.getElementById("menudeck");
  if (menudeck) {
    menudeck.parentNode.removeChild(menudeck);
  }

  menudeck = document.createElementNS(XUL_NS, "xul:vbox");
  menudeck.setAttribute("id", "menudeck");
  var menulist = document.createElementNS(XUL_NS, "xul:menulist");
  var menupopup = document.createElementNS(XUL_NS, "xul:menupopup");

  function handleItemChange(aEvent) {
    deck.selectedIndex = menulist.selectedIndex;
    dump(s.serializeToString(deck.selectedPanel, "application/xml") + "\n\n");
  }
  menupopup.addEventListener("command", handleItemChange, false);

  menulist.appendChild(menupopup);
  var deck = document.createElementNS(XUL_NS, "xul:deck");
  menulist.setAttribute("selectedIndex", "0");
  deck.setAttribute("selectedIndex", "0");
  menudeck.appendChild(menulist);
  menudeck.appendChild(deck);

  var templatePanels = [];
  var i;
  var menuitem;

  for (i = 0; i < aTemplateSet.length; i++) {
    assert(aTemplateSet[i].namespaceURI == MARKUP_NS, "<markup:template/>!");
    assert(aTemplateSet[i].localName == "template", "<markup:template/>!");
    var panel = aTemplateSet[i].cloneNode(true);
    document.adoptNode(panel);

    menuitem = document.createElementNS(XUL_NS, "xul:menuitem");
    menuitem.setAttribute("label", panel.getAttribute("menulabel"));
    menupopup.appendChild(menuitem);
    deck.appendChild(panel);

    templatePanels.push(panel);
  }

  panel = document.getElementById("newTemplatePanel").cloneNode(true);
  menuitem = document.createElementNS(XUL_NS, "xul:menuitem");
  menuitem.setAttribute("label", panel.getAttribute("menulabel"));
  menupopup.appendChild(menuitem);
  deck.appendChild(panel);

  var buttonsBox = document.getElementById("dialog-buttons-box");
  document.documentElement.insertBefore(menudeck, buttonsBox);

  for (i = 0; i < templatePanels.length; i++) {
    var output = templatePanels[i].getOutputContainer();
    var result = output.importSourceNode(aOrigNode);
    assert(result, "output.importSourceNode failed!");
    if (result) {
      templatePanels[i].processXPathInputs();
    }
  }

  var entityBoxes = document.getElementsByTagNameNS(MARKUP_NS, "entitybox");
  for (var i = 0; i < entityBoxes.length; i++) {
    entityBoxes[i].addEntityInputs();
  }
}

/**
 * Hide the panel and lose UI for changes.
 */
function clearPanel() {
  var floatBox = frameElement.parentNode;
  floatBox.style.display = "none";
  floatBox.floatTarget = null;
}

/**
 * Accept the changes to the template the user has selected.
 */
function acceptChanges() {
  var win = frameElement.ownerDocument.defaultView;
  var txn = new win.xeRecordedTransaction();
  txn.addProperties({
    doRecordedTransaction: function doRecordedTransaction() {
      var menudeck = document.getElementById("menudeck");
      assert(menudeck.deck, "No anonymous deck?");
      var panel = menudeck.selectedPanel;
      if (!panel) {
        warn("no panel from binding");
        dump(menudeck.selectedIndex + "\n\n");
        panel = menudeck.childNodes[menudeck.selectedIndex]
      }
      assert(panel, "No panel selected?");
      assert(panel instanceof Components.interfaces.xeIMarkupTemplate,
             "Not a markup template?");
      var entityBoxes = panel.getElementsByTagNameNS(MARKUP_NS, "entitybox");
      var entityArray = [];
      var i;
      for (i = 0; i < entityBoxes.length; i++) {
        entityArray = entityArray.concat(entityBoxes[i].entitySet);
      }

      for (i = 0; i < entityArray.length; i++) {
        var action = new win.EntityChangeAction(entityArray[i]);
        this.recordedActions.push(action);
        action.doAction();
      }

      var fragment = panel.exportEditedFragment(true);
      var node = frameElement.origNode;
      node.ownerDocument.adoptNode(fragment);
      node.parentNode.replaceChild(fragment, node);
    }
  });

  win.verbosio.advanceTxn(txn);
  win.verbosio.advanceTxn(null);

  clearPanel();
}

if ((typeof frameElement.origNode == "object") &&
    (typeof frameElement.templateSet == "object")) {
  resetTemplates(frameElement.origNode, frameElement.templateSet);
}
]]></script>
</window>
