/**
 * Calendar layer popup. This Javascript is tightly coupled to calendar.jsp.
 * 
 * Partly based on the popup calendar v2.1 from PCI Inc. Adapted to use W3C DOM,
 * added documentation, cleaned up code and added Blue Martini support.
 *
 * @author Don Hannema (Accenture Technology Solutions)
 */

/* PopUp Calendar v2.1
© PCI, Inc.,2000 • Freeware
webmaster@personal-connections.com
+1 (925) 955 1624
Permission granted for unlimited use so far
as the copyright notice above remains intact. */

var _formName=null;
var _dayField=null;
var _monthYearField=null;
var _oneFieldOnly=null;

var ppcML=new Array(31,28,31,30,31,30,31,31,30,31,30,31);
var ppcNow=new Date();
var ppcPtr=new Date();
var currentlyVisiblePopup=null;

// hide the calendar when clicking around it
document.onclick = hideCalendar;

/**
 * This is the main method to create a calendar.
 *
 * @param formName the form name where the dayField and monthYearField reside
 * @param dayField the day field name
 * @param monthYearField the monthYear field name
 * @param event the click event
 */
function getCalendarFor(formName, dayField, monthYearField, event) {
    _formName = formName;
    _dayField = dayField;
    _monthYearField = monthYearField;
    
    if (_monthYearField == null) {
    	_oneFieldOnly=true;
    } else {
      	_oneFieldOnly=false;
    } 

    // position and show the calendar
    var obj = getStyleObject('PopUpCalendar');
    obj.left 		= "205px";		//(document.body.scrollLeft+event.clientX+15)+"px";
    obj.top  		= "80px";		//(document.body.scrollTop+event.clientY)+"px";
    obj.height  	= "77px";
    obj.display 	= "";
    obj.visibility 	= "visible";

    // must reset display : otherwise calendar wont show on homepage
    var objTitle = getStyleObject('PopUpCalendarTitle');
    objTitle.display = "";
    var objTable = getStyleObject('PopUpCalendarTable');
    objTable.display = "";
    var objMonthdays = getStyleObject('monthDays');
    objMonthdays.display = "";
    
    currentlyVisiblePopup = true;

    setCalendar();

    // stop event from bubbling further
    event.cancelBubble = true;
}

/** 
 * This method sets the current calendar month.
 *
 * @param param the calendar month in YYYYMM format.
 */
function switchMonth(param) {
    setCalendar(param.substring(0,4),param.substring(4,6)-1);
}

/**
 * This method moves the current month forward or backwards.
 *
 * @param dir 'back' moves month backwards; 'forward' moves it forwards
 */
function moveMonth(dir) {
    var obj = document.getElementById("sItem");

    if (obj != null) {
        if ((dir == "back") && (obj.selectedIndex > 0)) {
            obj.selectedIndex--;
            switchMonth(obj.options[obj.selectedIndex].value);
        }
        else if ((dir == "forward") && (obj.selectedIndex < 11)) {
            obj.selectedIndex++;
            switchMonth(obj.options[obj.selectedIndex].value);
        }
    }
}

/**
 * This method sets the drop down date in the form.
 *
 * @param param the selected date in YYYY|MM|DD format.
 */
function selectDate(param) {
    var arr   = param.split("|");
    var year  = arr[0];
    var month = parseInt(arr[1]);
    var day  = parseInt(arr[2]);
    
    ppcPtr.setYear(year);
    ppcPtr.setMonth(month);
    ppcPtr.setDate(day);
    if (_oneFieldOnly) {
    	setFormDateField(ppcPtr, _formName, _dayField);    
    } else {
    	setFormDayMonthYearFields(ppcPtr, _formName, _dayField, _monthYearField);
    }
    	hideCalendar();
}

/**
 * This sets the content of the calendar to a specific month.
 *
 * @param year the year to set (or the current year if null)
 * @param month the month to set (or the current month if null)
 */
