
var myApp = {}; // a bit of protection for global variables
myApp.pArray = new Array(); // global variable to hold player_ids of players from selected squad
myApp.pNameArray = new Array(); // global variable to hold player names of players from selected squad
myApp.sel_cell = "";
myApp.ajaxActive = false;
myApp.pHash = new jsHash();
myApp.selPHash = new jsHash();

//Adds HashMap like functionality to javascript
//methods include removeItem, getItem, setItem, hasItem
function jsHash() {
  this.length = 0;
  this.items = new Array();
  for (var i = 0; i < arguments.length; i += 2) {
    if (typeof(arguments[i + 1]) != 'undefined') {
      this.items[arguments[i]] = arguments[i + 1];
      this.length++;
    }
  }

  this.removeItem = function(in_key)
  {
    var tmp_value;
    if (typeof(this.items[in_key]) != 'undefined') {
      this.length--;
      var tmp_value = this.items[in_key];
      delete this.items[in_key];
    }
    return tmp_value;
  }

  this.emptyHash = function()
  {
    this.length = 0;
  }

  this.getItem = function(in_key)
  {
    return this.items[in_key];
  }

  this.setItem = function(in_key, in_value)
  {
    if (typeof(in_value) != 'undefined') {
      if (typeof(this.items[in_key]) == 'undefined') {
        this.length++;
      }

      this.items[in_key] = in_value;
    }
    return in_value;
  }

  this.hasItem = function(in_key)
  {
    return typeof(this.items[in_key]) != 'undefined';
  }
}

//function to dynamically change player sizes by position
function getPlayerSizes(pos) {
  var size_sel = document.getElementById("player_size_options");
  var size_options = size_sel.getElementsByTagName("span");
  $("#player_size_options input:first").attr("checked","checked"); // select "All" as default

  if (pos.value === "3") {
    $(size_options[1]).html("Small");
    $(size_options[2]).html("Med");
    $(size_options[3]).html("Ruckmen");
  } else {
    $(size_options[1]).html("Small");
    $(size_options[2]).html("Med");
    $(size_options[3]).html("Tall");
  }
}

// gets activated when user clicks on Player name in main page
// set the player_id parameter in the querystring
// param : String player_id
function setPlayerID(id, el) {
  myApp.pArray = new Array();
  myApp.pNameArray = new Array();
  var playerId = id;
  var pFrame = document.getElementById("player_profile_iframe");
  pFrame.src = "player_profile.jsp?player_id=" + playerId;
  setThickBoxPlayers(id, el);
  ('#TB_window').scrollIntoView(true);
}


function setThickBoxPlayers(id, el) {
  var parent = $(el).closest("tbody");
  var p_children = parent.children();

  if (p_children != null) {
    for (var i = 0; i < p_children.length; i++){
      var elID = p_children[i].id;
      var idArr = elID.split("_");
      var p_id = idArr[1];
      var p_name = idArr[2];

      myApp.pArray[i] = p_id; // will be used for player_profile
      myApp.pNameArray[i] = p_name; // will be used for player_profile
    }

    var pl_arr = myApp.pArray;
    for (var i = 0; i < pl_arr.length; i++) {
      if (id === pl_arr[i]) {
        myApp.sel_cell = i;
      }
    }

    setPlayerHead(myApp.sel_cell);
    displayArrows(myApp.sel_cell);
  }
}

// used by the Prev and Next buttons to switch players
// param : String either "prev" or "next"
function switchPlayer(direction, squad_id) {
  var curr_cell = myApp.sel_cell;
  var pl_array = myApp.pArray;
  var pFrame = document.getElementById("player_profile_iframe");

  if (direction === "prev") {
    if (curr_cell != 0) {
      setPlayerHead(curr_cell - 1);
      displayArrows(curr_cell - 1);

      pFrame.src = "player_profile.jsp?player_id=" + pl_array[curr_cell - 1];
      myApp.sel_cell = curr_cell - 1;
    }
  } else {
    if (curr_cell != pl_array.length) {
      setPlayerHead(curr_cell + 1);
      displayArrows(curr_cell + 1);

      pFrame.src = "player_profile.jsp?player_id=" + pl_array[curr_cell + 1];
      myApp.sel_cell = curr_cell + 1;
    }
  }
}

