//
//  Comments:
//    show_comment_text(id)                 Replace truncated with full text.
//    create_comment(kind, id)              Draw form to create new comment.
//    edit_comment(id)                      Draw form to edit existing comment.
//    cancel_comment(kind, id, name)        Cancel above forms.
//    post_create_comment(kind, id, name)   Post new comment.
//    post_edit_comment(kind, id, name)     Post changes to existing comment.
//    delete_comment(id)                    Delete comment.
//
//  Folder selections:
//    folder_select_all()                   Check all boxes.
//    folder_select_none()                  Uncheck all boxes.
//    folder_submit(button)                 Submits form.
//
//  Other:
//    paginator(arg, url)                   Redraw paginated list.
//    show_panel(url)                       Redraw the right panel.
//    register_interest(kind, id, num)      Change interest in object.
//
///////////////////////////////////////////////////////////////////////////////

// ----------------------------
//  Pagination.
// ----------------------------

// This redraws a paginated list.  See also the corresponding Rails code in
// app/helpers/application.  The AJAX action renders the contents of the div.
//   div) paginator_<arg>
//   url) provided as argument <url>
function paginator(arg, url) {
  var div = e("paginator_"+arg);
  send_ajax_request({
    url: url,
    async: true,
    onsuccess: function(result) {
      write_html(div, result.responseText);
    },
    onerror: function(result) {
      write_html(div, "Sorry, couldn't load new page.");
    }
  });
  flash_notice(div, "Loading...", 1);
}

// ----------------------------
//  Panels.
// ----------------------------

// Send AJAX request for contents of right panel, and stuff it in there.
//   div) right_panel
//   url) provided aas argument <url>
function show_panel(url) {
  var div = e("right_panel");
  send_ajax_request({
    url: url,
    async: true,
    onsuccess: function(result) {
      write_html(div, result.responseText);
    },
    onerror: function(result) {
      write_html(div, "Sorry, couldn't load object.");
    }
  });
  ensure_visible(div);
  flash_notice(div, "Loading...", 1);
}

// ----------------------------
//  Interests.
// ----------------------------

// Initialize the three images.
var INT_IMGS = [
  "/images/icons/letter.png",
  "/images/icons/watch.png",
  "/images/icons/ignore.png"
];

// Callback to change interest.  Posts change, and on success changes image.
// The *only* complexity here is that there may be more than one image for the
// given object (e.g. if its listed in the left panel on an index, and shown
// currently in the right panel).  I look for 5 (a little overkill doesn't
// hurt since this is very inexpensive) images, and change any I find.
//   div) interest_<kind>_<id>_<num>
//   url) interest/change: kind=<kind>, id=<id>
function register_interest(kind, id, num) {
  var name = kind + "_" + id + (num == "" ? "" : "_"+num);
  var div = e("interest_" + name);
  var old_src = div.src;
  send_ajax_request({
    url: "/interest/change?kind="+kind+"&id="+id,
    async: true,
    onsuccess: function(result) {
      var val = result.responseText
      if (val.match(/^[0-2]$/)) {
        div.src = INT_IMGS[parseInt(val)];
        name = "interest_" + kind + "_" + id;
        ext = "";
        while (ext != "_5") {
          div = e(name+ext)
          if (div && ext != num && ext != "_"+num)
            div.src = INT_IMGS[parseInt(val)];
          ext = inc_string(ext);
        }
      } else {
        div.src = old_src;
        alert("Sorry, couldn't register your interest in this object.\n" + val);
      }
    },
    onerror: function(result) {
      alert("Sorry, couldn't register your interest in this object.");
      div.src = old_src;
    }
  });
  div.src = ajax_img;
}

// ----------------------------
//  Comments.
// ----------------------------

var textile_notes =
"<div class='notes'><p style='margin-bottom:0px;margin-top:0px'>" +
 "Note, you can use some simple mark-up using " +
 "<a href=\"/ways/textile\" target=\"_new\"><code>Textile</code></a>." +
"</p></div>";

// This writes the full text in place of the first line shown by default.
//   div) comment_text_<id>
//   url) comment/ajax_show_text: id=<id>
function show_comment_text(id) {
  var div = e("comment_text_"+id);
  send_ajax_request({
    url: "/comment/ajax_show_text/"+id,
    async: true,
    onsuccess: function(result) {
      write_html(div, result.responseText);
    },
    onerror: function(result) {
      write_html(div, "Couldn't get comment.");
    }
  });
  flash_notice(div, "Loading...", 1);
}

// The tricky part is when you post multiple comments.  Not sure I should
// care, but I solve it by creating a new comment form div inside the old one,
// incrementing the <num> each time.  This then just searches for the one with
// the highest <num> and returns it.
function find_comment_form(kind, id) {
  var name = "comment_form_"+kind+"_"+id;
  var num = "_1";
  while (1) {
    var num2 = inc_string(num);
    var div2 = e(name + num2);
    if (!div2) break;
    num = num2;
  }
  return(name + num);
}

// This draws a form to create a comment with textarea, post and cancel
// buttons, which go to post_create_comment() and cancel_comment().
//   div) comment_form_<kind>_<id>_<num>
function create_comment(kind, id) {
  var name  = find_comment_form(kind, id);
  var name2 = name + "_text";
  var div   = e(name);
  write_html(div,
"<form>\n" +
 "<textarea id='"+name2+"' cols='60' rows='5'></textarea><br/>\n" +
 textile_notes +
 "<input value='Post Comment' type='button'" +
  " onclick='post_create_comment(\""+kind+"\", \""+id+"\", \""+name+"\")'/>\n" +
 "<span style='margin-right:20px'>&nbsp;</span>\n" +
 "<input value='Cancel' type='button'" +
  " onclick='cancel_comment(\""+kind+"\", \""+id+"\", \""+name+"\")'/>\n" +
 "<br/><br/>\n" +
"</form>"
  );
  ensure_visible(div);
  e(name2).focus();
}

