/**
 * Filename    : JsonPrettyPrinting.js
 * Author      : Robert Cerny
 * Created     : 2007-03-19
 * Last Change : 2009-01-15
 */

CERNY.require("CO.cernyjs.demos.JsonPrettyPrinting",
              "CO.cernyjs",
              "CO.cernyjs.demos.Demo",
              "CO.cernyjs.demos.examples",
              "CERNY.json.HtmlPrettyPrinter",
              "CERNY.json.TextPrettyPrinter");

CO.cernyjs.demos.JsonPrettyPrinting = CERNY.object(CO.cernyjs.demos.Demo);
CO.cernyjs.demos.JsonPrettyPrinting.examples = CO.cernyjs.demos.examples.documents;
CO.cernyjs.demos.JsonPrettyPrinting.logger = CERNY.Logger("CO.cernyjs.demos.JsonPrettyPrinting");
CO.cernyjs.demos.JsonPrettyPrinting.html = false;

CO.cernyjs.demos.JsonPrettyPrinting.run = function () {
    var jsonString = this.inputField.value, obj, printer, prettyJsonString;

    this.configureLogging();

    // Clear the output field
    if (this.outputField.firstChild) {
        this.outputField.removeChild(this.outputField.firstChild);
    }

    // Parse the input
    try {
        obj = jsonString.parseJSON();
    } catch (e) {
        this.outputField.innerHTML = "<p>Your JSON String cannot be parsed!</p>";
        return;
    }

    // Get the pretty printer
    if (this.html) {
        printer = CERNY.json.HtmlPrettyPrinter();
        printer.logger = CERNY.Logger("CERNY.json.HtmlPrettyPrinter");
    } else {
        printer = CERNY.json.TextPrettyPrinter();
        printer.logger = CERNY.Logger("CERNY.json.TextPrettyPrinter");
    }

    // In Cerny.js 1.2 there is no interceptors installed on the Printers
    CERNY.intercept(printer);

    // Prettyprint it
    prettyJsonStr = printer.print(obj);
    this.logger.debug("prettyJsonStr.length: " + prettyJsonStr.length);

    // Display the result
    if (this.html) {
        // Not implemented yet, because i did not find a way to
        // make the result displayed right in IE; normalization, innerHTML
    } else {
        if (document.all) {
            this.outputField.innerText = prettyJsonStr;
        } else {
            this.outputField.appendChild(document.createTextNode(prettyJsonStr));
        }
    }
};

CERNY.intercept(CO.cernyjs.demos.JsonPrettyPrinting);

init = CERNY.joinFunctions(init, function () {
    CO.cernyjs.demos.JsonPrettyPrinting.init();
});

