/* js
   
   This file is part of arena.

   arena is free software: you can redistribute it and/or modify it
   under the terms of the GNU General Public License as published by the
   Free Software Foundation; either version 3 of the License or, at your
   option, any later version.

   arena is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABLITY
   or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
   License for more details.

   You should have received a copy of the GNU General Public License along
   with arena.  If not, see <http://www.gnu.org/licenses/>.
*/

/* This file extends ADynamicElement to allow post content to be displayed and
   retrieved dynamically.
*/

// APostChannelTree ***********************************************************/
subclass(APostChannelTree, ATree);

// A channel selection tree for posts that are being edited
function APostChannelTree(ThisPost, treeName) {
  ATree.call(this, ThisPost.identifier + "$" + treeName);
}

// This function handles mouse clicks for individual leaves
APostChannelTree.prototype.pickLeaf = function(leafName) {
  // Highlight the new leaf
  if (leafName.indexOf(this.treeName) != 0)
    leafName = this.treeName + "/" + leafName;

  leaf = document.getElementById(leafName + "$icon");

  if (leaf) {
    leaf.checked = (leaf.checked? false: true);
  }
}

// This function attaches an icon to the specified leaf
APostChannelTree.prototype.attachIcon = function(leaf, icon) {
  if (leaf) {
    newLeafIcon = document.createElement("INPUT");
    newLeafIcon.id = leaf.id + "$icon";
    newLeafIcon.type = "checkbox";
    newLeafIcon.value = leaf.id;
    // Attach the icon to the new leaf
    leaf.appendChild(newLeafIcon);
  }
}

// This function sets up a link for the specified leaf
APostChannelTree.prototype.attachLink = function(leaf, title, url) {
  if (leaf) {
    newLeafLink = document.createElement("A");
    newLeafLink.href = "javascript:void(0)";
    newLeafLink.title = title;
    newLeafLink.id = leaf.id + "$link";
    var self = this;

    newLeafLink.onclick = function() {
      self.pickLeaf(leaf.id);
      return true;
    }

    // Insert the link
    leaf.appendChild(newLeafLink);
    // Create a text node that contains the leaf name
    newLeafText = document.createTextNode(title);
    newLeafLink.appendChild(newLeafText);
  }
}

// This function returns a list of channel names that are checked
APostChannelTree.prototype.selection = function() {
  result = new Array();
    
  checkboxes = this.element.getElementsByTagName("input");
  for (var i=0; i < checkboxes.length; i++) {
    if ( (checkboxes[i].type == "checkbox") && (checkboxes[i].checked) ) {
      // Break out the channel name
      channelPath = checkboxes[i].id.split("/");
        
      channelName = "";
      // We start at 1 to leave off the name of the channel tree
      for (var j=1; j < channelPath.length; j++)  {
        channelName += channelPath[j];
        if (j < (channelPath.length - 1))
          channelName += "/";
      }
      channelName = channelName.split("$")[0];
      result.push(channelName);
    }
  }
    
  return result;
}

// APost ***********************************************************************
subclass(APost, ADynamicElement);

function APost(id) {
  ADynamicElement.call(this, "post_" + id);
  this.pid = id; 
  this.ChannelTree = false;
}

// Edit the specified post
APost.prototype.edit = function(url) {
  if (url == "")
    return;

  url += "&template=edit.tpl.html&id=" + escape(this.identifier);
  this.fetch(url);
}

// Save a draft of the specified post
APost.prototype.saveDraft = function(blocking) {
  // Get the form used to enter post data
  postData = document.getElementById(this.identifier + "$edit");
  if (!postData)
    return;

  previousTemplate = postData.elements["template"].value;
  postData.elements["template"].value = "draft-published.tpl.html";
  postData.elements["draft"].value = "y";

  // Validate the form
  if (!Form.valid(postData))
    return;

  // Encode the form
  queryString = Form.encode(postData) + "&ajax=y";
  // Reset the template
  postData.elements["template"].value = previousTemplate;
  // Reset the draft status
  postData.elements["draft"].value = "n";
  
  StatusBanner = new ADynamicElement(this.identifier + "$draft");
  StatusBanner.element.innerHTML = "<em>Saving draft...</em>";
  StatusBanner.fetch(postData.action, queryString, blocking);
  
  // Change the "Cancel" button to a "Discard" button
  if (postData.elements["cancel"].value != "Discard") {
    postData.elements["cancel"].value = "Discard"
    Self = this;
    postData.elements["onclick"] = function() {
      Self.delete();
    }
  }
  
  delete StatusBanner;
}

// Construct a channel tree for the post
APost.prototype.buildChannelTree = function(url, placement) {
  if ( (url != "") && (placement != "") ) {
    this.ChannelTree = new APostChannelTree(this, placement);
    this.ChannelTree.fetch(url, true);
  }
}

// Highlight a channel in the channel tree
APost.prototype.selectChannel = function(channelName) {
  if (this.ChannelTree)
    this.ChannelTree.pickLeaf(channelName);
}

// Add a new channel to the channel tree
APost.prototype.addChannel = function(channelFieldName) {
  if ( (!this.ChannelTree) || (channelFieldName == "") )
    return;

  channelField = 
    document.getElementById(this.identifier + "$" + channelFieldName);

  if ( (channelField) && (channelField.value != "") ) {
    this.ChannelTree.sprout(channelField.value);
    channelField.value = "";
  }
}

// Publish the post
APost.prototype.publish = function(thisForm) {
  thisForm.elements["channels"].value = this.ChannelTree.selection().join();
  // Validate the form
  return Form.valid(thisForm);
}  

// Delete the post
APost.prototype.delete = function(url, queryString) {
  confirmation = confirm("Do you really want to PERMANENTLY delete this " +
                         "item and all associated content?");
  
  if (!confirmation)
    return;
    
  // Delete the post
  if ( (queryString) && (queryString != ""))
      queryString += "&id=" + this.pid + "&do=delete&ajax=y";
      
  else
      queryString = "id=" + this.pid + "&do=delete&ajax=y";
      
  this.fetch(url, queryString);
}
  

/* Properties --------------------------------------------------------------- */
// Retrieve the title of the post
APost.prototype.title = function() {
  titleElement = document.getElementById("post_" + this.identifier + "$title");
  if (titleElement)
    return titleElement.firstChild.textContent;

  return "";
}

// Set the title of the post
APost.prototype.setTitle = function(newTitle) {
  titleElement = document.getElementById("post_" + this.identifier + "$title");
  if (titleElement)
    titleElement.firstChild.textContent = newTitle;
}

// Retrieve the content of the post
APost.prototype.content = function() {
  contentElement = document.getElementById("post_" + this.identifier + "$content");
  if (contentElement)
    return contentElement.innerHTML;

  return "";
}

// Set the content of the post
APost.prototype.setContent = function(newContent) {
  contentElement = document.getElementById("post_" + this.identifier + "$content");
  if (contentElement)
    contentElement.innerHTML = newContent;
}

// Toggle visibility a specific post section
APost.prototype.toggleDisplayOf = function(section, anchor) {
  OptionalArea = new ADynamicElement(this.identifier + "$" + section);
  OptionalArea.toggleVisibility(anchor);
  delete OptionalArea;
}
       
