$.facebox.settings.closeImage = "/images/close-grey.png";
$.facebox.settings.loadingImage = "/images/loading-orange.gif";

$(document).ready(function() {
  $("form#new_yarplet").botBlock();
  $('a[rel*=facebox]').livequery(function() { $(this).facebox(); });
  $('abbr[class*=timeago]').livequery(function() { $(this).timeago(); });
  SidebarHelper.wire();
  FormattingHelper.wire('#formatting_help', '#formatting_helpbox');
  ExampleHelper.wire($('input[id*=guests_allowed]'));
  GuestsAllowedHelper.wire($('input[id*=guests_allowed]'));
  DisableSubmitHelper.wire('form');
  $('#new_comment').hide();
  $('#new_comment').submitWithAjax();
  ShowMoreCommentsWithAjax.wire();
  SubmitResponseWithAjax.wire('#new_response');
  ChangeResponseWithAjax.wire('#responses .control a');
  UserVoiceHelper.wire();
  //$(':input:first').focus().select(); // Add this back after tweaking jquery.example
});

$(document).bind('reveal.facebox', function() {
  $('#facebox :input.copyable').click(function() { $(this).select(); });
  FormattingHelper.wire('#facebox #formatting_help', '#facebox #formatting_helpbox');
  ExampleHelper.wire($('#facebox input[id*=guests_allowed]'));
  CleverResponseHelper.wire('#facebox .clever_response');
  GuestsAllowedHelper.wire($('#facebox input[id*=guests_allowed]'));
  DisableSubmitHelper.wire('#facebox :submit');
  $('#facebox :input:visible:first:not([class*=copyable]):not([class*=example])').focus().select();
  $('#facebox .pagination a').facebox();
  $('#facebox .edit_comment').submitWithAjax("put");
  $('#facebox .edit_response').submitWithAjax("put");
});

$(document).bind('close.facebox', function() {
  $('#facebox :input.copyable').unbind("click");
  $.fn.example.bound_class_names['dynamic_example'] = false;
});

var FormattingHelper = {
  wire: function(anchor, help) {
    $(anchor).click(function() {
      $(help).slideToggle();
      return false;
    });
  }
};

var UserVoiceHelper = {
  wire: function() {
    $('#yarp_feedback').click(function() {
      try {
        UserVoice.Popin.show(uservoiceOptions);
        return false;
      } catch(e) {
        return true;
      }
    });
  }
}

var ExampleHelper = {
  changeText: function(guestsAllowed, className) {
    $('.' + className).val(''); // clear all example text
    $('#response_name').example("Your name here");
    if (guestsAllowed == "true") {
      $('#yarplet_title').example("Example: Party at my place!");
      $('#yarplet_description').example("Example: Saturday at 7pm.  Please leave a comment telling me what you're bringing for food/drinks.  Thanks!");
    }
    else {
      $('#yarplet_title').example("Example: OMG! Should I wear my LBD to the party?");
      $('#yarplet_description').example("Example: I can't decide, help me!");
    }
  },
  wire: function(radio) {
    var className = $.fn.example.defaults.class_name;
    ExampleHelper.changeText("true", className);
    radio.click(function() {
      ExampleHelper.changeText($(this).val(), className);
    });
    $.fn.example.defaults.class_name = 'dynamic_example';
  }
};

var GuestsAllowedHelper = {
  activateButton: function(label) {
    var id = $("input[id*=guests_allowed]:checked").attr("id");
    $("label.radio.checked").removeClass("checked");
    $("label.radio[for=" + id + "]").addClass("checked");
  },
  wire: function(radio) {
    radio.addClass("hide_far_away");
    GuestsAllowedHelper.activateButton();
    radio.click(function() { GuestsAllowedHelper.activateButton(); });
  }
};

var DisableSubmitHelper = {
  wire: function(form) {
    $(form).submit(function() {
      $(this).find(':submit').click(function() {
        $(this).val("Whoa, Chill!");
        return false;
      });
    });
  }
};

DisableSubmitTextHelper = {
  wire: function(submitButton) {
    $(submitButton).click(function() {
      return false;
    });
  }
}

var CleverResponseHelper = {
  wire: function(anchor) {
    $(anchor).click(function() {
      var responseValues = $(this).text().split(" or ");
      $(':input#yarplet_negative').val(responseValues.pop()).highlight();
      $(':input#yarplet_affirmative').val(responseValues.pop()).highlight();
      $(document).trigger('close.facebox');
      return false;
    });
  }
};

var SidebarHelper = {
  wire: function(anchor) {
    if ($.cookie('browser_token')) {
      if($('#yarplet_history').size() > 0) {
        $('#yarplet_history').load("/yarplets?sidebar=true");
      }
    }
    else {
      $('#sidebar').hide();
      $('#sessionbar').hide();
    }
  }
};

// Serializes the response button clicked then posts because JQuery's
// serialize doesn't pass the clicked submit input form element.
var SubmitResponseWithAjax = {
  wire: function(form) {
    $(form).submit(function() {
      return false; // don't submit
    });

    $(form + " :submit").click(function() {
      $(form).find('.example').val(''); // manually clear example text since we're overriding form#submit.
      var submitNameValue = $(this).attr('name') + "=" + $(this).val();
      $.post($(form).attr('action'), $(form).serialize() + "&" + submitNameValue, null, "script");
      return false;
    });
  }
};

var ChangeResponseWithAjax = {
  wire: function(anchor) {
    $(anchor).livequery('click', function() {
      $.post($(this).attr('href'), '_method=put', null, 'script');
      return false;
    });
  }
};

var ShowMoreCommentsWithAjax = {
  wire: function() {
    $('#comments_pagination .prev_page').livequery(function() { $(this).hide(); });
    $('#comments_pagination .next_page').livequery('click', function() {
      var path = "/yarplets" + window.location.pathname + "/comments?" + $(this).attr('href').split('?')[1];
      $('#comments_pagination').remove();
      $.get(path, null, null, 'script');
      return false;
    });
  }
};

$.fn.submitWithAjax = function(method) {
  this.submit(function() {
    if (method == null) { method = ""; }
    $.post(this.action, $(this).serialize() + "&_method=" + method, null, "script");
    $(document).trigger('close.facebox');
    return false;
  });
  return this;
};

$.fn.highlight = function(callback) {
  this.effect("highlight", { color: "#09e" }, 1000, callback);
};

$.fn.yarpFadeIn = function(callback) {
  this.fadeIn(500, callback);
};

$.fn.yarpFadeOut = function(callback) {
  this.fadeOut(500, callback);
};

$.fn.blindRemove = function(callback) {
  this.hide("blind", { direction: "vertical" }, 500, function() {
    $(this).remove();
    if (callback != null) { callback(); }
  });
};

$.fn.fadeOutRemove = function(callback) {
  this.yarpFadeOut(function() {
    $(this).remove();
    if (callback != null) { callback(); }
  });
};

$.fn.botBlock = function(callback) {
  this.append("<input type='hidden' name='captcha' value='hotfuzz' />");
};

// Displays any ajax errors in the Firebug console instead of hiding them (default jQuery behavior)
// http://www.thefutureoftheweb.com/blog/hidden-ajax-errors-in-jquery
$(document).ajaxError(function(){
    if (window.console && window.console.error) {
        console.error(arguments);
    }
});