/**
 * Sets the content to be edited.
 * 
 * @param url The base system ID of the content. Used to resolve referred resources.
 * @param content The serialized XML
 */
function setDocumentContent(url, content) {
    var sample = document.getElementById('authorComponentApplet').getAuthorComponentSample();
    if(sample != null){
      // May be null if not licensed.

      try {
          sample.setDocumentContent(url, content);
      }
      catch (e) {
          alert("setDocumentContent " + e);
      }
    }
}

/**
 * Message to be displayed if applet is loaded on systems other that Windows or Linux
 */
var REQ = 
	"<h4>" + 
	"Requirements:" +
	"</h4>" +
	"<ul>" +
		"<li>Java VM version 1.6 update 10 or later.</li>" +
		"<li>Your browser should support the New Java&trade; Plug-In Technology (usually this plugin is installed together with the Java VM). </li>" +		
		"<li>Please note that the New Java&trade; Plug-In Technology support is not enabled by default on Mac OS X. To enable the plugin please follow the next steps:<ul>" +
		    "<li>Upgrade to Java VM version 1.6 update 17 or later.</li>" +
		    "<li>Open the Java Preferences application and toggle setting to 'Run applets: in their own process'.</li>" +
		    "<li>Restart your browser and try viewing the applet.</li>" +
		"</ul></li>" +
	"</ul>";

var SDK = "   <p>The entire source code of this sample can be downloaded from <a href=\"author-component-sample.zip\">here</a>. " + 
	"           The sample was created using the <a href=\"http://www.oxygenxml.com/developer.html#XML_Editor_Authoring_SDK\">&lt;oXygen/> XML Editor Authoring SDK</a>.</p>" + 
	"        <p>The same SDK is used by the developers creating custom Java actions for the documentation frameworks. Please note that the" + 
	"           frameworks created for the standalone distribution of the &lt;oXygen/> XML Author and Editor can be reused for " + 
	"           the applet." + 
	"        </p>";

/**
 * Function to be call on loading page
 */
function onLoad(){
	 if (document.getElementById('authorComponentApplet').isActive()) {
		 onLoadWhenAppletReady();
	 } 
}

/**
 * This function is called when the page was loaded and the applet activated.
 */
function onLoadWhenAppletReady(){
	var xmlContent = 
      "<!DOCTYPE task PUBLIC '-//OASIS//DTD DITA Task//EN' 'http://docs.oasis-open.org/dita/v1.1/OS/dtd/task.dtd'>" + 
      "<task id='tutorial'>" + 
      "    <title>DITA customization of the oXygen Author Component</title>" + 
      "    <taskbody>" + 
      "        <context>" + 
      "            <p>Follow these steps to explore the applet functionality:</p>" + 
      "        </context>" + 
      "        <steps>" + 
      "            <step>" + 
      "                <cmd>Click on the above checboxes to control the side views.</cmd>" + 
      "            </step>" + 
      "            <step>" + 
      "                <cmd>Use the toolbar buttons to insert DITA elements.</cmd>" + 
      "            </step>" + 
      "            <step>" + 
      "                <cmd>Click in the editing area, then press the ENTER key, to use the content-completion list. Choose the DITA element to be inserted.</cmd>" + 
      "            </step>" + 
      "            <step>" + 
      "                <cmd>Click in the editing area, then press ALT-ENTER. " + 
      "                    The current element attributes are displayed. Change them as you like.</cmd>" + 
      "            </step>            " + 
      "            <step>" + 
      "                <cmd>Resize your browser. The applet will change its size accordingly.</cmd>" + 
      "            </step>" + 
      "            <step>" + 
      "                <cmd>Now <b>Click in the DITA map</b> from the left to open a topic!</cmd>" + 
      "            </step>" + 
      "        </steps>" + 
      "    </taskbody>" + 
      "</task>";          
    setDocumentContent(null, xmlContent);    
    updateUIControls();    
}




/**
 * Upates the Applet to match the HTML controls. 
 */
function updateUIControls(){
    setVisibleSideView('outline', document.getElementById('ck_outline').checked);
    setVisibleSideView('attributes', document.getElementById('ck_attributes').checked);
    setVisibleSideView('elements', document.getElementById('ck_elements').checked);
    setTagsDisplayMode(document.getElementById('sl_tags').value);    
}

/**
 * Parses a string representing the content of an XML document.
 * 
 * @param xml The serialized representation of the XML document.
 * @return The DOM object.
 */
function createDoc(xml){
	if (window.DOMParser){
		parser=new DOMParser();
		xmlDoc=parser.parseFromString(xml,"text/xml");
	}else {
		// Internet Explorer
		xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async="false";
		xmlDoc.loadXML(xml);
	}
	return xmlDoc;
}

/**
 * Builds an AJAX reques handler.
 * 
 * @return The handler.
 */