function setCalendar(year, month) {
    if (year  == null || year == undefined) {
      if ( ppcPtr != null )
      {
        year = getFullYear(ppcPtr);
      }
      else 
      {
        year = getFullYear(ppcNow);
      }
    }
 
    if (month == null || month == undefined) {
      if ( ppcPtr != null )
      {
        month = ppcPtr.getMonth();
      }
      else 
      {
        month = ppcNow.getMonth();
      }
    }
 
    if (month == 1) {
        ppcML[1]  = (isLeap(year)) ? 29 : 28;
    }

    ppcPtr.setYear(year);
    ppcPtr.setMonth(month);
    ppcPtr.setDate(1);
 
    ppcCD=generateContent();
 
    document.getElementById('monthDays').innerHTML = ppcCD;
}

/**
 * This method created the calendar content and places it in the ppcCD variable.
 */
function generateContent() {
    var year  = getFullYear(ppcPtr);
    var month = ppcPtr.getMonth();
    var date  = 1;
    var day   = ppcPtr.getDay();
    var len   = ppcML[month];
    var bgr,cnt,tmp = "";
    var j,i = 0;

    var ppcCD="<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" vspace=\"0\" hspace=\"0\">";

    // let week start at monday
    day--;
    if (day==-1) day=6;
 
    for (j = 0; j < 7; ++j) {
        if (date > len) break;
   
        for (i = 0; i < 7; ++i) {
            // weekend has a different color
            bgr = ((i == 5)||(i == 6)) ? "#FFFFFF" : "#FFFFFF";
        
            if (((j == 0)&&(i < day))||(date > len)) {
                tmp  += makeCell(bgr,year,month,0);
            } else {
                tmp  += makeCell(bgr,year,month,date);
                ++date;
            }
        }
  
        ppcCD += "<tr style=\"padding: 0px 0px 0px 0px;\" class=\"OrderPageTextBold\">" + tmp + "</tr>";
        tmp = "";
    }
    
    ppcCD += "</table>";
    
    return ppcCD;
}

/**
 * This method creates one <td>...</td> that contains one date selection item.
 *
 * @param bgr background color
 * @param year year
 * @param month month of the year
 * @param date day of the month
 * @return one <td>..</td> string
 */
function makeCell(bgr,year,month,date) {
    var param = "\'"+year+"|"+month+"|"+date+"\'";
    var td1 = "<td align=\"center\" width=\"28\" ";
    var td2 = "</span></td>\n";
    var evt = "onMouseOver=\"this.style.backgroundColor=\'#FFFFFF\'\" onMouseOut=\"this.style.backgroundColor=\'#FF8000\'\" onMouseUp=\"selectDate("+param+")\" ";
    var ext = "<span Style=\"cursor: hand\">";
    var lck = "<span Style=\"cursor: default\">";

    var lnk = "<a href=\"javascript:selectDate("+param+")\" onMouseOver=\"window.status=\' \';return true;\">";
        
    var cellValue = (date != 0) ? date+"" : "&nbsp;";

    if ((ppcNow.getDate() == date)&&(ppcNow.getMonth() == month)&&(getFullYear(ppcNow) == year)) {
        cellValue = "<span class=\"OrderRedText\">"+cellValue+"</span>";
    }
    
    var cellCode = "";
    
    if (date == 0) {
        cellCode = td1+">"+cellValue+td2;
    } else {
        cellCode = td1+evt+"Style=\"cursor: hand\">"+ext+cellValue+td2;
    }

    return cellCode;
}

/**
 * Hide the calendar
 *
 * @param event the click event
 */
function hideCalendar(event) {
    if (currentlyVisiblePopup) {
        getStyleObject('PopUpCalendar').visibility = "hidden";
 
        // set the calendar back to default so that Blue Martini's prefilling isn't in the way
        
    	if (!_oneFieldOnly) {
		var obj = document.ppcMonthList.sItem;
		obj.selectedIndex=0;
		switchMonth(obj.options[obj.selectedIndex].value);
	}
 
        setCalendar();
 
        currentlyVisiblePopup = false;
    }
}

/**
 * This method determines if the passed year is a leap year or not.
 *
 * @param year the year to check
 * @return true if leap; otherwise false
 */
function isLeap(year) {
    return ((year%400==0) || ((year%4==0) && (year%100!=0)));
}

/**
 * This method returns the year of the passed date object in YYYY format.
 *
 * @param obj Date object
 * @return the year of the Date object in YYYY format.
 */
function getFullYear(obj) {
    var year = obj.getYear();

    // IE returns 2004 for the year, NN returns 104
	if (year<2000) year=1900+year;

	return year;
}
