// $Id: ajax_comments.js 19 2007-05-14 16:22:24Z rhardy $

/* Global variable definitions */
var mi_comments_submit_state = false;
var mi_comments_display_state = false;
var mi_comments_expand_state = false;

function get_cookie(cname) {
  var arg = cname + '='; 
  var alen = arg.length;
  var clen = document.cookie.length; 
  var i = 0;
  var j;

  while (i < clen) {
    j = i + alen;

    if ( document.cookie.substring(i, j) === arg ) { 
      return get_cookie_val(j); 
    } 

    i = document.cookie.indexOf('', i) + 1;

    if (i === 0) {
      break; 
    }
  } 

  return null;
}

function get_cookie_val(offset) {
  var endstr = document.cookie.indexOf(';', offset);

  if (endstr === -1) { 
    endstr = document.cookie.length; 
  }

  return unescape( document.cookie.substring(offset, endstr) );
}

/* Handle the submission of the comment form via AJAX. */
function ajax_comment_form(drupal_loc, submit_path, story_id, this_form) {
  var inputs;

  if(!$('#edit-comment').val()) { 
    $('#edit-comment').css('border','1px solid red');
    set_submit_status('error','Your comment may not be blank.');
    return false;
  } 
  else {
    $('#edit-comment').css('border','1px inset white');
    set_submit_status('normal','Submitting comment...');

    inputs = $(this_form).serialize();
    inputs += '&' + escape($('.form-submit').attr('name')) + '=' + escape($('.form-submit').val());

    $('.form-submit').attr('disabled',true);
    try {
      $.ajax({
        type: 'POST',
        error: function(request, error_message, e) {
          set_submit_status('error', 'Comment submission temporarily failed. Please try again later.');
          $('.form-submit').attr('disabled',false);
        },
        success: function(data) {
          get_comments(drupal_loc, story_id);
          $('#edit-comment').val('');
          set_submit_status('normal','Comment submitted successfully.');
          self.setTimeout("set_submit_status('normal','Awaiting input...')", 5000);
          $('.form-submit').attr('disabled',false);
        },
        url: drupal_loc + submit_path,
        data: inputs 
      });
    }
    catch (e) {
      error_message = "Comment submission temporarily failed. Please try again later.";
      set_submit_status('error', error_message);
      $('.form-submit').attr('disabled',false);
    }

    return false;
  }

  return false;
}

function get_comments(drupal_loc, story_id){
  var url = drupal_loc + '/mi_ajax_comments/' + story_id;

  if (mi_comments_expand_state) {
    url = drupal_loc + '/mi_ajax_comments/full/' + story_id;
  }
  
  try {
    $.ajax({
      type: 'GET',
      error: function(request, error_messsage, except) {
        $('#mi_comments-comments').html('<div class="mi_comments-system_error"">Temporarily unable to load comments. Please try again later.</div>');
      },
      success: function(data) {
        $('#mi_comments-comments').html(data);
      },
      url: url
    });
  }
  catch (e) {
    $('#mi_comments-comments').html('<div class="mi_comments-system_error"">Temporarily unable to load comments. Please try again later.</div>');
  }

  return false;
}

function set_submit_status(status_type,submit_status) {
  if (status_type === 'error') {
    $("#mi_comments-submit_form-status").css('color','red');
  }
  else {
    $("#mi_comments-submit_form-status").css('color','');
  }

  $("#mi_comments-submit_form-status").html('<div class="form-item"><label>Status: </label></div>' + submit_status);

  return false;
}

function get_submit_message(submit) {
  if (submit == null) {
    submit = mi_comments_submit_state;
  }

  return 'Post Comment';
}

function toggle_submit(link) {
  set_submit(!mi_comments_submit_state);
  $(link).html( get_submit_message() );

  return false;
}

function set_submit(submit) {
  mi_comments_submit_state = submit;

  if (mi_comments_submit_state) {
    $('#mi_comments-submit_form').show();
  }
  else {
    $('#mi_comments-submit_form').hide();
  }
 
  return false;
}

