/**********************************
***						Variables					***
/*********************************/

/* Determines wheteher there is a opened calendar component
*/
var _opened = false;

var cal;

/* _firstClick is here due to order of events:
		1._open
		2. clicked
	 without this hack was calendar always closed right after opening
*/
var _firstClick = false;



/**********************************
***						Functions					***
/*********************************/

/* Opens new object of type LmnCalendar. Should be called "onmousedown" event of parent/calling object
	 Params:	daySelectId - id of html select for days
	 					monthYearSelectId - id of html select for month + year
	 					parId - id of parent object (calling object, under which the calendar should be opened - if resId not defined, sets here the focus after closing
	 					resId - id of html input, where the date value should be returned - id defined, also sets focus after closing
 */
function _open(daySelectId, monthYearSelectId, parId, resId){
	// open new calendar only where there is no one opened
	if (!_opened) {
		// set _firstClick, so that in clicked() we know, that calendar ist just opening
		_firstClick = true;
		
		// set local variables
		var par = document.getElementById(parId);
		if (resId)
			var res = document.getElementById(resId);
			
		// create new calendar
		cal = new dijit.LmnCalendar({
				
				onValueSelected: function(value){
					if (dojo.date.compare(value, new Date(), "date")<0)
						return;
					else {				
						// set return value to related components
						rebuildDays(document.getElementById(monthYearSelectId), document.getElementById(daySelectId), value);
						for( i=0; i<document.getElementById(monthYearSelectId).length; i++) {
							if (document.getElementById(monthYearSelectId).options[i].value == (value.getMonth()+1)) {
								document.getElementById(monthYearSelectId).selectedIndex = i;
							}
						}
	
						// if there is return componente, set the returning value there
						if (res) {
							res.value = value;
							res.focus();
						} else {
							par.focus();
						}
						
						// close calendar
						_close();
					}
				}
				
		});
		
		// create date object
		var selectedDay = document.getElementById(daySelectId).options[document.getElementById(daySelectId).selectedIndex].value;
		var selectedMonth = document.getElementById(monthYearSelectId).options[document.getElementById(monthYearSelectId).selectedIndex].value;
		var today = new Date();
		var selectedYear = ((selectedMonth >= (today.getMonth()+1)) ? today.getFullYear() : (today.getFullYear()+1));
		var selectedDate = new Date();
		selectedDate.setDate(selectedDay);
		selectedDate.setMonth(selectedMonth-1);
		selectedDate.setFullYear(selectedYear);
		
		// set date in calendar
		cal.setValue(selectedDate);
		
		// open calendar component
		dijit.popup.open({
				parent: par,
				popup: cal,
				around: par,
				onCancel: dojo.hitch(par, _close()),
				onClose: function(){ _opened = false }
			});
			
		// set global variable, co that only one calendar can be open at a time
		_opened = true;
					
		// draw border around calendar with specified width
		dojo.marginBox(cal.domNode,{ w:175 });
	}
	
}


/* Closes the current opened LmnCalendar component. There is only one calendar at a time.
 */
function _close(){
	if(_opened){
		dijit.popup.close(cal);
		_opened=false;
	}			
}


/* Creates select options for day-selection with adequate number of days for desired month
 */
function initDays(compSelect, selDate) {
	try {
		removeOptions(compSelect);
	} catch (err) {
	}
	var daysInMonth = dojo.date.getDaysInMonth(selDate);

	for (var i=0; i<daysInMonth; i++) {
		var option = document.createElement("option");
		option.setAttribute("value", i+1);
		// selected value is set hier, because in IE6 doesn't work following line (was earlier the last line of this function)
		// compSelect.selectedIndex = selDate.getDate()-1;
		if (i == (selDate.getDate()-1))
			option.setAttribute("selected", "selected");
		option.appendChild(document.createTextNode((i+1)+""));	
		compSelect.appendChild(option);		
	}
}


/* Creates select options for month/year-selection starting from input/current month for one year in advance
 */
