/**
 * Date picker
 * @author	Anatoli Deryshev
 */
var SHOW_CALENDAR_WINDOW = 0;
var SHOW_CALENDAR_LAYER = 1;
var SHOW_CALENDAR_ON_TRIGGER = 2;
var CALENDAR_WEEKEND = [5,6];
var CALENDAR_WEEKDAYS = ['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So'];
var CALENDAR_MONTHS = ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"];
var CALENDAR_DAYS = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var CALENDAR_RED_DAYS = {}//{1: [1], 5: [1], 10: [3], 12: [24, 25]};//Should be filled this way - {12: [24, 25]}, this means that in december we have such red dates as 24, 25
var CALENDAR_STYLE_URL = ""; //url for style that will be used in windowed mode
var CALENDAR_STYLE_ID = "calendarStyle";
var CALENDAR_DEFAULT_DISPLAY_MODE = SHOW_CALENDAR_ON_TRIGGER;
var CALENDAR_INITIAL_WIDTH = 200;
var CALENDAR_INITIAL_HEIGHT = 200;
var CALENDAR_DEFAULT_TITLE = "Kalender";
var CALENDAR_SIZE_CONTAINER_ID = "detailsContainer";
var CALENDAR_HOLDER_ID = "calendarHolder";
/**
 * Calendars base class
 */
