/*
 * Javasript used to render a calendar.
 * You can initialise the calender by calling this method in your on load method : 
 * var now= new Date(); showCal(<<scope>>, now.getDate(), now.getMonth(), now.getFullYear());
 * The 3 scopes you can have are day=1, week=2, month=3
 * It will write the calendar to the this div that you need on the page : <div id="displayCal"></div>
 * When a date change is selected it will call this method if it is on the page : onDateChanged()
 * You can also call the following methods to move to a different day, week or month : nextCalDate() or previousCalDate()
 * And if you want to retrieve the current select date or scope at any point call these : getSelectDate() or getScope()
 */
 
var mn=['January','February','March','April','May','June','July','August','September','October','November','December'];
var dim=[31,0,31,30,31,30,31,31,30,31,30,31];
var scanfortoday;
var currentlySelectedDate=new Date();
var selectCalBy=1;

function getNumDaysInMonth(month) {

  if (month == 1) {
    return (((oD.getFullYear()%100!=0)&&(oD.getFullYear()%4==0))||(oD.getFullYear()%400==0))?29:28;
  }
  
  return dim[month];
}

/*
 *  Function:   showCal
 *
 *  Purpose:    Displays the calendar within the div with id = displayCal
 *
 *  Parameters: displayBy - either 1, 2 or 3 for day, week and month respectively
 *
 *  Returns:    Nothing
 */
function showCal(displayBy, d, m, y) {
  currentlySelectedDate=new Date(y,m,d);
  var curmonth=currentlySelectedDate.getMonth()+1; //get current month (1-12)
  var curyear=currentlySelectedDate.getFullYear(); //get current year
  var curdate=currentlySelectedDate.getDate(); //get current year
  
  //Check to see if we have a list of Highlighted dates.
  if (window.getHighlightedDates) {
    // We have a list so pass them through to the build method.
    var highlightDates = getHighlightedDates();
    document.getElementById("displayCal").innerHTML=buildCal(curdate, curmonth , curyear, highlightDates);
  } else {
    document.getElementById("displayCal").innerHTML=buildCal(curdate, curmonth , curyear);
  }

  displayCalBy(displayBy);
}



/*
 *  Function:   getScope
 *
 *  Purpose:    Returns the scope of the calendar (either 1, 2 or 3)
 *
 *  Parameters: None
 *
 *  Returns:    1=day, 2=week, 3=month
 */
function getScope() {
  return selectCalBy;
}

/*
 *  Function:   getSelectDate
 *
 *  Purpose:    Returns the currently selected date in the calendar
 *
 *  Parameters: None
 *
 *  Returns:    The date that is selected
 */
function getSelectedDate() {
  return currentlySelectedDate;
}

/*
 *  Function:   nextCalDate
 *
 *  Purpose:    Moves the selected date forwards by a unit of 1, either a day, a week or a year
 *
 *  Parameters: None
 *
 *  Returns:    Nothing
 */
function nextCalDate() {
  move(1);
  return;
}

/*
 *  Function:   previousCalDate
 *
 *  Purpose:    Moves the selected date backwards by a unit of 1, either a day, a week or a year
 *
 *  Parameters: None
 *
 *  Returns:    Nothing
 */
function previousCalDate() {
  move(-1);
  return;
}

/*
 *  Function:   nextCalMonth
 *
 *  Purpose:    Moves the selected date forwards by 1 month
 *
 *  Parameters: None
 *
 *  Returns:    Nothing
 */
function nextCalMonth() {
  moveMonth(1);
  return;
}

/*
 *  Function:   previousCalMonth
 *
 *  Purpose:    Moves the selected date backwards by 1 month
 *
 *  Parameters: None
 *
 *  Returns:    Nothing
 */
function previousCalMonth() {
  moveMonth(-1);
  return;
}

/*
 *  Function:   buildCal
 *
 *  Purpose:    Actually builds the calendar and writes out the html
 *
 *  Parameters: d - day, m- month, year - year
 *
 *  Returns:    Nothing
 */