function initMonths(compSelect, inpDate) {
	try {
		removeOptions(compSelect);
	} catch (err) {
	}
	//alert('initMonths: ' + selDate.toString());
	var selDate = new Date();
	//alert('initMonths: ' + selDate.toString());
	var curMonthIdx = selDate.getMonth()+1;
	var mn = dojo.date.locale.getNames("months", "wide", "standAlone", "de"); 
	for (var i=0; i<12; i++) {
		var option = document.createElement("option");
		if (i<(12-curMonthIdx+1)) {
			option.setAttribute("value", i+curMonthIdx);
			option.appendChild(document.createTextNode(mn[i+curMonthIdx-1] + " " + selDate.getFullYear()));
		} else {
			option.setAttribute("value", (i+curMonthIdx)%12);
			option.appendChild(document.createTextNode(mn[((i+curMonthIdx)%12)-1] + " " + (selDate.getFullYear()+1)));
		}
		compSelect.appendChild(option);	
	}
	if (inpDate != null) {
		for( i=0; i<12; i++) {
			if (compSelect.options[i].value == (inpDate.getMonth()+1)) {
				if (navigator.userAgent.substring(25,33) == 'MSIE 6.0')
					compSelect.options[i].setAttribute("selected", "selected");
				else
					compSelect.selectedIndex = i;
			}
		}
	} else {
		compSelect.selectedIndex = 0;
	}
}


/* Removes all options from select componente
 */
function removeOptions(compSelect) {
	if (compSelect != null) {
		try {
			for (var i=compSelect.length; i>=0; i--) {
				compSelect.remove(i);
			}
		}	catch (err) {
		}
	}
}


/* Recreates the select options for day-selection. If selDate is:
	 1. date - takes the month from this date, sets adequate number of days and sets the selected day from this date
	 2. month - sets adequate days of this month and selected day is the same as it was (when desired month has less days, then it is 1.day in month)
 */
function rebuildDays(compSelectMonthYear, compSelectDay, selDate /* selected date or month*/) {
	var selectedDay = compSelectDay.options[compSelectDay.selectedIndex].value;
	removeOptions(compSelectDay);
	if (typeof selDate == "number") {
		// selDate is just number, we need to create a new Date
		selDate = new Date();
		if (compSelectMonthYear.options[compSelectMonthYear.selectedIndex].value < (selDate.getMonth()+1))
			selDate.setFullYear(selDate.getFullYear()+1);
		selDate.setMonth(compSelectMonthYear.options[compSelectMonthYear.selectedIndex].value-1);
		if (dojo.date.getDaysInMonth(selDate) < selectedDay)
			selDate.setDate(1);
		else
			selDate.setDate(selectedDay);
	}
	initDays(compSelectDay, selDate);
}


/* Returns true, if trg is component inside calendar (searches recursive from current component until document). Otherwise returns false.
   Calendar is enclosed in span with id and class "LmnCalendar"
*/
function isInCalendar(trg) {
	if ((trg == null) || (trg == "") || (trg == document)) {
		return false;
	} else {
		if (((trg.getAttribute('id') != null) && (trg.getAttribute('id').indexOf("LmnCalendar") >= 0)) || ((trg.getAttribute('class') != null) && (trg.getAttribute('class').indexOf("LmnCalendar") >= 0))) {
			return true;
		} else {
			return isInCalendar(trg.parentNode);
		}
	}
}


/* Function called onclick in document - after click outside the calendar component it should be closed
*/
function clicked(evt) {
	// close calendar only if it is opened and not opening
	if (_opened && !_firstClick) {
		if (!evt) {
	    evt = window.event;
	  }
	
		// find out whether we are in calendar component
		if (dojo.isIE) {
			//if (((evt.srcElement.getAttribute('name') != null) && (evt.srcElement.getAttribute('name') != "")) || ((evt.srcElement.getAttribute('class') != null) && (evt.srcElement.getAttribute('class').indexOf("dijitCalendar") == -1)))
			if (!isInCalendar(evt.srcElement))
				_close();
			
		} else {
			//if (((evt.target.getAttribute('name') != null)) || ((evt.target.getAttribute('class') != null) && (evt.target.getAttribute('class').indexOf("dijitCalendar") == -1)))
			if (!isInCalendar(evt.target))
				_close();
		}
	}
	
	// unset _firstClick, so that now we can close calendar after each click outside calendar
	if (_firstClick)
		_firstClick = false;
}


/* After each click in browser we call clicked() to close calendar, if it is opened and click was outside calendar
*/
document.onmousedown = clicked;