// runs when thickbox close button is clicked
function doOnClose_iframe() {
  if ($.browser.safari) {
    //saveToMain(myApp.pArray[myApp.sel_cell]);
  } else {
    window.location.reload()
  }
}

// function that gets elements by classname
function getElementsByClassName(classname, node)  {
  if(!node) node = document.getElementsByTagName("body")[0];
  var a = [];
  var re = new RegExp('\\b' + classname + '\\b');
  var els = node.getElementsByTagName("*");
  for(var i=0,j=els.length; i<j; i++)
      if(re.test(els[i].className))a.push(els[i]);
  return a;
}

// sets the thickbox player name header
function setPlayerHead(cCell) {
  var pName = myApp.pNameArray[cCell];
  var heading = document.getElementById("playerName_Head");
  heading.innerHTML = pName;
}

// controls which of the left/right arrow are displayed in the thickbox
function displayArrows(cCell) {
  var prev_but = document.getElementById("prev_button");
  var next_but = document.getElementById("next_button");
  var pl_array = myApp.pArray;
  if (cCell === 0) {
    prev_but.className = "hidden";
  } else {
    prev_but.className = "thickbox prev";
  }

  if (cCell === (pl_array.length - 1)) {
    next_but.className = "hidden";
  } else {
    next_but.className = "thickbox next";
  }
}

// gets the skills chosen by the user
function getSelectedSkills() {
  var sel_skills = "";
  var skillChecks = $("#'skill_table':input[type=checkbox][checked]").each(
      function() {
        sel_skills += $(this).val() + "#";
      }
    );

  if (sel_skills !== "") {
    sel_skills = sel_skills.substring(0, ((sel_skills.length) - 1)); // remove trailing #
  }
  return sel_skills;

}

// gets the 7 players from the Player Wishlist
function getSelectedPlayers() {
  var sel_players = "";
  var wishlist = document.getElementById("wishlist");
  var pArr = $(".topLevel");

  for (var i = 0; i < pArr.length; i++) {
    //sel_players += pArr[i].id + "_" + (pArr.length - i) + "#";
    sel_players += pArr[i].id + "_" + (i) + "#";
  }
  sel_players = sel_players.substring(0, ((sel_players.length) - 1)); // remove trailing #
  return sel_players;
}


//update database with user's top five player choices
function ajax_update() {
  var sel_players = getSelectedPlayers();
  var squadId = document.getElementById("squad_id").value;

  if ((!myApp.ajaxActive)) {
    $.ajax({
      beforeSend: function(){
        myApp.ajaxActive = true;
      },
      type: "POST",
      url: "update.jsp",
      data: "squad_id="+ squadId + "&players=" + sel_players,
      dataType: "html",
      success : function(msg) {
        myApp.ajaxActive = false;
        doAfterUpdateSuccess();
      },
      error : function() {
        myApp.ajaxActive = false;
      }
    });
  }
  return false;
}

//clears wishlist table, shows update successful message
function doAfterUpdateSuccess() {
  var wishList = document.getElementById("wishlist");
  clearTable(wishList); //clear wishlist table
  showHideUpdateSuccess(true);
  myApp.selPHash.emptyHash(); // empty the stored player_ids from hashmap
}

function showHideUpdateSuccess(doShow) {
  var wishFoot = $('#wishFoot');
  var successText = '<tr id="success_msg"><td class="success_msg" colspan="4">Thanks for submitting your list. <br />Check out your club&rsquo;s overall top picks and see what other fans think in the comments below.</td></tr>';
  if (doShow) {
    var saveButton = $('#saveButton');
    var saveOther1 = $('#saveOther1');
    var saveOther2 = $('#saveOther2');
    var saveOther = $('#saveOther');
    saveButton.hide();
    saveOther1.hide();
    saveOther2.hide();
    saveOther.hide();
    $(wishFoot).html(successText);
  } else {
    $('tr .success_msg').remove();
  }
}

