/**
 * @name    FutureDatePicker
 * @author  Kaj Haffenden
 *
 * Finds a date in the future which matches certain conditions
 */
var FutureDatePicker = function() {
  
  // Conditions to check
  
  this.dayOfWeekCondition = 2;                        // Thursday
  this.instanceInMonth = new RegExp('^(?:1|3)$');   // 1st, 3rd days of month
 
  // 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
          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._setNextDate = function(curDate) {
    this.nextDate = curDate;
    this.nextDateDisplay =                                  // D MMM YYYY
      this.nextDate.getDate() + ' ' +
      this._months[this.nextDate.getMonth()] + ' ' +
      this.nextDate.getFullYear();
  }

}


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