var MINUTE = 60 * 1000;
var HOUR = 60 * MINUTE;
var DAY = 24 * HOUR;
var WEEK = 7 * DAY;

var today = null;

function isDisabled(date) {
  
  if (((today.getFullYear() > date.getFullYear()) ||
      (today.getFullYear() == date.getFullYear() && today.getMonth() > date.getMonth()) ||
      (today.getFullYear() == date.getFullYear() && today.getMonth() == date.getMonth() &&
       today.getDate() >= date.getDate())) &&
       ((date.getFullYear() == 2009 && date.getMonth() >= 9) || date.getFullYear() > 2009)
       ) {
      
    return false;    
  } else {
    return true;
  }
}

function flatSelected(cal, date) {
  
  if (!isDisabled(cal.date)) {
  
    var month;
    var day;
    
    if (cal.date.getMonth()+1 < 10) {
      month = "0" + (cal.date.getMonth() + 1);
    } else {
      month = (cal.date.getMonth() + 1);
    }
    
    if (cal.date.getDate() < 10) {
      day = "0" + (cal.date.getDate());
    } else {
      day = (cal.date.getDate());
    }
    
    if ((today.getFullYear() == cal.date.getFullYear()) 
      && (today.getMonth() == cal.date.getMonth())
      && (today.getDate() == cal.date.getDate())) {
    
      window.location = "?";
    } else {
      window.location = "?date=y" + cal.date.getFullYear() + "m" + month + "d" + day;
    }
  }

}

function showFlatCalendar(initDate, fdow, todayDate) {
  
  var parent = document.getElementById("display");

  var dateInit = null;

  if (initDate != undefined) {
    var initDateString = initDate.toString();
    
    if (initDateString.length > 0) {
    
      dateInit = new Date();
      dateInit.setFullYear(initDateString.substring(0,4));
      dateInit.setMonth(initDateString.substring(4,6)-1);
      dateInit.setDate(initDateString.substring(6,8));
      
    }
  }
  
  if (todayDate != undefined) {
    var todayDateString = todayDate.toString();
    
    if (todayDateString.length > 0) {
    
      today = new Date();
      today.setFullYear(todayDateString.substring(0,4));
      today.setMonth(todayDateString.substring(4,6)-1);
      today.setDate(todayDateString.substring(6,8));
    }
  }

  // construct a calendar giving only the "selected" handler.
  var cal = new Calendar(fdow, dateInit, flatSelected, today);

  // hide week numbers
  cal.weekNumbers = false;

  // We want some dates to be disabled; see function isDisabled above
  cal.setDisabledHandler(isDisabled);
  cal.setDateFormat("%A, %B %e");
  //cal.setDateFormat("%Y%m%d);

  // this call must be the last as it might use data initialized above; if
  // we specify a parent, as opposite to the "showCalendar" function above,
  // then we create a flat calendar -- not popup.  Hidden, though, but...
  cal.create(parent);

  // ... we can show it here.
  
  cal.show();
}