function readDraftLog () {
   if (typeof unit == "undefined") {
      unit = 'LEAGUE';
   }
   var url = xmlBaseURL + league_id + '_' + unit + '_draft_status.xml?random=' + get_random_string();
   new Request({ url: url, method: 'get', onSuccess: parseDraftLogXML }).send();
   url = null;
}

function do_timeout () {
   var url = window.location.protocol + "//" + window.location.host + "/" + year + "/timeout?L=" + league_id + "&XML=1&random=" +  get_random_string();
   new Request({ url: url, method: 'get'}).send();
}

function readDraftStatus () {
   if (typeof unit == "undefined") {
      unit = 'LEAGUE';
   }
   var url = xmlBaseURL + league_id + '_' + unit + '_draft_results.xml?random=' + get_random_string();
   new Request({ url: url, method: 'get', onSuccess: parseDraftResultsXML }).send();
   if (is_mock_draft) {
      // if it's a mock draft, check for timeout, too!
      setTimeout('do_timeout()', 1000);
   }
   url = null;
}

function formatShortTime (timestamp) {
   var d = new Date(timestamp * 1000);
   var h = d.getHours();
   var m = d.getMinutes();
   var s = d.getSeconds();
   var am_pm = "a.m.";
   if (h >= 12) {
      if (h > 12) {
         h -= 12;
      }
      am_pm = "p.m.";
   } else if (h == 0) {
      h = 12;
   }
   if (("" + m).length == 1) {
      m = "0" + m;
   }
   if (("" + s).length == 1) {
      s = "0" + s;
   }
   var formattedTime = h + ":" + m + ":" + s + " " + am_pm;
   return formattedTime;
}

function parseDraftLogXML (responseText, draftLogXML) {

   var statusMessages = draftLogXML.getElementsByTagName("statusMessage");
   var thisLastUpdated = 0;
   if (statusMessages && statusMessages.length > 0) {
      thisLastUpdated = statusMessages[0].getAttribute("timestamp");
   }
   if (typeof draftLogLastUpdated == "undefined" || thisLastUpdated > draftLogLastUpdated) {
      var log = document.createElement("UL");
      for (var i = 0; i < statusMessages.length; i++) {
         var item = document.createElement("LI");
         item.innerHTML = statusMessages[i].getAttribute("content");
         item.setAttribute("className", "oddtablerow");
         item.setAttribute("class", "oddtablerow");
         var timestamp = statusMessages[i].getAttribute("timestamp");
         item.setAttribute("id", "draft_log_" + timestamp);
         log.appendChild(item);
         if (typeof draftLogLastUpdated != "undefined" && timestamp > draftLogLastUpdated) {
            item.setAttribute("className", "moohighlight");
            item.setAttribute("class", "moohighlight");
         }
         if (statusMessages[i].getAttribute("undo") && statusMessages[i].getAttribute("undo").length > 0) {
            var player = statusMessages[i].getAttribute("undo");
            if (typeof last_undo == "undefined" || last_undo != player) {
               if (playerDatabase['pid_' + player] && playerDatabase['pid_' + player].times_available <= 0) {
                  playerDatabase['pid_' + player].times_available++;
                  last_undo = player;
                  if (document.pick_form) {
                     show_only(document.pick_form.position);
                  }
               }
            }
            player = null;
         }
         if (statusMessages[i].getAttribute("fid") && statusMessages[i].getAttribute("fid").length > 0) {
            // got a new franchise name in the middle of a live draft...
            var new_fid = statusMessages[i].getAttribute("fid");
            var new_fname = statusMessages[i].getAttribute("fname");
            update_franchise_name(new_fid, new_fname);
         }
         if (statusMessages[i].getAttribute("im_away") && statusMessages[i].getAttribute("im_away").length > 0) {
            var im_away = statusMessages[i].getAttribute("im_away");
            if (im_away == franchise_id) {
               // this franchise is now away - check the checkbox!
               document.pick_form.IM_AWAY.checked = true;
            }
         }
         if (statusMessages[i].getAttribute("draft_limit_seconds") && statusMessages[i].getAttribute("draft_limit_seconds").length > 0) {
            draft_limit_seconds = statusMessages[i].getAttribute("draft_limit_seconds");
         }
         if (statusMessages[i].getAttribute("invalidPick") && statusMessages[i].getAttribute("invalidPick").length > 0) {
            var invalidPick = statusMessages[i].getAttribute("invalidPick");
            if (typeof last_invalid_pick == "undefined" || last_invalid_pick != invalidPick) {
               last_invalid_pick = invalidPick;
               play_audio_clip("invaliddraftpick");
            }
            invalidPick = null;
         }
      }
      var draft_status = document.getElementById("draft_status");
      if (draft_status) {
         if (draft_status.firstChild) {
            draft_status.replaceChild(log, draft_status.firstChild);
         } else {
            draft_status.appendChild(log);
         }
         var myEffect = new Fx.Morph("draft_log_" + thisLastUpdated, {duration: 1000, transition: Fx.Transitions.Sine.easeOut}).start('.oddtablerow');
      }
      draftLogLastUpdated = thisLastUpdated;
   }
   statusMessages = null;
   innerHTML = null;
   responseText = null;
   draftLogXML = null;
}

