var MAX_LIST_SIZE = 15;
var FIELD_SEPERATOR = '&';
var COOKIE_SEPERATOR = ';';

//This needs to be consistant with the server.
var NAME_SEPERATOR = '*';

var ADD_LINK = '<img src="/images/lists/add.gif" class="linebutton" alt="+"/>';
var REMOVE_LINK = '<img src="/images/lists/remove.gif" class="linebutton" alt="-"/>';
var SIDE_REMOVE_LINK = '<img src="/images/lists/side_remove.gif" alt="-"/>';

var PROFILE_ADD_LINK = {
  "buddy" : '<img src="/images/lists/addbuddy.gif" alt="Add to Buddy List"/>',
  "comparison" : '<img src="/images/lists/addcompare.gif" alt="Add to Compare List"/>'
};

var PROFILE_REMOVE_LINK = {
  "buddy" : '<img src="/images/lists/removebuddy.gif" alt="Remove from Buddy List"/>',
  "comparison" : '<img src="/images/lists/removecompare.gif" alt="Remove from Compare List"/>'
};

var BUDDY_COLUMN = "BUDDY<br/>LIST";
var COMPARE_COLUMN = "COMPARE<br/>LIST";

var EMPTY_HTML = "<li class=\"help\">Click the links at left to add buddies to your list. Up to 15 buddies may be stored and compared.</li>";

//This function comes from http://simonwillison.net/2006/Jan/20/escape/#c32703
function escapeForRegex(s) { return s.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1') }

var Cookie = {
  create: function(name, value) {
    document.cookie = name + "=" + value + "; path=/";
  },

  // This function from http://www.railsweenie.com/forums/2/topics/749
  read: function(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(COOKIE_SEPERATOR);
    var result = null;
    
    for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
      if (c.indexOf(nameEQ) == 0){
        result = c.substring(nameEQ.length,c.length);
        break;
      }
    }
    if(result == null)
      result = ""
    return result;
  }
}

function toggle_in_list(id, list_id, link_id){
  var list = Cookie.read(list_id);
  var link = document.getElementById (link_id);

  //Determine what to do with the list and id(add or remove)
  if (player_on_list(id, list)){
    list = remove_from_list(id, list);
    if( link ) link.innerHTML = ADD_LINK;
  } else {
    if (list.split(FIELD_SEPERATOR).length >= MAX_LIST_SIZE) {
      alert ("You can only have a maximum of " + MAX_LIST_SIZE + " players on your " + list_id +" list");
      return false;
    }

    list = add_to_list(id, list);
    if( link ) link.innerHTML = REMOVE_LINK;
  }

  if( link ) link.title = determine_title_text(list, list_id, id);
  
  //Save the cookie
  Cookie.create(list_id, list);
  display_list(list_id);
}

function toggle_in_profile( id, list_id, link_id ) {
  var list = Cookie.read( list_id )
  var link = document.getElementById( link_id )

  if( player_on_list( id, list ) ) {
    list = remove_from_list( id, list )
    if( link ) link.innerHTML = PROFILE_ADD_LINK[list_id]
  }

  else {
    if( list.split( FIELD_SEPERATOR ).length >= MAX_LIST_SIZE ) {
      alert( "You can only have a maximum of " + MAX_LIST_SIZE + " players on your " + list_id + " list" )
      return false
    }

    list = add_to_list( id, list )
    if( link ) link.innerHTML = PROFILE_REMOVE_LINK[list_id]
  }

  if( link ) link.title = determine_title_text( list, list_id, id );

  // save the cookie
  Cookie.create( list_id, list );
  display_list( list_id, true );
}

function add_to_list(id, list){
  // If the list length is zero we don't want to append &
  if (list.length == 0){
    return list.concat(id);
  }
  return list.concat(FIELD_SEPERATOR + id);
}

function remove_from_list(id, list){
  // Regexp was not playing nice so I had to put it in timeout.
  // In other words, save the regex to a variable.
  var bar = new RegExp("((^|&)" + escapeForRegex(id) + "($|&))")
  var list = list.replace(bar, FIELD_SEPERATOR);
  list = list.replace(/(&&|&$|^&)/g, "");
  return list;
}

function player_on_list(id, list){
  return list.match("(^|&)" + escapeForRegex(id) + "($|&)");
}

function add_list_columns(table){
  var insert = table.rows[1].cells[1].className != 'not_found';
  var compare_header = document.createElement('th');
  var buddy_header = document.createElement('th');
  var rows = table.rows;
  var len = rows[0].cells.length + 1;
  var comparison_list = Cookie.read('comparison');
  var buddy_list = Cookie.read('buddy');
  
  compare_header.className = 'comparison';
  compare_header.innerHTML = COMPARE_COLUMN;
  rows[0].appendChild(compare_header);
  buddy_header.className = 'buddy';
  buddy_header.innerHTML = BUDDY_COLUMN;
  rows[0].appendChild(buddy_header);
  
  for( var i = 1; i < rows.length; i ++){
    var id = rows[i].cells[0].innerHTML
    rows[i].appendChild(add_remove_element(comparison_list, 'comparison', id, insert));
    rows[i].appendChild(add_remove_element(buddy_list, 'buddy', id, insert));
  }
}