//gets players that match the search criteria
function ajax_get_players() {
  $('#ajax_loader').show();
  var sel_skills = getSelectedSkills();
  var sel_role = $("#position_select").val();
  var sel_size = $("#'player_size_options':input[type=radio][checked]").val();

  if (sel_skills !== "") {
    $.ajax({
      beforeSend: function(){
        myApp.ajaxActive = true;
      },
      type: "POST",
      url: "getPlayers.jsp",
      data: "player_role_id=" + sel_role + "&player_size_id=" + sel_size + "&skills=" + sel_skills,
      dataType: "xml",
      success : function(msg) {
        myApp.ajaxActive = false;
        afterAjaxSuccess(msg);
      },
      error : function() {
        myApp.ajaxActive = false;
      }
    });
  } else {
    $('#ajax_loader').hide();
    showAlertBox("You need to to pick at least 1 skill from the skill list");
  }
  return false;
}

//this function is run after ajax call is successful.
//gets xml data and fills table with data
function afterAjaxSuccess(results) {
  var targetTable = document.getElementById("search_results_table");
  var targetDiv = document.getElementById("search_results");
  var targetHeading = document.getElementById("search_results_title");

  var sideDiv = document.getElementById("wishlist_div");
  var squadId = document.getElementById("squad_id").value;
  var xz = 1;
  var counter = 0;

  $(targetTable).children('tbody').empty(); // clear previous contents

  targetDiv.style.display = 'block';
  sideDiv.style.display = 'block';
  targetHeading.style.display = 'block';

  $(results).find('PLAYER').each(function() {
      xz = (counter % 2) + 1;
      var id = $(this).find('ID').text();
      var name = $(this).find('NAME').text();
      var position = $(this).find('POSITION').text();
      var dob = $(this).find('DOB').text();
      var state = $(this).find('STATE').text();
      var club = $(this).find('CLUB').text();
      var height = $(this).find('HEIGHT').text();
      var weight = $(this).find('WEIGHT').text();

      myApp.pArray[counter] = id; // will be used for player_profile
      myApp.pNameArray[counter] = name; // will be used for player_profile

      $('<tr id="results_'+ id +'_' + name + '" class="' + (xz == 1 ? "" : "alt") +'"></tr>').html('<td><a class="thickbox" onclick="setPlayerID(\''
          + id + '\', this);" href="#TB_inline?height=900&width=560&inlineId=offseason_profile1"><strong>'
          + name +' &raquo;</strong></a></td><td>'+position+'</td><td style="text-align:center" nowrap>'+dob+'</td><td>'
          +club+'</td><td>'+state+'</td><td style="text-align:center">'+height+'</td><td style="text-align:center">'
          +weight+'</td><td class="aC"><img height="10px" width="12px" src="images/results/icnArrow-'
          + squadId + '.gif" id="pickPlayerButton_' + id +'"  onclick="choosePlayer(this);" /></td>').appendTo('#search_results_table');
      counter++;
  }
  );
  disableSelectedPlayers();
  var sec_2 = document.getElementById("page_section_2");
  $(sec_2).show();
  doWishListMisl();
  tb_init('a.thickbox');
  $('#ajax_loader').hide();
  document.getElementById('search_results_title').scrollIntoView(true);
}

/**
 * Removes all children from table
 * @param obj: table object
 */
 function clearTable(obj) {
   // so long as obj has children, remove them
   while(obj.firstChild) {
     obj.removeChild(obj.firstChild);
   }
 }