function DraftQueue (new_pick, new_pid, new_player, new_timestamp) {
   this.pick = new_pick;
   this.pid = new_pid;
   this.player = new_player;
   this.timestamp = new_timestamp;
}

function addToDraftQueue (new_pick, new_pid, new_player, new_timestamp) {
   myDraftQueue[myDraftQueue.length] = new DraftQueue(new_pick, new_pid, new_player, new_timestamp);
}

var myDraftQueue = new Array();

function emptyDraftQueue () {
// alert("inside emptyDraftQueue!");
   if (myDraftQueue.length > 0) {
// alert("myDraftQueue.length = " + myDraftQueue.length);
      var thisDraftPick = myDraftQueue.shift();
      if (typeof thisDraftPick == "object") {
// alert("myDraftQueue length is " + myDraftQueue.length + ", thisDraftPick = " + thisDraftPick.pick);
         var currentRow = document.getElementById(thisDraftPick.pick);
         if (currentRow) {
            var currentClass = currentRow.getAttribute("className");
            if (currentClass == null || currentClass.length == 0) {
               currentClass = currentRow.getAttribute("class");
            }
            currentRow.setAttribute("className", "moohighlight");
            currentRow.setAttribute("class", "moohighlight");
            var myEffect = new Fx.Morph(thisDraftPick.pick, {duration: 1000, transition: Fx.Transitions.Sine.easeOut}).start('.' + currentClass);
            var cells = currentRow.getElementsByTagName("TD");
            cells[2].innerHTML = thisDraftPick.player;
            cells[3].innerHTML = thisDraftPick.timestamp;
            document.getElementById("draft_picks_container").scrollTop = document.getElementById(thisDraftPick.pick).offsetTop - 80;
            var this_pid = thisDraftPick.pid;
// alert("before: calling play_audio_clip with " + this_pid);
            if (playerDatabase['pid_' + this_pid] && playerDatabase['pid_' + this_pid].name && myDraftQueue.length == 0) {
// alert("inside: calling play_audio_clip with " + this_pid);
               play_audio_clip(this_pid);
            }
         }
         if (myDraftQueue.length > 0) {
            draftQueueTimeout = setTimeout('emptyDraftQueue()', 1.5 * 1000);
         } else {
            // draftQueueTimeout = null;
         }
      } else {
         alert("huh? thisDraftPick is a " + (typeof thisDraftPick));
      }
   }
}

