
var randomCountdownID = Math.random();
var habXMLCountdownSuccess = false;
var habXMLCountdownAttempt = 0;

randomCountdownID     = "ID" + randomCountdownID;

if(habCountdownArray == undefined) {
  var habCountdownArray     = new Array();
  var habCountdownKeys      = new Array();
  var habCountdownKeyCount  = 0;
  var habCountdownInitiated = false;
  var habCountdownTimer;
}

habCountdownArray[randomCountdownID] = new Array();

habCountdownArray[randomCountdownID]['title']          = countdownTitle;
habCountdownArray[randomCountdownID]['message']        = countdownMessage;
habCountdownArray[randomCountdownID]['deadlineDate']   = countdownMonth + " " + countdownDay + " " + countdownHour + ":" + countdownMinute + ":00 " + countdownYear;
habCountdownArray[randomCountdownID]['hideCountdown']  = countdownHiddenOnDeadline;
habCountdownArray[randomCountdownID]['size']           = countdownSize;

habCountdownArray[randomCountdownID]['countdownOver']  = false;
habCountdownArray[randomCountdownID]['endTimestamp']   = 0;
habCountdownArray[randomCountdownID]['endTime']        = "";
habCountdownArray[randomCountdownID]['timeDifference'] = 0; 
habCountdownArray[randomCountdownID]['countdownTimer'] = 0;

habCountdownKeys[habCountdownKeyCount] = randomCountdownID;
habCountdownKeyCount++;

function makeSyncHttpRequest_Countdown(url,callback_function,fieldTag) {  // My SJAX Function
  var sync_http_request = false;
  if (window.XMLHttpRequest) { // Mozilla, Safari,...
   sync_http_request = new XMLHttpRequest();
   if (sync_http_request.overrideMimeType) {
    sync_http_request.overrideMimeType('text/xml');
   }
  } else if (window.ActiveXObject) { // IE
          try {
           sync_http_request = new ActiveXObject("Msxml2.XMLHTTP");
          }
          catch (e) {
           try {
            sync_http_request = new ActiveXObject("Microsoft.XMLHTTP");
           } catch (e) {}
          }
         }
         if (!sync_http_request) {
          // alert('Giving up - Cannot create an XMLHTTP instance');
          return false;
         }
  sync_http_request.open('GET', url, false);
  sync_http_request.send(null);
  if(sync_http_request.status == 200) {
   var xmldoc = sync_http_request.responseXML;
   var ajaxValue = xmldoc.getElementsByTagName(fieldTag)[0].childNodes[0].nodeValue;
   if (ajaxValue == "0") {
    alert("DCL " + validatingDCL + " is invalid.");
    setTimeout("originalField.select()", 5); 
   }
   eval(callback_function + '(sync_http_request.responseXML)');   
  }
}

function parseNFLCountdown (resultsXML) {
  var data = resultsXML.getElementsByTagName("nflSchedule");
  try {
   var weekNum = data[0].getAttribute("week");
   habXMLCountdownSuccess = true;
  } catch(er) {
   //Did not successfully grab XML data so return and re-try
   habXMLCountdownAttempt += 1;
   habXMLCountdownSuccess = false;
   return -1;
  } 
  var matchup    = resultsXML.getElementsByTagName("matchup");
  var timestamp  = parseInt(matchup[0].getAttribute("kickoff"),10); //GET FIRST KICKOFF FOR WEEK
  var serverTime = parseInt(serverTime,10);
  if(timestamp>serverTime) habCountdownArray[randomCountdownID]['countdownOver'] = true;
  habCountdownArray[randomCountdownID]['title']        = "Countdown to Week #" + weekNum;
  habCountdownArray[randomCountdownID]['deadlineDate'] = new Date(timestamp*1000);
  habCountdownArray[randomCountdownID]['endTimestamp'] = timestamp;
  habCountdownArray[randomCountdownID]['message']      = "Games are in Progress";
}

function doNFLKickoffTimes() {
  if(completedWeek==liveScoringWeek)
   var weekNum = completedWeek+1;
  else
   var weekNum = liveScoringWeek;
  if (unescape(location.href).indexOf("http://football")!=-1) var url = baseURLDynamic+"/"+year+"/export?TYPE=nflSchedule&W="+weekNum+"&rand=" + Math.random(); else var url = baseURLStatic+"/"+year+"/export?TYPE=nflSchedule&W="+weekNum+"&rand=" + Math.random();
  habXMLCountdownAttempt = 0;
  habXMLCountdownSuccess = false;
  while (!habXMLCountdownSuccess&&habXMLCountdownAttempt<2) { // Two attempts at grabbing XML data
   makeSyncHttpRequest_Countdown( url , 'parseNFLCountdown' , 'nflSchedule' );
  }
}