// This draws a form to edit a comment with textarea, post and cancel
// buttons, which go to post_edit_comment() and cancel_comment().
//   div) comment_form_<kind>_<id>_<num>
//   url) comment/ajax_show_text: id=<id>, noformat=1
function edit_comment(kind, id) {
  var name  = find_comment_form(kind, id);
  var name2 = name + "_text";
  var div   = e(name);
  send_ajax_request({
    url: "/comment/ajax_show_text/"+id+"?noformat=1",
    async: true,
    onsuccess: function(result) {
      var val = result.responseText
      if (val != "") {
        write_html(div,
"<form>\n" +
 "<textarea id='"+name2+"' cols='60' rows='5'>" +
  val.replace(/</g,"&lt;").replace(/>/g,"&gt;") +
 "</textarea><br/>\n" +
 textile_notes +
 "<input value='Post Changes' type='button'" +
  " onclick='post_edit_comment(\""+kind+"\", \""+id+"\", \""+name+"\")'/>\n" +
 "<span style='margin-right:20px'>&nbsp;</span>\n" +
 "<input value='Cancel' type='button'" +
  " onclick='cancel_comment(\""+kind+"\", \""+id+"\", \""+name+"\")'/>\n" +
 "<br/><br/>\n" +
"</form>"
        );
        e(name2).focus();
      } else {
        flash_error(div, "Sorry, couldn't load comment.", 0);
      }
    },
    onerror: function(result) {
      flash_error(div, "Sorry, couldn't load comment.", 0);
    }
  });
  flash_notice(div, "Loading...", 0);
  ensure_visible(div);
}

// This just destroys the div.
function cancel_comment(kind, id, name) {
  write_html(e(name), "");
}

// This posts the comment via AJAX.
//   div) old form: comment_form_<kind>_<id>_<num>
//        new form: comment_form_<kind>_<id>_<num+1>
//   url) comment/ajax_create: kind=<code>, id=<id>, text=<textarea.value>
var new_comment_div = "new_comment_div";
function post_create_comment(kind, id, name) {
  var name2 = name + "_text";
  var name3 = inc_string(name);
  var div   = e(name);
  var val   = e(name2).value;
  send_ajax_request({
    method: "post",
    url: "/comment/ajax_create/"+id+"?kind="+kind,
    body: "text=" + encodeURIComponent(val),
    async: true,
    onsuccess: function(result) {
      if (result.responseText.match(/^[0-9]/)) {
        var new_id = parseInt(result.responseText);
        write_html(div, "<div id='"+name3+"'></div>" +
          result.responseText.replace(/^[0-9]*/,""));
      } else {
        flash_error(div, result.responseText, 0);
      }
    },
    onerror: function(result) {
      flash_error(div, "Sorry, couldn't post comment.", 0);
    }
  });
  flash_notice(div, "Posting...", 0);
}

// This posts the changes via AJAX.
//   div) form: comment_form_<kind>_<id>_<num>
//        text: comment_text_<id>
//   url) comment/ajax_edit: id=<id>, text=<textarea.value>
function post_edit_comment(kind, id, name) {
  var name2 = name + "_text";
  var name3 = "comment_"+id+"_text";
  var div   = e(name);
  var val   = e(name2).value;
  var div3  = e(name3);
  send_ajax_request({
    method: "post",
    url: "/comment/ajax_edit/"+id,
    body: "text=" + encodeURIComponent(val),
    async: true,
    onsuccess: function(result) {
      if (result.responseText.match(/^[0-9]/)) {
        write_html(div, "");
        write_html(div3, result.responseText.replace(/^[0-9]*/,""));
      } else {
        flash_error(div, result.responseText, 0);
      }
    },
    onerror: function(result) {
      flash_error(div, "Sorry, couldn't post changes.", 0);
    }
  });
  flash_notice(div, "Posting...", 0);
}

// This deletes the comment via AJAX.
//   div) object_0_<id>         Erases this if successful.
//        comment_text_<id>     Draws "loading..." and error message here.
//   url) comment/ajax_delete: id=<id>
function delete_comment(id) {
  if (confirm("Are you sure?")) {
    var name  = "object_0_"+id;
    var name2 = "comment_text_"+id;
    var div   = e(name);
    var div2  = e(name2);
    send_ajax_request({
      method: "post",
      url: "/comment/ajax_delete/"+id,
      async: true,
      onsuccess: function(result) {
        if (result.responseText == "") {
          write_html(div, "");
          hide_div(div);
        } else {
          flash_error(div2, result.responseText, 0);
        }
      },
      onerror: function(result) {
        flash_error(div2, "Sorry, couldn't delete comment.", 0);
      }
    });
    flash_notice(div2, "Deleting...", 0);
  }
}

// ----------------------------
//  Interests.
// ----------------------------

function folder_select_all() {
  for (var i=0; i< FOLDER_BOX_IDS.length; i++)
    e(FOLDER_BOX_IDS[i]).checked = "checked";
}

function folder_select_none() {
  for (var i=0; i< FOLDER_BOX_IDS.length; i++)
    e(FOLDER_BOX_IDS[i]).checked = null;
}

function folder_submit(button) {
  if (button != "delete" ||
    confirm("Are you sure you want to delete the selected files?")) {
    e("button").value = button;
    document.folder_boxes.submit();
  }
}