function parseDraftResultsXML (responseText, draftResultsXML) {

   if (document.getElementById("currentServerTime")) {
      document.getElementById("currentServerTime").innerHTML = "server: " + (Date.parse(new Date(Date.parse(this.getHeader('Date'))).toUTCString())/1000) + ", client: " + currentServerTime;
   }
   headerCurrentServerTime = (Date.parse(new Date(Date.parse(this.getHeader('Date'))).toUTCString())/1000);
   if (headerCurrentServerTime - currentServerTime > 1) {
      currentServerTime = headerCurrentServerTime;
   }

   if (typeof draftResultsLastUpdated == "undefined") {
      draftResultsLastUpdated = currentServerTime;
   }
   if (typeof last_pick_time == "undefined") {
      last_pick_time = 0;
   }
   if (typeof draftPaused == "undefined") {
      draftPaused = 0;
   }
   if (typeof draftResumed == "undefined") {
      draftResumed = 0;
   }
   if (typeof draftOver == "undefined") {
      draftOver = 0;
   }
   var old_last_pick_time = last_pick_time;
   var old_draftResultsLastUpdated = draftResultsLastUpdated;
   var refreshList = false;
   try {
      var draftResults = draftResultsXML.getElementsByTagName("draftResults");
      var thisLastUpdated = draftResults[0].getAttribute("timestamp");
      draftPaused = draftResults[0].getAttribute("paused");
      draftResumed = draftResults[0].getAttribute("resumed");
      draftOver = draftResults[0].getAttribute("over");
      if (thisLastUpdated > draftResultsLastUpdated) {
         var draftPicks = draftResultsXML.getElementsByTagName("draftPick");
         var next_fid = undefined;
         var on_deck_fid = undefined;
         var this_pick = undefined;
         for (var i = 0; i < draftPicks.length; i++) {
            var thisPickTimestamp = draftPicks[i].getAttribute("timestamp");
            var pick = "pick_" + draftPicks[i].getAttribute("round") + "_" + draftPicks[i].getAttribute("pick");
            var currentRow = document.getElementById(pick);
// if (draftPicks[i].getAttribute("round") == "15") {
// alert("got a pick " + pick + " with a timestamp of " + thisPickTimestamp);
// }
            if (thisPickTimestamp && thisPickTimestamp > draftResultsLastUpdated) {
               if (currentRow) {
                  var player = draftPicks[i].getAttribute("player");
                  var playerDisplay;
                  if (player == '0000') {
                     playerDisplay = "Timer Expired";
                  } else if (player == '----') {
                     playerDisplay = "No Pick";
                  } else if (playerDatabase['pid_' + player] && playerDatabase['pid_' + player].name) {
                     playerDisplay = playerDatabase['pid_' + player].name;
                     playerDatabase['pid_' + player].times_available--;
                     // play_audio_clip(player);
                     var fid = draftPicks[i].getAttribute("franchise");
                     add_player_to_roster(fid, player);
                     // only if this franchise is the one that's selected now...
                     if (document.ROSTER.ROSTER_FRANCHISE[document.ROSTER.ROSTER_FRANCHISE.selectedIndex].value == fid) {
                        display_one_roster(fid);
                     }
                     refreshList = true;
                  } else {
                     playerDisplay = "Missing Player Name - Press Refresh.";
                  }
                  var timestamp = draftPicks[i].getAttribute("timestamp");
                  addToDraftQueue(pick, player, playerDisplay, formatShortTime(timestamp));
                  this_pick = pick;
               }
            } else if (! thisPickTimestamp && currentRow) {
               var cells = currentRow.getElementsByTagName("TD");
               // don't clear out this cell if it says 'Pre-Draft Selection Made' or 'Franchise Set To Auto-Pick'!
               if ((cells[2].innerHTML.indexOf("Pre-Draft") < 0) && (cells[2].innerHTML.indexOf("Auto-Pick") < 0)) {
                  cells[2].innerHTML = '';
                  var newClass = ((i % 2) == 0 ? "oddtablerow" : "eventablerow");
                  currentRow.setAttribute("className", newClass);
                  currentRow.setAttribute("class", newClass);
               }
               cells[3].innerHTML = '';
               if (typeof next_fid == "undefined") {
                  next_fid = draftPicks[i].getAttribute("franchise");
               } else if (typeof on_deck_fid == "undefined") {
                  on_deck_fid = draftPicks[i].getAttribute("franchise");
               }
            } else if (currentRow) {
               var newClass = ((i % 2) == 0 ? "oddtablerow" : "eventablerow");
               currentRow.setAttribute("className", newClass);
               currentRow.setAttribute("class", newClass);
            }
            if (thisPickTimestamp > last_pick_time) {
               last_pick_time = thisPickTimestamp;
            }
         }
         draftResultsLastUpdated = thisLastUpdated;
         if (typeof next_fid != "undefined" && document.pick_form && document.pick_form.FRANCHISE_PICK && document.pick_form.FRANCHISE_PICK.options) {
            for (var i = 0; i < document.pick_form.FRANCHISE_PICK.length; i++) {
               if (document.pick_form.FRANCHISE_PICK.options[i].value == next_fid) {
                  document.pick_form.FRANCHISE_PICK.options[i].selected = true;
               } else {
                  document.pick_form.FRANCHISE_PICK.options[i].selected = false;
               }
            }
            var draftcoach = document.getElementById("draftcoach");
            if (draftcoach) {
               var host = baseURLDynamic.substr("http://".length);
               draftcoach.href = "http://www.fantasysharks.com/apps/Remora/draftcoach.php?league=" + league_id + "&host=" + host + "&team=" + next_fid;
            }
         }
         if (typeof this_pick != "undefined") {
            emptyDraftQueue();
         }
         if (thisLastUpdated > currentServerTime) {
            currentServerTime = thisLastUpdated;
         }
         if (typeof next_fid != "undefined" && typeof franchise_id != "undefined" && next_fid == franchise_id) {
         play_audio_clip("yourturntopick");
         } else if (typeof on_deck_fid != "undefined" && typeof franchise_id != "undefined" && on_deck_fid == franchise_id) {
            play_audio_clip("ondeck");
         }
         if (refreshList && document.pick_form) {
            show_only(document.pick_form.position);
         }
         draftPicks = null;
      }
      draftResults = null;
   } catch (e) {
      // can't parse invalid XML - todo - what variables need to be reset here?
      // let's get rid of the alert - caused too many questions.
      // alert("can't parse invalid XML: " + e.message + ", name = " + e.name);
      last_pick_time = old_last_pick_time;
      draftResultsLastUpdated = old_draftResultsLastUpdated;
   }
   refreshList = null;
   thisLastUpdated = null;
   responseText = null;
   draftResultsXML = null;
}

