jQueryFactory(document).ready(function ($) {
  var processing = false;

  $("html").ajaxStart(function() {
  	processing = true;
	}).ajaxStop(function() {
  	processing = false;
	});

  // Ask for friendship
  $("#lovefactory-ask-friendship").click(function () {
    if (processing)
    {
      return false;
    }

    var status = $(this).attr("rel");

    switch (parseInt(status))
    {
      case 0: // Ask for friendship
        var fieldset = $("#lovefactory-interactions");
        var legend   = fieldset.find("legend");
        var list     = $(".lovefactory-interactions");

        var output = '<div style="position:relative; display: none;">'
                   + '  <div class="lovefactory-interaction-title">' + txt_ask_for_friendship + '</div>'
                   + '  <textarea></textarea>'
                   + '  <div class="lovefactory-actions">'
                   + '    <a href="#" class="lovefactory-button lovefactory-bullet-add">' + txt_send + '</a>'
                   + '    <a href="#" class="lovefactory-button lovefactory-bullet-delete">' + txt_cancel + '</a>'
                   + '  </div>'
                   + '</div>';

        list.fadeOut("fast", function() {
          fieldset.append(output);
          var div = fieldset.find("div:first");

          div.fadeIn("fast", function () {
            fieldset.find("textarea").focus();

            // Cancel button
            fieldset.find(".lovefactory-bullet-delete").click(function () {
              fieldset.find("div:first").fadeOut("fast", function () {
                $(this).remove();
                list.fadeIn("fast");
              });

              return false;
            });

            // Send button
            fieldset.find(".lovefactory-bullet-add").click(function () {
              div.append('<div class="lovefactory-loading-cover" style="display: none"></div>');
              div.find(".lovefactory-loading-cover").fadeIn("fast", function () {
                var message = fieldset.find("textarea").val();
                $.post(route_ask_friendship, { format: "raw", id: user_id, message: message },  function (response) {

                  if (2 == response.code)
                  {
                    window.location.href = root + "index.php?option=com_lovefactory&controller=membership&task=redirectnomembership&code=4";
                    return false;
                  }

                  div.fadeOut("fast", function () {
                    $(this).remove();
                    list.fadeIn("fast");

                    $.showMessage({id: "lovefactory-interactions-response", response: response });

                    if (1 == response.status)
                    {
                      $("#lovefactory-ask-friendship").attr("rel", 1).html(response.text);
                      friendship_id = response.request_id;
                    }
                  });
                }, "json");
              });

              return false;
            });
          });
        });
      break;

      case 1: // Cancel pending request
        var link = $(this);
        link.addClass("lovefactory-loader-button");

        $.post(route_cancel_pending, { format: "raw", id: friendship_id },  function (response) {
          $.showMessage({id: "lovefactory-interactions-response", response: response });
          link.removeClass("lovefactory-loader-button");

          if (1 == response.status)
          {
            link.fadeOut("fast", function () {
              link.attr("rel", 0).html(response.text).fadeIn("fast");
            });
          }
        }, "json");
      break;

      case 2: // Pending request
        document.location.href = route_pending_friends;
      break;

      case 3: // Break friendship
        var link = $(this);
        link.addClass("lovefactory-loader-button");

        $.post(route_break_friendship, { format: "raw", id: friendship_id },  function (response) {
          $.showMessage({id: "lovefactory-interactions-response", response: response });
          link.removeClass("lovefactory-loader-button");

          if (1 == response.status)
          {
            link.fadeOut("fast", function () {
              link.attr("rel", 0).html(response.text).fadeIn("fast");
            });
          }
        }, "json");
      break;
    }

    return false;
  }); // Ask for friendship


  // Ask for relationship
  $("#lovefactory-ask-relationship").click(function () {
    if (processing)
    {
      return false;
    }

    var status = $(this).attr("rel");

    switch (parseInt(status))
    {
      case 0: // Ask for relationship
        var fieldset = $("#lovefactory-interactions");
        var legend   = fieldset.find("legend");
        var list     = $(".lovefactory-interactions");

        var output = '<div style="position:relative; display: none;">'
                   + '  <div class="lovefactory-interaction-title">' + txt_ask_for_relationship + '</div>'
                   + '  <textarea></textarea>'
                   + '  <div class="lovefactory-actions">'
                   + '    <a href="#" class="lovefactory-button lovefactory-bullet-add">' + txt_send + '</a>'
                   + '    <a href="#" class="lovefactory-button lovefactory-bullet-delete">' + txt_cancel + '</a>'
                   + '  </div>'
                   + '</div>';

        list.fadeOut("fast", function() {
          fieldset.append(output);
          var div = fieldset.find("div:first");

          div.fadeIn("fast", function () {
            fieldset.find("textarea").focus();

            // Cancel button
            fieldset.find(".lovefactory-bullet-delete").click(function () {
              fieldset.find("div:first").fadeOut("fast", function () {
                $(this).remove();
                list.fadeIn("fast");
              });

              return false;
            });

            // Send button
            fieldset.find(".lovefactory-bullet-add").click(function () {
              div.append('<div class="lovefactory-loading-cover" style="display: none"></div>');
              div.find(".lovefactory-loading-cover").fadeIn("fast", function () {
                var message = fieldset.find("textarea").val();
                $.post(route_ask_relationship, { format: "raw", id: user_id, message: message },  function (response) {
                  div.fadeOut("fast", function () {
                    $(this).remove();
                    list.fadeIn("fast");

                    $.showMessage({id: "lovefactory-interactions-response", response: response });

                    if (1 == response.status)
                    {
                      $("#lovefactory-ask-relationship").attr("rel", 1).html(response.text);
                      relationship_id = response.request_id;
                    }
                  });
                }, "json");
              });

              return false;
            });
          });
        });
      break;

      case 1: // Cancel pending request
        var link = $(this);
        link.addClass("lovefactory-loader-button");

        $.post(route_cancel_pending_relationship, { format: "raw", id: relationship_id },  function (response) {
          $.showMessage({id: "lovefactory-interactions-response", response: response });
          link.removeClass("lovefactory-loader-button");

          if (1 == response.status)
          {
            link.fadeOut("fast", function () {
              link.attr("rel", 0).html(response.text).fadeIn("fast");
            });
          }
        }, "json");
      break;

      case 2: // Pending request
        document.location.href = route_pending_friends;
      break;

      case 3: // Break relationship
        var link = $(this);
        link.addClass("lovefactory-loader-button");

        $.post(route_break_relationship, { format: "raw", id: relationship_id },  function (response) {
          $.showMessage({id: "lovefactory-interactions-response", response: response });
          link.removeClass("lovefactory-loader-button");

          if (1 == response.status)
          {
            link.fadeOut("fast", function () {
              link.attr("rel", 0).html(response.text).fadeIn("fast");
            });
          }
        }, "json");
      break;
    }

    return false;
  }); // Ask for relationship

  // Send interaction
  $(".lovefactory-interaction").click(function () {
    if (processing)
    {
      return false;
    }

    var link   = $(this);
    var type   = link.attr("rel");

    link.addClass("lovefactory-loader-button");

    $.post(route_send_interaction, { format: "raw", type_id: type, user_id: user_id}, function (response) {

      if (2 == response.code)
      {
        window.location.href = root + "index.php?option=com_lovefactory&controller=membership&task=redirectnomembership&code=2";
      }
      else
      {
        $.showMessage({id: "lovefactory-interactions-response", response: response });
        link.removeClass("lovefactory-loader-button");
      }

    }, "json");

    return false;
  }); // Send interaction


  // Send quick message
  $("#lovefactory-quick-message").click(function () {
    if (processing)
    {
      return false;
    }

    var fieldset = $("#lovefactory-interactions");
    var legend   = fieldset.find("legend");
    var list     = $(".lovefactory-interactions");

    var output = '<div style="position:relative; display: none;">'
               + '  <div class="lovefactory-interaction-title">' + txt_send_quick_message + '</div>'
               + '  <div id="lovefactory-quick-error" class="lovefactory-error-field" style="display: none;"><span class="lovefactory-button lovefactory-bullet-error">' + txt_enter_message + '</span></div>'
               + '  <textarea></textarea>'
               + '  <div class="lovefactory-actions">'
               + '    <a href="#" class="lovefactory-button lovefactory-bullet-add">' + txt_send + '</a>'
               + '    <a href="#" class="lovefactory-button lovefactory-bullet-delete">' + txt_cancel + '</a>'
               + '  </div>'
               + '</div>';

    list.fadeOut("fast", function() {
      fieldset.append(output);
      var div = fieldset.find("div:first");

      div.fadeIn("fast", function () {
        fieldset.find("textarea").focus();

        // Cancel button
        fieldset.find(".lovefactory-bullet-delete").click(function () {
          fieldset.find("div:first").fadeOut("fast", function () {
            $(this).remove();
            list.fadeIn("fast");
          });

          return false;
        });

        // Send button
        fieldset.find(".lovefactory-bullet-add").click(function () {
          var message = fieldset.find("textarea").val();
          var error   = $("#lovefactory-quick-error");

          error.fadeOut("fast");

          if ('' == message)
          {
            error.fadeIn("fast");
            return false;
          }
          else
          {
            $("#lovefactory-quick-error").hide();
          }

          div.append('<div class="lovefactory-loading-cover" style="display: none"></div>');
          div.find(".lovefactory-loading-cover").fadeIn("fast", function () {
            $.post(route_send_message, { format: "raw", user_id: user_id, text: message },  function (response) {

              if (2 == response.code)
              {
                window.location.href = root + "index.php?option=com_lovefactory&controller=membership&task=redirectnomembership&code=3";

                return false;
              }

              div.fadeOut("fast", function () {
                $(this).remove();
                list.fadeIn("fast");

                $.showMessage({id: "lovefactory-interactions-response", response: response });
              });

            }, "json");
          });

          return false;
        });
      });
    });

    return false;
  }); // Send quick message


  // Ignore list
  $("#lovefactory-ignore-list").click(function () {
    if (processing)
    {
      return false;
    }

    var link = $(this);
    var status = link.attr("rel");

    link.addClass("lovefactory-loader-button");

    switch (parseInt(status))
    {
      case 0: // Add
        $.post(route_add_blacklist, { format: "raw", user_id: user_id }, function (response) {
          $.showMessage({id: "lovefactory-interactions-response", response: response });
          link.removeClass("lovefactory-loader-button");

          if (1 == response.status)
          {
            link.fadeOut("fast", function () {
              link.html(response.text).attr("rel", 1).fadeIn("fast");
            });

            blacklist_id = response.blacklist_id;
          }

        }, "json");
      break;

      case 1: // Remove
        $.post(route_remove_blacklist, { format: "raw", id: blacklist_id }, function (response) {
          $.showMessage({id: "lovefactory-interactions-response", response: response });
          link.removeClass("lovefactory-loader-button");

          if (1 == response.status)
          {
            link.fadeOut("fast", function () {
              link.html(response.text).attr("rel", 0).fadeIn("fast");
            });
          }
        }, "json");
      break;
    }

    return false;
  }); // Ignore list



  ajaxPaginationLinks();

  // Comments pagination
  function ajaxPaginationLinks()
  {
    // Pagination
    $(".lovefactory-pagination a").unbind().click(function () {
      var href     = $(this).attr("href");
      var comments = $("#lovefactory-comments");
      var height   = comments.css("height");

      $(".lovefactory-pagination").addClass("lovefactory-button lovefactory-loader-button");

      $.post(href, { format: "raw"}, function (response) {
        $("#lovefactory-comments").html(response);
        comments.removeClass('lovefactory-loader')
        ajaxPaginationLinks();

        var targetOffset = $("a[name='comments']").offset().top;
        jQueryFactory("html,body").animate({scrollTop: targetOffset}, "normal");
      });

      return false;
    });

    // Add comment button
    $("#lovefactory-add-comment").unbind().click(function () {
      var link   = $(this);
      var parent = link.parent();
      var output = '<div style="position:relative; display: none;">'
                 + '  <div id="lovefactory-quick-error" class="lovefactory-error-field" style="display: none;"><span class="lovefactory-button lovefactory-bullet-error">' + txt_enter_message + '</span></div>'
                 + '  <textarea></textarea>'
                 + '  <div class="lovefactory-actions">'
                 + '    <a href="#" class="lovefactory-button lovefactory-bullet-add">' + txt_send + '</a>'
                 + '    <a href="#" class="lovefactory-button lovefactory-bullet-delete">' + txt_cancel + '</a>'
                 + '  </div>'
                 + '</div>';

      parent.append(output);

      link.fadeOut("fast", function () {
        parent.find("div:first").fadeIn("fast", function () {
          parent.find("textarea:first").focus();
        });
      });

      // Cancel button
      parent.find(".lovefactory-bullet-delete").click(function () {
        parent.find("div:first").fadeOut("fast", function () {
          $(this).remove();
          link.fadeIn("fast");
        });

        return false;
      });

      // Send button
      parent.find(".lovefactory-bullet-add").click(function () {
        var message = parent.find("textarea:first").val();
        var error = parent.find(".lovefactory-error-field:first");

        error.fadeOut("fast");

        if ('' == message)
        {
          error.fadeIn("fast");
          return false;
        }

        parent.find("div:first").append('<div class="lovefactory-loading-cover" style="display: "></div>');
        parent.find(".lovefactory-loading-cover").fadeIn("fast");

        $.post(route_add_comment, { format: "raw", user_id: user_id, text: message }, function (response) {
          $.showMessage({id: "lovefactory-comment-response", response: response });

          parent.find("div:first").fadeOut("fast", function () {

            if (1 == response.status)
            {
              $.post(document.location.href, { format: "raw"}, function (response) {
                $("#lovefactory-comments").html(response);
                ajaxPaginationLinks();

                link.fadeIn("fast");
                parent.find("div:first").remove();
              });
            }
            else
            {
              link.fadeIn("fast");
              parent.find("div:first").remove();
            }
          });
        }, "json");

        return false;
      });

      return false;
    });

    // Delete comment button
    $(".lovefactory-comment-actions .lovefactory-bullet-delete").click(function () {
      var link   = $(this);
      var parent = $(this).parent().parent().parent();
      var id     = parent.attr("id");

      id = id.split("-");
      id = id[2];

      link.addClass("lovefactory-loader-button");
      $.post(route_delete_comment, { format: "raw", comment_id: id}, function (response) {
        if (1 == response.status)
        {
          link.fadeOut("fast", function () {
            parent.find(".lovefactory-comment-actions").fadeOut("fast", function () {
              parent.css("text-decoration", "line-through");
            })

            link.remove();
          });
        }
      }, "json");

      return false;
    });

    // Report comment button
    $(".lovefactory-comment-actions .lovefactory-bullet-blue").click(function () {
      var link = $(this);
      var id   = $(this).parent().parent().parent().attr("id");

      id = id.split("-");
      id = id[2];

      var div = link.parent().find("div:first");
      div.fadeOut("fast");

      link.addClass("lovefactory-loader-button");
      $.post(route_report_comment, { format: "raw", comment_id: id}, function (response) {
        if (1 == response.status)
        {
          link.fadeOut("fast", function () {
            link.parent().append('<span class="lovefactory-button">' + response.text + '</span>');
            link.parent().find("span:last").fadeIn("fast");
            link.remove();
          });
        }
        else
        {
          link.removeClass("lovefactory-loader-button");

          link.parent().append('<div class="lovefactory-comment-action-error" style="display:none;">' + response.error + '</div>');
          div = link.parent().find("div:first");
          div.fadeIn("fast");
        }
      }, "json");

      return false;
    });

    // Show comment action buttons
    $(".lovefactory-comment").hover(function () {
      $(this).find(".lovefactory-comment-actions").css("visibility", "visible");
    }, function () {
      $(this).find(".lovefactory-comment-actions").css("visibility", "hidden");
    });
  }

  // Hover stars
  $(".lovefactory-star-clickable").hover(function () {
    var id = $(this).attr("id");
    id = id.split('-');
    id = id[2];

    for (var i = 0; i <= id; i++)
    {
      $("#lovefactory-star-" + i).addClass("lovefactory-star-on");
    }
  }, function () {
    for (var i = 0; i < 10; i++)
    {
      $("#lovefactory-star-" + i).removeClass("lovefactory-star-on");
    }
  }).click(function () {
    var id = $(this).attr("id");
    id = id.split('-');
    id = id[2];
    id++;

    var parent = $(this).parent().parent();
    parent.append('<div class="lovefactory-loading-cover" style="display:"></div>');

    $.post(route_profile_vote, { format: "raw", user_id: user_id, rating: id }, function (response) {
      if (0 == response.status)
      {
        parent.find(".lovefactory-loading-cover").remove();
        $.showMessage({id: "lovefactory-rating-response", response: response });
      }
      else
      {
        var output = '';
        for (var i = 0; i < 10; i++)
        {
          output += '<div class="lovefactory-star lovefactory-star-off';
          if (i < id)
          {
            output += ' lovefactory-star-on';
          }
          output += '"></div>';
        }
        parent.html(output);
        $.showMessage({id: "lovefactory-rating-response", response: response });

        $("#lovefactory-rating").fadeOut("slow", function () {
          $(this).html(response.new_rating).fadeIn("slow");
        });
        $("#lovefactory-votes").fadeOut("slow", function () {
          $(this).html(response.new_votes).fadeIn("slow");
        });

        $(".lovefactory-ratings").prepend('<li id="lovefactory-latest-rating" style="display:none;">' + response.userlink + '</li>');
        $("#lovefactory-latest-rating").fadeIn("slow");
        $("#lovefactory-no-ratings").fadeOut("slow");
      }
    }, "json");
  });

  // Go to comments
  $("#lovefactory-goto-comments").click(function () {
    var targetOffset = $("a[name='comments']").offset().top;
    jQueryFactory("html,body").animate({scrollTop: targetOffset}, "normal");

    return false;
  });

  // Edit status
  $("#lovefactory-edit-status").live("click", function () {
    var status_length = $("#lovefactory-status-text").html().length;

    $("#lovefactory-status-text").html("<textarea>" + $("#lovefactory-status-text").html() + "</textarea><div><span class='lovefactory-chars-remaining'>" + (status_max_length - status_length) + "</span> " + txt_chars_remaining + "</div>");
    $("#lovefactory-status-actions").html('<a href="#" class="lovefactory-button lovefactory-bullet-add" id="lovefactory-save-status">' + txt_save + '</a><a href="#" class="lovefactory-button lovefactory-bullet-delete" id="lovefactory-cancel-status">' + txt_cancel + '</a>');

    return false;
  });

  // Text area chars remaining
  $("#lovefactory-status-text textarea").live("keyup", function () {
    var chars = $(this).val().length;

    if (status_max_length - chars < 0)
    {
      $(this).val($(this).val().substr(0, status_max_length));
      $(".lovefactory-chars-remaining").html(0);
    }
    else
    {
      $(".lovefactory-chars-remaining").html(status_max_length - chars);
    }
  });

  // Status cancel
  $("#lovefactory-cancel-status").live("click", function () {
    $("#lovefactory-status-text").html($("#lovefactory-status-text textarea").html());
    $("#lovefactory-status-actions").html('<a href="#" class="lovefactory-button lovefactory-page-white-edit" id="lovefactory-edit-status">' + txt_edit + '</a>');

    return false;
  });

  // Status save
  $("#lovefactory-save-status").live("click", function () {
    $("#lovefactory-status-text").parent().append('<div class="lovefactory-loading-cover" style="display: none;"></div>');

    $("#lovefactory-status .lovefactory-loading-cover").fadeIn("fast");
    var text      = $("#lovefactory-status-text textarea").val();
    var text_html = $("#lovefactory-status-text textarea").html();

    $.post(
      root + "index.php?option=com_lovefactory&controller=status&task=update",
      { format: "raw", text: text },
      function (response) {
        $.showMessage({id: "lovefactory-status-response", response: response });

        $("#lovefactory-status .lovefactory-loading-cover").remove();

        if (1 == response.status)
        {
          $("#lovefactory-status-text").html(response.text);
        }
        else
        {
          $("#lovefactory-status-text").html(text_html);
        }

        $("#lovefactory-status-actions").html('<a href="#" class="lovefactory-button lovefactory-go" id="lovefactory-edit-status">' + txt_edit + '</a>');

    }, "json");

    return false;
  });
});
