var defaultReturnDateDaysAhead = -1;

function showCal(id, daysGap) {
 activeID=id;
 defaultReturnDateDaysAhead = daysGap;
 var array=getValidatedDateArray(id);
 if (!isValidDate(array)&&id>1) {
   if (fieldExists(id-1)) {
     array=getValidatedDateArray(id-1);
   }
 }
 if (!isValidDate(array)) {
  var now = new Date();
  array=new Array(now.getFullYear(),now.getMonth()+1,now.getDate());
 }
 var dt=new Date(array[0],array[1]-1,array[2],0,0,0,1);
 while (dt.getDate()<array[2] && array[2]>=1) {
  dt=new Date(array[0],array[1]-1,--array[2],0,0,0,1);
 }
 genCal(dt);
}

var activeID=0;
function selectDate(year,month,day) {
 setDate(activeID,year,month,day);
 updateDateState();
 if (typeof doDateChanged == "function") doDateChanged(activeID,defaultReturnDateDaysAhead);
}

 function numDays(y,m) {
  return (m==3 || m==5 || m==8 || m==10)? 30 : ((m==1) && (((y%4==0) && y%100!=0) || y%400==0)) ? 29 : (m==1)? 28 : 31;
 }

 function genCal(inputDate) {
  var selectedDate = new Date(inputDate.getFullYear(), inputDate.getMonth(), inputDate.getDate());
  inputDate.setDate(1);

  inputDate.setMonth(inputDate.getMonth() - calPastMonthsCount);
  var totalCalendars = 1 + calPastMonthsCount + calFutureMonthsCount;

  genCalDoHtmlAndPopup(inputDate, selectedDate, totalCalendars);
}

/* This function takes a string such as "2years30m5" and returns an array with entries [2] [30] [5] */
function getValues(sourceString) {

    /*only allow numbers and commas - then only single commas - the remove commas from start, then remove from end*/
  sourceString = sourceString.replace(/[^0-9|-]/g,",").replace(/[,]+/g,",").replace(/,$/,"").replace(/^,/,"");

  return sourceString.split(",");
}

/*get argument from array or return nought if not found */
/*generally used on an array such as [-1,0,0] - meaning 1 year ago*/
function getArgument(theArray, index) {

  if (theArray.length >= index) {
    return parseInt(theArray[index],10/* BASE-10 */);
  }
  return 0;
}

function dateAdd(theDate, Years, Months, Days) {
  theDate.setFullYear(theDate.getFullYear()+Years);
  theDate.setMonth(theDate.getMonth()+Months);
  theDate.setDate(theDate.getDate()+Days);
  theDate.setHours(0);
  theDate.setMinutes(0);
  theDate.setSeconds(0);
  theDate.setMilliseconds(1);
  return theDate;
}

function genCalDoHtmlAndPopup(inputDate, selectedDate, totalCalendars) {
  var todayDate = new Date();
  todayDate = new Date(todayDate.getFullYear(),(todayDate.getMonth()),todayDate.getDate(),0,0,0,1);

  /*What date range are we going to allow users to select */
  /*value from resources should be e.g. */
  /*    "1YEAR 3MONTHS 5DAYS"  or  "-2MONTHS, -40DAYS" */
  /* order IS important - MUST be YMD  -  any number of non-numeric chars can be used as separators    */

  /*  GetValues() takes the YMD numbers and puts them in an array */
   var selectableDaysOffsetsArrayStart = getValues(calSelectableDaysOffsetStart);
   var selectableDaysOffsetsArrayEnd = getValues(calSelectableDaysOffsetEnd);

  /* START DATE - get the numeric values from the array - assume YMD order*/
  var days = getArgument(selectableDaysOffsetsArrayStart,2);
  var months  = getArgument(selectableDaysOffsetsArrayStart, 1);
  var years = getArgument(selectableDaysOffsetsArrayStart, 0);

  /* add the values to today's date */
  var selectableDaysStartDate = dateAdd( new Date(), years, months, days);

  /* END DATE */
  days = getArgument(selectableDaysOffsetsArrayEnd, 2);
  months  = getArgument(selectableDaysOffsetsArrayEnd, 1);
  years = getArgument(selectableDaysOffsetsArrayEnd, 0);
  var selectableDaysEndDate = dateAdd( new Date(), years, months, days);
  

  var popupHeader = '<body marginheight="0" leftmargin="0" topmargin="0" marginwidth="0">'
  + '<div class="cal">'
  + '<center>'
  + '<table border="0" cellpadding="0" cellspacing="0" class="structure">'
  + '<tr>'
  + '<td>';

  var popupBody = "";
  for(var i=0; i < totalCalendars; i++) {
   var showPrevArrow = (i==0);
   var showNextArrow = (i+1 == totalCalendars);
    popupBody += doCalForMonth(inputDate, todayDate, selectedDate, selectableDaysStartDate, selectableDaysEndDate, showPrevArrow, showNextArrow, totalCalendars);
    inputDate.setMonth(inputDate.getMonth() +1);
  }

  var popupFooter = '</td>'
  +'</tr>'
  +'<tr>'
  +'<td class="calfooter">'
  +'<a href="javascript:self.close()">'
  +calCloseThisWindowText
  +'</a>'
  +'</td>'
  +'</tr>'
  +'</table>'
  +'</center>'
  +'</div>'
  +'</body>';

  var scrollbars = "no";
  var widthPerCal = 700;
  
  if (totalCalendars > 3) {
      scrollbars = "yes";
  } 
  else {
      widthPerCal = calWinWidthPerCalendar*totalCalendars;
  }
  doCalendarPopup(popupHeader + popupBody + popupFooter, widthPerCal, scrollbars);
}



