<?php
/**
 * @version		$Id: json.php 115 2009-06-17 07:20:36Z eddieajau $
 * @copyright	Copyright (C) 2009 New Life in IT Pty Ltd. All rights reserved.
 * @license		GNU General Public License <http://www.gnu.org/copyleft/gpl.html>
 * @link		http://www.theartofjoomla.com
 * @author		John Glazebrook <open-flash-chart@teethgrinder.co.uk>
 */

// no direct access
defined('_JEXEC') or die;

/**
 * JSON formatter
 *
 * @package		TAOJ.Quanta
 * @subpackage	com_quanta
 */
class JHtmlJSON
{
	/**
	 * @param	mixed	A JSON string or object.
	 *
	 * @return	string
	 */
	function format($json)
	{
		// Flatten the string or object.
		$json	= json_encode(json_decode($json));

		$tab	= '  ';
		$result	= '';
		$indent = 0;
		$instr	= false;
		$len	= strlen($json);

		for ($c = 0; $c < $len; $c++)
		{
			$char = $json[$c];
			switch ($char)
			{
				case '{':
				case '[':
					if (!$instr) {
						$result .= $char."\n".str_repeat($tab, $indent+1);
						$indent++;
					}
					else {
						$result .= $char;
					}
					break;
				case '}':
				case ']':
					if (!$instr) {
						$indent--;
						$result .= "\n".str_repeat($tab, $indent).$char;
					}
					else {
						$result .= $char;
					}
					break;
				case ',':
					$result .= (!$instr ? ",\n".str_repeat($tab, $indent) : $char);
					break;

				case ':':
					$result .= (!$instr ? ": " : $char);
					break;

				case '"':
					if ($c > 0 && $json[$c-1] != '\\') {
						$instr = !$instr;
					}

				default:
					$result .= $char;
					break;
			}
		}

		return $result;
	}
}