$(document).ready(function() {
    $("#prompt").slideDown(500);
});

var TWIT_STATES = {};
var CALLOUT_TWIT = null;
var CALLOUT_ACTION = null;

function fill_list_with_results(twable_xml, list_id, follow, unfollow, block) {

    var twits = $(twable_xml).find(list_id).find("twit");
    var html_list = $("#" + list_id);

    //Clear old results out of the list (if any.)
    html_list.empty();
    
    //Populate the list with new/current results.    
    twits.each(function(index, data) {

        var twit = $(data).text();

        var li = $(document.createElement("li"));
        li.attr("id", "li-" + twit);

        var twitState = {
          ALLOW_FOLLOW: false,
          ALLOW_UNFOLLOW: false,
          ALLOW_BLOCK: false
        };

        if (follow) {
          var a = $(document.createElement("a"));
          a.html('<img src="images/follow-active.png" alt="Follow ' + twit + '"></img>');
          a.attr("href", "javascript:twit_action('" + twit + "', 'follow');");
          a.attr("id", "follow-" + twit);
          a.attr("title", "Follow " + twit);
          li.append(a);

          twitState.ALLOW_FOLLOW = true;
        }

        if (unfollow) {
          var a = $(document.createElement("a"));
          a.html('<img src="images/unfollow-active.png" alt="Unfollow ' + twit + '"></img>');
          a.attr("href", "javascript:twit_action('" + twit + "', 'unfollow');");
          a.attr("id", "unfollow-" + twit);
          a.attr("title", "Unfollow " + twit);
          li.append(a);

          twitState.ALLOW_UNFOLLOW = true;
        }

        if (block) {
          var a = $(document.createElement("a"));
          a.html('<img src="images/block-active.png" alt="Block ' + twit + '"></img>');
          a.attr("href", "javascript:twit_action('" + twit + "', 'block');");
          a.attr("id", "block-" + twit);
          a.attr("title", "Block " + twit);
          li.append(a);

          twitState.ALLOW_BLOCK = true;
        }

        var a = $(document.createElement("a"));
        a.html(twit);
        a.attr("href", "http://twitter.com/" + twit);
        a.attr("title", twit + " on Twitter");
        a.attr("target", "_blank");
        li.append(a);

        html_list.append(li);

        TWIT_STATES[twit] = twitState;

    });

    //If no real results were added to the list, add a placeholder instead.
    if (html_list.children().length == 0) {
        var li = $(document.createElement("li"));
        li.html("Nobody!");
        html_list.append(li);
    }

}

//Initial handler for a user's click of a follow/unfollow/block button.
function twit_action(twit, action) {

  CALLOUT_TWIT = twit;
  CALLOUT_ACTION = action;
  var twitState = TWIT_STATES[twit];  

  //Hide all prompts/notices that appear in the callout.
  $(".follow").addClass("hidden");
  $(".unfollow").addClass("hidden");
  $(".block").addClass("hidden");

  var marginLeft = "0px"; //Will be used to horizontally position the callout later on.

  //Show the appropriate prompts/notices in the callout depending on the chosen action.
  if (action == "follow") {
    if (!twitState.ALLOW_FOLLOW) return;
    $(".follow").removeClass("hidden");
    marginLeft = "-21px";    
  } else if (action == "unfollow") {
    if (!twitState.ALLOW_UNFOLLOW) return;
    $(".unfollow").removeClass("hidden");
    marginLeft = "-21px";
  } else if (action == "block") {
    if (!twitState.ALLOW_BLOCK) return;
    $(".block").removeClass("hidden");
    marginLeft = "-3px";
  }

  //Substitute the twit into all appropriate places in the callout.
  $(".calloutTwit").html(twit);

  //Effectively move the callout inside the associated <li> so that it maintains its position if the page is resized.
  var callout = $("#callout");
  var twitLI = $("#li-" + twit);
  var newCallout = callout.clone();
  callout.remove();
  twitLI.append(newCallout);

  //Position the callout appropriately based on the chosen action.
  newCallout.css("margin-top", "6px");
  newCallout.css("margin-left", marginLeft);

  //Show the callout.
  var modalOverlay = $("#modalOverlay");
  //Slight hack to get the overlay to extend past the viewport - CSS body,html{ height:100%; } didn't cut it.
  modalOverlay.css("height", $(document).height());
  modalOverlay.fadeTo(500, .7, function() {
    newCallout.fadeIn(500);    
  });

}

