/**
  Cause Stream Poster
  2009-09-29 / <brad@causes.com>
**/
if (typeof (Causes) === 'undefined') Causes = {};
if (typeof (Causes.CauseStream) === 'undefined') Causes.CauseStream = {};

Causes.CauseStream.Poster = (function () {

  var jqContentContainer;
  var jqContentRefreshForm;
  var jqPostButton;
  var jqPostComment;
  var jqPostContainer;
  var originalInterfaceContent = {};
  var rxPostInterfaceType = /poster_for_(\w+)/;
  var rxPostLinkType = /^stream_post_(\w+)$/;

  // *-* public methods *-*

  function setup() {
    // retain references to a few of the elements
    jqContentContainer = $("#cause_stream_content");
    jqContentRefreshForm = $("#cause_stream_refresh");
    jqPostButton = $("#cause_stream_post_submit");
    jqPostComment = $("#cause_stream_post_comment")
    jqPostContainer = $("#cause_stream_post_form");

    // attach click handlers to posting "links"
    // TODO: re-namespace these with cause_stream_post_link_* for consistency
    var idsPostLinks = [
      'stream_post_comment'
//      'stream_post_comment',
//      'stream_post_photo',
//      'stream_post_video',
//      'stream_post_link'
    ];
    $.each(idsPostLinks, function () {
      $('#' + this).click(eventPostLinkClicked);
    });

    // set the first "link" as the current one
    $('#' + idsPostLinks[0]).addClass('current');
    showPostInterfaceForType('comment');

    // attach click handler for the "Post" button
    jqPostButton.click(eventPostButtonClicked);

    // set up submit handlers for each posting interface form
    ajaxifyPostForms(jqPostContainer.find('.poster_interface > form'));

    jqPostContainer.find('ul.radio_inputs > li').click(eventRadioLIClicked);

    if ($.fn.hint) {
      $('.hinted').hint();
    }
  }

  // *-* utility methods *-*

  function ajaxifyPostForms(jqForms) {
    jqForms.each(function () {
      var jqParent = $(this).parent();

      // TODO: save original target div content so we can restore it
      var type = rxPostInterfaceType.exec(jqParent.get(0).className)[1];
      originalInterfaceContent[type] = $(this).html();

      $(this).ajaxForm({
        target: jqParent,
        beforeSubmit: eventInitialFormSubmitted,
        success: eventInitialFormDone(jqParent) // TODO: rename (generator)
      });
    });
  }

  function copyCommentValue() {
    if (jqActivePostForm) {
      var jqComment = jqActivePostForm.find("input[name='comment']");
      if (jqComment.size() <= 0) {
        jqComment = jqActivePostForm.find("input[name='comment[comment]']");
      }
      jqComment.val(jqPostComment.val());
    }
  }

  function enablePostFormFor(jqForm) {
    if (jqForm) {
      // save this form as the form we're submitting
      jqActivePostForm = jqForm;

      // enable "Post" button
      jqPostButton.attr('disabled', false);
    }
    else {
      jqActivePostForm = null;
      jqPostButton.attr('disabled', true);
    }
  }

  function showLoading(bShow) {
    if (bShow) {
      $('#cause_stream_post_loading').css(
        'height',
        (jqPostContainer.height() - 20) + 'px'
      );
      $('#cause_stream_post_loading').show();
    }
    else {
      $('#cause_stream_post_loading').hide();
    }
  }

  function showPostInterfaceForType(type) {
    type = type || 'comment';

    // set the current tab
    jqPostContainer.find('span.poster').removeClass('current');
    $('#stream_post_'+ type).addClass('current');

    // show the current interface
    jqPostContainer.find('.poster_interface').hide();
    var jqInterface = jqPostContainer.find('.poster_for_' + type);
    jqInterface.show();

    enablePostFormFor(jqInterface.find('form'));
  }

  function reloadStreamContent() {
    jqContentRefreshForm.ajaxSubmit({
      target: jqContentContainer,
      success: resetPostInterface
    });
  }

  function resetInterfaceContent() {
    jqPostContainer.find('.poster_interface').each(function () {
      var type = rxPostInterfaceType.exec(this.className)[1];
      $(this).html(originalInterfaceContent[type]);
    });
  }

  function resetPostInterface() {
    FB.XFBML.Host.parseDomElement(jqContentContainer.get(0));
    jqPostComment.val('');
    resetInterfaceContent();
    showPostInterfaceForType(null);
    showLoading(false);
  }

  // TODO: clean this up to not depend so heavily on non-namespaced IDs
  function toggleImages(elementToShow, elementToHide) {
    elementToHide.hide();
    elementToShow.show();
    $('#photo_url').val(elementToShow.attr('src'));
    elementToHide.attr('id', '');
    elementToShow.attr('id', 'selectedImage');
  }

  // *-* event methods *-*

  function eventInitialFormDone(jqParent) {
    return function() {
      var jqNewForm = jqParent.find('form');
      if (jqNewForm.size() > 0) {
        enablePostFormFor(jqNewForm);
        showLoading(false);
      }
      else {
        reloadStreamContent();
      }
    }
  }

  function eventInitialFormSubmitted(data, jqForm) {
    jqForm.find('.hinted').each(function () {
      if ($(this).val() == $(this).attr('title')) {
        $(this).val('');
      }
    });
    copyCommentValue();
    showLoading(true);
    jqForm.append('<input type="hidden" name="ajax" value="true" />');
  }

  // TODO: clean this up to not depend so heavily on non-namespaced IDs
  function eventLinkThumnailArrowClicked(dir) {
    var delta = (dir == 'prev') ? -1 : 1;
    var idEndpoint =  (dir == 'prev') ? 'leftArrow' : 'rightArrow';
    var idOppositeEnd = (dir == 'prev') ? 'rightArrow' : 'leftArrow';
    var elementToHide = $('#selectedImage');
    var elementToShow = $('#selectedImage')[dir]();
    if (elementToShow.size() > 0) {
      toggleImages(elementToShow, elementToHide);
      $('#count').text(parseInt($('#count').text(), 10) + delta);
      $('#'+ idOppositeEnd).removeClass('disabled');
      if (!(elementToShow[dir]().size() > 0)) {
        $('#'+ idEndpoint).addClass('disabled');
      }
    }
  }

  function eventPostButtonClicked(evt) {
    if (jqActivePostForm) {
      eventPreviewFormSubmitted.call(jqActivePostForm.get(0));
    }
  }

  function eventPostLinkClicked(evt) {
    $(this).parent().find('span.poster').removeClass('current');
    $(this).addClass('current');

    var matchType = rxPostLinkType.exec(this.id);
    showPostInterfaceForType(matchType[1]);
  }

  function eventPreviewFormSubmitted(evt) {
    copyCommentValue();

    $(this).append('<input type="hidden" name="ajax" value="true" />');

    $(this).ajaxSubmit({
      success: eventPreviewFormDone
    });

    showLoading(true);
  }

  function eventPreviewFormDone() {
    reloadStreamContent();
  }

  function eventRadioLIClicked(evt) {
    $(this).parent().find('li').removeClass('checked_option');
    $(this).addClass('checked_option').
            find('input.inputradio').attr('checked', true);
  }

  // expose public methods
  return {
    setup: setup,
    prevImage: function() { eventLinkThumnailArrowClicked('prev'); },
    nextImage: function() { eventLinkThumnailArrowClicked('next'); }
  };
})();

$(document).ready(Causes.CauseStream.Poster.setup);

// old style global functions for lame sharing preview content; TODO: refactor
prevImage = Causes.CauseStream.Poster.prevImage;
nextImage = Causes.CauseStream.Poster.nextImage;
