/**
 * @name    FutureDatePicker
 * @author  Kaj Haffenden
 *
 * Finds a date in the future which matches certain conditions
 */
var FutureDatePicker = function() {
  
  // Conditions to check
  
  this.dayOfWeekCondition = 4;                        // Thursday
  this.instanceInMonth = new RegExp('^(?:1|3|5)$');   // 1st, 3rd, 5th days of month

  // Exclusions (blocked out days) - format is D MMM YYYY (must match _setNextDate)
  this.excludeDates = {
    '6 Jan 2011' : '',
    '5 Jan 2012' : ''
  }
 
  // Other settings
 
  this._maxReachDays = 100;                           // Don't look forward more than this many days before finding a match (infinite loop sanity check)  

  // Defaults

  this.nextDate = false;                              // Holds date object of matched future date
  this.nextDateDisplay = false;                       // Holds display string of matched future date

  this._months = {
    0:  'Jan',
    1:  'Feb',
    2:  'Mar',
    3:  'Apr',
    4:  'May',
    5:  'Jun',
    6:  'Jul',
    7:  'Aug',
    8:  'Sep',
    9:  'Oct',
    10: 'Nov',
    11: 'Dec'
  }

  this.findFutureDate = function() {
    var curDate = new Date();
    // Walk forward until condition is met or sanity check is hit
    var i = 0;
    var found = false;
    while (!found && ++i < this._maxReachDays) {
      // Check conditions
      if (curDate.getDay() == this.dayOfWeekCondition) {                       // Check day of week condition
        if (this.instanceInMonth.test(Math.ceil(curDate.getDate() / 7))) {     // Check instance in month condition
          if (!this._isDateExcluded(curDate)) {                                // Check if this date is in the excluded dates array
            this._setNextDate(curDate);
            return true;
          }
        }
      }
      // Advance current date by one day
      curDate.setDate(curDate.getDate() + 1);
    }
    // Could not find date
    this.nextDateDisplay = '[Error: Could not find date]';
    return false;
  }

  this._isDateExcluded = function(curDate) {
    if (this._renderDateDisplay(curDate) in this.excludeDates)
      return true;
    else
      return false;
  }

  this._renderDateDisplay = function(curDate) {
    displayDate =                                  // D MMM YYYY
      curDate.getDate() + ' ' +
      this._months[curDate.getMonth()] + ' ' +
      curDate.getFullYear();
    return displayDate;
  }
  
  this._setNextDate = function(curDate) {
    this.nextDate = curDate;
    this.nextDateDisplay = this._renderDateDisplay(this.nextDate);
  }

}


getNextDate = function() {
  var NextDate = new FutureDatePicker();
  NextDate.findFutureDate();
  return NextDate.nextDateDisplay;
}