function buildCal(d, m, y, highlightDates) {
	
  var hasHighlightDates = true;
  if (!highlightDates) {
    hasHighlightDates = false;
  }
  
  var oD = new Date(y, m-1, 1);
  oD.od=oD.getDay();
  if(oD.od==0) {
    oD.od=6; //if sunday then put it as last day of week, since calendar takes monday as 1st day of week.
  } else {
    oD.od=  oD.od-1;
  }
  
  // Check to see if we need to highlight the date passed in;
  scanfortoday=(y==currentlySelectedDate.getFullYear() && m==currentlySelectedDate.getMonth()+1)? currentlySelectedDate.getDate() : 0;
  
  //determines if February is 29 or 28 days based on leap year.
  dim[1]=(((oD.getFullYear()%100!=0)&&(oD.getFullYear()%4==0))||(oD.getFullYear()%400==0))?29:28;
  
  var t='<div class="layout clubLatestHeader" id="caldiv">  <table class="graphicBorderTop" width="100%" cellspacing="0" cellpadding="2"><tbody><tr class="calendarTrClass"><td class="topLeftGraphic"/>';
  t+='<td class="topGraphic"><div class="calendarArrowsWrapClass"><div class="calendarTrLeftArrow" onclick="javascript:previousCalMonth();"></div><div class="decorationHeadline">&nbsp;'
	  +mn[m-1]+' '+y+'</div><div class="calendarTrRightArrow" onclick="javascript:nextCalMonth();"></div></div></td><td class="topRightGraphic"/></tbody></table>';
  t+='<table class="graphicBorderMiddle" width="100%" cellspacing="0"><tbody><tr> <td class="middleLeftGraphic"/><td class="middleCenterContent" align="center"><table id="caltable"  width="100%" border="0"  cellspacing="0"  cellpadding="0">';
  var chkLastRow=0; // variable to check whether the row is the last printed row.
  var boolExitFor=false;
  var lastCalRow=42;
  t+='<tr >';
  
  for(i=1;i<=lastCalRow;i++) {
    // x : if
    var x=((i-oD.od>0)&&(i-oD.od<=dim[m-1]))? i-oD.od : '&nbsp;';
    var paramClick;
        
    var highlightField = false;
    if (hasHighlightDates) {
      highlightField = getHighlightDate(highlightDates, oD, x);
    }
    
    if (x!="&nbsp;") {
      if (hasHighlightDates && !highlightField) {
        // If we are handling date highlighting then we check to ensure the date is allowed
        paramClick=' style="text-align:center;"';
      } else {
        paramClick=' onClick="sendDate('+x+','+m+','+y+')"  style="text-align:center;cursor:pointer;cursor:hand;"';
      }
    }
    
    if (x==scanfortoday) {
      if (hasHighlightDates && highlightField) {
        t+='<td  class="highlightedDate today" id="todayTd" ' +paramClick+'  align="center" >'+x+'</td>';
      } else {
        t+='<td  class="today" id="todayTd" ' +paramClick+'  align="center" >'+x+'</td>';
      }
    } else {
      if (hasHighlightDates && highlightField) {
      
        t+='<td  class="highlightedDate" ' +paramClick+'  align="center" >'+x+'</td>';
      } else {
      
        t+='<td ' +paramClick+'  align="center" >'+x+'</td>';
      }
    }
  
    if(((i)%7==0)&&(i<36)){
      if(chkLastRow==1){
        boolExitFor=true;
      }
      if(boolExitFor)break;
      t+='</tr><tr align="center" ><td colspan="7" class="calBorderTop">&nbsp;</td></tr><tr align="center" >';
      if(x>=(dim[m-1]-7)) {
        chkLastRow=1;
      }
    }
    if(boolExitFor)break;
  }
    
  t+='</tr></table></td><td class="middleRightGraphic"/></tr></tbody></table>';
  t+='<table class="graphicBorderBottom" width="100%" cellspacing="0"><tbody><tr><td class="bottomLeftGraphic"/><td class="bottomMiddleGraphic">'
  t+='<img width="1" height="1" alt="" src="/shim.gif"/></td><td class="bottomRightGraphic"/></tr></tbody></table></div>';
  
  return t;
}

function getHighlightDate(highlightDates, dateObj, day) {
  if (day == "&nbsp;") {
    return false;
  }
  
  var currentDate = new Date(dateObj.getFullYear(), dateObj.getMonth(), day);
  
  for (var i=0; i < highlightDates.length; i++) {
    if (highlightDates[i].getTime() - currentDate.getTime() == 0) {
      return true;
    }
  }
  
  return false;
}

/*
 *  Function:   displayCalBy
 *
 *  Purpose:    Chooses which days on the calendar to highlight
 *
 *  Parameters: displayBy - the scope, either 1=day, 2=week, 3=month
 *
 *  Returns:    Nothing
 */
