var dayCounts = new Array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );

function prepareWeeks() {
  var weekCombo = document.getElementById("week");
  var myCombo = document.getElementById("monthAndYear");
  var fd = document.getElementById("firstDay");
  
  optionTest = true;
  lgth = weekCombo.options.length - 1;
  weekCombo.options[lgth] = null;
  if (weekCombo.options[lgth]) optionTest = false;
  
  myCombo.onchange = function() {
    return getWeeks(fd, this);
  }
  
  return getWeeks(fd, myCombo);
}

function getWeeks(fd, myCombo) {
  if (!optionTest) return;

  var myString = myCombo.options[myCombo.selectedIndex].value;
  var my = myString.split("-");
  
  var numWeeks;
  
  if(fd) {
    var firstDay = fd.value;
    // get week count for this month-year
    numWeeks = getWeeksInMonth(firstDay, my[0], my[1]);
  }
  if(!fd)
    numWeeks = getNumWeeks(my[0], my[1]);
  
  var weekCombo = document.getElementById("week");
  weekCombo.options.length = 0;
  
  for ( var i=1; i <= numWeeks; i++) { // add new options
      weekCombo.options[i-1] = new Option('Week '+i,i+'');
  }
    
  return true;
}

function getWeeksInMonth(firstDay, month, year) {
  var date = new Date(year,(month-1),1);
  var firstDayOfMonth = date.getDay()+1;
  var flexStartDay = firstDayOfMonth - firstDay;
  var lastDay = getDaysInMonth(month, year);
        
  if(flexStartDay < 1) { // goes back one row?
    flexStartDay = 7 + flexStartDay;
  }
        
  return Math.ceil(((flexStartDay + lastDay)-1)/7.0);
}

function getNumWeeks(month, year) {
  var date = new Date(year,month-1,1);
  var firstDay = date.getDay();
  var totalDays = getDaysInMonth(month, year);
  return Math.ceil(((firstDay + totalDays)+1)/7.0);
}

function getDaysInMonth(month, year) {
  if(month == 2) {
    if( (year % 400) == 0 || ((year % 4) == 0 && !(year % 100) == 0) )
      return 29;
    else
      return 28;
  }
  else {
    return dayCounts[month-1];
  }
}

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

addLoadEvent(prepareWeeks);
