function getId (id) { return document.getElementById(id) }
var popUpCal = {

	calNum:		0,

	calendarId:	'calendarDiv',
	inputClass:	'calendarSelectDate',

	init:		function () {
				var inputs = getElementsByClass(popUpCal.inputClass, document, 'input');
				for (var i=0; i<inputs.length; i++) {

					startDate = calStart.split('.');
					popUpCal.sD = function () { return (startDate)	? new Date(
						startDate[2], 
						startDate[1]-1, 
						parseInt(startDate[0], 10)
					)	: new Date();} ()

					curDate = (inputs[i].getAttribute('value')) ? inputs[i].getAttribute('value').split('.') : calToday.split('.');
					popUpCal.cD = function () { return (curDate)	? new Date(
						curDate[2],
						curDate[1]-1,
						parseInt(curDate[0])
					)  	: new Date();} ()

					inputs[i].onfocus = function () { setPos(this, getId(popUpCal.calendarId)); popUpCal.drawCalendar(this); }
				}
			},

	drawCalendar:	function (inputObj) {
				
				popUpCal.cFrom 	= new Date();
				popUpCal.cToday = new Date();
				
		   		var html='<div id="popupCalBg"></div></a><a href="javascript: void(0)" id="closeCalender">&nbsp;</a>'
					+'<table cellpadding="0" cellspacing="0" id="linksTable"><tr>'
					+'	<td>&nbsp;</td>'
					+'</tr></table>'
				  	+'<table id="calendar" cellpadding="0" cellspacing="0"><tr>';

				var sel = popUpCal.cD.getMonth() - popUpCal.sD.getMonth();
				sel = (sel < 0) ? sel + 12 : sel;

/**/ 

				var fromDay = popUpCal.sD.getDate();
				var endDay  = calRes;
				Months = new Date(popUpCal.sD.getFullYear(), popUpCal.sD.getMonth(), popUpCal.sD.getDate() + calRes).getMonth() - popUpCal.sD.getMonth() + 1;
				Months = (Months<0) ? Months + 12 : Months;

				for (var cnt=0; cnt<Months; cnt++) 
					{
					var aC = Math.abs(sel-cnt);
					html += '<td class="subcal sc'+aC+'" id="sC'+cnt+'"><table cellpadding="0" cellspacing="0"><tr>'
						+'<th colspan="7" class="calendarHeader">'
						+new Array('Январь','Февраль','Март','Апрель','Май','Июнь','Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь')[popUpCal.sD.getMonth()]
						+popUpCal.sD.getFullYear() 	+'</th></tr><tr class="weekDaysTitleRow">';
					
					for (var j=0; j<7; j++) html += '<td' + ((j >=5) ? ' class="weekEnd"' : '') + '>' + new Array('Пн','Вт','Ср','Чт','Пт','Сб','Вс')[j] + '</td>';

								
					var daysInMonth	=    32-new Date(popUpCal.sD.getFullYear(), popUpCal.sD.getMonth(), 32).getDate();
					var startDay	=	new Date(popUpCal.sD.getFullYear(), popUpCal.sD.getMonth(), 0 ).getDay();
					var numRows 	= 0;
					var printDate 	= 1;

					if (startDay != 7) {
						numRows = Math.ceil(((startDay)+(daysInMonth))/7);
						var noPrintDays = startDay;
					} else 	var noPrintDays = 0;
								
					var today	= popUpCal.sD.getDate();
					var thisMonth	= popUpCal.sD.getMonth();
					var thisYear	= popUpCal.sD.getFullYear();
								
					for (var e=0; e<numRows; e++) {

						html += '<tr class="weekDaysRow">';

						for (var f=0; f<7; f++) {
							
							if (noPrintDays == 0 && printDate <= daysInMonth) {
								--fromDay;
								if (fromDay < 0) --endDay;
							}
							DIS = (fromDay > 0 || endDay < 0 || noPrintDays != 0 || printDate > daysInMonth) ? 'disCell' : '';
							DIS +=(f>=5) ? ' weekEnd' : '';
							if (	   ( printDate 			==  popUpCal.cD.getDate() )
								&& ( noPrintDays 		==  0 )
								&& ( popUpCal.sD.getMonth()	==  popUpCal.cD.getMonth() )
								&& ( popUpCal.sD.getFullYear()	==  popUpCal.cD.getFullYear() )
							   )	html += '<td id="today" class="weekDaysCell '+ DIS +'">'
							else	html += '<td class="weekDaysCell '+ DIS +'">'

							if (noPrintDays == 0) {
								if (printDate <= daysInMonth)	html += '<a href="javascript: void(0)">'+printDate+'</a>';
								else html += '&nbsp;'
								printDate++; 
							} else html += '&nbsp;'

							html += '</td>';

							if (noPrintDays > 0)	noPrintDays--;

						}

						html += '</tr>';
					}

					html += '</table></td>';
	

				
					
					lastMonth = popUpCal.sD.getMonth();
					popUpCal.sD.setMonth(popUpCal.sD.getMonth()+1)
					if(lastMonth + 1 != popUpCal.sD.getMonth())popUpCal.sD.setMonth(lastMonth+1) //дёргает назад лишний месяц. При это съезжает дата конца продаж. Происходит из-за некорректной работы setMonth. Сделать нормально как только возможно
					//html+=popUpCal.sD.getMonth();
				}
				html += '</tr></table>';
				
				popUpCal.sD.setMonth(popUpCal.sD.getMonth()-Months)



	
				var calendarDiv = getId(popUpCal.calendarId);
				calendarDiv.innerHTML = html;
	
				getId('closeCalender').onclick = function () { calendarDiv.innerHTML = '';  popUpCal.init() }

				getId('linksTable').style.width = getId('popupCalBg').style.width = Months * 184 - 8 + 'px';
				getId('calendar').style.width = Months * 184 + 'px';

				var y = getId('calendar');
				
				getId('popupCalBg').style.height = y.offsetHeight + 14 + 'px';
				
				var x = y.getElementsByTagName('a');

				for (var i=0; i<x.length; i++) {

					if (!/\bdisCell\b/.test(x[i].parentNode.className)) {
						x[i].onmouseover =  function () { this.parentNode.className = this.parentNode.className.replace('weekDaysCell', 'weekDaysCellOver'); }
						x[i].onmouseout  =  function () { this.parentNode.className = this.parentNode.className.replace('weekDaysCellOver', 'weekDaysCell'); }
						x[i].onclick 	 =  function () {
							popUpCal.cD.setDate(this.innerHTML);
							var curCalNum = parseInt(this.parentNode.parentNode.parentNode.parentNode.parentNode.getAttribute('id').replace('sC', ''), 10);

							if (popUpCal.calNum > curCalNum && popUpCal.sD.getMonth() > popUpCal.cD.getMonth() ) { popUpCal.cD.setFullYear(popUpCal.cD.getFullYear() -1) }
							
							popUpCal.calNum = curCalNum;
							popUpCal.cD.setMonth(popUpCal.sD.getMonth()  + popUpCal.calNum)
							
							var dD = popUpCal.cD.getDate()
							var dM = popUpCal.cD.getMonth()+1
							var dY = popUpCal.cD.getFullYear()
							dD = (dD < 10) ? '0'+dD: dD
							dM = (dM < 10) ? '0'+dM: dM

							inputObj.value = dD+'.'+dM+'.'+dY
							getId(popUpCal.calendarId).style.display = 'none'
						}
					}

				}

				var z = y.getElementsByTagName('table');
				for (var i=0; i<Months; i++) {
					z[i].parentNode.onmouseover = function () {
						var curId = parseInt(this.getAttribute('id').replace('sC', ''), 10);
						for (var j = 0; j<Months; j++) {
							var calNum = Math.abs(curId - j);
							calNum = (calNum > 2) ? 2 : calNum;
							getId('sC'+j).className = 'subcal sc' + calNum;
						}
					}
				}
			}

}

if ( window.onload != null ) {
	var oldOnload = window.onload;
	window.onload = function (e) { oldOnload(e); popUpCal.init() }
} else 	window.onload = popUpCal.init;

function getElementsByClass(searchClass,node,tag) {
	if  ( node == null ) node = document
	if  ( tag == null  ) tag  = '*'

	var classElements = new Array();
	var els = node.getElementsByTagName(tag);
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < els.length; i++) { if ( pattern.test(els[i].className) ) { classElements[j] = els[i]; j++; } }
	return classElements;
}

function setPos(targetObj,moveObj) {
	var coors = findPos(targetObj);
	with (moveObj.style) { position = 'absolute'; display = 'block'; top = coors[1]; left = coors[0]; }
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft + 'px', curtop + 'px'];
}
