var Activeweave = window.Activeweave || {};

Activeweave.validatePost = function(titleId,bodyId)
  {
  try
    {
    var title         = $(titleId);
    var t             = null;
    var b             = null;
    var invalidTitle  = false;
    var message       = "";
    if(title)
      {
      t = title.value;
      }
    if(t!=null)
      {
      t = t.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
      }
    if(t==null||t.length<2)
      {
      invalidTitle = true;
      message += "Please make sure to enter a title for this post.";
      }
    if(invalidTitle)
      {
      alert(message);
      return false;
      }
    return true;
      }
  catch(ex)
    {
    return false;
    }
  }

Activeweave.notes = {};

Activeweave.notes.update = function(offset)
  {
  Activeweave.HistorySupport.navigateToOffset("offset", offset);
  };

Activeweave.notes.checkImages = function()
  {
  Activeweave.log("Activeweave.notes.checkImages() - Starting.");
  var max = 440;
  try
    {
    var centerCol = $('center_col');
    if(centerCol)
      {
      var divs = centerCol.getElementsByTagName('div');
      if(divs)
        {
        for(var d=0;d<divs.length;d++)
          {
          var div = divs[d];
          if(div)
            {
            if(div.className=='body')
              {
              var docImgs = div.getElementsByTagName('img');
              if(docImgs)
                {
                for(var i=0; i<docImgs.length; i++)
                  {
                  var img         = docImgs.item(i);
                  var w           = img.width;
                  var h           = img.height;
                  var styleW      = img.style.width;
                  var styleH      = img.style.height;
                  var absStyleW   = false;

                  if(styleW)
                    {
                    var pxInd = styleW.indexOf('px');
                    if(pxInd>0)
                      {
                      styleW    = styleW.substring(0,pxInd);
                      absStyleW = true;
                      }
                    else
                      {
                      // width and height styles could be specified in any uniy (%, em, inches, etc.) - we're only handling px for now.
                      styleW = 0;
                      styleH = null;
                      img.style.width = '';
                      img.style.height = '';
                      }
                    }
                  if(styleH)
                    {
                    var pxInd = styleH.indexOf('px');
                    if(pxInd>0) styleH = styleH.substring(0,pxInd);
                    }
                  else
                    {
                    styleH = null;
                    img.style.height = '';
                    }

                  if(w>max||(absStyleW&&styleW>max))
                    {
                    var r   = (1.0*max)/(1.0*w);
                    var maxh  = Math.floor((1.0*h)*r);
                    img.setAttribute("width",max);
                    img.setAttribute("height",maxh);
                    if(styleW>max)
                      {
                      img.style.width   = max+"px";
                      img.style.height  = maxh+"px";
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  catch(ex)
    {
    Activeweave.log("Activeweave.notes.checkImages()",ex);
    }
  }

Object.extend(Activeweave.notes,
  {
  isEmpty : function()
    {
    return ($("post-0").parentNode.getElementsByTagName("FORM").length == 1);
    },

  checkEmpty : function()
    {
    Activeweave.log("Activeweave.notes.checkEmpty() - Starting.");
    if (this.isEmpty())
      {
      this.add();
      }
    },

  add : function()
    {
    new this._Broker($("post-0")).edit();
    },

  edit : function(postForm)
    {
    new this._Broker(postForm).edit();
    },

  drop : function(postForm)
    {
    new this._Broker(postForm).drop();
    },

  _Broker : function(postForm)
    {
    // find the real post form
    while (!(postForm.id && postForm.id.substring(0, 5) == "post-"))
      {
      postForm = postForm.parentNode;
      }
    var postId = parseInt(postForm.id.substring(5), 10);
    var isAdd = !(postId > 0); // post-0 is a holder for create new post

    // the rendered proxied uri is in format: http://www.activeweave.com/preview/?b=&p=&uri=...
    function getAnnotationURI(anchorElement)
      {
      var proxyUri = anchorElement.href;
      var i = proxyUri.lastIndexOf("&uri=");
      return (i!=-1) ? decodeURIComponent(proxyUri.substring(i + 5)) : proxyUri;
      }

    // generate a rounded shadowed input box
    function generateInput(name,value,title,label)
      {
      var html = "<span class='label'>"+label+"</span><span class='L'></span><input class='sizedInput' type='text' name='" + name + "'";
      if (value) html += ' value="' + value.escapeHTML().replace(/"/gm,"&quot;") + '"';
      if (title) html += ' title="' + title.escapeHTML().replace(/"/gm,"&quot;") + '"';
      return html + " /><span class='R'></span>";
      }

    // functions to retrieve some host elements
    function getTitle()       {return document.getElementsByClassName("title",      postForm)[0];}
    function getTitleLink()   {return document.getElementsByClassName("titleLink",  postForm)[0];}
    function getBody()        {return document.getElementsByClassName("body",       postForm)[0];}
    function getTags()        {return document.getElementsByClassName("tags",       postForm)[0];}
    function getTagsInput()   {return document.getElementsByClassName("sizedInput", getTags())[0];}
    function getAnnotations() {return document.getElementsByClassName("annotation", postForm)[0];}
    function getPrivateBtn()  {return document.getElementsByClassName("privateBtn", postForm)[0];}

    // return an array of tags
    function $tags()          {return $A(getTags().getElementsByTagName("A")).pluck("innerHTML");}
    // return an array of annonation uris
    function $URIs()          {return $A(getAnnotations().getElementsByTagName("A")).collect(getAnnotationURI);}
    // return an array of control button input elements (two buttons)
    function $buttons()       {return document.getElementsByClassName("controls",   postForm)[0].getElementsByTagName("a");}

    function show()    { Element.show(postForm, getTags().parentNode, getAnnotations().parentNode) }
    function hide()    { Element.hide(postForm) }
    function visible() { return Element.visible(postForm); }

    function updatePrivateBtn()
      {
      var publishedInput = postForm.publish;
      getPrivateBtn().src = "/client/images/button.private." + ((publishedInput.value=='true')? "off" : "on") + ".rg.png";
      }

    this.edit = function()
      {
      var container;
      if (isAdd)
        {
        if (visible())
          {
          getTitle().firstChild.focus();
          return;
          }
        container = postForm.nextSibling;
        if (!container || container.tagName != "DIV" || container.firstChild != null)
          {
          container = postForm.parentNode.insertBefore(document.createElement("DIV"), postForm.nextSibling);
          }
        }
      else
        {
        container = postForm.parentNode;
        }

      var postHTML = postForm.innerHTML;

      var privateBtn = getPrivateBtn();
      Object.extend(privateBtn,
        {
        onclick : function()
              {
              var publishedInput = postForm.publish;
              publishedInput.value = (publishedInput.value=='false')? 'true' : 'false';
              updatePrivateBtn();
              },
        onmouseup   : function() {onButton(this,'hi')},
        onmouseover : function() {onButton(this,'hi')},
        onmouseout  : function() {onButton(this,'rg')}
        });

      privateBtn.style.display = "inline";
      updatePrivateBtn();

      function onButton(elem,modifier)
        {
        if(!modifier) modifier = "rg";
        try
          {
          var mod = modifier+".png";
          var src = elem.src;
          src = src.substring(0,src.length-mod.length);
          src += mod;
          elem.src = src;
          }
        catch(ex)
          {
          }
        }

      function restore()
        {
        if (isAdd && Activeweave.notes.isEmpty())
          {
          postForm.reset();
          editor._richText.editNode.innerHTML = "";
          editor.updateToolbar();
          return;
          }
        editor.destroy();
        postForm.innerHTML = ""; // help GC by IE
        postForm.innerHTML = postHTML; // restore all
        if (isAdd) hide();
        }

      var titleValue        = getTitleLink().innerHTML;
      var tagsValue         = $tags().concat("").join(", "); // When editing, the list of tags should end with a comma so that the autocomplete can work for a next word
      var annotsValue       = $URIs().invoke("escapeHTML").join(" ");
      getTitle().innerHTML       = generateInput('post.title',          titleValue,  "","Title");
      getTags().innerHTML        = generateInput('tags',        tagsValue,   "Comma separated tags","Tags");
      getAnnotations().innerHTML = generateInput('post.annot.uri', annotsValue, "Space separated URLs","Links");

      // init tag suggest div
      new Insertion.After(getTags().parentNode,
          '<div class="tagSuggestShadow" id="noteEditorTags"><div class="tagSuggestContainer"></div></div>')
      Activeweave.setTagSuggest(getTagsInput(), getTags().parentNode.nextSibling.firstChild);
      var editorArgs =
        {
        items: ["linkGroup","|","textGroup","|","justifyGroup","|","fontName","|","colorGroup"/*, "blockGroup"*/]
        };

      var b = getBody();
      b.style.height   = "200px";
      b.style.overflow = "auto";
      b.style.border= "1px dotted #cccccc";
      show();
      var editor = dojo.widget.fromScript("Editor", editorArgs, b);

      b.onclick = function() {editor._richText.focus();};

      // set the first button with event
      Object.extend($buttons()[0],
        {
        innerHTML : Activeweave.notes.messageEditSave,
        onclick   : function()
          {
          var validated = postForm["post.title"].value
              || body || postForm["tags"].value
              || postForm["post.annot.uri"].value;
          if (!validated)
            {
            alert(Activeweave.notes.messageEditValidate);
            return;
            }

          var body  = editor.getEditorContent();
          postForm["post.id"].value = postId;
          postForm["post.body"].value = body;
          new Ajax.Updater({success:container}, "/notes/renderNote.jsp",
            {
            postBody  : Form.serialize(postForm),
            evalScripts : true,
            onSuccess : function() { if (isAdd) restore(); }
            })

          }
        });

      // set the second button with event
      Object.extend($buttons()[1],
        {
        innerHTML : Activeweave.notes.messageEditCancel,
        onclick   : function()
          {
          if (confirm(Activeweave.notes.messageCancelConfirm))
            {
            restore();
            }
          }
        });
      };

    this.hide = function()
      {
      var container = postForm.parentNode;
      container.style.display = 'none';
      };

    this.drop = function()
      {
      var container = postForm.parentNode;
      if (!confirm(Activeweave.notes.messageDeleteConfirm))
        {
        return;
        }
      if(container)
        {
        container.style.opacity = 0.5;
        container.style.filter = "alpha(opacity=50)";
        window.setTimeout("Activeweave.notes.hide",500);
        }
      new Ajax.Updater({success:container}, "/notes/renderNote.jsp",
        {
        postBody : $H(
          {
          "evt" : "e.delete",
          "b" : Activeweave.notes.blogId,
          "post.id" : postId
          }).toQueryString()
        });
      };
    }
  });  // Object.extend(Activeweave.notes)
