/*

    JsonRenderer.js (v1.4)
    --------------
   
    A Javascript Object that allows you to render JSON tag elements into 
    any container HTML element.
    
    Requirements
    ------------
    * Prototype 1.4+
      <http://prototype.conio.net>    

    Usage
    -----
    
    For simple one off usage the constructor has convenience parameters:
    
      var jsonHtml = {tag: 'p', attributes:{style:'color: red;'}, 
                      children:['This is a generic paragraph!']};
    
      new JsonRenderer('id_of_container_element', jsonHtml);
    
    
    A reference to a render can also be recycled to swap out the contents of
    the container:
    
      var renderer = new JsonRenderer('');
      renderer.render(jsonHTML);
      ...
      // change structure of jsonHTML
      ...
      renderer.render(jsonHTML);
      
    Default ouput is XHTML to change this pass in an options array.  Currently,
    only 'html' and 'xhtml' are supported.
    
      new JsonRenderer(container, jsonHtml, {format: 'html'})
    
    Copyright
    ---------
    Copyright 2005,2006 (c) Alex Arnell <alex@typicalnoise.com>
    
    Licensed under the new BSD License. See end of file for full license terms.
        
    Changes (Ascending Order)
    -------------------------
    
    [4 May 2005]  0.9   * Initial Concept Release.
    [6 May 2005]  1.0   * Re-written as a class.
    [7 May 2005]  1.1   * Added final touches for first public releease.
    [8 May 2005]  1.2   * Added support for 'html' or 'xhtml' as specified using the options.
    [8 May 2005]  1.2.1 * Bugfix release.  Addresses issues:
                          - Better HTML output handling
                          - Various Syntax issues (now parses through JSLint.com)
    [8 May 2005]  1.2.2 * Empty tags '{}' and null in the jsonTags array will now be ignored.
    [9 May 2005]  1.3   * Refactored core to use more prototype enumeration methods.
    [10 May 2005] 1.4   * Bugfixes plus moved _renderNode into the Handlers which will slowly 
                          be transformed into Transformers.

    TODO
    ----
    * Add support for injecting as DOM instead of innerHTML
    * Current support for differt output formats is kind of cludgy.  I should
      really find a method that uses true inheritence.

*/
JsonRenderer = Class.create();
JsonRenderer.prototype = {
  initialize: function(container, jsonTags, options) {
    this.container = $(container);
    this.options = options || {format: 'xhtml', dom: false};
    
    if (typeof(jsonTags) != 'undefined') {
      this.render(jsonTags);
    }
  },
  render: function(jsonTags) {
    // loop through all json elements
    var html = $A(jsonTags).compact().inject('', function(memo, element){
      return memo + this.getTransformer().renderNode(element, 0); 
    }.bind(this));
    
    // Now update the form container
    //alert(html);
    Element.update(this.container, html);
    //this.container.innerHTML = html;
  },
  useDOM: function() {
    return this.options.dom || false;
  },
  
  getTransformer: function() {
    var transformer;
    
    switch (this.options.format) {
      case 'html':
        transformer = new HtmlHandler(this);
        break;
      case 'xhtml':
        transformer = new XhtmlHandler(this);
        break;
	  case 'code':
        transformer = new CodeHandler(this);
        break;
      default:
        throw "Unknown format cannot render.";
    }
    return transformer;
  }
};

// --
// AbstractHandler defines base properties
// --
AbstractHandler = function() {};
AbstractHandler.prototype = {
  initialize: function() {},
  renderNode: function(node) {
    var ret = '';
    if (node) {
      if (typeof(node) == 'string') {  
        ret = this.handleString(node);
      } else if (typeof(node) == 'object' && typeof(node.tag) == 'string') {
        ret = this.handleHtmlTag(node);
      }
    }
    return ret;
  }
};

// --
// Handles output to XHTML
// -- 
XhtmlHandler = Class.create();
XhtmlHandler.prototype = Object.extend(new AbstractHandler(), {
  handleString: function(node) {
    return node;
  },
  handleHtmlTag: function(node) {
    var retVal = '';
    retVal += this._openTag(node.tag) + this.handleAttributes(node.attributes);
    if (node.children) {
      retVal += '>';
      
      retVal += $A(node.children).inject('', function(memo, child){
        return memo + this.renderNode(child);
      }.bind(this));
      if(node.tag!='input')
      {
        retVal += this._closeTag(node.tag);
      }
    } else {
      retVal += this._closeTag();
    }

    return retVal;
  },
  _openTag: function(tag) {
    return '<' + tag;
  },
  _closeTag: function(tag) {
      if (tag) {
        return '</' + tag + '>';
      } else {
        return '/>';
      }
  },
  handleAttributes: function(attributes) {
    return $H(attributes).inject('', function(memo, dict){
      return memo + this.handleAttr(dict);
    }.bind(this));
  },
  handleAttr: function(attr) {
    return ' ' + attr.key + "=\"" + attr.value + "\"";
  }
});

// -- 
// Handles output to HTML
// --
HtmlHandler = Class.create();
HtmlHandler.prototype = Object.extend(new AbstractHandler(), Object.extend(XhtmlHandler.prototype, {
  _closeTag: function(tag) {
    if (tag) {
      return '</' + tag + '>';
    } else {
      return '>';
    }
  },
  handleAttr: function(attr) {
    var ret = ' ';
    switch(attr.key) {
      case 'selected': case 'checked':
        ret += attr.key;
        break;
      default:
        ret += attr.key + "=\"" + attr.value + "\"";
    }
    return ret;
  }
}));
// -- 
// Handles HTML Code output
// --
CodeHandler = Class.create();
CodeHandler.prototype = Object.extend(new AbstractHandler(),
Object.extend(XhtmlHandler.prototype, {
	toString: function() {
		return "CodeHandler";
	},
	_openTag: function(tag) {
    return '&lt;' + tag;
  	},
	_closeTag: function(tag) {
		if(tag) {
		  if (tag!='input')
      {
          endpiece = '&lt;/' + tag + '&gt;'
			}
			if (tag=='div')
			{
        endpiece += '<br><br>';
      }
      return endpiece;
		} else {
			return '&gt;';
		}
	},
	handleAttr: function(attr) {
    var ret = ' ';
    switch(attr.key) {
      case 'selected': case 'checked':
        ret += attr.key;
        break;
      default:
        ret += attr.key + "=\"" + attr.value + "\"";
    }
    return ret;
  }
}));

/*

Copyright (c) 2005, 2006, Alex Arnell <alex@typicalnoise.com>
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are 
permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this list 
  of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this 
  list of conditions and the following disclaimer in the documentation and/or other 
  materials provided with the distribution.
* Neither the name of the typicalnoise.com nor the names of its contributors may be 
  used to endorse or promote products derived from this software without specific prior 
  written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT 
OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

