/* Common js code for the site */

$(document).ready( function() {
  
  var feedItems = getFeedItems();

  /* Add events to all comment links */
  bindAllCommentLinkEvents();
  
  /* Add click events to filter form */
  bindFeedFilterEvents();
  
  /* Add click events to add/remove scout links */
  bindScoutToggleLinks();
  
  /* Add events to team boxes */
  bindTeamBoxListeners();
  
  /* Add events to scoring rules disclosures */
  bindScoringRulesListeners();
  
  /* Add search box events */
  setupSearchBox();
  
  /* Set up voting */
  setupVoting(feedItems);
  
  /* Set up alert/error boxes */
  setupAlertAndErrorBoxes();
  
});

function setupAlertAndErrorBoxes() {
  var boxes = $(".alert_box,.error_box,.tooltip_box");
  var images = boxes.find("img");
  images.css("cursor", "pointer");
  images.click(function() {
    $(this).parent().parent().parent().parent().parent().css("display","none");
  });
}

function setupVoting(feedItems) {
  for (var i=0; i<feedItems.length; i++) {
    addVoteHandler(feedItems[i]);
  }
}

function addVoteHandler(feedItem) {
  feedItem.voteUpIcon = $("div.vote_thumbs_up img", feedItem.voteBox);
  feedItem.voteDownIcon = $("div.vote_thumbs_down img", feedItem.voteBox);
  
  feedItem.voteUpIcon.one("click", function() {
    vote(feedItem, "up");
    toggleVoteIcon(feedItem, "left");
    
  });
  feedItem.voteDownIcon.one("click", function() {
    vote(feedItem, "down");
    toggleVoteIcon(feedItem, "right");
  });
}

function toggleVoteIcon(feedItem, selectedIcon) {
  if (selectedIcon == "left") {
    feedItem.voteUpIcon.attr("src", '/site_media/img/thumbs_up_disabled.png');
    feedItem.voteUpIcon.css("cursor", "default");
    feedItem.voteDownIcon.attr("src", '/site_media/img/thumbs_down.png');
    feedItem.voteDownIcon.css("cursor", "pointer");
    feedItem.voteUpIcon.unbind("click");
  } else if (selectedIcon == "right") {
    feedItem.voteUpIcon.attr("src", '/site_media/img/thumbs_up.png');
    feedItem.voteUpIcon.css("cursor", "pointer");
    feedItem.voteDownIcon.attr("src", '/site_media/img/thumbs_down_disabled.png');
    feedItem.voteDownIcon.css("cursor", "default");
    feedItem.voteDownIcon.unbind("click");
  }
  
  addVoteHandler(feedItem);
}

function vote(feedItem, direction) {
  if (direction == "down") {
    var tail = feedItem.voteDownIcon.attr("src").slice("-12");
  } else if (direction == "up") {
    var tail = feedItem.voteUpIcon.attr("src").slice("-12");
  }
  if (tail != "disabled.png") {
    var postData = {"decision_id":feedItem.id, "vote": direction};
    api("vote", postData, function(response, textStatus) {
      $("span.vote_count_yes", feedItem.container).html(response.uv);
      $("span.vote_count_no", feedItem.container).html(response.dv);
    });
  }
}