function start_draft_timer () {
   var draft_countdown_timer = document.getElementById("draft_countdown_timer");
   var last_pick_seconds_ago = currentServerTime - ((typeof draftResumed != "undefined" && draftResumed > 0) ? draftResumed : last_pick_time);
   var to_display_seconds = (draft_limit_seconds - last_pick_seconds_ago);
   if (to_display_seconds > draft_limit_seconds) {
      // to_display_seconds = draft_limit_seconds;
   }
   currentServerTime++;
   if (typeof draftOver != "undefined" && draftOver > 0) {
      draft_countdown_timer.innerHTML = "Draft Is Over.";
   } else if (typeof draftPaused != "undefined" && draftPaused > 0) {
      draft_countdown_timer.innerHTML = "Draft Timer Is Currently Paused.";
   } else {
      if (to_display_seconds >= 0) {
         draft_countdown_timer.innerHTML = formatAsMinutes(to_display_seconds);
      } else if (draft_start_time > currentServerTime) {
         draft_countdown_timer.innerHTML = "Draft Can Start In " + formatAsMinutes(draft_start_time - currentServerTime);
      } else if (last_pick_time == 0) {
         draft_countdown_timer.innerHTML = "Timer Will Start After First Pick.";
      } else if (to_display_seconds >= -10 || to_display_seconds % 5 == 0) {
         do_timeout();
      } else {
         draft_countdown_timer.innerHTML = "Timer Has Expired";
      }
   }
   if (to_display_seconds == 10) {
      play_audio_clip("timerisabouttoexpire");
   }
   last_pick_seconds_ago = null;
   to_display_seconds = null;
}

function display_one_roster (fid) {
   var roster_table = document.getElementById("rostertable");
   var table_body = roster_table.getElementsByTagName("TBODY");
   var body_rows = table_body[0].getElementsByTagName("TR");
   var to_delete = body_rows.length;
   for (var i = 1; i < to_delete; i++) {
      table_body[0].deleteRow(1);
   }
   // for (var i = 0; i < franchiseRosters['fid_' +  fid].length; i++)
   var sortedArray = franchiseRosters['fid_' + fid].sort(sort_player);
   for (var i = 0; i < sortedArray.length; i++) {
      var this_pid = sortedArray[i];
      var new_row = document.createElement("TR");
      new_row.setAttribute("className", (i%2 == 1 ? "eventablerow" : "oddtablerow"));
      new_row.setAttribute("class", (i%2 == 1 ? "eventablerow" : "oddtablerow"));
      var rank = document.createElement("TD");
      rank.innerHTML = "" + (i + 1) + ".";
      var new_cell = document.createElement("TD");
      var name = "";
      if (playerDatabase['pid_' + this_pid] && playerDatabase['pid_' + this_pid].name) {
         name = playerDatabase['pid_' + this_pid].name;
      } else {
         name = this_pid;
      }

      if (playerDatabase['pid_' + this_pid] && playerDatabase['pid_' +  this_pid].bye_week > 0) {
         name += " " + playerDatabase['pid_' +  this_pid].bye_week;
      }
      if (playerDatabase['pid_' + this_pid] && typeof playerDatabase['pid_' +  this_pid].formatted_salary != "undefined" && playerDatabase['pid_' +  this_pid].formatted_salary.length > 0 && playerDatabase['pid_' +  this_pid].formatted_salary != "0") {
         name += " " + playerDatabase['pid_' +  this_pid].formatted_salary;
      }
      if (playerDatabase['pid_' + this_pid] && typeof playerDatabase['pid_' +  this_pid].picked != "undefined" && playerDatabase['pid_' +  this_pid].picked.length > 0) {
         name += " (" + playerDatabase['pid_' +  this_pid].picked + ")";
      }

      new_cell.innerHTML = name;
      new_row.appendChild(rank);
      new_row.appendChild(new_cell);
      table_body[0].appendChild(new_row);
   }
}

