/* start - functions to deal with date calculations */
function daysInMonth(theYear, theMonth) {
    var numDays = 27;
    var refMonth = --theMonth;
    while (refMonth == theMonth) {
      var refDate = new Date(theYear, theMonth, ++numDays, 0, 0, 0, 0);
      refMonth = refDate.getMonth();
    }
    return --numDays;
}

function addDaysToDate(myDate,days) {
    return new Date(myDate.getTime() + days*24*60*60*1000);
}

function addMonthsToDate(startDate, numMonths) {
    var addYears = Math.floor(numMonths/12);
    var addMonths = numMonths - (addYears * 12);
    var newMonth = startDate.getMonth() + addMonths;
    if (startDate.getMonth() + addMonths > 11) {
      ++addYears;
      newMonth = startDate.getMonth() + addMonths - 12;
    }
    var newDate = new Date(startDate.getFullYear()+addYears,newMonth,startDate.getDate(),startDate.getHours(),startDate.getMinutes(),startDate.getSeconds());

    // adjust to correct month
    while (newDate.getMonth() != newMonth) {
      newDate = addDaysToDate(newDate, -1);
    }

    return newDate;
}

function addDuration(startDate, durationUnit, durationValue) {
  var numMonths;
  if (durationUnit == "YEAR")
    numMonths = durationValue * 12;
  else
    if (durationUnit == "MONTH")
      numMonths = durationValue;
    else
      if (durationUnit == "DAY") {
        return addDaysToDate(startDate, durationValue);
      }
      else
        return startDate();   // invalid durationUnit
  return addMonthsToDate(startDate, numMonths);
}

function isValidDate(year, month, day) {
  checkDate = new Date(year, --month, day, 0, 0, 0, 0);
  return checkDate.getMonth() == month;
}

function addZero(number) {
    if(number < 10) {
        return '0'+number;
    } else {
        return number;
    }
}

function formatDate(aDate) {
  return addZero(aDate.getDate()) + '/' + addZero((aDate.getMonth() + 1)) + '/' + aDate.getFullYear();
}
/* end - functions to deal with date calculations */




// working function
function setNewDate(duration,target) {
    if (!isNaN(duration)) {
        startDate = new Date();
        endDate = addDuration(startDate, 'MONTH', duration);
        document.getElementById(target).value = formatDate(endDate);
    } else {
        document.getElementById(target).value = duration;
    }
}