/* See license.txt for terms of usage */

/**
 * Initial UI construction.
 */
var initialized = false;
$(document).ready(function()
{
    if (initialized)
        return;

    initialized = true;

    // Generate page content.
    var content = $("#content")[0];
    viewer = SourceView.tag.replace({}, content, SourceView);
    SourceView.selectTabByName(viewer, "Input");

    // Get default example if any.
    var filePath = getQueryVariable("example");
    if (!filePath)
        filePath = getQueryVariable("path");

    if (filePath)
        loadExampleArchive(filePath);
});

function getQueryVariable(variable)
{
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable)
      return pair[1];
  }
  return null;
}

/**
 * Global variables
 */
var viewer;

// Views templates for the page
//-----------------------------------------------------------------------------

with ($.domplate) {

//-----------------------------------------------------------------------------

// Main page template
var TabView = domplate(
{
    tag:
        TABLE({"class": "tabView", cellpadding: 0, cellspacing: 0},
            TBODY(
                TR({"class": "tabViewRow"},
                    TD({"class": "tabViewCol", valign: "top"},
                        TAG("$tabList")
                    )
                )
            )
        ),

    selectTabByName: function(tabView, tabName)
    {
        var tab = getElementByClass(tabView, "tab", tabName + "Tab");
        if (tab)
            this.selectTab(tab);
    },

    onClickTab: function(event)
    {
        var e = jQuery.event.fix(event || window.event);
        this.selectTab(e.target);
    },

    selectTab: function(tab)
    {
        var view = tab.getAttribute("view");
        var viewBody = getAncestorByClass(tab, "tabViewBody");
        if (!viewBody)
            return;

        // Deactivate current tab.
        if (viewBody.selectedTab)
        {
            viewBody.selectedTab.removeAttribute("selected");
            viewBody.selectedBody.removeAttribute("selected");
        }

        // Store info about new active tab.
        var tabBody = getElementByClass(viewBody, "tab" + view + "Body");
        if (!tabBody)
            return;

        viewBody.selectedTab = tab;
        viewBody.selectedBody = tabBody;

        // Activate new tab.
        viewBody.selectedTab.setAttribute("selected", "true");
        viewBody.selectedBody.setAttribute("selected", "true");

        this.updateTabBody(viewBody, view, null);
    },

    updateTabBody: function(viewBody, view, message)
    {
    }
});

//-----------------------------------------------------------------------------

var SourceView = domplate(TabView,
{
    tabList:
        DIV({"class": "tabViewBody"},
            DIV({"class": "tabBar"},
                A({"class": "InputTab tab", onclick: "$onClickTab", view: "Input"},
                    "Input JSON"
                ),
                A({"class": "PreviewTab tab", onclick: "$onClickTab", view: "Preview"},
                    "Preview"
                ),
                A({"class": "DOMTab tab", onclick: "$onClickTab", view: "DOM"},
                    "DOM"
                ),
                /*A({"class": "SourceTab tab", onclick: "$onClickTab", view: "Source"},
                    "Source"
                ),*/
                A({"class": "HelpTab tab", onclick: "$onClickTab", view: "Help"},
                    "About",
                    "&nbsp;",
                    SPAN({"style": "font-size:11px;color:#DD467B;"},
                        "1.0"
                    )
                ),
                A({"class": "SchemaTab tab", onclick: "$onClickTab", view: "Schema"},
                    "Schema"
                )
            ),
            DIV({"class": "tabInputBody tabBody"}),
            DIV({"class": "tabPreviewBody tabBody"}),
            DIV({"class": "tabDOMBody tabBody"}),
            DIV({"class": "tabSourceBody tabBody"},
                PRE({"class": "sourcePreview"})
            ),
            DIV({"class": "tabHelpBody tabBody"}),
            DIV({"class": "tabSchemaBody tabBody"},
                PRE({"class": "schemaPreview"})
            )
        ),

    updateTabBody: function(viewBody, view, object)
    {
        var tab = viewBody.selectedTab;

        var tabInputBody = getElementByClass(viewBody, "tabInputBody");
        if (hasClass(tab, "InputTab") && !tabInputBody.updated)
        {
            tabInputBody.updated = true;

            var template = document.getElementById("InputTabTemplate");
            tabInputBody.innerHTML = template.cloneNode(true).innerHTML;
            //tabInputBody.appendChild(template.cloneNode(true));
            eraseNode(template.innerHTML);
        }

        var tabPreviewBody = getElementByClass(viewBody, "tabPreviewBody");
        if (hasClass(tab, "PreviewTab") && !tabPreviewBody.updated)
        {
            tabPreviewBody.updated = true;

            var inputData = NetBuilder.getInputData();
            if (!inputData)
            {
                var tabPreviewBody = getElementByClass(viewBody, "tabPreviewBody");
                NetBuilder.buildErrorList(tabPreviewBody, NetBuilder.errors);
                return;
            }

            //var sourceEditor = getElementByClass(document.documentElement, "sourceEditor");
            //sourceEditor.value = "";

            // Validation
            if (document.getElementById("validate").checked)
            {
                dojo.require("dojox.json.schema");
                dojo.require("dojox.json.ref"); 

                var resolvedSchema = dojox.json.ref.resolveJson(schema);
                var results = dojox.json.schema.validate(inputData, resolvedSchema.logType);
                if (!results.valid)
                {
                    NetBuilder.buildErrorList(tabPreviewBody, results.errors);
                    return;
                }
            }

            NetBuilder.buildPageList(tabPreviewBody, inputData);
        }

        var tabDOMBody = getElementByClass(viewBody, "tabDOMBody");
        if (hasClass(tab, "DOMTab") && !tabDOMBody.updated)
        {
            tabDOMBody.updated = true;
            var table = DomView.tag.replace({object: NetBuilder.inputData}, tabDOMBody);
            // xxxHonza
            //table.firstChild.firstChild.repObject = DomView.memberIterator(NetBuilder.inputData);
            if (table.firstChild.firstChild)
                DomView.toggleRow(table.firstChild.firstChild);
        }

        var tabSchemaBody = getElementByClass(viewBody, "tabSchemaBody");
        if (hasClass(tab, "SchemaTab") && !tabSchemaBody.updated)
        {
            tabSchemaBody.updated = true;

            var request = new XMLHttpRequest();
            request.onreadystatechange = function () {
                if (request.readyState == 4 && request.status == 200)
                {
                    if (jQuery.browser.msie)
                        tabSchemaBody.firstChild.innerText = request.responseText;
                    else
                        tabSchemaBody.firstChild.innerHTML = request.responseText;
                }
            };
            request.open("GET", "schema.js", true);
            request.send(null);
        }

        var tabHelpBody = getElementByClass(viewBody, "tabHelpBody");
        if (hasClass(tab, "HelpTab") && !tabHelpBody.updated)
        {
            tabHelpBody.updated = true;

            var template = document.getElementById("HelpTabTemplate");
            tabHelpBody.innerHTML = template.cloneNode(true).innerHTML;
            eraseNode(template.innerHTML);
        }

        var tabSourceBody = getElementByClass(viewBody, "tabSourceBody");
        if (hasClass(tab, "SourceTab")/* && !tabSourceBody.updated*/)//xxxHonza
        {
            tabSourceBody.updated = true;

            if (NetBuilder.inputData)
            {
                dojo.require("dojo._base.json");
                var jsonString = dojo.toJson(NetBuilder.inputData, true);

                if (jQuery.browser.msie)
                    tabSourceBody.firstChild.innerText = jsonString;
                else
                    tabSourceBody.firstChild.innerHTML = escapeHTML(jsonString);
            }
            else
            {
                tabSourceBody.firstChild.innerHTML = "";
            }
        }
    },

    onPreview: function()
    {
        var tabPreviewBody = getElementByClass(document.documentElement, "tabPreviewBody");
        tabPreviewBody.updated = false;
        this.selectTabByName(viewer, "Preview");
    },

    onAppendPreview: function()
    {
        var inputData = NetBuilder.parseInputData();
        if (!inputData)
        {
            console.log("Failed to parse input data");
            return;
        }

        dojo.require("dojo._base.json");

        var newData = NetBuilder.addInputData(inputData);
        var jsonString = dojo.toJson(newData, true);
        var sourceEditor = getElementByClass(document.documentElement, "sourceEditor");
        sourceEditor.value = "(" + jsonString + ")";
        //sourceEditor.value = "";

        var tabPreviewBody = getElementByClass(document.documentElement, "tabPreviewBody");
        var table = PageList.tableTag.append({groups: inputData.log.pages},
            tabPreviewBody, PageList);
        var rows = table.firstChild.childNodes;
        for (var i=0; i<rows.length; i++)
            rows[i].repObject = inputData.log.pages[i];

        if (table.firstChild.firstChild)
            PageList.toggleRow(table.firstChild.firstChild);

        //xxxHonza: Don't relayout the entire content in updateContent.
        // What if the content isn't generated yet?
        tabPreviewBody.updated = true;

        // DOM tab must be regenerated
        var tabDOMBody = getElementByClass(document.documentElement, "tabDOMBody");
        tabDOMBody.updated = false;

        //onSourceChange();
        //this.onPreview();
        this.selectTabByName(viewer, "Preview");
    }
});

//-----------------------------------------------------------------------------
};

/*************************************************************************************************/

function onValidationChange()
{
    onSourceChange();
}

function onSourceChange()
{
    var tabPreviewBody = getElementByClass(document.documentElement, "tabPreviewBody");
    tabPreviewBody.updated = false;

    var tabDOMBody = getElementByClass(document.documentElement, "tabDOMBody");
    tabDOMBody.updated = false;

    var tabSourceBody = getElementByClass(document.documentElement, "tabSourceBody");
    tabSourceBody.updated = false;
}

function loadExampleArchive(filePath)
{
    var editor = document.getElementById("sourceEditor");
    editor.value = "Loading...";

    var request = new XMLHttpRequest();
    request.onreadystatechange = function () {
        if (request.readyState == 4 && request.status == 200)
        {
            editor.value = request.responseText;
            onSourceChange();
            SourceView.onAppendPreview();
        }
    };

    request.open("GET", filePath, true);
    request.send(null);
}

/*************************************************************************************************/

function insertHighlighted(parentNode, sourceCode)
{
    parentNode.innerHTML = sourceCode;
}