function fmt00(x){
 if (Math.abs(parseInt(x)) < 10){
  x = '0'+ Math.abs(x);
 }
 return x;
}

function fmtDay(x) {
  switch(x) {
   case 0 : { var day = 'Sun'; break; }
   case 1 : { var day = 'Mon'; break; }
   case 2 : { var day = 'Tue'; break; }
   case 3 : { var day = 'Wed'; break; }
   case 4 : { var day = 'Thu'; break; }
   case 5 : { var day = 'Fri'; break; }
   case 6 : { var day = 'Sat'; break; }
  }
  return day;
}

function fmtMonth(x) {
  switch(x) {
   case 1  : { var month = 'Jan'; break; }
   case 2  : { var month = 'Feb'; break; }
   case 3  : { var month = 'Mar'; break; }
   case 4  : { var month = 'Apr'; break; }
   case 5  : { var month = 'May'; break; }
   case 6  : { var month = 'Jun'; break; }
   case 7  : { var month = 'Jul'; break; }
   case 8  : { var month = 'Aug'; break; }
   case 9  : { var month = 'Sep'; break; }
   case 10 : { var month = 'Oct'; break; }
   case 11 : { var month = 'Nov'; break; }
   case 12 : { var month = 'Dec'; break; }
  }
  return month;
}

function getCountdownSecondsRemaining () {
  var pcTime = new Date();
  pcTime = Date.parse(pcTime) - habCountdownArray[randomCountdownID]['timeDifference'];
  var actualTime = new Date(pcTime);

  var today_timezone = actualTime.getTimezoneOffset();
  var todayYear      = actualTime.getYear();

  if(todayYear < 1000) {
   todayYear += 1900;
  }

  var todayMonth  = actualTime.getMonth()+1;
  var todayDate   = actualTime.getDate();
  var todayHour   = actualTime.getHours();
  var todayMin    = actualTime.getMinutes();
  var todaySec    = actualTime.getSeconds();
  var todayString = todayMonth+'/'+todayDate+'/'+todayYear+' '+todayHour+':'+todayMin+':'+todaySec;

  var deadlineYear   = habCountdownArray[randomCountdownID]['endTime'].getYear();;
  var deadlineMonth  = habCountdownArray[randomCountdownID]['endTime'].getMonth()+1;;
  var deadlineDate   = habCountdownArray[randomCountdownID]['endTime'].getDate();
  var deadlineHour   = habCountdownArray[randomCountdownID]['endTime'].getHours();
  var deadlineMin    = habCountdownArray[randomCountdownID]['endTime'].getMinutes();

  if(deadlineYear < 1000) {
   deadlineYear += 1900;
  }

  var futurestring = deadlineMonth+'/'+deadlineDate+'/'+deadlineYear+' '+deadlineHour+':'+deadlineMin+':'+'00';

  // Get the Difference between Server and PC for more accurate comparison

  var correctedTime = (Date.parse(futurestring)-Date.parse(todayString));

  return correctedTime;
}


function habCountdown() {
  for(var i = 0; i < habCountdownKeys.length; i++) {
   var ID = habCountdownKeys[i];
   var thisCountdown = habCountdownArray[ID]['countdownTimer'];
   var dDay  = Math.floor(thisCountdown/(60*60*1000*24)*1);
   var dHour = fmt00(Math.floor((thisCountdown%(60*60*1000*24))/(60*60*1000)*1));
   var dMin  = fmt00(Math.floor(((thisCountdown%(60*60*1000*24))%(60*60*1000))/(60*1000)*1));
   var dSec  = fmt00(Math.floor((((thisCountdown%(60*60*1000*24))%(60*60*1000))%(60*1000))/1000*1));
   
   if(dSec < 0 || dMin < 0 || dHour < 0 ||  dDay < 0 ) { //When countdown ends!!
    if(habCountdownArray[ID]['hideCountdown'])
     document.getElementById(ID).innerHTML = "";
    else {
     var temp="d"+ID; document.getElementById(temp).innerHTML = "0";
     var temp="h"+ID; document.getElementById(temp).innerHTML = "00";
     var temp="m"+ID; document.getElementById(temp).innerHTML = "00";
     var temp="s"+ID; document.getElementById(temp).innerHTML = "00";
     var temp="f"+ID; document.getElementById(temp).innerHTML = habCountdownArray[ID]['message']
    }
   } else {
    var temp="d"+ID; document.getElementById(temp).innerHTML = dDay;
    var temp="h"+ID; document.getElementById(temp).innerHTML = dHour;
    var temp="m"+ID; document.getElementById(temp).innerHTML = dMin;
    var temp="s"+ID; document.getElementById(temp).innerHTML = dSec;
   
    habCountdownArray[ID]['countdownTimer'] = habCountdownArray[ID]['countdownTimer'] - 1000;
   }
  }
  habCountdownTimer = setTimeout("habCountdown()",1000)
}