function sort_player (a, b) {
   if (playerDatabase['pid_' + a] && playerDatabase['pid_' + b] && typeof playerDatabase['pid_' + a].position != "undefined" && typeof playerDatabase['pid_' + b].position != "undefined") {
      var pos_a = playerDatabase['pid_' + a].position;
      var pos_b = playerDatabase['pid_' + b].position;
      if (positionSort[pos_a] != positionSort[pos_b]) {
         return (positionSort[pos_a] - positionSort[pos_b]);
      } else {
         var name_a = playerDatabase['pid_' + a].name;
         var name_b = playerDatabase['pid_' + b].name;
         return name_a>name_b ? 1 : name_a<name_b ? -1 : 0
      }
   } else {
      return 0;
   }
}

function update_franchise_name (new_fid, new_fname) {

   if (new_fname != franchiseDatabase['fid_' + new_fid].name) {
      franchiseDatabase['fid_' + new_fid] = new Franchise(new_fid, new_fname);
      var fnames = document.getElementsByClassName("fname" + new_fid);
      for (var i = 0; i < fnames.length; i++) {
         fnames[i].innerHTML = new_fname;
      }
   }
}

function load_player (object) {

   if (object.selectedIndex > -1) {
      var pid = object.options[object.selectedIndex].value;
      if (document.getElementById("draft_player_photo")) {
         var photo = document.getElementById("draft_player_photo");
         photo.src = "http://www.myfantasyleague.com/player_photos/" + pid + "_thumb.jpg";
         photo.alt = playerDatabase['pid_' + pid].name;
         photo.title = playerDatabase['pid_' + pid].name;
         photo.onerror = "this.onerror=null;this.src='http://www.myfantasyleague.com/player_photos/no_photo_available.jpg';";
      }
      if (document.getElementById("draft_player_link")) {
         var link = document.getElementById("draft_player_link");
         link.href = baseURLDynamic + '/' + year + '/player?L=' + league_id + '&P=' + pid;
         link.innerHTML = playerDatabase['pid_' + pid].name;
      }
      // var url = baseURLStatic + '/' + year + '/export?TYPE=playerProfile&P=' + pid + '&random=' + get_random_string();
      // var url = baseURLStatic + '/' + year + '/export?TYPE=playerProfile&P=' + pid;
      var url = baseURLStatic + '/fflnetdynamic' + year + '/' + pid + '_player_profile.xml';
      new Request({ url: url, method: 'get', onSuccess: parsePlayerProfileXML }).send();
      url = null;
   }
}

function parsePlayerProfileXML (responseText, playerProfileXML) {

   var profile = playerProfileXML.getElementsByTagName("player");

   var player_height_weight = document.getElementById("player_height_weight");
   if (player_height_weight && profile[0].getAttribute("height")) {
      player_height_weight.innerHTML = profile[0].getAttribute("height") + ' / ' + profile[0].getAttribute("weight");
   }
   var player_dob_age = document.getElementById("player_dob_age");
   if (player_dob_age && profile[0].getAttribute("dob")) {
      player_dob_age.innerHTML = profile[0].getAttribute("dob") + ' / ' + profile[0].getAttribute("age");
   }
   var player_adp = document.getElementById("player_adp");
   if (player_adp && profile[0].getAttribute("adp")) {
      player_adp.innerHTML = profile[0].getAttribute("adp");
   }

   var player_news = document.getElementById("player_news");
   var articles = playerProfileXML.getElementsByTagName("article");
   if (player_news) {
      var news = "";
      if (articles.length > 0 && articles[0].getAttribute("headline")) {
         for (var i = 0; i < articles.length; i++) {
            news += "<a target=\"_blank\" href=\"" + baseURLDynamic + "/" + year + "/view_news_article?L=" + league_id + "&ID=" + articles[i].getAttribute("id") + "\">" + articles[i].getAttribute("headline") + "</a> - " + articles[i].getAttribute("published") + "<br />";
         }
      } else {
         news = "No recent news articles.";
      }
      player_news.innerHTML = news;
   }
}