function setupSearchBox() {
  var suggestList = $("#search_suggest_list")[0];
  var selectedIndex = -1; // Nothing selected to start
  
  $("#search_field").focus( function(event) {
    if ($(this).attr("value") == "Type player names...") {
      $(this).attr("value", "");
    } 
  });
  
  $("#search_field").blur( function(event) {
    if ($(this).attr("value") == "") {
      $(this).attr("value", "Type player names...");
    }
    selectedIndex = -1;
  });
  
  $("#search_suggest div.close_link a").click( function() {
    $("#search_suggest").css("display", "none");
  });
  
  $("#search_field").keyup( function(event) {
    
      if (event.keyCode == 38) {
        // Navigate up
        var listItems = $(suggestList).children();
        if (selectedIndex > 0) {
          listItems.removeClass("selected");
          $(listItems[--selectedIndex]).addClass("selected");
        }
      
      } else if (event.keyCode == 40) {
        // Navigate down
        var listItems = $(suggestList).children();
        if (selectedIndex < (listItems.length - 1)) {
          listItems.removeClass("selected");
          $(listItems[++selectedIndex]).addClass("selected");
        }
      
      } else if (event.keyCode == 13) {
        // Get selected player
        if ($("#search_suggest").css("display") == "block") {
          var listItems = $(suggestList).find("li.selected");
          addPlayer(listItems.html());
        } else {
          $("#hidden_search_form input[name=q]")[0].value = $(this).attr("value");
          $("#hidden_search_form").submit();
        }
      
      } else {
        // Search for players
        var tail = getTail($(this).attr("value"));
        if (tail.length > 0) {
          searchPlayers(tail);
        } else {
          $("#search_suggest").css("display", "none");
        }
      }
  });
  
  function addPlayer(newPlayerName) {
    var players = getCurrentPlayerList();
    players.pop(); // Remove the typed stub
    players.push(newPlayerName); // Add the proper player name
    rewriteWithPlayers(players);
    $("#search_suggest").css("display", "none");
    $("#search_field").focus();
  }
  
  function getCurrentPlayerList() {
    var players = $("#search_field").attr("value").split(",");
    for (var i=0; i<players.length; i++) {
      players[i] = jQuery.trim(players[i]);
    }
    return players;
  }
  
  function getTail(string) {
    var comma = string.lastIndexOf(",");
    if (comma < 0) {
      return jQuery.trim(string);
    } else {
      return jQuery.trim(string.substr(comma+1));
    }
  }
  
  function replaceTail(withString) {
    var comma = string.lastIndexOf(",");
    return string.substring(0, comma) + ", " + withString;
  }
  
  function rewriteWithPlayers(players) {
    $("#search_field").attr("value", players.join(", ") + ", ");
  }
  
  /* Find players that matched the string typed */
  function searchPlayers(string) {
    var postData = {"q":string};
    $("#search_spinner").css("display", "block");
    api("player_suggest", postData, function(response, textStatus) {
      
      var matchedPlayers = response['players']
      // Update suggest box
      if (matchedPlayers.length > 0) {
        suggestList = $("#search_suggest_list")[0];
        $("#search_suggest").css("display", "block");
        var listHtml = getPlayerSelector(matchedPlayers).join("");
        $(suggestList).html(listHtml);
        // Add click listeners
        $(suggestList).children().hover( function() {
          $(suggestList).children().removeClass("selected");
          $(this).addClass("selected");
        }, function() {
          $(this).removeClass("selected");
        });
        $(suggestList).children().click( function() {
          addPlayer($(this).html());
        });
        // Select the first item
        selectedIndex = 0;
        $($(suggestList).children()[0]).addClass("selected");
      } else {
        $("#search_suggest").css("display", "none");
      }
      
      $("#search_spinner").css("display", "none");
      
    });
  }
  
  /* Build the html for matched players */
  function getPlayerSelector(players) {
    var listItems = [];
    for (var i=0; i<players.length; i++) {
      var player = players[i];
      var html = "<li>" + player[0] + "</li>";
      listItems.push(html);
    }
    return listItems;
  }
  
}

function bindScoringRulesListeners() {
  var boxes = $(".scoring_rules");
  for (i=0; i<boxes.length; i++) {
    $(boxes[i]).find(".scoring_rules_toggler").click( function() {
      var childBox = $(this).next();
      var img = $(this).children()[0];
      if (childBox.css("display") == "none") {
        childBox.css("display", "block");
        img.src = "/site_media/img/scoring_rules_open.png";
      } else {
        childBox.css("display", "none");
        img.src = "/site_media/img/scoring_rules_closed.png";
      }
    });
  }
}

function bindTeamBoxListeners() {
  var boxes = $(".toolbar_box_team");
  for (i=0; i<boxes.length; i++) {
    $(boxes[i]).find(".toolbar_box_collapse").click( function() {
      toggleTeamBox(this);
    });
  }
}

function toggleTeamBox(div) {
  var childBox = $(div).next();
  if (childBox.css("display") == "none") {
    childBox.slideDown("fast");
    $("div.collapse img", $(div)).attr("src", "/site_media/img/collapse_box_blue.png");
  } else {
    childBox.slideUp("fast");
    $("div.collapse img", $(div)).attr("src", "/site_media/img/expand_box_blue.png");
  }
}

function bindScoutToggleLinks() {
  
  if (fiq.feedUser) {
  
    var removeLink = $("#remove_scout_link");
    var addLink = $("#add_scout_link");
    
    var postData = {
        "scouting" : fiq.currentUser.id,
        "scouted" : fiq.feedUser.id
    };
    
    var currentScoutCount = $("#scouting_count");
    
    if (removeLink.length) {
      removeLink.click(function() {
        api("toggle_scout", postData, function(response, textStatus) {
          $("#scout_row_already_scouting").css("display", "none");
          $("#scout_row_not_scouting").css("display", "table-cell");
          currentScoutCount.html(parseInt(currentScoutCount.html()) - 1 + "");
        });
      });
    }
    
    if (addLink.length) {
      addLink.click(function() {
        api("toggle_scout", postData, function(response, textStatus) {
          // Do stuff
        });
        $("#scout_row_already_scouting").css("display", "table-cell");
        $("#scout_row_not_scouting").css("display", "none");
        currentScoutCount.html(parseInt(currentScoutCount.html()) + 1 + "");
      });
    }
  
  }
    
}

function bindFeedFilterEvents() {
  if ($("#feed_items")) {
    $("#filter_form input").each( function() {
      $(this).click( function() {
        $("#filter_form").submit();
      });
    });
    $("#filter_form select").change( function() {
      $("#filter_form").submit();
    });
  }
}