function displayCalBy(displayBy) {
  selectCalBy=displayBy;
  var calTabObj=document.getElementById("caltable");
  
  if (selectCalBy=="2"){
    var td,rowTd;
    var weekFlag=0;
    document.getElementById("todayTd").parentNode.parentNode.className="";
    
    if (hasHighlightedField(document.getElementById("todayTd").className)) {
      document.getElementById("todayTd").className="highlightedDate";
    } else {
      document.getElementById("todayTd").className="";
    }
        
    for (tr=0;tr<calTabObj.rows.length;tr++){
      weekFlag=0;
      for(td=0; td<calTabObj.rows[tr].cells.length; td++){
      
        if (weekFlag==0){
          var tdInnerHTML = calTabObj.rows[tr].cells[td].innerHTML;
          if (tdInnerHTML == scanfortoday) {
            weekFlag=1;
            td=-1;
          }
        } else {
          
          if (hasHighlightedField(calTabObj.rows[tr].cells[td].className)) {
            calTabObj.rows[tr].cells[td].className="today highlightedDate";
          } else {
            calTabObj.rows[tr].cells[td].className="today";
          }
        }
      }
    }
  } else if (selectCalBy=="3") {
    
    if (hasHighlightedField(document.getElementById("todayTd").className)) {
      document.getElementById("todayTd").className="highlightedDate";
    } else {
      document.getElementById("todayTd").className="";
    }    
    
    document.getElementById("todayTd").parentNode.className="";
    for(tr=0;tr<calTabObj.rows.length;tr++){
      for(td=0;td<calTabObj.rows[tr].cells.length;td++){
        if (tr%2==1){
          if (hasHighlightedField(calTabObj.rows[tr].cells[td].className)) {
            calTabObj.rows[tr].cells[td].className="today calBorderTop highlightedDate";
          } else {
            calTabObj.rows[tr].cells[td].className="today calBorderTop";
          }
          
          tr=tr+1;
        }
        
        if (hasHighlightedField(calTabObj.rows[tr].cells[td].className)) {
          calTabObj.rows[tr].cells[td].className="today highlightedDate";
        } else {
          calTabObj.rows[tr].cells[td].className="today";
        }
        
      }
    }
  } else if(selectCalBy=="1"){
    var elem = document.getElementById("todayTd");
  
    elem.parentNode.className="";
    elem.parentNode.parentNode.className="";
    
    if (hasHighlightedField(elem.className)) {
    elem.className="today highlightedDate" ;
    } else {
    elem.className="today";
    }
    
  }
}

function hasHighlightedField(style) {
  return style.indexOf('highlightedDate') != -1;
}


/*
 *  Function:   sendDate
 *
 *  Purpose:    Called when a date in the calendar is selected by a user
 *
 *  Parameters: d=day, m=month,y=year
 *
 *  Returns:    Nothing
 */
function sendDate(d,m,y){
  showCal(scope,d,m-1,y);
  if(window.onDateChanged) {
    onDateChanged();
  }
}

/*
 *  Function:   move
 *
 *  Purpose:    Moves the selected date by the given value
 *
 *  Parameters: adjustment - the amount to move
 *
 *  Returns:    Nothing
 */
function move(adjustment){
  var d = currentlySelectedDate.getDate();
  var m = currentlySelectedDate.getMonth();
  var y = currentlySelectedDate.getFullYear();

  if(selectCalBy == 3) {
    if(adjustment > 0 && m == 11) {
      m=0;
      y=y+adjustment;
    } else if(adjustment < 0 && m == 0) {
      m=11;
      y=y+adjustment;
    } else {
      m=m+adjustment;
    }
  } else if(selectCalBy == 2) {
    var weekAdjust = d + (adjustment*7);
    if(adjustment > 0 && m == 11 && weekAdjust > dim[m]) {
      d=weekAdjust-dim[m];
      m=0;
      y=y+adjustment;
    } else if(adjustment > 0 && m == 11 && weekAdjust < 0) {
      d=dim[m-1]+weekAdjust;
      m=11;
      y=y+adjustment;
    } else if(adjustment > 0 && weekAdjust > dim[m]) {
      d=weekAdjust-dim[m];
      m=m+adjustment;
    } else if(adjustment > 0 && weekAdjust < 0) {
      d=dim[m-1]+weekAdjust;
      m=m+adjustment;
    } else {
      d=d+(adjustment*7);
    }
  } else if(selectCalBy == 1) {
    if(adjustment > 0 && m == 11 && d == dim[m]) {
      d=1;
      m=0;
      y=y+adjustment;
    } else if(adjustment < 0 && m == 0 && d == 1) {
      d=31;
      m=11;
      y=y+adjustment;
    } else if(adjustment > 0 && d == dim[m]) {
      d=1;
      m=m+adjustment;
    } else if(adjustment < 0 && d == 1) {
      d=dim[m-1];
      m=m+adjustment;
    } else {
      d=d+adjustment;
    }
  } else {
    alert('Invalid selectCalBy : ' + selectCalBy);
  }
  
  showCal(selectCalBy,d,m,y);
  
  return;
}

/*
 *  Function:   moveMonth
 *
 *  Purpose:    Moves the selected date by the given value
 *
 *  Parameters: adjustment - the amount to move
 *
 *  Returns:    Nothing
 */
function moveMonth(adjustment){
  var d = currentlySelectedDate.getDate();
  var m = currentlySelectedDate.getMonth();
  var y = currentlySelectedDate.getFullYear();

  if(adjustment > 0 && m == 11) {
    m=0;
    y=y+adjustment;
  } else if(adjustment < 0 && m == 0) {
    m=11;
    y=y+adjustment;
  } else {
    m=m+adjustment;
  }
  
  showCal(selectCalBy,d,m,y);
  
  if(window.onDateChanged) {
    onDateChanged();
  }
  
  return;
}