function doCalForMonth(inputDate, todayDate, selectedDate, selectableDaysStartDate, selectableDaysEndDate, showPrevArrow, showNextArrow, totalCalendars) {
  var row = 1;
  var month = inputDate.getMonth()+1;
  var year = inputDate.getFullYear();
  var todayMonthMatch = (inputDate.getMonth()==todayDate.getMonth() && inputDate.getFullYear()==todayDate.getFullYear());
  var selectedMonthMatch = (inputDate.getMonth()==selectedDate.getMonth() && inputDate.getFullYear()==selectedDate.getFullYear());
  var out = '<table align="left" border="0" cellpadding="0" cellspacing="10" width="200" class="monthblock">';
  out+='<tr>';
  out+='<td>';
  /* Output header e.g.             <<     March 2004     >>      */
  out+='<table width="200" border="0" cellpadding="0" cellspacing="0" class="monthhead">';
  out+='<tr>';
  out+='<td class="monthprevious">';
  if (showPrevArrow) {
    out+='<a href="javascript:opener.prevCal(\''+inputDate.toGMTString()+'\', \''+selectedDate.toGMTString()+'\', '+totalCalendars+')">'+calPrevImg+'</a>';
  } else {
    out+='&nbsp;';
  }
  out+='</td>';
  out+='<td class="monthname">'+months[month - 1] + ' ' + year + '</td>';
  out+='<td class="monthnext">';
  if (showNextArrow) {
    out+='<a href="javascript:opener.nextCal(\''+inputDate.toGMTString()+'\', \''+selectedDate.toGMTString()+'\', '+totalCalendars+')">'+calNextImg+'</a>';
  } else {
    out+='&nbsp;';
  }
  out+='</td>';
  out+='</tr>';
  out+='</table>';
  out+='</td>';
  out+='</tr>';
  out+='<tr>';
  out+='<td>';
  /* Output days e.g.    Sun  Mon  Tue  Wed  Thu  Fri  Sat    */
  out+='<table width="200" border="0" cellpadding="0" cellspacing="0" class="monthmain">';
  out+='<tr>';
  for (d=0;d<7;d++) {
   out+='<td class="day dayname">'+days[d] + '</td>';
  }
  out+='</tr>';

  /* Output dates e.g.    -   -  1  2  3  4  5   */
  /* first, we must handle the offset from Sunday   */
  var offset = 7 - firstDayOfWeekOffset;
  var firstDayRelativeToSunday = new Date(year,month - 1,1,0,0,0,0).getDay();

  offset = offset + firstDayRelativeToSunday;
  if (offset >= 7) offset = offset - 7;
  var day=1-offset;

  var col=0;
  out+='<tr>';
  totalDays = numDays(year,month - 1);
  while (day<=totalDays) {
   if (day>0) {
    if ((null == selectableDaysStartDate) 
    || (null == selectableDaysEndDate) 
    || ((new Date(year, month-1, day, 0,0,0,1).getTime() >= selectableDaysStartDate.getTime())
    && (new Date(year, month-1, day, 0,0,0,1).getTime() <= selectableDaysEndDate.getTime()))) {
        if (todayMonthMatch && day==todayDate.getDate()) { 
         out+='<td class="day dayselectable today">'; 
        } else if (selectedMonthMatch && day==selectedDate.getDate()) { 
         out+='<td class="day dayselectable selected">'; 
        } else { 
         out+='<td class="day dayselectable">';
        }
        out+='<a href="javascript:self.close();opener.selectDate('+year+','+month+','+day+');">';
        out+='&nbsp;&nbsp;'+day+'&nbsp;&nbsp;';
        out+='</a>';
      } else {
        if (todayMonthMatch && day==todayDate.getDate()) { 
         out+='<td class="day dayselectable today">'; 
        } else if (selectedMonthMatch && day==selectedDate.getDate()) { 
         out+='<td class="day dayselectable selected">'; 
        } else { 
         out+='<td class="day daynotselectable">';
        }
        out+=day;
      }
   } else {
      out+='<td class="day dayempty">';
     out+='&nbsp;';
   }

   out+='</td>';
   col++;
   if (col>6) {
    out+='</tr>';
    col=0;
    row++;
   }
   if (col==0 && day<totalDays) {
    out+='<tr>';
   }
   day++;
  }
  if (col!=0) {
   for (;col<7;col++) {
    out+='<td class="day dayempty">&nbsp;</td>';
   }
  }
  out+='</tr>';
  if (row<6 || (row==6 && col==0)) {
   out+='<tr>';
   for (col=0;col<7;col++) {
    out+='<td class="day dayempty">&nbsp;</td>';
   }
   out+='</tr>';
  }
  out+='</table>';
  /*end outer table for this calendar */
  out+='</td>';
  out+='</tr>';
  out+='</table>';

return out;
}
    
function prevCal(inputDateStr, selDateStr, totalCalendars){
  var inputDate = new Date(inputDateStr);
  var selDate = new Date(selDateStr);
  var month = inputDate.getMonth() - 1;
  if (month<0) {
   month = month+12;
   inputDate.setFullYear(inputDate.getFullYear()-1);
  }
  inputDate.setMonth(month);
  genCalDoHtmlAndPopup(inputDate, selDate, totalCalendars);
}

function nextCal(inputDateStr, selDateStr, totalCalendars){
  var inputDate = new Date(inputDateStr);
  var selDate = new Date(selDateStr);
  var month = inputDate.getMonth() + 2 - totalCalendars;
  if (month>11) {
   month = month-12;
   inputDate.setFullYear(inputDate.getFullYear()+1);
  }
  inputDate.setMonth(month);
  genCalDoHtmlAndPopup(inputDate, selDate, totalCalendars);
}
