var broadcastEventDate;
var calendarStyle = "day";

Event.observe(window, 'load', function() {
  adjustDate(0);
});

// This is called when a 'flag' is clicked in the full schedule calendar
function selectDay(dayValue) {
  calendarStyle = "day";
  broadcastEventDate = dayValue;
  callPHP();
}

function flipStyle() {
  if (calendarStyle == "day") {
    calendarStyle = "week";
  } else {
    calendarStyle = "day";
  }
  showUpdating();
  callPHP();
}

function showUpdating() {
  // Set the rows to Updating...
  var row = '<tr class="highlight now"><td class="time"></td>' +
    '<td colspan="2">Updating...</td></tr>';

  // table->tbody->tr[]
  $('agenda-table').firstDescendant().update(row);
}

function callPHP() {
  var offset = getTimeZoneOffset();
  var calStartDate, calEndDate, nextDate;
  var numDays;
  if (calendarStyle == "day") {
    numDays = 1;
  } else { // calendarStyle == "week"
    // reset the day to Sunday 
    if (broadcastEventDate.getDay() != 0) {
      broadcastEventDate.setDate(broadcastEventDate.getDate() - broadcastEventDate.getDay());
    }
    numDays = 13;
  }
  calStartDate = getFormatedDate(broadcastEventDate);
  nextDate = new Date(broadcastEventDate);
  nextDate.setDate(broadcastEventDate.getDate()+numDays);
  calEndDate = getFormatedDate(nextDate);

  new Ajax.Updater('agenda', '/getcalendar.php?bc='+curBroadcaster, {
    parameters : {tzoffset : offset, style : calendarStyle, startdate : calStartDate, enddate : calEndDate}
    });
}


function adjustDate(adjustment) {
  if (adjustment == 0) {
    broadcastEventDate = new Date();
  } else {
    broadcastEventDate.setDate(broadcastEventDate.getDate()+adjustment);
  }

  showUpdating();

  callPHP();
}

function getTimeZoneOffset() {
  var utcHours = broadcastEventDate.getUTCHours();
  var offset = broadcastEventDate.getHours() - utcHours;
  if (offset > 12) {
    offset -= 24;
  }
  return offset;
}

function getFormatedDate(dateToFmt) {
  var temp = dateToFmt.getFullYear() + '-';
  if (dateToFmt.getMonth()+1 < 10) {
    temp += '0';
  }
  temp += (dateToFmt.getMonth()+1) + '-';
  
  if (dateToFmt.getDate() < 10) {
    temp += '0';
  }
  temp += dateToFmt.getDate();
  return temp;
}