//Perform a follow/unfollow/block as requested by the user, then change the callout text to indicate success or error.
function callout_action() {
  var twitState = TWIT_STATES[CALLOUT_TWIT];
  $("#callout .prompt").addClass("hidden");
  $("#callout .loading").removeClass("hidden");
  $.ajax({
    method: "GET",
    url: "./index.php",
    data: "action=do_" + CALLOUT_ACTION + "&twit_id=" + CALLOUT_TWIT,
    dataType: "json",
    success: function(data) {
      if (data['success'] == true) {
        $("#callout .loading").addClass("hidden");
        $("#callout .success").removeClass("hidden");
        if (CALLOUT_ACTION == "follow" || CALLOUT_ACTION == "block") {
          twitState.ALLOW_FOLLOW = false;
          twitState.ALLOW_BLOCK = false;
          $("#follow-" + CALLOUT_TWIT).html('<img src="images/follow-inactive.png" alt="Follow ' + CALLOUT_TWIT + '"></img>');
          $("#block-" + CALLOUT_TWIT).html('<img src="images/block-inactive.png" alt="Block ' + CALLOUT_TWIT + '"></img>');
        } else if (CALLOUT_ACTION == "unfollow") {
          twitState.ALLOW_UNFOLLOW = false;
          $("#unfollow-" + CALLOUT_TWIT).html('<img src="images/unfollow-inactive.png" alt="Unfollow ' + CALLOUT_TWIT + '"></img>');
        }
      } else {
        $("#callout .loading").addClass("hidden");
        $("#callout .error").removeClass("hidden");        
      }
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        $("#callout .loading").addClass("hidden");
        $("#callout .error").removeClass("hidden");
    }
  });
}

//Hide the callout, then reset it.
function callout_dismiss() {
  $("#callout").fadeOut(500, function() {
    $("#modalOverlay").fadeOut(500, function() {
      CALLOUT_TWIT = null;
      CALLOUT_ACTION = null;
      $("#callout .prompt").removeClass("hidden");
      $("#callout .success").addClass("hidden");
      $("#callout .error").addClass("hidden");
      $("#callout .loading").addClass("hidden");
    });
  });
}

function do_twable() {
    //Clear old state (if any.)
    TWIT_STATES = {};

    //Clear all notifications and show the "loading..." notificaiton.
    clearNotifications(function() {
        $("#loading").slideDown(500, function() {
            //Attempt to make an AJAX call to the backend, then display appropriate output.
            $.ajax({
                url: "./index.php?action=do_twable",
                dataType: "xml",
                data : {},
                success : function(data) {
                    var twable_xml = data.documentElement;
                    var status_code = Number(twable_xml.getElementsByTagName("status_code")[0].childNodes[0].data);
                    if (isNaN(status_code)) status_code = 2;
                    
                    //Display results or error as necessary.
                    $("#loading").slideUp(500, function() {
                        switch(status_code) {
                            case 0: //Success. Display the data that was fetched.
                                $("#api_call_count").html(twable_xml.getElementsByTagName("api_call_count")[0].childNodes[0].data);
                                fill_list_with_results(twable_xml, "only_following_me", true, false, true);
                                fill_list_with_results(twable_xml, "only_following_them", false, true, false);
                                fill_list_with_results(twable_xml, "mutually_following", false, false, false);
                                $("#success").slideDown(500, function() {
                                    $("#results_container").slideDown(500);
                                });
                            break;
                            case 1: //An account error occurred.
                                $("#account_error").slideDown(500, function() {
                                    $("#prompt").slideDown(500);
                                });
                            break;
                            default: //A general Twitter error occurred (probably couldn"t connect.)
                                //NOTE: This is a catch-all. The PHP backend returns "2" to actually trigger this case.
                                $("#twitter_error").slideDown(500, function() {
                                    $("#prompt").slideDown(500);
                                });
                            break;
                        }
                    });
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    //The AJAX call failed, so display the general Twitter error.
                    $("#loading").slideUp(500, function() {
                        $("#twitter_error").slideDown(500, function() {
                            $("#prompt").slideDown(500);
                        });
                    });
                }
            });
        });
    });
}

//For any elements that are already hidden, slideUp() should fire its callback instantly.
//The elements slide up in order from the bottom to the top of the page.
function clearNotifications(callback) {
    $("#results_container").slideUp(500, function() {
        $("#success").slideUp(500, function() {
            $("#prompt").slideUp(500, function() {
                $("#twitter_error").slideUp(500, function() {
                    $("#account_error").slideUp(500, callback);
                });
            });
        });
    });
}
