;(function($) {

	$.widget("ui.dateInput", $.extend({
	
		_init: function() {
		
			this.init.apply(this, arguments);
		},
		
		init: function() {
	
//			console.log("dateInput.init")
			this.build();
	
			this.selectDate(this.getData('selectedValue'));
	
			var self = this
	
			this.setHiders(true)
		},
	
		isShow: function() {
			return this.$container.isShow();
		},
	
		close: function() {
			//fixIE.hide()
			floatWidget.activePop(this)
	
			this.$container.hide();
		},
	
	
		getMonthFirstDay: function(date) {
	
			var monthFirstDay = new Date(date) // clone
			monthFirstDay.setDate(1)
			monthFirstDay = monthFirstDay.getDay() || 7 // 0 is sunday => make it 7
	
			return monthFirstDay
		},
	
		fillMonthTable: function(date) {
	
//			console.log("dateInput.fillMonthTable")
	
			var buffer = ['<table> \
				<thead><tr><th>Пн</th><th>Вт</th><th>Ср</th><th>Чт</th><th>Пт</th><th>Сб</th><th>Вс</th></tr></thead><tbody>'];
	
	
			var today = new Date()
	
			var monthFirstDay = this.getMonthFirstDay(date)
	
	
	
			buffer.push('<tr>')
			// push empty days
	                if (monthFirstDay>1) {
				buffer.push('<td colspan="'+(monthFirstDay-1)+'"></td>') // empty space before first day of month
			}
	
			var monthLastDay = new Date(date)
			monthLastDay.setMonth(monthLastDay.getMonth()+1)
			monthLastDay.setDate(0) // a day before next month
	
			var daysInMonth = monthLastDay.getDate()
			var maxCell = daysInMonth + monthFirstDay - 1
	
			var i
			// date in js format: month can be 0, single-digit 1.0.2009 possible
			var currentJsDateSuffix = '.'+date.getMonth()+'.'+date.getFullYear()
	
			var todayNumber = null
			if (date.getMonth() == today.getMonth() && date.getFullYear() == today.getFullYear()) {
				todayNumber = today.getDate()
			}
	
			var selectedNumber = null
			if (this.selectedDate && date.getMonth()==this.selectedDate.getMonth() && date.getFullYear()==this.selectedDate.getFullYear()) {
				selectedNumber = this.selectedDate.getDate()
			}
	
			var pastNumber = -1
			if (date.getFullYear() < today.getFullYear() || (date.getFullYear()==today.getFullYear() && date.getMonth() == today.getMonth())) {
				var pastNumber = today.getDate()
			}
	
	
	
			for(i=monthFirstDay;i<=maxCell;i++) {// or <= ? or <maxCell-1 ?
				var number = i - monthFirstDay + 1
	
				buffer.push('<td class="dayCell day'+(i%7 || 7)+(number<pastNumber ? ' past':'')+(number===todayNumber ? ' today':'')+(number===selectedNumber ? ' selected':'')+'" date="'+number+currentJsDateSuffix+'"> \
					<a href="javascript:void(0)">' + number + '</a></td>')
				if (i % 7 == 0) {
					buffer.push('</tr><tr>')// FIXME: check for months that end strictly at cal end
				}
			}
	
			var cellsLeft = 7 - (maxCell % 7)
			if (cellsLeft < 7) {
				buffer.push('<td colspan="'+cellsLeft+'"></td>')
			}
	
			if (maxCell <= 35) {
				// add 1 more row if needed => to keep same calendar size
				buffer.push('<tr><td colspan="7">&nbsp;</td></tr>')
			}
	
			buffer.push('</tr></tbody></table>')
			
			return buffer
		},
	
	
	
		build: function() {
			var self = this
	
//			console.log("dateInput.build "+this.getId())
	
			this.$container = $('<div style="display:none" class="date_wrapper"><div class="date_selector close"></div></div>').appendTo(document.body)
	
			var $container = this.realContainer = $(this.$container[0].firstChild)
	
			// table opener, first month
			var template = '<table>\
				<tr class="month_nav"> \
					<td><span class="dateInput-prev">&laquo;</span><span class="month_name month_name1"></span></td> \
					<td><span class="month_name month_name2"></span><span class="dateInput-next">&raquo;</span></td>\
				</tr> \
				<tr><td class="dateInput-month-holder"></td><td class="dateInput-month-holder"></td></tr></table> \
				<div class="stringCheckbox-close"></div>'
	
	
			$container.html(template)
	
			$($container[0].lastChild).click(function() { self.close() })
	
	
			this.monthPrevSpan = $('span.dateInput-prev', $container).click(function() { self.prevMonth() })
			$('span.dateInput-next', $container).click(function() { self.nextMonth() })
	
			this.monthNameSpan1 = $('span.month_name1', $container)
			this.monthNameSpan2 = $('span.month_name2', $container)
	
			this.monthHolder1 = $($('td.dateInput-month-holder', $container)[0])
			this.monthHolder2 = $($('td.dateInput-month-holder', $container)[1])
	
	
			$('td.dateInput-month-holder', $container).click(function(e) {
				if (e.target && e.target.tagName=='A') e.target.blur()
				var o = e.target
				while(o.tagName!='TBODY') {
					if (o.tagName == 'TD') {
						if (!o.getAttribute('date')) return
						if ($(o).hasClass('past')) return
						self.selectDate(self.stringToDate(o.getAttribute('date')))
						self.close()
						e.stopPropagation()
						break
					} else {
						o = o.parentNode
					}
				}
			})
			
		},
	
	
		stringToDate: function(jsDateStr) {
			var s = jsDateStr.split('.')
			return new Date(s[2],s[1],s[0])
		},
	
	
		buildMonths: function(date) {
//			console.log("buildMonths "+date)
	
			var today = new Date();
			if (date.getFullYear() == today.getFullYear() && date.getMonth() <= today.getMonth()) {
				this.monthPrevSpan.hide()
			} else {
				this.monthPrevSpan.show()
			}
	
			/* add year if month is not of current year */
			var monthName1 = this.getData('monthNames')[date.getMonth()]
			if (today.getFullYear()!=date.getFullYear()) {
					monthName1 = monthName1 + ' '+date.getFullYear()
			}
	
			//console.log("Fill "+this.monthHolder1[0].innerHTML)
	
			this.monthHolder1.html(this.fillMonthTable(date).join(''))
	
			//alert(this.monthHolder1[0].innerHTML)
	
			this.monthNameSpan1.html(monthName1)
	
			var nextMonth = new Date(date)
			nextMonth.setMonth(nextMonth.getMonth()+1)
	
			var monthName2 = this.getData('monthNames')[nextMonth.getMonth()]
			if (today.getFullYear()!=nextMonth.getFullYear()) {
					monthName2 = monthName2 + ' '+nextMonth.getFullYear()
			}
			this.monthHolder2.html(this.fillMonthTable(nextMonth).join(''))
			this.monthNameSpan2.html(monthName2)
	
	
	
			this.currentMonth = date
		},
	
	
	    nextMonth: function() {
			var m = new Date(this.currentMonth)
			m.setMonth(m.getMonth()+1)
			this.buildMonths(m)
		},
	
	    prevMonth: function() {
			var m = new Date(this.currentMonth)
			m.setMonth(m.getMonth()-1)
			this.buildMonths(m)
		},
	
	    buildMonthsForDate: function(date) {
	
			var requiredMonth = new Date(date.getFullYear(), date.getMonth(), 1)
			var today = new Date()
			if (today.getFullYear() != date.getFullYear() || today.getMonth() != date.getMonth()) {
					// take date-1month as first month if possible
					requiredMonth.setMonth(requiredMonth.getMonth()-1)
			}
	
			this.buildMonths(requiredMonth)
		},
	
	
		set: function(date) {
			if (!date) {
					alert("date_input.set without date")
					return
			}
			var cm = this.currentMonth
			if (cm) {
					// we already have months built here
					// check if need to rebuild
					var bottomDate = new Date(cm.getFullYear(), cm.getMonth(), 1)
					var topDate = new Date(cm.getFullYear(), cm.getMonth()+2, 1)
	
					if (date < bottomDate || date > topDate) {
							// yes need to rebuild
							this.buildMonthsForDate(date)
					}
			} else {
					this.buildMonthsForDate(date)
			}
	
	
			if (this.selectedDate) {
					$('td[date=' + this.dateToString(this.selectedDate) + ']', this.$container).removeClass("selected");
			}
	
			this.selectedDate = date;
	
			$('td[date=' + this.dateToString(date) + ']', this.$container).addClass("selected");
	
		},
	
		dateToString: function(date) {
			return date.getDate()+'.'+date.getMonth()+'.'+date.getFullYear()
		},
	
		selectDate: function(date) {
			this.set(date)
	
			this.element.triggerHandler('select', [date])
		},
	
		open: function() {
			
			this.$container.show();
			//fixIE.show()
			floatWidget.activePush(this)
			this.setPosition();
		},
	
		setPosition: function() {
			
			var offset = this.element.offset();
			this.$container.css({
				top: offset.top + this.element.outerHeight() - 7,
				left: offset.left
			});
		}
	
		/*
		monthName: function(date) {
			return this.getData('monthNames')[date.getMonth()];
		}*/
	
	}, floatWidgetMixin))
	
	Date.defaults = {
		dayNames: ['Воскресенье', 'Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота'],
		shortDayNames: ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб'],
		monthNames: ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'],
		monthNames1: ['января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря'],
		monthNames2: ['январь', 'февраль', 'март', 'апрель', 'май', 'июнь', 'июль', 'август', 'сентябрь', 'октябрь', 'ноябрь', 'декабрь'],
//		shortMonthNames: ['янв', 'фев', 'мар', 'апр', 'май', 'июн', 'июл', 'авг', 'сен', 'окт', 'ноя', 'дек']
		shortMonthNames:['янв.','февр.','марта','апр.','мая','июня','июля','авг.','сент.','окт.','нояб.','дек.']
	}
	
	$.extend($.ui.dateInput, {
		defaults: Date.defaults,
		getter: 'getMonthFirstDay getOpenActive isShow'
	}); 
	
})(jQuery);

// Date object needs that to override jquery/date.js settings
for(var prop in Date.defaults) {
	Date[prop] = Date.defaults[prop]
}