function ajaxRequest(){
  var xhttp;
  if (window.XMLHttpRequest) {
            xhttp = new XMLHttpRequest();
  } else {
	    // Internet Explorer 5/6
	    xhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  return xhttp;      
}


/**
 * Loads the DOM model of the DITA map file, using an AJAX request, then
 * displays it as a tree of HTML DIVs.
 * 
 * @param mapUrl
 *            The URL of the map file.
 */
function displayDitaMap(mapUrl) {
    try {
        xhttp = ajaxRequest();
        var currentLocationBase = window.location.href;
        currentLocationBase = currentLocationBase.substr(0,currentLocationBase.lastIndexOf("/") + 1);
        mapUrl = currentLocationBase + mapUrl;
        xhttp.open("GET", mapUrl, false);
        xhttp.send("");
        xmlDoc = createDoc(xhttp.responseText);
        
        var mapBase = mapUrl;
        mapBase = mapBase.substr(0,mapBase.lastIndexOf("/") + 1);
        traverse(xmlDoc.documentElement, mapBase);
    }
    catch (e) {
        alert(e.message);
    }
}

var progress_id = 0; 

/**
 * Creates an HTML tree over the DITA map DOM document.
 * 
 * @param cNode
 *            The current node.
 * @param base
 *            The base URI for the creating the topic links.
 */
function traverse(cNode, base) {
    if (cNode.tagName != null) {
        document.write('<div class="dita_map_entry">');
        if (cNode.attributes != null) {
            href = cNode.getAttribute("href");
            if (href != null) {
                target = base + href;
                document.write('<a onClick="openMapEntry(\'' + target + '\', \'progress_' + progress_id +'\');" href="#dita_map_anchor">');
                
                if (cNode.getAttribute("title") != null) {
                    document.write(cNode.getAttribute("title"));
                } else if (cNode.getAttribute("navtitle") != null) {
                    document.write(cNode.getAttribute("navtitle"));
                } else {
                    document.write(href);
                }
                document.write('</a>');
                document.write('<span class="progress" id="progress_' + progress_id + '">&nbsp;</span>');                
                progress_id ++;
            } else if (cNode.getAttribute("title") != null) {
                document.write('<a>' + cNode.getAttribute("title") + '</a>');
            }

        }
        
        var nodes = cNode.childNodes.length;
        for (var i = 0; i < cNode.childNodes.length; i++) {
            traverse(cNode.childNodes[i], base);
        }
        document.write('</div>');
    }
}

/**
 * Loads the speicified URL into the editor.
 * 
 * @param target The URL of the topic to be loaded.
 * @param progress_id The ID of the HTML element that represents the progress animation.
 */
function openMapEntry(target, progress_id) {
	var progress = document.getElementById(progress_id);    
	try {
    	// Displays progress..
    	if(progress != null){
    		progress.style.visibility = 'visible';
    	}
    	
        xhttp = ajaxRequest();
        xhttp.open("GET", target, false);
        xhttp.send("");
        
        setDocumentContent(target, xhttp.responseText);
        
    } catch (e) {
        alert("openMapEntry " + e);
    } finally {
    	// Hide the progress..
    	setTimeout(function(){
    		// But allow the editor to load completetly
        	if(progress != null){
        		progress.style.visibility = 'hidden';
        	}    	    		
    	}, 3000);
    }
}

/**
 * Makes visible or hides a side-view.
 * 
 * @param sideViewName The name of the side view. Can be one of <code>outline</code>, 
 * <code>attributes</code>, <code>elements</code>.
 * @param visible <code>true</code> makes the side view visible, 
 * <code>false</code> hides the view. 
 */
function setVisibleSideView(sideViewname, visible) {
    var sample = document.getElementById('authorComponentApplet').getAuthorComponentSample();
    if(sample != null){
    	// May be null if not licensed.
	    try {
	        sample.setVisibleSideView(sideViewname, visible);
	    }
	    catch (e) {
	        alert("setVisibleSideView " +e);
	    }
    }
}


/**
 * Extracts the serialized XML from the editor.
 * 
 * @return The XML string.
 */
function getSerializedDocument() {
    var sample = document.getElementById('authorComponentApplet').getAuthorComponentSample();
    if(sample != null){
    	// May be null if not licensed.
	    try {
	        return sample.getSerializedDocument();
	    }
	    catch (e) {
	        alert("getSerializedDocument " + e);
	        return null;
	    }
    } else {
    	return null;
    }
}

/**
 * Changes the tags display mode.
 * 
 * @param mode
 *            Can be one of <code>full_tags</code>,
 *            <code>full_tags_with_attributes</code>, <code>no_tags</code>,
 *            <code>partial_tags</code>.
 * @return
 */
function setTagsDisplayMode(mode) {
    var sample = document.getElementById('authorComponentApplet').getAuthorComponentSample();
    if(sample != null){
    	// May be null if not licensed.
	    try {
	        sample.setTagsDisplayMode(mode);
	    }
	    catch (e) {
	        alert("setFullTagsDisplayMode " + e);
	    }
    }
}

/**
 * @return The string the browser should display when navigating away from the
 *         page containing the applet.
 */
function askConfirm() {
    if (isModified()) {
        return "There are changes in the oXygen XML Author component.";
    }
}

/**
 * Check the modification state of the current editor.
 * 
 * @return true if the document from the editor is modified.
 */
function isModified() {
    var sample = document.getElementById('authorComponentApplet').getAuthorComponentSample();
    if(sample != null){
    	// May be null if not licensed.
    	return sample.isModified();
    } else {
    	return null;
    }
}