/* Gets all feed items on the page */
function getFeedItems() {
  var items = [];
  if ($("#feed_items")) {
    $("#feed_items").find("[id^=feed_item_id_]").each( function() {
      var idAttr = $(this).attr("id");
      var feedItemId = idAttr.substr(idAttr.lastIndexOf("_") + 1);
      var commentLink = $("div.feed_bottom_links a.comment_link:first", $(this));
      var commentFormBlock = $("div.inline_comment_form_container", $(this));
      var voteBox = $("div.vote_box", $(this));
      // Create a new FeedItem, not setting the submit button because we don't know
      // whether or not it'll be needed
      var feedItem = new FeedItem(feedItemId, $(this), commentLink, commentFormBlock, voteBox);
      items[items.length] = feedItem;
    });
  }
  return items;
}

/* Set up the click handlers for all comment links */
function bindAllCommentLinkEvents() {
  var feedItems = getFeedItems();
  for (i = 0; i < feedItems.length; i++) {
    var feedItem = feedItems[i];
    var link = feedItem.commentLink;
    bindSingleCommentLinkEvent(link, feedItem);
  }
}

/* Closure to add click handler to an individual comment */
function bindSingleCommentLinkEvent(link, feedItem) {
  
  link.click( function() {

    // Set secondary feedItem properties
    if (!feedItem.commentForm) {
      feedItem.findCommentForm();
    }

    if (!feedItem.commentFormInput) {
      feedItem.findCommentFormInput();
    }
    
    if (!feedItem.commentFormCancel) {
      feedItem.findCommentFormCancel();
    }

    // Show/hide the form
    if (feedItem.commentFormBlock.css("display") == "none") {
      feedItem.commentFormBlock.css("display", "block");
      feedItem.commentFormInput.focus();
    } else {
      feedItem.commentFormBlock.css("display", "none");
    }

    // Bind submit event
    feedItem.commentForm.unbind("submit");
    feedItem.commentForm.submit(function() {
      
      // Show a captcha if not logged in
      if (!fiq.currentUser) {
        jQuery.facebox(getCommentCaptchaHTML());
        var container = document.getElementById("comment_captcha");
        Recaptcha.create("6LeKKwcAAAAAADxprA2MJys7Zd96i7o4NNcXy94G", container, {
          theme: 'white',
          callback: Recaptcha.focus_response_field
        });

        // Attach click listeners
        $("#comment_captcha_submit").click( function() {
          var commentText = feedItem.commentFormInput.value;
          saveComment(commentText, feedItem);
          return false;
        });
        $("#comment_captcha_cancel").click( function() {
          jQuery(document).trigger('close.facebox');
        });

        return false;

      } else {
        var commentText = feedItem.commentFormInput.value;
        saveComment(commentText, feedItem);
        return false;
      }

      //TODO: Really shouldn't have this much raw html here
      function getCommentCaptchaHTML() {
        var html = "<div class='comment_captcha_container'>";
        html +=    "<div class='comment_captcha_title'>Prove you're not a robot.</div>";
        html +=    "<div id='comment_captcha' style='margin-left:-2px'></div>";
        html +=    "<div class='comment_captcha_signup_teaser'>Hate scrambled letters? <a href='/signup'>Sign up</a>. It takes, like, two seconds.</div>";
        html +=    "<div id='comment_captcha_error'></div><div class='comment_captcha_buttons'><input type='Button' value='Cancel' id='comment_captcha_cancel' /> ";
        html +=    "<input type='Button' value='Finish' id='comment_captcha_submit' /></div>";
        html +=    "</div>";
        return html;
      }

    });
    
    // Handle cancelations
    feedItem.commentFormCancel.click( function() {
      feedItem.commentFormBlock.css("display", "none");
    });

  });
}

/* Save a comment with no captcha */
//function saveComment(commentText, feedItem) {
//  saveComment(commentText, feedItem, null);
//}

/* Send a comment to the backend */
function saveComment(commentText, feedItem) {
  
  captchaChallenge = Recaptcha.get_challenge();
  captchaResponse = Recaptcha.get_response();
  
  var postData = {
      "comment_text" : commentText,
      "decision_id" : feedItem.id,
      "captcha_challenge" : captchaChallenge,
      "captcha_response" : captchaResponse
  };
  
  api("add_comment", postData, function(response, textStatus) {
    if (response.success) {
      var comment = new Comment(commentText, response.comment.timestamp, response.comment.username);
  
      // Make sure we know where the comment list is
      if (!feedItem.commentList) {
        feedItem.findCommentList();
      }
  
      // Draw the new comment on the page
      comment.draw(feedItem.commentList);

      // Cleanup
      jQuery(document).trigger('close.facebox');
      feedItem.commentFormBlock.css("display", "none");
      feedItem.commentFormInput.value = "";
  
    } else {
      $('#comment_captcha_error').html(response.message);
      Recaptcha.reload();
    }
  });

 }


/* API utility method */
function api(operation, postData, successCallback) {
  $.ajax({
    url: "/service/" + operation + "/",
    type: "POST",
    data: postData,
    dataType: "json",
    success: successCallback,
    error: function(XMLHttpRequest, textStatus, errorThrown) {
      alert(textStatus);
    }
  });
}
