/*
Copyright (c) 2003-2008, Frederico Caldeira Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
 */

importClass( java.io.StringWriter );
importClass( java.io.FileInputStream );

importClass( javax.xml.parsers.DocumentBuilderFactory );
importClass( javax.xml.transform.dom.DOMSource );
importClass( javax.xml.transform.OutputKeys );
importClass( javax.xml.transform.stream.StreamResult );
importClass( javax.xml.transform.TransformerFactory );

( function()
{
	var docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();

	CKRELEASER.xml = {

		replaceNodeWithNodes : function( document, oldNode, nodeList )
		{
			var length = nodeList.getLength();
			for ( var i = 0 ; i < length ; i++ )
			{
				/**
				 * Skip empty text nodes (containing white space characters) at the beginning and at the end.
				 */
				if ( (i === 0 || i == length - 1) && nodeList.item( i ).getNodeType() == org.w3c.dom.Node.TEXT_NODE
						&& nodeList.item( i ).getNodeValue().match( /^\s*$/ ) !== null )
					continue;

				oldNode.getParentNode().insertBefore( document.importNode( nodeList.item( i ), true ), oldNode );
			}

			oldNode.getParentNode().removeChild( oldNode );
		},

		replaceNode : function( document, oldNode, newNode )
		{
			oldNode.getParentNode().insertBefore( document.importNode( newNode, true ), oldNode );
			oldNode.getParentNode().removeChild( oldNode );
		},

		loadDocument : function( location )
		{
			return docBuilder.parse( location );
		},

		asXml : function( document, node )
		{
			var transformer = TransformerFactory.newInstance().newTransformer();
			transformer.setOutputProperty( OutputKeys.INDENT, "no" );
			transformer.setOutputProperty( OutputKeys.OMIT_XML_DECLARATION, "yes" );

			var result = new StreamResult( new StringWriter() );
			var source = new DOMSource( document );
			if ( node )
				source.setNode( node );
			transformer.transform( source, result );

			return result.getWriter().toString();
		},

		/**
		 * FIXME: New line characters in comments are changed. x0Dx0A is changed
		 * into x0A.
		 */
		saveXml : function( document, file )
		{
			var docType = document.getDoctype();
			var transformer = TransformerFactory.newInstance().newTransformer();
			transformer.setOutputProperty( OutputKeys.DOCTYPE_PUBLIC, docType.getPublicId() );
			transformer.setOutputProperty( OutputKeys.DOCTYPE_SYSTEM, docType.getSystemId() );
			transformer.setOutputProperty( OutputKeys.INDENT, "no" );
			transformer.setOutputProperty( OutputKeys.OMIT_XML_DECLARATION, "yes" );

			var result = new StreamResult( file );
			var source = new DOMSource( document );
			transformer.transform( source, result );
		}
	};
})();