// puts chosen player from Results table into Wishlist table
function choosePlayer(el) {
  var p_row_arr = $(el).closest('tr').children();
  var wishlist_table = $('#wishlist');
  var temp_p_id = $(el).closest('tr').attr('id');
  var temp_pArr = temp_p_id.split("_");
  var p_id = temp_pArr[1];

  var squad_id = document.getElementById("squad_id").value;
  var p_name_temp = $(p_row_arr[0]).text();
  var p_name = p_name_temp.slice(0, (p_name_temp.length - 2));
  var p_state = $(p_row_arr[4]).html();
  var p_club = $(p_row_arr[3]).html();

  var wChildren = wishlist_table.children();
  if (wChildren.length < 7) {
    $(wishlist_table).append('<tr id="selPlayer_'
        + p_id + '"><td class="">&nbsp;</td><td class="">' + p_name
        + '</td><td class="">' + p_club + '</td><td class="">'
        + p_state +'</td><td class="aC" width="12px"><span style="cursor:move;"><img height="13" weight="7" src="images/top7/icnArrowUD-'
        + squad_id +'.gif"/></span></td><td onclick="removeWishPlayer(' + p_id + ');" class="aC" width="12px"><span style="cursor:pointer;"><img src="images/top7/icnArrowX-' + squad_id +'.gif"/></span></td>');
    $("#pickPlayerButton_" + p_id).css('display', 'none').parent().css('cursor', 'default');
    doWishListMisl();
    doWishListRank();
  } else {
    showAlertBox("The maximum number of players allowed in your Wishlist is 7. Remove players from Wishlist first to add more.");
  }
}

// hides and shows Save button and 'Wishlist is Empty' message.
function doWishListMisl() {
  showHideUpdateSuccess(false);
  var wishBody = $('#wishlist');
  var saveButton = $('#saveButton');
  var saveOther1 = $('#saveOther1');
  var saveOther2 = $('#saveOther2');
  var saveOther = $('#saveOther');
  var wishFoot = $('#wishlist_foot');
  var wChildren = $(wishBody).children();

  if (wChildren.length == 0) {
    $(wishFoot).show();
    $(saveButton).hide();
    $(saveOther1).hide();
    $(saveOther2).hide();
    $(saveOther).hide();
  } else {
    $(wishFoot).hide();
    $(saveButton).show();
    $(saveOther1).show();
    $(saveOther2).show();
    $(saveOther).show();
  }
}

// adds votes points and alternative row colors
function doWishListRank() {
  //var rowNo = new Array(7, 6, 5, 4, 3, 2, 1);
  var rowNo = new Array(1, 2, 3, 4, 5, 6, 7);
  var wishlist_table = $('#wishlist');
  var wChildren = wishlist_table.children();
  var xz = 1;

  for (var i = 0; i < wChildren.length; i++) {
    xz = (i % 2) + 1;
    var thisTR = wChildren[i];
    var firstChild = thisTR.children[0];

    if (xz == 1) {
      $(thisTR).attr("class","topLevel");
    } else {
      $(thisTR).attr("class","alt topLevel");
    }

    $(firstChild).text(rowNo[i]).css({'font-weight' : 'bold', 'font-size' : 12, 'text-align' : 'center'});
  }
}

// removes player from wishlist
function removeWishPlayer(id) {
  $("#selPlayer_" + id).remove();
  $("#pickPlayerButton_" + id).css('display', 'inline').parent().css('cursor', 'pointer');
  doWishListRank();
  doWishListMisl();
}

// disables already selected players
function disableSelectedPlayers() {
  var wishlist = document.getElementById("wishlist");
  var pArr = $(".topLevel");
  var myHash = new jsHash();
  var tArr = $("#search_results_tbody").children("tr");

  for (var i = 0; i < pArr.length; i++) {
    var arrValues = pArr[i].id.split("_");
    var playerId = arrValues[1];
    myApp.selPHash.setItem(playerId, playerId);
  }

  for (var i = 0; i < tArr.length; i++) {
    var tArr_id_text = tArr[i].id;
    var tempArr = tArr_id_text.split("_");
    var t_id = tempArr[1];
    if (myApp.selPHash.hasItem(t_id)) {
      $("#pickPlayerButton_" + t_id).css('display', 'none').parent().css('cursor', 'default');
    }
  }
}

function showAlertBox(alertText) {
  alert(alertText);
}

// replaces missing player mugshots with a generic image
function missingImage() {
  var imgID = $('#player_mugshot');
  $(imgID).attr('src', 'http://offseasondraft.championdata.com/static/headshots/no_photo.jpg');
}