function toggle_comment(drupal_loc, action, div_id, comment_id) {
  if(action === 'expand') {
    $('#' + div_id).load(drupal_loc + '/mi_ajax_comments/single/' + comment_id);
  }
  if(action === 'collapse') {
    $('#' + div_id).load(drupal_loc + '/mi_ajax_comments/short/' + comment_id);
  }
}

function get_display_message(display) {
  if (display == null) {
    display = mi_comments_display_state;
  }

  if (display) {
    return 'Hide Comments';
  }

  return 'Show Comments';
}

function set_display(display) {
  mi_comments_display_state = display;

  if (mi_comments_display_state) {
    $('#mi_comments-comments').show();
    $('#mi_comments-menu-expand').show();
  }
  else {
    $('#mi_comments-comments').hide();
    $('#mi_comments-menu-expand').hide();
  }

  return false;
}

function toggle_display(div_id, link) {
  set_display(!mi_comments_display_state);
  $(link).html( get_display_message() );
 
  return false;
}

function get_expand_message(expand) {
  if (expand == null) {
    expand = mi_comments_expand_state;
  }

  if (expand) {
    return 'Collapse All Comments';
  }

  return 'Expand All Comments';
}

function set_expand(expand) {
  mi_comments_expand_state = expand;

  return false;
}

function toggle_expand(drupal_loc, link, story_id) {
  set_expand(!mi_comments_expand_state);
  get_comments(drupal_loc, story_id);
  $(link).html( get_expand_message() );

  return false;
}

/**
 * Draw the comment block on the page.
 *
 * Draws the comment handling menu, as well as any comments specified by the "view" parameter.
 */
function draw_comment_block(drupal_loc, story_id, story_title, story_body, login_link, cookie_name, view, submit, display, expand) {
  var icname;
  var cookie_values;

  if(view) {

    document.write('<div id="mi_comments"></div>');

    /* We must have the location of the Drupal, the Story ID and the name of the authentication cookie or else comments won't work at all. */
    if(!drupal_loc || !story_id || !cookie_name) {
      $('#mi_comments').html('Comments for this story are not available.');
      return;
    }

    $('#mi_comments').append('<div id="mi_comments-submit_menu"></div>');
    $('#mi_comments').append('<div id="mi_comments-submit_form"></div>');
    $('#mi_comments').append('<div id="mi_comments-menu"></div>');
    $('#mi_comments').append('<div id="mi_comments-comments"></div>');

    set_submit(false);
    set_display(false);
    set_display(false);

    icname = get_cookie(cookie_name);
    if (icname) {
      cookie_values = icname.split('|');
    }
    if (!icname || cookie_values[0] === '.threshold') {
      $('#mi_comments-submit_menu').html('<a href="' + login_link + '">Login to leave a comment!</a>');
    }
    else {
      $('#mi_comments-submit_menu').html('<a id="mi_comments-submit_menu-submit" href="" onclick="toggle_submit(this); return false;">' + get_submit_message(submit) + '</a>');
      try {
        $.ajax({
          type: 'POST',
          error: function(request, error_message, except) {
            $('#mi_comments-submit_form').html('<div class="mi_comments-system_error">Temporarily unable to load comment form. Please try again later.</div>');
          },
          success: function(data) {
            $('#mi_comments-submit_form').html(data);
            set_submit_status('normal','Awaiting input....');
          },
          url: drupal_loc + '/mi_ajax_comments/form/' + story_id,
          data: { story_title: story_title, story_body: story_body }
        });
      }
      catch (e) {
        $('#mi_comments-submit_form').html('<div class="mi_comments-system_error">unable to load comment form. Please try again later.</div>');
      }
    }
    set_submit(submit);

    $('#mi_comments-menu').append('<a id="mi_comments-menu-display" href="" onclick="toggle_display(\'mi_comments-comments\', this); return false;">' + get_display_message(display) + '</a>');
    $('#mi_comments-menu').append('<a id="mi_comments-menu-expand" href="" onclick="toggle_expand(\'' + drupal_loc + '\', this, \'' + story_id + '\'); return false;">' + get_expand_message(expand) + '</a>');
    if (!display) {
      $("#comments_menu-expand").hide();
    }

    set_expand(expand);
    get_comments(drupal_loc, story_id);
    set_display(display);
  }
}