function add_profile_buttons( namebar ) {
  var id = document.getElementById( "user_id" ).innerHTML
  var comparison_id = "comparison" + id.split( "*" )[0]
  var comparison_list = Cookie.read( "comparison" )
  var buddy_id = "buddy" + id.split( "*" )[0]
  var buddy_list = Cookie.read( "buddy" )

  namebar.innerHTML += '<span class="right">' +
                         '<a id="' + buddy_id +
                         '" onclick="toggle_in_profile( \'' + id + '\', \'buddy\', \'' + buddy_id + '\' )"' +
                         'title="' + determine_title_text( buddy_list, 'buddy', id ) +
                         '">' +
                           (player_on_list( id, buddy_list ) ? PROFILE_REMOVE_LINK : PROFILE_ADD_LINK)["buddy"] +
                         '</a>' +

                         '<a id="' + comparison_id +
                         '" onclick="toggle_in_profile( \'' + id + '\', \'comparison\', \'' + comparison_id + '\' )' + 
                         '" title="' + determine_title_text( comparison_list, 'comparison', id ) +
                         '">' +
                           (player_on_list( id, comparison_list ) ? PROFILE_REMOVE_LINK : PROFILE_ADD_LINK)["comparison"] +
                         '</a>' +
                       '</span>'
}

function determine_title_text(list, list_id, id){
  var title_text = "Add to";
  if(player_on_list(id, list)){
    //row_marker = REMOVE_LINK;
    title_text = "Remove from";
  }
  title_text += " " + list_id + " list";
  return title_text;
}

function add_remove_element(list, list_id, id, insert){
  var td = document.createElement("td");
      td.className = list_id
  
  if (insert) td.innerHTML = add_or_remove_link(list, list_id, id);
  return td;
}

//the list type is used for the title text of the link. It's basically a title text string.
//This function creates a link to add or remove this person from list
function add_or_remove_link( list, list_type, id, affectid, profile ){
  var title_text = determine_title_text(list, list_type, id); 
  var row_marker;
  var elem_id = list_type + id.split(NAME_SEPERATOR)[0];
  var fname = profile ? "toggle_in_profile" : "toggle_in_list"

  // okay, if we need to affect somebody else, we're adding into a side list
  // so, note who to change in the A tag, and use SIDE_REMOVE_LINK
  if (affectid) {
    row_marker = SIDE_REMOVE_LINK;

    return '<a title="' + title_text +
           '" class="' + 'add_remove_link' +
           '" href="#" onclick="' + fname + '( \'' + id + '\', \'' + list_type + '\', \'' + affectid + '\'); return false;">'+ 
           row_marker + '</a>';
  }

  // otherwise, we affect ourselves, so we're in the main listing
  // figure out whether to use REMOVE_LINK or ADD_LINK, and render accordingly
  else {
    row_marker = player_on_list(id, list) ? REMOVE_LINK : ADD_LINK;

    return '<a id="' + elem_id + 
           '" title="' + title_text +
           '" class="' + 'add_remove_link' +
           '" href="#" onclick="' + fname + '( \'' + id + '\', \'' + list_type + '\', \'' + elem_id + '\'); return false;">'+ 
           row_marker + '</a>';
  }
}

//Displays the list provided by the list_id cookie by replacing the element in location
// profile is true if we're on a profile page, and null otherwise
function display_list(list_id, profile){
  var ul = document.getElementById(list_id),
      base_list = Cookie.read(list_id),
      split_list = base_list.split(FIELD_SEPERATOR),
      body = '',
      zebra = false;

  if (ul) {
    for(var i = 0; i < split_list.length; i++){
      if (split_list[i]) {
        zebra = !zebra;
        var el = split_list[i].split(NAME_SEPERATOR);
        body += (zebra ? '<li class="zebra">' : "<li>") + add_or_remove_link(base_list, list_id, split_list[i], list_id + el[0], profile) + " " + el[1] + "</li>";
      }
    }

    if (body == '') body = EMPTY_HTML;
    ul.innerHTML = body;
  }
}

function clear_list(list_id, profile) {
  var base_list = Cookie.read(list_id),
      split_list = base_list.split(FIELD_SEPERATOR);

  var f = profile ? toggle_in_profile : toggle_in_list

  for(var i = 0; i < split_list.length; i++)
    if (split_list[i])
      f( split_list[i], list_id, list_id + split_list[i].split(NAME_SEPERATOR)[0] );

  display_list(list_id);
}