var calendar = function(){
	var _initialWidth = 0;
	var _initialHeight = 0;
	var _styleUrl = "";
	var _styleElementId = null;
	var _month = 0;
	var _realMonth = 0;
	var _day = 0;
	var _year = 0;
	var _weekday = null;
	var _date = new Date();
	var _currentDate = new Date();
	var _displayMode = null;
	var _headElement = null;
	var _rendered = false;
	var _defaultTitle = "";
	var _calendarWindow = null;
	var _calendarHolder = null;
	var _calendarLayerBg = null;
	var _calendarAnchor = null;
	var _calendarHolderId = null;
	var _contentTable = null;
	var _calendarTable = null;
	var _sizeContainerId = "";
	var _redDates = {};
	var _weekDaysArr = [];
	var _monthsArr = [];
	var _daysArr = [];
	var _weekEndArr = [];
	var _dateField = null;
	var _triggerField = null;
	var _usedControlId = null;
	var _isIE = (navigator.userAgent.toLowerCase().indexOf('msie') > -1);
	var _isIE6 = null;
	var _calendarCloseCallback = null;
	var _selectedMonth = null;
	var _selectedYear = null;
	var _selectedDay = null;
	var _self = this;
	
	/**
	 * Main calendar initialization function
	 */
	this.initialize = function(month, year, day, dateField, triggerField, usedControlId, baseSyleUrl, displayMode, weekend, months, title){
        _month = month || month == 0?month : _currentDate.getMonth();
        _year = year || _currentDate.getFullYear();
        _day = day || _currentDate.getDate();
        _realMonth = _month + 1;
        if (!usedControlId){
        	this._setSelectedDay(month, year, day);
        }
        _date.setDate(1);
        _date.setMonth(_month);
        _date.setFullYear(_year);
        _weekday = _date.getDay();
		_styleUrl = baseSyleUrl || CALENDAR_STYLE_URL || "";
		_styleElementId = CALENDAR_STYLE_ID || "";
		_displayMode = displayMode || CALENDAR_DEFAULT_DISPLAY_MODE || SHOW_CALENDAR_WINDOW;
		_defaultTitle = title || CALENDAR_DEFAULT_TITLE || "";
		_initialWidth = CALENDAR_INITIAL_WIDTH || 100;
		_initialHeight = CALENDAR_INITIAL_HEIGHT || 100;
		_sizeContainerId = CALENDAR_SIZE_CONTAINER_ID || 'sizeContainer';
		_calendarHolderId = CALENDAR_HOLDER_ID || 'calendarHolder';
		_weekDaysArr = CALENDAR_WEEKDAYS || ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'];
		_monthsArr = CALENDAR_MONTHS || ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
		_daysArr = CALENDAR_DAYS || [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
		_redDates = CALENDAR_RED_DAYS || {};
		_weekEndArr = CALENDAR_WEEKEND || [];
		_dateField = dateField;
		_triggerField = triggerField;
		_usedControlId = usedControlId || null;
		if (_isIE){
			this.checkIE6();
		}
		if (_dateField){
			this._renderCalendar();
		}
	};
	/**
	 * Checks for IE version below 7
	 */
	this.checkIE6 = function(){
		var isIE6 = false;
		if (_isIE){
			var ua = navigator.userAgent.toLowerCase();
			var re = new RegExp("msie ([0-9]{1,}[\.0-9]{0,})");
			if (re.exec(ua) != null) {
				if (parseFloat(RegExp.$1) < 7){
					isIE6 = true;
				}
			}
		}
		_isIE6 = isIE6;
		return isIE6;
	};
	/**
	 * Checks for the leap year
	 * @param	{String}	year	String representing year to check, must be four digits long(ex 2009)
	 */
	this._isLeapYear = function(year){
		var isLeap = false;
		if ((year % 4) == 0){
			isLeap = true;
			if ((year % 100) == 0 && (year % 400) != 0){
				isLeap = false;
			}
		}
		return isLeap;
	};
	/**
	 * Sets selected day 
	 */
	this._setSelectedDay = function(month, year, day){
	    _selectedMonth = month;
	    _selectedYear = year;
	    _selectedDay = day;
	}
	/**
	 * Sets head element of calendar window if it was not set already
	 */
	this._setHeadElement = function() {
		if (!_headElement || !_rendered){
        	_headElement = _calendarWindow.document.getElementsByTagName('head')[0] || null;
		}
    };
	
	/**
	 * Loads calender style sheet, used for windowed mode
	 */
	this._loadCalendarStyles = function(){
		this._setHeadElement();
		if (_headElement && !_calendarWindow.document.getElementById(_styleElementId)){
			this._createElement({tagName: 'title', textNode: _defaultTitle}, _headElement);
			var styleElement = this._createElement({
				tagName: 'link',
				attributes: {
					type: 'text/css',
					rel: 'stylesheet',
					href: _styleUrl,
					media: 'screen',
					id: _styleElementId
				}
			}, _headElement);
			styleElement.onload = function(){
				setTimeout(function(){
										if (_rendered){
											_self._correctWindowSize();
										}
									}, 200);
			}
		}
	};
	
	/**
	 * Checks where calendar is rendered or not.
	 */
	this.isCalendarRendered = function(){
		if (SHOW_CALENDAR_WINDOW == _displayMode){
			if (_calendarWindow){
				_rendered = !_calendarWindow.closed;
			}
			else{
				_rendered = false;
			}
		}
		return _rendered;
	}
	
	/**
	 * Main calendar rendering function, internal, please use initialize method instead
	 */
	this._renderCalendar = function(){
		this.isCalendarRendered();
		if (SHOW_CALENDAR_WINDOW == _displayMode){
			if (!_rendered){
				this._renderBaseWindow();
			}
		}
		else if (SHOW_CALENDAR_LAYER == _displayMode || SHOW_CALENDAR_ON_TRIGGER == _displayMode){
			if (!_rendered){
				this._renderBaseLayer();
			}
		}
		if (_rendered){
			this._removeCalendarHolderContent();
		}
		this._renderCalendarData();
		if (SHOW_CALENDAR_WINDOW == _displayMode){
			this._correctWindowSize();
			setTimeout(function(){_self._correctWindowSize();}, 200);
		}
		_rendered = true;
		_calendarWindow.setDate = function(){};
		_calendarWindow.decreaseYear = function(){};
		_calendarWindow.decreaseMonth = function(){};
		_calendarWindow.increaseMonth = function(){};
		_calendarWindow.increaseYear = function(){};
		_calendarWindow.closeCalendar = function(){};
		this.setFocus();
	};
	
	/**
	 * Sets focus to calendars window or anchor
	 */
	this.setFocus = function(){
		if (_rendered){
			if (SHOW_CALENDAR_WINDOW == _displayMode){
				_calendarWindow.focus();
				if (_usedControlId){
					_calendarWindow.document.getElementById(_usedControlId).focus();
				}
			}
			else if (SHOW_CALENDAR_LAYER == _displayMode || SHOW_CALENDAR_ON_TRIGGER == _displayMode){
				if (_usedControlId){
					_calendarWindow.document.getElementById(_usedControlId).focus();
				}
				else{
					_calendarAnchor.focus();
				}
			}
		}
	}
	
	/**
	 * Rearranges calender window size, based on content size 
	 */
	this._correctWindowSize = function(){
		arrangeWindowSize(_calendarWindow, _initialWidth, _initialHeight);
		_calendarTable.style.width = "100%";
	};
	
	this._renderMonthYearSwitch = function(){
		var row = this._createElement({
			tagName: "tr",
			className: "monthHeading"
		}, _calendarTable.firstChild);
		var link = this._createElement(
			{
				tagName: 'a',
				id: 'decreaseYear',
				textNode: '<<',
				attributes: {
					href: "javascript: decreaseYear();",
					title: "Ein Jahr zurück"
				}
			}, 
			this._createElement({
					tagName: "th",
					className: "calendarCell"
				},
				row
			)
		);
		link.onclick = function(){
			var year = parseInt(_year, 10) - 1;
			_self.initialize(_month, year, _day, _dateField, _triggerField, 'decreaseYear');
		};
		var link = this._createElement(
			{
				tagName: 'a',
				id: 'decreaseMonth',
				textNode: '<',
				attributes: {
					href: "javascript: decreaseMonth();",
					title: "Einen Monat zurück"
				}
			}, 
			this._createElement({
					tagName: "th",
					className: "calendarCell"
				},
				row
			)
		);
		link.onclick = function(){
			var month = parseInt(_month, 10) - 1;
			var year = parseInt(_year, 10);
			if (0 > month){
				year = year - 1;
				month = 11;
			}
			_self.initialize(month, year, _day, _dateField, _triggerField, 'decreaseMonth');
		};
		this._createElement({
				tagName: "th",
				className: "calendarCell",
				textNode: _monthsArr[_month] + ' ' + _year,
				attributes: {
					colspan: "3",
					colSpan: _isIE? "3" : null
				}
			},
			row
		);
		var link = this._createElement(
			{
				tagName: 'a',
				id: 'increaseMonth',
				textNode: '>',
				attributes: {
					href: "javascript: increaseMonth();",
					title: "Einen Monat vor"
				}
			}, 
			this._createElement({
					tagName: "th",
					className: "calendarCell"
				},
				row
			)
		);
		link.onclick = function(){
			var month = parseInt(_month, 10) + 1;
			var year = parseInt(_year, 10);
			if (11 < month){
				year++;
				month = 0;
			}
			_self.initialize(month, year, _day, _dateField, _triggerField, 'increaseMonth');
		};
		var link = this._createElement(
			{
				tagName: 'a',
				id: 'increaseYear',
				textNode: '>>',
				attributes: {
					href: "javascript: increaseYear();",
					title: "Ein Jahr vor"
				}
			}, 
			this._createElement({
					tagName: "th",
					className: "calendarCell"
				},
				row
			)
		);
		link.onclick = function(){
			var year = parseInt(_year, 10) + 1;
			_self.initialize(_month, year, _day, _dateField, _triggerField, 'increaseYear');
		};
	};
	
	/**
	 * Renders calender data
	 */
	this._renderCalendarData = function(){
		_calendarTable = this._createElement({
				tagName: "table",
				className: "calendarTable"
			}
		);
		this._createElement({
				tagName: "tbody"
			},
			_calendarTable
		);
		this._renderMonthYearSwitch();
        var weekFirstDay = _weekday - 1;
        if (0 > weekFirstDay) weekFirstDay = 6;
        
        var monthDays = parseInt(_daysArr[_month], 10);
        if (this._isLeapYear(_year) && _month == 1){
        	monthDays++; 
        }
        var weeksToRender = Math.round((monthDays + weekFirstDay) / 7);
        if (weeksToRender < ((monthDays + weekFirstDay) / 7)){
        	weeksToRender++;
        }
        var row = this._createElement({
				tagName: "tr",
				className: "daysHeading"
			},
			_calendarTable.firstChild
		);
        for (var d = 0; d < 7; d++){
        	this._createElement({
					tagName: "th",
					textNode: _weekDaysArr[d],
					className: "calendarCell"
				},
				row
			);
        }
        var displayValue = "";
        var currDisplayDay = 0 - weekFirstDay;
        for (var w = 0; w < weeksToRender; w++){
        	var row = this._createElement({
					tagName: "tr"
				},
				_calendarTable.firstChild
			);
			for (var d = 0; d < 7; d++){
				currDisplayDay++;
				var cellStyle = "";
				if (0 >= currDisplayDay || monthDays < currDisplayDay){
					displayValue = " ";
					this._createElement({
							tagName: "td",
							textNode: displayValue,
							className: cellStyle
						},
						row
					);
					continue;
				}
				else{
					displayValue = currDisplayDay;
					cellStyle = this._calculateCellStyle(currDisplayDay, d);
				}
				var dateString = (9 < currDisplayDay? currDisplayDay: "0" + currDisplayDay) + '.' + (9 < _realMonth? _realMonth: "0" + _realMonth) + '.' + _year;
				var link = this._createElement(
					{
						tagName: 'a',
						textNode: displayValue,
						attributes: {
							href: "javascript: setDate();",
							title: dateString
						}
					}, 
					this._createElement({
							tagName: "td",
							className: cellStyle
						},
						row
					)
				);
				var setLinkFunction = function(dateString, link){
					link.onclick = function(){
						_dateField.value = dateString;
						_triggerField = _dateField;
						_self._closeCalendar();
		        	}
				};
				setLinkFunction(dateString, link);
	        }
        }
        _calendarHolder.appendChild(_calendarTable);
	};
	
	this._calculateCellStyle = function(currDisplayDay, weekDay){
		var cellStyle = "calendarCell";
		if (_redDates && _redDates[_realMonth] && _redDates[_realMonth].length && -1 != _redDates[_realMonth].indexOf(currDisplayDay)){
			cellStyle += " redDay";
		}
		if (_weekEndArr && _weekEndArr.length && -1 != _weekEndArr.indexOf(weekDay)){
			cellStyle += " weekend";
		}
		if (currDisplayDay == _selectedDay && _month == _selectedMonth && _year == _selectedYear){
			cellStyle += " selectedDay";
		}
		if (currDisplayDay == _currentDate.getDate() && _month == _currentDate.getMonth() && _year == _currentDate.getFullYear()){
			cellStyle += " currentDate";
		}
		return cellStyle;
	}
	
	/**
	 * Removes all content from calendar holder
	 */
	this._removeCalendarHolderContent = function(){
		if (SHOW_CALENDAR_WINDOW == _displayMode){
			_calendarHolder.style.width = "auto";
		}
		var childs = _calendarHolder.childNodes;
		for (var i=0; i < childs.length; i++){
			if (((SHOW_CALENDAR_LAYER == _displayMode || SHOW_CALENDAR_ON_TRIGGER == _displayMode) && 0 != i) || (SHOW_CALENDAR_LAYER != _displayMode && SHOW_CALENDAR_ON_TRIGGER != _displayMode)){
				_calendarHolder.removeChild(childs[i]);
			}
		}
	};
	
	/**
	 * Generates default xhtml layout for calendar in the new window, please note that before we add doctype and close document we are working in the quirks mode.
	 */
	this._generateXhtmlLayout = function(){
		if (_calendarWindow){
			_calendarWindow.document.open();
			_calendarWindow.document.write("<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>");
			_calendarWindow.document.write("<html xmlns='http://www.w3.org/1999/xhtml'>");
			_calendarWindow.document.write("<head></head>");
			_calendarWindow.document.write("<body></body>");
			_calendarWindow.document.write("</html>");
			_calendarWindow.document.close();
		}
	};
	
	/**
	 * Creates element using DOM compliant methods
	 * @param	{Object}		elementData		Element data object with properties, tagName, id, className, name, textNode, attributes
	 * 											attributes containes atrributes object {attr1: value1, attr2: value2, ...}
	 * @param	{DOM Object}	parentElement	If provided newly created element will be appended to this element
	 */
	this._createElement = function(elementData, parentElement){
		var element = null;
		if (null != elementData && elementData.tagName && _calendarWindow){
			element = _calendarWindow.document.createElement(elementData.tagName);
			if (element){
				if (elementData.id){
					element.id = elementData.id;
				}
				if (elementData.name){
					element.name = elementData.name;
				}
				if (elementData.className){
					element.className = elementData.className;
				}
				if (elementData.attributes){
					for(var x in elementData.attributes){
						if (null != elementData.attributes[x]){
							element.setAttribute(x, elementData.attributes[x]);
						}
					}
				}
				if (elementData.textNode){
					element.appendChild(_calendarWindow.document.createTextNode(elementData.textNode));
				}
			}
			if (parentElement){
				parentElement.appendChild(element);
			}
		}
		return element;
	};
	
	/**
	 * Renders base layout for calendar in window
	 */
	this._renderBaseWindow = function(){
		_calendarWindow = window.open("", "calendar", "location=no, menubar=no, resizable=yes, status=no, toolbar=no, scrollbars=yes, width=" + _initialWidth + ", height=" + _initialHeight);
		this._generateXhtmlLayout();
		this._loadCalendarStyles();
		var bodyElement = _calendarWindow.document.getElementsByTagName("body")[0];
		_contentTable = this._createElement({
			tagName: 'table',
			id: _sizeContainerId
		});
		var tr = this._createElement({
			tagName: 'tr'
		}, _contentTable);
		_calendarHolder = this._createElement({
			tagName: 'td',
			className: 'measureCell',
			id:	_calendarHolderId
		}, tr);
		bodyElement.appendChild(_contentTable);
	};
	
	/**
	 * Finds absolute position of the element according to the most top layout element in the DOM(html)
	 * @param	{DOM Object}	elmObj		DOM element wich coordinates we need to find
	 */
	this._findPosition = function (elmObj){
		var curLeft = 0
		var curTop = 0;
		if (elmObj.offsetParent){
			do{
				curLeft += elmObj.offsetLeft;
				curTop 	+= elmObj.offsetTop;
			}
			while (elmObj = elmObj.offsetParent);
			
			return {'x' : curLeft, 'y' : curTop};
		}
	};
	
	/**
	 * Searches recursivelly all child elements for node
	 * @param	{DOM object}	container	parent element
	 * @param	{DOM object}	node		element to search under the parent
	 * 
	 * @return	{Boolean}					true if found, false if not
	 */
	this._contains = function(container, node) {
		var found = false;
		if (null != node){
			if (node == container)
				found = true;
			else if (node.parentNode)
				found = this._contains(container, node.parentNode);
		}
		return found;
	};
	
	/**
	 * Calculates position of calender in SHOW_CALENDAR_ON_TRIGGER mode
	 */
	this._setCalendarOnTriggerPosition = function(){
		var position = this._findPosition(_triggerField);
		_calendarHolder.style.top = position.y + 'px';
		_calendarHolder.style.left = (position.x) + 'px';
	};
	
	/**
	 * Sets close event for document click in SHOW_CALENDAR_ON_TRIGGER mode
	 */
	this._setCalendarOffOnDocumentClick = function(){
		_calendarCloseCallback = function(event){
			event = event || window.event;
			if (event.target != _calendarHolder && !_self._contains(_calendarHolder, event.target)){
				_self._closeCalendar();
			}
		}
		if (_isIE){
			_calendarWindow.document.attachEvent('onclick', _calendarCloseCallback);
		}
		else{
			_calendarWindow.document.addEventListener('click', _calendarCloseCallback, true); 
		}
	};
	
	/**
	 * Renders base layout for calendar in layer, or calendar on trigger
	 */
	this._renderBaseLayer = function(){
		_calendarWindow = window;
		if (_isIE6 && SHOW_CALENDAR_LAYER == _displayMode){
			this._hideSelects();
		}
		if (SHOW_CALENDAR_LAYER == _displayMode){
			_calendarLayerBg = this._createElement({tagName: 'div', className: "calendarBg"}, _calendarWindow.document.getElementsByTagName("body")[0]);
			this.recalculateBgSize();
			_calendarWindow.onresize = function(){
				_self.recalculateBgSize();
				_self.recalculateCalendarPosition();
			}
		}
		_calendarHolder = this._createElement({
				tagName: 'div',
				id: _calendarHolderId
			},
			_calendarWindow.document.getElementsByTagName("body")[0]
		);
		if (SHOW_CALENDAR_ON_TRIGGER == _displayMode && _isIE6){
			this._createElement({
					tagName: 'iframe',
					className: "calendarIframe"
				},
				_calendarHolder
			);
		}
		var calHeader = this._createElement({
				tagName: 'div',
				className: "calendarHeading"
			},
			_calendarHolder
		);
		_calendarAnchor = this._createElement({
				tagName: 'a',
				id: "calendarAnchor",
				textNode: " ",
				attributes: {
					href: "javascript: void(0);",
					title: "Kalender"
				}
			},
			calHeader
		);
		calHeader.appendChild(_calendarWindow.document.createTextNode(_defaultTitle));
		var closeLink = this._createElement({
				tagName: 'a',
				className: "calendarCloseBtn",
				attributes : {
					href: "javascript: closeCalendar();"
				}
			},
			calHeader
		);
		this._createElement({
				tagName: 'span',
				textNode: "Kalender schließen"
			},
			closeLink
		);
		closeLink.onclick = this._closeCalendar;
		if (SHOW_CALENDAR_ON_TRIGGER == _displayMode){
			this._setCalendarOnTriggerPosition();
			this._setCalendarOffOnDocumentClick();
		}
	};
	
	/**
	 * Calculates size of the background layer
	 */
	this.recalculateBgSize = function(){
		var bodyWidth = _calendarWindow.document.getElementsByTagName("body")[0][(_isIE? 'clientWidth': 'offsetWidth')];
		var width = _calendarWindow.document.documentElement[(_isIE? 'clientWidth': 'offsetWidth')];
		if (bodyWidth > width){
			width = bodyWidth;
		}
		_calendarLayerBg.style.width = width + 'px';
		_calendarLayerBg.style.height = (_calendarWindow.document.documentElement.scrollHeight || _calendarWindow.document.documentElement.offsetHeight) + 'px';
	}
	/**
	 * recalculates calendar position according to the size of the viewport
	 */
	this.recalculateCalendarPosition = function(){
		if (_calendarWindow.document.documentElement.clientWidth < _calendarHolder.offsetWidth){
			_calendarHolder.style.marginLeft = -(_calendarWindow.document.documentElement.clientWidth/2) + 'px';
		}
		else {
			_calendarHolder.style.marginLeft = -(_calendarHolder.offsetWidth/2) + 'px';
		}
		if (_calendarWindow.document.documentElement.clientHeight < _calendarHolder.offsetHeight){
			_calendarHolder.style.marginTop = -(_calendarWindow.document.documentElement.clientHeight/2) + 'px';
		}
		else {
			_calendarHolder.style.marginTop = -(_calendarHolder.offsetHeight/2) + 'px';
		}
	};
	
	/**
	 * Closes calendar window or removes calendar layer
	 */
	this._closeCalendar = function(){
		if (SHOW_CALENDAR_WINDOW == _displayMode){
			_calendarWindow.close();
		}
		else if (SHOW_CALENDAR_LAYER == _displayMode || SHOW_CALENDAR_ON_TRIGGER == _displayMode){
			_calendarWindow.document.getElementsByTagName("body")[0].removeChild(_calendarHolder);
			if (SHOW_CALENDAR_LAYER == _displayMode){
				_calendarWindow.onresize = function(){};
				_calendarWindow.document.getElementsByTagName("body")[0].removeChild(_calendarLayerBg);
				if (_isIE6){
					_self._showSelects();
				}
			}
			if (SHOW_CALENDAR_ON_TRIGGER == _displayMode){
				if (_isIE){
					_calendarWindow.document.detachEvent('onclick', _calendarCloseCallback);
				}
				else{
					_calendarWindow.document.removeEventListener('click', _calendarCloseCallback, true); 
				}
			}
		}
		_rendered = false;
		if (_triggerField){
			_triggerField.focus();
		}
	};
	
	/**
	 * Shows select elements on calender close (IE6-)
	 */
	this._showSelects = function(){
		var selects = _calendarWindow.document.getElementsByTagName("select");
		for (var i = 0; i < selects.length; i++){
			if (selects[i].style.visibility == "hidden" && selects[i].hidedByCalender){
				selects[i].style.visibility = "";
				selects[i].hidedByCalender = false;
			}
		}
	};
	
	/**
	 * Hides select elements on calender open (IE6-)
	 */
	this._hideSelects = function(){
		var selects = _calendarWindow.document.getElementsByTagName("select");
		for (var i = 0; i < selects.length; i++){
			if (selects[i].style.visibility != "hidden"){
				selects[i].style.visibility = "hidden";
				selects[i].hidedByCalender = true;
			}
		}
	};
};
/**
 * Shows javascript calendar for date choosing
 * @param	{DOMobject}		trigger		field that started this function, mandatory parameter, required for accessibility.
 * @param	{String}		fieldId		id of result field, where select data will be set
 */
var showCalendar = function(trigger, fieldId){
	var calendarField = document.getElementById(fieldId);
	if (calendarField){
		var dateParsed = [null, null, null];
		if (!calendarField.dataError && calendarField.value){
			dateParsed = parseDate(calendarField.value)
		}
		if (!calendarField.calendar){
			calendarField.calendar = new calendar;
		}
		if (null != dateParsed[0]){
			dateParsed[0] = dateParsed[0] - 1;
		}
		trigger.calendarField = calendarField;
		calendarField.calendar.initialize(dateParsed[0], dateParsed[1], dateParsed[2], calendarField, trigger);
	}
};
/**
 * Sets focus on rendered calendar field.
 */
var focusActiveCalendar = function(trigger){
	if (trigger.calendarField && trigger.calendarField.calendar && trigger.calendarField.calendar.isCalendarRendered()){
		trigger.calendarField.calendar.setFocus();
	}
};
/**
 * Parses date for calendar
 */
var parseDate = function(date){
	var dataReturn = [null, null, null];
	var test = /^\d{2}.\d{2}.\d{4}$/i;
	if (test.exec(date)){
		dataReturn2 = [null, null, null];
		var data = date.split('.');
		if (data.length == 3){
			dataReturn2[2] = parseInt(data[0]);
			dataReturn2[0] = parseInt(data[1]);
			dataReturn2[1] = parseInt(data[2]);
		}
		if (dataReturn2[2] > 0 && dataReturn2[2] < 32 && dataReturn2[0] > 0 && dataReturn2[0] < 13 && dataReturn2[1] > 1990 && dataReturn2[1] < 2100){
			dataReturn = dataReturn2;
		}
	}
	return dataReturn;
};
