/**
 * Scripting for markupfactory.com public site
 */

/*global WWW, Prototype, Class, $, $$, prettyPrint, Element, Control */

if (typeof Prototype == "object") {
  var WWW = Class.create({
    initialize : function () {
      // Documentation
      if ($('doctoc')) { 
        // Check for duplicate lists
        if ($$('#doctoc').length > 1) {
          $$('#doctoc')[1].id = "";
        }
        this.loadDocumentationTreeState(); 
      }

      if ($('bd')) {
        this.insertTopLinks();
      }

      this.addObservers();

      // Add pretty print
      if (typeof prettyPrint === "function" && !Prototype.Browser.IE) {
        // Insert style sheet tag
        $$('head')[0].insert(new Element('link', {
          rel : "stylesheet",
          href : "/assets/www/prettify/prettify.css",
          type : "text/css"
        }));
        prettyPrint();
      }

      // Add external links
      $$('a[rel="external"]').each(function (a) { a.target = "_blank"; });
    },

    addObservers : function () {
      if ($('doctoc')) { 
        $('doctoc').observe('click', this.saveDocumentationTreeState);
      }
      // Disable example form submit button
      if ($('exampleRequestForm')) {
        $('exampleRequestForm').observe('submit', function (evt) {
          evt.stop();
        });
      }

      // Package modals 
      if ($$('table.packages').length > 0) {
        this.packagePopups();
      }
    },

    /**
     * Create modal popups for packages table
     */
    packagePopups : function () {
      if (typeof Control == "object" && typeof Control.Modal == "function") {
        var isButton = function (el) {
          return $(el).up().hasClassName("signup");
        };
        // Stop click from happening on table
        $($$('table.packages').first()).observe("click", function (evt) {
          var el = evt.element();
          if (el.tagName == "A" && !isButton(el)) { evt.stop(); }
        });
        // Create modals
        $$('table.packages a').each (function (a) {
          if (!isButton(a)) { // Don't do buttons
            new Control.Modal(a, {
              hover : true,
              method : "get",
              position : 'relative',
              className : ".modal_conatainer",
              offsetLeft : 110,
              offsetTop : 5
            });
          }
        });
      }
    },

    /**
     * Find named anchors and create a link to the top of the page.
     */
    insertTopLinks : function () {
      if ($$('a[name="top"]').length > 0) {
        $$('a[name]').each(function (a) {
          if (a.name != "top") {
            a.up().insert(new Element('a', {
                'class' : 'topLink',
                'title' : 'Back to the top',
                'href' : '#top'}).update("&uarr;"), {
              top : ""});
          }
        });  
      }
    },

    /**
     * Create a string with the closed/open state of the documentation
     * tree nodes and save it to a cookie
     */
    saveDocumentationTreeState : function (evt) {
      var el = evt.element();
      var state = "";

      if (el.tagName == "SPAN") {
        $$('#doctoc li.children').each(function (li) {
          state += li.hasClassName("closed") ? 0 : 1;
        });
        document.cookie = encodeURIComponent(
            "documentationTreeState=" + state + "; path=/documentation");
      }
    },

    /**
     * load the documenation tree state from a cookie
     */                                 
    loadDocumentationTreeState : function () {
      var state = [];
      document.cookie.split(";").each(function (cookie) {
        if (cookie.startsWith("documentationTreeState")) {
          state = decodeURIComponent(cookie).split("=")[1].gsub(
            /;.*$/, "").split("");
        }
      });

      var i = 0;
      initTree($('doctoc'));
      $$('#doctoc li.children').each(function (li) {
        if (state[i] == 0) { li.addClassName('closed'); }
        i += 1;
      });
    }
  });

  document.observe("dom:loaded", function () { new WWW(); });
}
