function DatepickerSpecialDay(date,className){
	this.date = this.cutTime(date);
	this.className = className || null;
}
DatepickerSpecialDay.prototype.cutTime = function(date){
	date = new Date(date);
	var ndate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
	return ndate;
}

function DatepickerObj(options){	
	var self = this;
	
	// Надо выводить дату пользователя, проверять её корректность с учетом временно зоны пользователя.
	this.ServerToday = new Date();
	this.date = this.cutTime(this.ServerToday);
	//this.selDate = null;//this.cutTime(new Date());
    this.selDate = null;//this.cutTime(new Date());
	//this.today = this.cutTime(new Date());
	this.today = this.cutTime(this.ServerToday);
	this.selSetted = false;
	
	this.entObj = document.createElement("div");
	this.entCalendar = document.createElement("div");
	this.monthPan = document.createElement("table");
	this.dlabelPan = document.createElement("table");
	this.daysPan = document.createElement("table");
	this.doOnClick = null;
	this.el_Input = null;
	this.el_forPosition = null;
	
	this.SpecialDays = {};

	if(options && options.selectAll && options.selectAll == true){
		this.selectAll = true;
		
	}
	
	//this.SelectedDays = [];

	this.options = {};
	defLeng = {
		langname:	'ru-ru',
		monthesFNames:	["Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь"],
		monthesDNames:	["Января", "Февраля", "Марта", "Апреля", "Мая", "Июня", "Июля", "Августa", "Сентября", "Октября", "Ноября", "Декабря"],
		monthesSNames:	["Янв", "Фев", "Мар", "Апр", "Май", "Июн", "Июл", "Авг", "Сен", "Окт", "Ноя", "Дек"],
		daysFNames:	["Воскресенье", "Понедельник", "Вторник", "Среда", "Четверг", "Пятница", "Суббота"],
		daysSNames:	["Вс", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб"],
		weekend:	[0, 6],
		weekstart:	1
	};

/////////////////////////////
	if( language == "en" || document.getElementById('Language') != null && document.getElementById('Language').value == 'en') {
		defLeng = {
			lang:			'en-en',
			monthesFNames:	["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
			monthesDNames:	["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
			monthesSNames:	["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sen", "Oct", "Nov", "Dec"],
			daysFNames:		["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
			daysSNames:		["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
			weekend:		[0, 6],
			weekstart:		1
		};
	}
/////////////////////////////
    if( language == 'uk' || document.getElementById('Language') != null && document.getElementById('Language').value == 'uk') {
            defLeng = {
                lang:                    'uk-uk',
                monthesFNames:            ["Січень", "Лютий", "Березень", "Квітень", "Травень", "Червень", "Липень", "Серпень", "Вересень", "Жовтень", "Листопад", "Грудень"],
                monthesDNames:    ["Січня", "Лютого", "Березня", "Квітня", "Травня", "Червня", "Липня", "Серпня", "Вересня", "Жовтня", "Листопада", "Грудня"],
                monthesSNames:        ["Січ", "Лют", "Бер", "Кві", "Тра", "Чер", "Лип", "Сер", "Вер", "Жов", "Лис", "Гру"],
                daysFNames:                ["Неділя", "Понеділок", "Вівторок", "Середа", "Четвер", "П`ятниця'", "Субота"],
                daysSNames:            ["Нд", "Пн", "Вт", "Ср", "Чт", "Пт'", "Сб"],
                weekend:                [0, 6],
                weekstart:                1
            };
    }

	for (lg in defLeng) 
		this.options[lg] = defLeng[lg];
}
DatepickerObj.prototype.cutTime = function(date) {
	date = new Date(date);
	var ndate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
	return ndate;
}
DatepickerObj.prototype.setFormatedDate = function(date){
	var tempDate = date.getDate();
	var tempMonth = date.getMonth()+1;
	
	if(tempDate < 10)
		tempDate = '0' + tempDate;
	if(tempMonth < 10)
		tempMonth = '0' + tempMonth;
    return tempDate + "." + tempMonth + "." + date.getFullYear();
}
DatepickerObj.prototype.getMonthDName = function(MonthN) {
	var sysMonth = parseInt(MonthN,10)-1; 
	var MonthDName = this.options.monthesDNames[sysMonth];
	return MonthDName;
}
DatepickerObj.prototype.getDayName = function(k){
	var q = k + this.options.weekstart;
	if (q > 6) q = q - 7;
	return this.options.daysSNames[q];
}
DatepickerObj.prototype.drawMonth = function(){
	var self = this;
	if(this.monthPan.childNodes.length>0)
		this.monthPan.deleteRow(0);
		
	var monthPanRow = this.monthPan.insertRow(-1);
	
	var monthArLeft = monthPanRow.insertCell(0);
		monthArLeft.className = "monthArLeft";
		var monthArLeftSpan = document.createElement("span");
		monthArLeftSpan.appendChild( document.createTextNode('\u25C4') );
		monthArLeftSpan.onclick = function(){ self.prevMonth() };
		monthArLeft.appendChild(monthArLeftSpan);
		
	var monthContent = monthPanRow.insertCell(1);
		monthContent.className = "monthContent";
		var monthContentSpan = document.createElement("span");
		monthContentSpan.appendChild( document.createTextNode( this.options.monthesFNames[this.date.getMonth()]+" "+this.date.getFullYear() ) );
		monthContent.appendChild(monthContentSpan);
		
	var monthArRight = monthPanRow.insertCell(2);
		monthArRight.className = "monthArRight";
		var monthArRightSpan = document.createElement("span");
		monthArRightSpan.appendChild( document.createTextNode('\u25BA') );
		monthArRightSpan.onclick = function(){ self.nextMonth() };
		monthArRight.appendChild(monthArRightSpan);
}
DatepickerObj.prototype.nextMonth = function(){
	this.selSetted = false;
	//this.date = new Date(this.selDate);
	//this.date = new Date(this.selDate.setMonth(this.selDate.getMonth()+1));
	this.date = new Date(this.date.setMonth(this.date.getMonth()+1));
	this.draw();
}
DatepickerObj.prototype.prevMonth = function(){
	this.selSetted = false;
	//this.date = new Date(this.selDate)
	//this.date = new Date(this.selDate.setMonth(this.selDate.getMonth()-1));
	this.date = new Date(this.date.setMonth(this.date.getMonth()-1));
	this.draw();
}
DatepickerObj.prototype.drawDayLabels = function(){
	var self = this;
	if(this.dlabelPan.childNodes.length>0)
		this.dlabelPan.deleteRow(0);
	
	var row = this.dlabelPan.insertRow(-1);
	for(var i=0; i<7; i++){
		var cDay = row.insertCell(i);
		cDay.appendChild(document.createTextNode(this.getDayName(i)))
	}
}
DatepickerObj.prototype.drawDays = function() {
	var self = this;
	if (this.daysPan.firstChild) {
		for(var r=0;this.daysPan.firstChild.childNodes.length>0;r++){
			this.daysPan.firstChild.deleteRow(0);
		}
	}
	
	var row = {}, cell = {};
        var tempDate = new Date(this.date);
		if( this.selSetted )
		{
			//alert( this.selDate );
			tempDate = new Date( tempDate.setMonth( this.selDate.getMonth() ) );
		}
    	tempDate.setDate(1);
		
    	var day1 = (tempDate.getDay() - this.options.weekstart) % 7;
    	if( day1 < 0 ) day1 += 7;
    		tempDate.setDate(- day1);
	    tempDate.setDate(tempDate.getDate() + 1);
        if (tempDate.getDate() < tempDate.getDay()) 
			tempDate.setMonth(tempDate.getMonth() - 1);
		
		//set days
		for (var weekNumber=0; weekNumber<6; weekNumber++) {
            row = this.daysPan.insertRow(-1);
			for (var i=0; i<7; i++) {
                cell = row.insertCell(-1);
                cell.appendChild(document.createTextNode(tempDate.getDate()));
				cell.setAttribute('thisdate', this.setFormatedDate(tempDate));
				cell.className = "thismonth";
				
				if(tempDate.getMonth()!=this.date.getMonth()){
					cell.className = "othermonth";
				}
				
                if (tempDate.toDateString() == this.today.toDateString())
					cell.className = "today";
				
				
				
				try {
					if( Directions != null && Directions.length > 0 ) {
						for( j=1, DLength = Directions.length; j < DLength; j++ ) {
							if( this.setFormatedDate(tempDate) == Directions[j].Date) {
								$(cell).addClass('hasDirection');
								$(cell).addClass('Direction'+j);
							}
						}
					}
				} catch(e){}
				
				if(this.SpecialDays[tempDate.valueOf()] != null){
					$(cell).addClass(self.SpecialDays[tempDate.valueOf()].className);
				}
				
				var ADayBeforeToday = new Date(this.today);
				ADayBeforeToday.setDate(ADayBeforeToday.getDate());
				if( !this.selectAll && (tempDate < ADayBeforeToday) )
					cell.className += ' ' + "cantPick";
				
				cell.onclick = function(event){
					if( !$(this).hasClass( "cantPick" ) ) {
						this.className +=' '+ "selected";
						self.el_Input.value = this.getAttribute('thisdate');
						if( self.SegmentDOMObj != null )
						{
							self.SegmentDOMObj.update();
						}
						self.hide();
					}
				}
                tempDate.setDate(tempDate.getDate() + 1);
			}
		}
}
DatepickerObj.prototype.createStructure = function(){
	// Create Structure
	var self = this;
	
	this.entBox = new objBox();
	this.entBox.className = "datepicker";
	this.entBox.content = this.entObj;
	this.entBox.build();
	
	this.entObj.appendChild(this.entCalendar);
	this.entCalendar.appendChild(this.monthPan);
		this.monthPan.className = "monthPan";
	this.entCalendar.appendChild(this.dlabelPan);
		this.dlabelPan.cellSpacing = "4";
		this.dlabelPan.className = "dlabelPan";
	this.entCalendar.appendChild(this.daysPan);
		this.daysPan.cellSpacing = "4";
		this.daysPan.className = "daysPan";
	document.body.appendChild(this.entBox.entObj);
}
DatepickerObj.prototype.draw = function(){
	//this.createStructure();
	// Set constructor options
	this.drawMonth();
	this.drawDayLabels();
	this.drawDays();
}
DatepickerObj.prototype.show = function(el_Input,el_forPosition,SegmentDOMObj){
	var self = this;
	
	this.SegmentDOMObj = SegmentDOMObj || null;
	this.el_Input = el_Input;
	if( this.el_Input.value != "" )
	{
		this.selSetted = true;
		this.selDate = Date.parseAWADString(el_Input.value);
		this.date = this.selDate;
	}

	$(this.el_Input).keyup(function(event){
		var e = e || event;
		switch (e.keyCode){
			case 27: // <Esc>
			self.hide();
			break;
		}
	});
	$("#page").bind("click", {self: self}, self.hideIfClickOutside);
	this.el_forPosition = el_forPosition;
	this.setPosition();
	this.draw();
	this.entBox.entObj.style.display = "block";
}
DatepickerObj.prototype.getPosition = function(oNode,pNode) { 
	if(!pNode)
		var pNode = document.body
	var oCurrentNode=oNode;
	var iLeft=0;
	var iTop=0;
	while ((oCurrentNode)&&(oCurrentNode!=pNode)){//.tagName!="BODY"){ 
		iLeft+=oCurrentNode.offsetLeft-oCurrentNode.scrollLeft;
		iTop+=oCurrentNode.offsetTop-oCurrentNode.scrollTop;
		oCurrentNode=oCurrentNode.offsetParent;//isIE()?:oCurrentNode.parentNode;
	}
	return new Array(iTop,iLeft);
}
DatepickerObj.prototype.setPosition = function(){
	var XY = this.getPosition(this.el_forPosition);
	//var entBoxHeight = this.entBox.offsetHeight();
	
	this.entBox.entObj.style.top = XY[0] - 40 +"px";
	this.entBox.entObj.style.left = XY[1]+"px";
}
DatepickerObj.prototype.hide = function(){
	$("#page").unbind("click", this.hideIfClickOutside);
	this.entBox.entObj.style.display = "none";
}
DatepickerObj.prototype.hideIfClickOutside = function(event){
	var self = event.data.self;
    if (event.target != self.el_Input) {
		self.hide();
    }
}

// Box
function objBox(){
	this.entObj = document.createElement("div");
	this.boxBorders = '<div class="corner_tl"><div class="IE6"></div></div><div class="corner_tr"><div class="IE6"></div></div><div class="corner_br"><div class="IE6"></div></div><div class="corner_bl"><div class="IE6"></div></div><div class="side_t"><div class="IE6"></div></div><div class="side_b"><div class="IE6"></div></div><div class="side_l"><div class="IE6"></div></div><div class="side_r"><div class="IE6"></div></div>';
	this.content = '';
	this.build = function(){
		this.entObj.className = "box "+this.className;
		this.entObj.innerHTML = this.boxBorders;
		var boxInner = document.createElement("div");
		boxInner.className = "boxContent";
		this.entObj.appendChild(boxInner);
		this.entObj.lastChild.appendChild(this.content);
	}
}