function getTimeDifference (){
  var pctime = new Date(); pctime = Date.parse(pctime);
  var actualtime = new Date(currentServerTime*1000); actualtime = Date.parse(actualtime);
  var difference = pctime-actualtime;
  return difference;
}

function createCountdownTable(ID){
  switch(habCountdownArray[ID]['size']) {
   case 'S'   : { var fontsize = 12; break; }
   case 'M'   : { var fontsize = 18; break; }
   case 'L'   : { var fontsize = 24; break; }
   case 'XL'  : { var fontsize = 32; break; }
   case 'XXL' : { var fontsize = 48; break; }
   default    : { var fontsize = 24; }
  }

  var tempHTML = "";
  tempHTML += "<table cellspacing='1' class='homepagemodule report'><caption><span id='t" + ID + "'></span></caption>";
  tempHTML += "<tr><th class='countdowntitle'>days</th><th>&nbsp;</th><th class='countdowntitle'>hours</th><th>&nbsp;</th><th class='countdowntitle'>mins</th><th>&nbsp;</th><th class='countdowntitle'>secs</th></tr>";
  tempHTML += "<tr class='oddtablerow' style='text-align: center; font-size: " + fontsize + "px;'><td id='d"+ID+"'></td><td>:</td><td id='h"+ID+"'></td><td>:</td><td id='m"+ID+"'></td><td>:</td><td id='s"+ID+"'></td></tr>";
  tempHTML += "<tr class='eventablerow' style='text-align: center;'><td colspan=7 id='f"+ID+"'></td></tr>"; 
  tempHTML += "</table>";

  document.getElementById(randomCountdownID).innerHTML = tempHTML;

  var temp="t"+ID; 
  document.getElementById(temp).innerHTML = habCountdownArray[ID]['title'];

  var endTime = new Date(habCountdownArray[ID]['endTimestamp']*1000);
  var end_timezone = endTime.getTimezoneOffset();
  var endYear      = endTime.getYear();
  if(endYear < 1000) {
   endYear += 1900;
  }
  var endMonth  = endTime.getMonth()+1;
  var endDate   = endTime.getDate();
  var endDay    = endTime.getDay();
  var endHour   = endTime.getHours();
  if (endHour>=12) { 
   endHour = endHour - 12; 
   var AMPM='PM'; 
  } else { 
   var AMPM='AM'; 
  }
  if(endHour==0) endHour = 12;
  var endMin    = endTime.getMinutes();
  var endString = fmtDay(endDay)+' '+fmtMonth(endMonth)+' '+endDate+' '+endYear+' '+endHour+':'+fmt00(endMin)+' '+AMPM;
//  var temp="f"+ID; document.getElementById(temp).innerHTML = habCountdownArray[ID]['endTime'];
  var temp="f"+ID; document.getElementById(temp).innerHTML = endString;
}

function startHabCountdown (ID) {
  habCountdownArray[ID]['timeDifference'] = getTimeDifference();
  if(weeklyNFLKickoff)
   doNFLKickoffTimes();
  else 
   habCountdownArray[randomCountdownID]['endTimestamp'] = Date.parse(habCountdownArray[randomCountdownID]['deadlineDate'])/1000;

  habCountdownArray[ID]['endTime'] = new Date(habCountdownArray[ID]['endTimestamp']*1000);
  //SETUP TIMING VARIABLES

  habCountdownArray[ID]['countdownTimer'] = getCountdownSecondsRemaining();
  createCountdownTable(randomCountdownID);
  if(!habCountdownInitiated) { //ONLY START COUNTDOWN ONE TIME
   habCountdown(); 
   habCountdownInitiated = true; 
  }
}

document.write("<div align='center' id='" + randomCountdownID + "'></div>");

startHabCountdown(randomCountdownID);